• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmc-dev / openmc / 25930573650

15 May 2026 05:01PM UTC coverage: 81.375% (+0.05%) from 81.326%
25930573650

Pull #3863

github

web-flow
Merge 95bd57fc1 into d56cda254
Pull Request #3863: Shared Secondary Particle Bank

17950 of 25871 branches covered (69.38%)

Branch coverage included in aggregate %.

407 of 417 new or added lines in 17 files covered. (97.6%)

1464 existing lines in 34 files now uncovered.

59095 of 68808 relevant lines covered (85.88%)

48517262.56 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.32
/src/particle.cpp
1
#include "openmc/particle.h"
2

3
#include <algorithm> // copy, min
4
#include <cmath>     // log, abs
5

6
#include <fmt/core.h>
7

8
#include "openmc/bank.h"
9
#include "openmc/capi.h"
10
#include "openmc/cell.h"
11
#include "openmc/collision_track.h"
12
#include "openmc/constants.h"
13
#include "openmc/dagmc.h"
14
#include "openmc/error.h"
15
#include "openmc/geometry.h"
16
#include "openmc/hdf5_interface.h"
17
#include "openmc/lattice.h"
18
#include "openmc/material.h"
19
#include "openmc/message_passing.h"
20
#include "openmc/mgxs_interface.h"
21
#include "openmc/nuclide.h"
22
#include "openmc/particle_data.h"
23
#include "openmc/photon.h"
24
#include "openmc/physics.h"
25
#include "openmc/physics_mg.h"
26
#include "openmc/random_lcg.h"
27
#include "openmc/settings.h"
28
#include "openmc/simulation.h"
29
#include "openmc/source.h"
30
#include "openmc/surface.h"
31
#include "openmc/tallies/derivative.h"
32
#include "openmc/tallies/tally.h"
33
#include "openmc/tallies/tally_scoring.h"
34
#include "openmc/track_output.h"
35
#include "openmc/weight_windows.h"
36

37
#ifdef OPENMC_DAGMC_ENABLED
38
#include "DagMC.hpp"
39
#endif
40

41
namespace openmc {
42

43
//==============================================================================
44
// Particle implementation
45
//==============================================================================
46

47
double Particle::speed() const
2,147,483,647✔
48
{
49
  if (settings::run_CE) {
2,147,483,647✔
50
    // Determine mass in eV/c^2
51
    double mass = this->mass();
2,147,483,647✔
52

53
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
54
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,147,483,647✔
55
           (this->E() + mass);
2,147,483,647✔
56
  } else {
57
    auto mat = this->material();
2,081,363,801✔
58
    if (mat == MATERIAL_VOID)
2,081,363,801!
UNCOV
59
      return 1.0 / data::mg.default_inverse_velocity_[this->g()];
×
60
    auto& macro_xs = data::mg.macro_xs_[mat];
2,081,363,801✔
61
    int macro_t = this->mg_xs_cache().t;
2,081,363,801✔
62
    int macro_a = macro_xs.get_angle_index(this->u());
2,081,363,801✔
63
    return 1.0 / macro_xs.get_xs(
2,147,483,647✔
64
                   MgxsType::INVERSE_VELOCITY, this->g(), macro_t, macro_a);
2,081,363,801✔
65
  }
66
}
67

68
double Particle::mass() const
2,147,483,647✔
69
{
70
  switch (type().pdg_number()) {
2,147,483,647✔
71
  case PDG_NEUTRON:
72
    return MASS_NEUTRON_EV;
73
  case PDG_ELECTRON:
88,210,077✔
74
  case PDG_POSITRON:
88,210,077✔
75
    return MASS_ELECTRON_EV;
88,210,077✔
76
  default:
40,563,926✔
77
    return this->type().mass() * AMU_EV;
40,563,926✔
78
  }
79
}
80

81
bool Particle::create_secondary(
183,211,230✔
82
  double wgt, Direction u, double E, ParticleType type)
83
{
84
  // If energy is below cutoff for this particle, don't create secondary
85
  // particle
86
  int idx = type.transport_index();
183,211,230✔
87
  if (idx == C_NONE) {
183,211,230!
88
    return false;
89
  }
90
  if (E < settings::energy_cutoff[idx]) {
183,211,230✔
91
    return false;
92
  }
93

94
  // Increment number of secondaries created (for ParticleProductionFilter)
95
  n_secondaries()++;
95,463,551✔
96

97
  SourceSite bank;
95,463,551✔
98
  bank.particle = type;
95,463,551✔
99
  bank.wgt = wgt;
95,463,551✔
100
  bank.r = r();
95,463,551!
101
  bank.u = u;
95,463,551✔
102
  bank.E = settings::run_CE ? E : g();
95,463,551!
103
  bank.time = time();
95,463,551✔
104
  bank_second_E() += bank.E;
95,463,551✔
105
  bank.parent_id = current_work();
95,463,551✔
106
  if (settings::use_shared_secondary_bank) {
95,463,551✔
107
    bank.progeny_id = n_progeny()++;
15,373,406✔
108
  }
109
  bank.wgt_born = wgt_born();
95,463,551✔
110
  bank.wgt_ww_born = wgt_ww_born();
95,463,551✔
111
  bank.n_split = n_split();
95,463,551✔
112

113
  local_secondary_bank().emplace_back(bank);
95,463,551✔
114
  return true;
115
}
116

117
void Particle::split(double wgt)
10,308,400✔
118
{
119
  SourceSite bank;
10,308,400✔
120
  bank.particle = type();
10,308,400✔
121
  bank.wgt = wgt;
10,308,400✔
122
  bank.r = r();
10,308,400✔
123
  bank.u = u();
10,308,400✔
124
  bank.E = settings::run_CE ? E() : g();
10,308,400✔
125
  bank.time = time();
10,308,400✔
126

127
  // Convert signed index to a signed surface ID
128
  if (surface() == SURFACE_NONE) {
10,308,400✔
129
    bank.surf_id = SURFACE_NONE;
10,304,528✔
130
  } else {
131
    int surf_id = model::surfaces[surface_index()]->id_;
3,872✔
132
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
3,872✔
133
  }
134

135
  bank.wgt_born = wgt_born();
10,308,400✔
136
  bank.wgt_ww_born = wgt_ww_born();
10,308,400✔
137
  bank.n_split = n_split();
10,308,400✔
138
  bank.parent_id = current_work();
10,308,400✔
139
  if (settings::use_shared_secondary_bank) {
10,308,400✔
140
    bank.progeny_id = n_progeny()++;
5,140,044✔
141
  }
142

143
  local_secondary_bank().emplace_back(bank);
10,308,400✔
144
}
10,308,400✔
145

146
void Particle::from_source(const SourceSite* src)
293,652,464✔
147
{
148
  // Reset some attributes
149
  clear();
293,652,464✔
150
  surface() = SURFACE_NONE;
293,652,464✔
151
  cell_born() = C_NONE;
293,652,464✔
152
  material() = C_NONE;
293,652,464✔
153
  n_collision() = 0;
293,652,464✔
154
  fission() = false;
293,652,464✔
155
  zero_flux_derivs();
293,652,464✔
156
  lifetime() = 0.0;
293,652,464✔
157
#ifdef OPENMC_DAGMC_ENABLED
158
  history().reset();
26,862,849✔
159
#endif
160

161
  // Copy attributes from source bank site
162
  type() = src->particle;
293,652,464✔
163
  wgt() = src->wgt;
293,652,464✔
164
  wgt_last() = src->wgt;
293,652,464✔
165
  r() = src->r;
293,652,464✔
166
  u() = src->u;
293,652,464✔
167
  r_born() = src->r;
293,652,464✔
168
  r_last_current() = src->r;
293,652,464✔
169
  r_last() = src->r;
293,652,464✔
170
  u_last() = src->u;
293,652,464✔
171
  if (settings::run_CE) {
293,652,464✔
172
    E() = src->E;
176,797,600✔
173
    g() = 0;
176,797,600✔
174
  } else {
175
    g() = static_cast<int>(src->E);
116,854,864✔
176
    g_last() = static_cast<int>(src->E);
116,854,864✔
177
    E() = data::mg.energy_bin_avg_[g()];
116,854,864✔
178
  }
179
  E_last() = E();
293,652,464✔
180
  time() = src->time;
293,652,464✔
181
  time_last() = src->time;
293,652,464✔
182
  parent_nuclide() = src->parent_nuclide;
293,652,464✔
183
  delayed_group() = src->delayed_group;
293,652,464✔
184

185
  // Convert signed surface ID to signed index
186
  if (src->surf_id != SURFACE_NONE) {
293,652,464✔
187
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
113,872✔
188
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
113,872✔
189
  }
190

191
  wgt_born() = src->wgt_born;
293,652,464✔
192
  wgt_ww_born() = src->wgt_ww_born;
293,652,464✔
193
  n_split() = src->n_split;
293,652,464✔
194
}
293,652,464✔
195

196
void Particle::event_calculate_xs()
2,147,483,647✔
197
{
198
  // Set the random number stream
199
  stream() = STREAM_TRACKING;
2,147,483,647✔
200

201
  // Store pre-collision particle properties
202
  wgt_last() = wgt();
2,147,483,647✔
203
  E_last() = E();
2,147,483,647✔
204
  u_last() = u();
2,147,483,647✔
205
  r_last() = r();
2,147,483,647✔
206
  time_last() = time();
2,147,483,647✔
207

208
  // Reset event variables
209
  event() = TallyEvent::KILL;
2,147,483,647✔
210
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
211
  event_mt() = REACTION_NONE;
2,147,483,647✔
212

213
  // If the cell hasn't been determined based on the particle's location,
214
  // initiate a search for the current cell. This generally happens at the
215
  // beginning of the history and again for any secondary particles
216
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
217
    if (!exhaustive_find_cell(*this)) {
284,594,509!
UNCOV
218
      mark_as_lost(
×
UNCOV
219
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
220
      return;
×
221
    }
222

223
    // Set birth cell attribute
224
    if (cell_born() == C_NONE)
284,594,509!
225
      cell_born() = lowest_coord().cell();
284,594,509✔
226

227
    // Initialize last cells from current cell
228
    for (int j = 0; j < n_coord(); ++j) {
586,584,437✔
229
      cell_last(j) = coord(j).cell();
301,989,928✔
230
    }
231
    n_coord_last() = n_coord();
284,594,509✔
232
  }
233

234
  // Write particle track.
235
  if (write_track())
2,147,483,647✔
236
    write_particle_track(*this);
10,309✔
237

238
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
239
    check_cell_overlap(*this);
×
240

241
  // Calculate microscopic and macroscopic cross sections
242
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
243
    if (settings::run_CE) {
2,147,483,647✔
244
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
245
          density_mult() != density_mult_last()) {
902,331,826✔
246
        // If the material is the same as the last material and the
247
        // temperature hasn't changed, we don't need to lookup cross
248
        // sections again.
249
        model::materials[material()]->calculate_xs(*this);
2,147,483,647✔
250
      }
251
    } else {
252
      // Get the MG data; unlike the CE case above, we have to re-calculate
253
      // cross sections for every collision since the cross sections may
254
      // be angle-dependent
255
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,081,363,801✔
256

257
      // Update the particle's group while we know we are multi-group
258
      g_last() = g();
2,081,363,801✔
259
    }
260
  } else {
261
    macro_xs().total = 0.0;
111,950,040✔
262
    macro_xs().absorption = 0.0;
111,950,040✔
263
    macro_xs().fission = 0.0;
111,950,040✔
264
    macro_xs().nu_fission = 0.0;
111,950,040✔
265
  }
266
}
267

268
void Particle::event_advance()
2,147,483,647✔
269
{
270
  // Find the distance to the nearest boundary
271
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
272

273
  // Sample a distance to collision
274
  if (type() == ParticleType::electron() ||
2,147,483,647✔
275
      type() == ParticleType::positron()) {
2,147,483,647✔
276
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
176,420,154!
277
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
278
    collision_distance() = INFINITY;
111,950,040✔
279
  } else {
280
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
281
  }
282

283
  double speed = this->speed();
2,147,483,647✔
284
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
285
  double distance_cutoff =
2,147,483,647✔
286
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
287

288
  // Select smaller of the three distances
289
  double distance =
2,147,483,647✔
290
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
291

292
  // Advance particle in space and time
293
  this->move_distance(distance);
2,147,483,647✔
294
  double dt = distance / speed;
2,147,483,647✔
295
  this->time() += dt;
2,147,483,647✔
296
  this->lifetime() += dt;
2,147,483,647✔
297

298
  // Score timed track-length tallies
299
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
300
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
301
  }
302

303
  // Score track-length tallies
304
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
305
    score_tracklength_tally(*this, distance);
2,147,483,647✔
306
  }
307

308
  // Score track-length estimate of k-eff
309
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
310
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
311
  }
312

313
  // Score flux derivative accumulators for differential tallies.
314
  if (!model::active_tallies.empty()) {
2,147,483,647✔
315
    score_track_derivative(*this, distance);
2,147,483,647✔
316
  }
317

318
  // Set particle weight to zero if it hit the time boundary
319
  if (distance == distance_cutoff) {
2,147,483,647✔
320
    wgt() = 0.0;
224,928✔
321
  }
322
}
2,147,483,647✔
323

324
void Particle::event_cross_surface()
2,147,483,647✔
325
{
326
  // Saving previous cell data
327
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
328
    cell_last(j) = coord(j).cell();
2,147,483,647✔
329
  }
330
  n_coord_last() = n_coord();
2,147,483,647✔
331

332
  // Set surface that particle is on and adjust coordinate levels
333
  surface() = boundary().surface();
2,147,483,647✔
334
  n_coord() = boundary().coord_level();
2,147,483,647✔
335

336
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
337
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
338
      boundary().lattice_translation()[2] != 0) {
2,147,483,647✔
339
    // Particle crosses lattice boundary
340

341
    bool verbose = settings::verbosity >= 10 || trace();
801,265,566!
342
    cross_lattice(*this, boundary(), verbose);
801,265,566✔
343
    event() = TallyEvent::LATTICE;
801,265,566✔
344

345
    // Score cell to cell partial currents
346
    if (!model::active_surface_tallies.empty()) {
801,265,566!
UNCOV
347
      auto& lat {*model::lattices[lowest_coord().lattice()]};
×
UNCOV
348
      bool is_valid;
×
UNCOV
349
      Direction normal =
×
UNCOV
350
        lat.get_normal(boundary().lattice_translation(), is_valid);
×
UNCOV
351
      if (is_valid) {
×
UNCOV
352
        normal /= normal.norm();
×
UNCOV
353
        score_surface_tally(*this, model::active_surface_tallies, normal);
×
354
      }
355
    }
356

357
  } else {
358

359
    const auto& surf {*model::surfaces[surface_index()].get()};
2,147,483,647✔
360

361
    // Particle crosses surface
362
    // If BC, add particle to surface source before crossing surface
363
    if (surf.surf_source_ && surf.bc_) {
2,147,483,647✔
364
      add_surf_source_to_bank(*this, surf);
1,007,797,612✔
365
    }
366
    this->cross_surface(surf);
2,147,483,647✔
367
    // If no BC, add particle to surface source after crossing surface
368
    if (surf.surf_source_ && !surf.bc_) {
2,147,483,647✔
369
      add_surf_source_to_bank(*this, surf);
1,850,110,458✔
370
    }
371
    if (settings::weight_window_checkpoint_surface) {
2,147,483,647✔
372
      apply_weight_windows(*this);
173,985✔
373
    }
374
    event() = TallyEvent::SURFACE;
2,147,483,647✔
375

376
    // Score cell to cell partial currents
377
    if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
378
      Direction normal = surf.normal(r());
34,931,567✔
379
      normal /= normal.norm();
34,931,567✔
380
      score_surface_tally(*this, model::active_surface_tallies, normal);
34,931,567✔
381
    }
382
  }
383
}
2,147,483,647✔
384

385
void Particle::event_collide()
2,147,483,647✔
386
{
387

388
  // Score collision estimate of keff
389
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
390
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,147,483,647✔
391
  }
392

393
  // Score surface current tallies -- this has to be done before the collision
394
  // since the direction of the particle will change and we need to use the
395
  // pre-collision direction to figure out what mesh surfaces were crossed
396

397
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
398
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
399

400
  // Clear surface component
401
  surface() = SURFACE_NONE;
2,147,483,647✔
402

403
  if (settings::run_CE) {
2,147,483,647✔
404
    collision(*this);
1,457,100,555✔
405
  } else {
406
    collision_mg(*this);
1,800,818,030✔
407
  }
408

409
  // Collision track feature to recording particle interaction
410
  if (settings::collision_track) {
2,147,483,647✔
411
    collision_track_record(*this);
150,087✔
412
  }
413

414
  // Score collision estimator tallies -- this is done after a collision
415
  // has occurred rather than before because we need information on the
416
  // outgoing energy for any tallies with an outgoing energy filter
417
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
418
    score_collision_tally(*this);
108,955,328✔
419
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
420
    if (settings::run_CE) {
406,059,376✔
421
      score_analog_tally_ce(*this);
404,851,114✔
422
    } else {
423
      score_analog_tally_mg(*this);
1,208,262✔
424
    }
425
  }
426

427
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
428
    pht_collision_energy();
8,096✔
429
  }
430

431
  // Reset banked weight during collision
432
  n_bank() = 0;
2,147,483,647✔
433
  bank_second_E() = 0.0;
2,147,483,647✔
434
  wgt_bank() = 0.0;
2,147,483,647✔
435

436
  // Clear number of secondaries in this collision. This is
437
  // distinct from the number of created neutrons n_bank() above!
438
  n_secondaries() = 0;
2,147,483,647✔
439

440
  zero_delayed_bank();
2,147,483,647✔
441

442
  // Reset fission logical
443
  fission() = false;
2,147,483,647✔
444

445
  // Save coordinates for tallying purposes
446
  r_last_current() = r();
2,147,483,647✔
447

448
  // Set last material to none since cross sections will need to be
449
  // re-evaluated
450
  material_last() = C_NONE;
2,147,483,647✔
451

452
  // Set all directions to base level -- right now, after a collision, only
453
  // the base level directions are changed
454
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
455
    if (coord(j + 1).rotated()) {
286,206,843✔
456
      // If next level is rotated, apply rotation matrix
457
      const auto& m {model::cells[coord(j).cell()]->rotation_};
11,724,229✔
458
      const auto& u {coord(j).u()};
11,724,229✔
459
      coord(j + 1).u() = u.rotate(m);
11,724,229✔
460
    } else {
461
      // Otherwise, copy this level's direction
462
      coord(j + 1).u() = coord(j).u();
274,482,614✔
463
    }
464
  }
465

466
  // Score flux derivative accumulators for differential tallies.
467
  if (!model::active_tallies.empty())
2,147,483,647✔
468
    score_collision_derivative(*this);
1,297,587,473✔
469

470
#ifdef OPENMC_DAGMC_ENABLED
471
  history().reset();
298,227,001✔
472
#endif
473
}
2,147,483,647✔
474

475
void Particle::event_revive_from_secondary(const SourceSite& site)
106,786,148✔
476
{
477
  // Write final position for the previous track (skip if this is a freshly
478
  // constructed particle with no prior track, e.g., Phase 2 of shared
479
  // secondary transport)
480
  if (write_track() && n_event() > 0) {
106,786,148!
481
    write_particle_track(*this);
5,234✔
482
  }
483

484
  from_source(&site);
106,786,148✔
485

486
  n_event() = 0;
106,786,148✔
487
  if (!settings::use_shared_secondary_bank) {
106,786,148✔
488
    n_tracks()++;
85,467,036✔
489
  }
490
  bank_second_E() = 0.0;
106,786,148✔
491

492
  // Subtract secondary particle energy from interim pulse-height results.
493
  // In shared secondary mode, this subtraction was already done on the parent
494
  // particle during create_secondary(), so skip it here.
495
  if (!settings::use_shared_secondary_bank &&
192,253,184✔
496
      !model::active_pulse_height_tallies.empty() && this->type().is_photon()) {
106,786,148✔
497
    // Since the birth cell of the particle has not been set we
498
    // have to determine it before the energy of the secondary particle can be
499
    // removed from the pulse-height of this cell.
500
    if (lowest_coord().cell() == C_NONE) {
2,420!
501
      bool verbose = settings::verbosity >= 10 || trace();
2,420!
502
      if (!exhaustive_find_cell(*this, verbose)) {
2,420!
NEW
503
        mark_as_lost("Could not find the cell containing particle " +
×
NEW
504
                     std::to_string(id()));
×
NEW
505
        return;
×
506
      }
507
      // Set birth cell attribute
508
      if (cell_born() == C_NONE)
2,420!
509
        cell_born() = lowest_coord().cell();
2,420✔
510

511
      // Initialize last cells from current cell
512
      for (int j = 0; j < n_coord(); ++j) {
4,840✔
513
        cell_last(j) = coord(j).cell();
2,420✔
514
      }
515
      n_coord_last() = n_coord();
2,420✔
516
    }
517
    pht_secondary_particles();
2,420✔
518
  }
519

520
  // Enter new particle in particle track file
521
  if (write_track())
106,786,148✔
522
    add_particle_track(*this);
5,234✔
523
}
524

525
void Particle::event_check_limit_and_revive()
2,147,483,647✔
526
{
527
  // If particle has too many events, display warning and kill it
528
  n_event()++;
2,147,483,647✔
529
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
NEW
530
    warning("Particle " + std::to_string(id()) +
×
531
            " underwent maximum number of events.");
NEW
532
    wgt() = 0.0;
×
533
  }
534

535
  // In non-shared-secondary mode, revive from local secondary bank
536
  if (!alive() && !settings::use_shared_secondary_bank &&
2,147,483,647✔
537
      !local_secondary_bank().empty()) {
262,492,312✔
538
    SourceSite& site = local_secondary_bank().back();
85,467,036✔
539
    event_revive_from_secondary(site);
85,467,036✔
540
    local_secondary_bank().pop_back();
85,467,036✔
541
  }
542
}
2,147,483,647✔
543

544
void Particle::event_death()
199,129,884✔
545
{
546
#ifdef OPENMC_DAGMC_ENABLED
547
  history().reset();
18,186,617✔
548
#endif
549

550
  // Finish particle track output.
551
  if (write_track()) {
199,129,884✔
552
    write_particle_track(*this);
1,010✔
553
    finalize_particle_track(*this);
1,010✔
554
  }
555

556
// Contribute tally reduction variables to global accumulator
557
#pragma omp atomic
109,309,995✔
558
  global_tally_absorption += keff_tally_absorption();
199,129,884✔
559
#pragma omp atomic
109,523,084✔
560
  global_tally_collision += keff_tally_collision();
199,129,884✔
561
#pragma omp atomic
109,392,121✔
562
  global_tally_tracklength += keff_tally_tracklength();
199,129,884✔
563
#pragma omp atomic
109,139,041✔
564
  global_tally_leakage += keff_tally_leakage();
199,129,884✔
565

566
  // Reset particle tallies once accumulated
567
  keff_tally_absorption() = 0.0;
199,129,884✔
568
  keff_tally_collision() = 0.0;
199,129,884✔
569
  keff_tally_tracklength() = 0.0;
199,129,884✔
570
  keff_tally_leakage() = 0.0;
199,129,884✔
571

572
  if (!model::active_pulse_height_tallies.empty()) {
199,129,884✔
573
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
22,000✔
574
  }
575

576
  // Accumulate track count for this particle history
577
  if (!settings::use_shared_secondary_bank) {
199,129,884✔
578
#pragma omp atomic
96,640,116✔
579
    simulation::simulation_tracks_completed += n_tracks();
177,026,276✔
580
  }
581

582
  // Record the number of progeny created by this particle.
583
  // This data will be used to efficiently sort the fission bank.
584
  if (settings::run_mode == RunMode::EIGENVALUE ||
199,129,884✔
585
      settings::use_shared_secondary_bank) {
586
    simulation::progeny_per_particle[current_work()] = n_progeny();
171,998,308✔
587
  }
588
}
199,129,884✔
589

590
void Particle::pht_collision_energy()
8,096✔
591
{
592
  // Adds the energy particles lose in a collision to the pulse-height
593

594
  // determine index of cell in pulse_height_cells
595
  auto it = std::find(model::pulse_height_cells.begin(),
8,096✔
596
    model::pulse_height_cells.end(), lowest_coord().cell());
8,096!
597

598
  if (it != model::pulse_height_cells.end()) {
8,096!
599
    int index = std::distance(model::pulse_height_cells.begin(), it);
8,096✔
600
    pht_storage()[index] += E_last() - E();
8,096✔
601

602
    // If the energy of the particle is below the cutoff, it will not be sampled
603
    // so its energy is added to the pulse-height in the cell
604
    int photon = ParticleType::photon().transport_index();
8,096✔
605
    if (E() < settings::energy_cutoff[photon]) {
8,096✔
606
      pht_storage()[index] += E();
3,300✔
607
    }
608
  }
609
}
8,096✔
610

611
void Particle::pht_secondary_particles()
2,420✔
612
{
613
  // Removes the energy of secondary produced particles from the pulse-height
614

615
  // determine index of cell in pulse_height_cells
616
  auto it = std::find(model::pulse_height_cells.begin(),
2,420✔
617
    model::pulse_height_cells.end(), cell_born());
2,420!
618

619
  if (it != model::pulse_height_cells.end()) {
2,420!
620
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,420✔
621
    pht_storage()[index] -= E();
2,420✔
622
  }
623
}
2,420✔
624

625
void Particle::cross_surface(const Surface& surf)
2,147,483,647✔
626
{
627

628
  if (settings::verbosity >= 10 || trace()) {
2,147,483,647✔
629
    write_message(1, "    Crossing surface {}", surf.id_);
88✔
630
  }
631

632
// if we're crossing a CSG surface, make sure the DAG history is reset
633
#ifdef OPENMC_DAGMC_ENABLED
634
  if (surf.geom_type() == GeometryType::CSG)
260,856,996✔
635
    history().reset();
260,799,314✔
636
#endif
637

638
  // Handle any applicable boundary conditions.
639
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
640
      settings::run_mode != RunMode::VOLUME) {
641
    surf.bc_->handle_particle(*this, surf);
1,008,149,720✔
642
    return;
1,008,149,720✔
643
  }
644

645
  // ==========================================================================
646
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
647

648
#ifdef OPENMC_DAGMC_ENABLED
649
  // in DAGMC, we know what the next cell should be
650
  if (surf.geom_type() == GeometryType::DAG) {
168,762,876✔
651
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,742✔
652
                       lowest_coord().universe()) -
46,742✔
653
                     1;
46,742✔
654
    // save material, temperature, and density multiplier
655
    material_last() = material();
46,742✔
656
    sqrtkT_last() = sqrtkT();
46,742✔
657
    density_mult_last() = density_mult();
46,742✔
658
    // set new cell value
659
    lowest_coord().cell() = i_cell;
46,742✔
660
    auto& cell = model::cells[i_cell];
46,742✔
661

662
    cell_instance() = 0;
46,742✔
663
    if (cell->distribcell_index_ >= 0)
46,742✔
664
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,718✔
665

666
    material() = cell->material(cell_instance());
46,742!
667
    sqrtkT() = cell->sqrtkT(cell_instance());
46,742!
668
    density_mult() = cell->density_mult(cell_instance());
46,742✔
669
    return;
46,742✔
670
  }
671
#endif
672

673
  bool verbose = settings::verbosity >= 10 || trace();
1,852,896,164!
674
  if (neighbor_list_find_cell(*this, verbose)) {
1,852,896,164✔
675
    return;
676
  }
677

678
  // ==========================================================================
679
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
680

681
  // Remove lower coordinate levels
682
  n_coord() = 1;
29,977✔
683
  bool found = exhaustive_find_cell(*this, verbose);
29,977✔
684

685
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
29,977!
686
    // If a cell is still not found, there are two possible causes: 1) there is
687
    // a void in the model, and 2) the particle hit a surface at a tangent. If
688
    // the particle is really traveling tangent to a surface, if we move it
689
    // forward a tiny bit it should fix the problem.
690

691
    surface() = SURFACE_NONE;
5,865✔
692
    n_coord() = 1;
5,865✔
693
    r() += TINY_BIT * u();
5,865✔
694

695
    // Couldn't find next cell anywhere! This probably means there is an actual
696
    // undefined region in the geometry.
697

698
    if (!exhaustive_find_cell(*this, verbose)) {
5,865!
699
      mark_as_lost("After particle " + std::to_string(id()) +
17,586✔
700
                   " crossed surface " + std::to_string(surf.id_) +
17,586✔
701
                   " it could not be located in any cell and it did not leak.");
702
      return;
5,856✔
703
    }
704
  }
705
}
706

707
void Particle::cross_vacuum_bc(const Surface& surf)
37,256,578✔
708
{
709
  // Score any surface current tallies -- note that the particle is moved
710
  // forward slightly so that if the mesh boundary is on the surface, it is
711
  // still processed
712

713
  if (!model::active_meshsurf_tallies.empty()) {
37,256,578✔
714
    // TODO: Find a better solution to score surface currents than
715
    // physically moving the particle forward slightly
716

717
    r() += TINY_BIT * u();
937,222✔
718
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
719
  }
720

721
  // Score to global leakage tally
722
  keff_tally_leakage() += wgt();
37,256,578✔
723

724
  // Kill the particle
725
  wgt() = 0.0;
37,256,578✔
726

727
  // Display message
728
  if (settings::verbosity >= 10 || trace()) {
37,256,578!
729
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
730
  }
731
}
37,256,578✔
732

733
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
969,651,921✔
734
{
735
  // Do not handle reflective boundary conditions on lower universes
736
  if (n_coord() != 1) {
969,651,921!
UNCOV
737
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
738
                 " off surface in a lower universe.");
UNCOV
739
    return;
×
740
  }
741

742
  // Score surface currents since reflection causes the direction of the
743
  // particle to change. For surface filters, we need to score the tallies
744
  // twice, once before the particle's surface attribute has changed and
745
  // once after. For mesh surface filters, we need to artificially move
746
  // the particle slightly back in case the surface crossing is coincident
747
  // with a mesh boundary
748

749
  if (!model::active_surface_tallies.empty()) {
969,651,921✔
750
    Direction normal = surf.normal(r());
285,021✔
751
    normal /= normal.norm();
285,021✔
752
    score_surface_tally(*this, model::active_surface_tallies, normal);
285,021✔
753
  }
754

755
  if (!model::active_meshsurf_tallies.empty()) {
969,651,921✔
756
    Position r {this->r()};
46,885,487✔
757
    this->r() -= TINY_BIT * u();
46,885,487✔
758
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
759
    this->r() = r;
46,885,487✔
760
  }
761

762
  // Set the new particle direction
763
  u() = new_u;
969,651,921✔
764

765
  // Reassign particle's cell and surface
766
  coord(0).cell() = cell_last(0);
969,651,921✔
767
  surface() = -surface();
969,651,921✔
768

769
  // If a reflective surface is coincident with a lattice or universe
770
  // boundary, it is necessary to redetermine the particle's coordinates in
771
  // the lower universes.
772
  // (unless we're using a dagmc model, which has exactly one universe)
773
  n_coord() = 1;
969,651,921✔
774
  if (surf.geom_type() != GeometryType::DAG &&
1,939,301,084!
775
      !neighbor_list_find_cell(*this)) {
969,649,163✔
UNCOV
776
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
777
                 std::to_string(surf.id_) + ".");
×
UNCOV
778
    return;
×
779
  }
780

781
  // Set previous coordinate going slightly past surface crossing
782
  r_last_current() = r() + TINY_BIT * u();
969,651,921✔
783

784
  // Diagnostic message
785
  if (settings::verbosity >= 10 || trace()) {
969,651,921!
UNCOV
786
    write_message(1, "    Reflected from surface {}", surf.id_);
×
787
  }
788
}
789

790
void Particle::cross_periodic_bc(
2,246,687✔
791
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
792
{
793
  // Do not handle periodic boundary conditions on lower universes
794
  if (n_coord() != 1) {
2,246,687!
UNCOV
795
    mark_as_lost(
×
UNCOV
796
      "Cannot transfer particle " + std::to_string(id()) +
×
797
      " across surface in a lower universe. Boundary conditions must be "
798
      "applied to root universe.");
799
    return;
×
800
  }
801

802
  // Score surface currents since reflection causes the direction of the
803
  // particle to change -- artificially move the particle slightly back in
804
  // case the surface crossing is coincident with a mesh boundary
805
  if (!model::active_meshsurf_tallies.empty()) {
2,246,687!
UNCOV
806
    Position r {this->r()};
×
UNCOV
807
    this->r() -= TINY_BIT * u();
×
UNCOV
808
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
809
    this->r() = r;
×
810
  }
811

812
  // Adjust the particle's location and direction.
813
  r() = new_r;
2,246,687✔
814
  u() = new_u;
2,246,687✔
815

816
  // Reassign particle's surface
817
  surface() = new_surface;
2,246,687✔
818

819
  // Figure out what cell particle is in now
820
  n_coord() = 1;
2,246,687✔
821

822
  if (!neighbor_list_find_cell(*this)) {
2,246,687!
UNCOV
823
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
824
                 "boundary on surface " +
×
UNCOV
825
                 std::to_string(surf.id_) + ".");
×
UNCOV
826
    return;
×
827
  }
828

829
  // Set previous coordinate going slightly past surface crossing
830
  r_last_current() = r() + TINY_BIT * u();
2,246,687✔
831

832
  // Diagnostic message
833
  if (settings::verbosity >= 10 || trace()) {
2,246,687!
UNCOV
834
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
835
  }
836
}
837

838
void Particle::mark_as_lost(const char* message)
5,865✔
839
{
840
  // Print warning and write lost particle file
841
  warning(message);
5,865✔
842
  if (settings::max_write_lost_particles < 0 ||
5,865✔
843
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
844
    write_restart();
440✔
845
  }
846
  // Increment number of lost particles
847
  wgt() = 0.0;
5,865✔
848
#pragma omp atomic
3,190✔
849
  simulation::n_lost_particles += 1;
2,675✔
850

851
  // Count the total number of simulated particles (on this processor)
852
  auto n = simulation::current_batch * settings::gen_per_batch *
5,865✔
853
           simulation::work_per_rank;
854

855
  // Abort the simulation if the maximum number of lost particles has been
856
  // reached
857
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,865✔
858
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
859
    fatal_error("Maximum number of lost particles has been reached.");
9✔
860
  }
861
}
5,856✔
862

863
void Particle::write_restart() const
440✔
864
{
865
  // Dont write another restart file if in particle restart mode
866
  if (settings::run_mode == RunMode::PARTICLE)
440✔
867
    return;
33✔
868

869
  // Set up file name
870
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
407✔
871
    simulation::current_batch, id());
407✔
872

873
#pragma omp critical(WriteParticleRestart)
217✔
874
  {
407✔
875
    // Create file
876
    hid_t file_id = file_open(filename, 'w');
407✔
877

878
    // Write filetype and version info
879
    write_attribute(file_id, "filetype", "particle restart");
407✔
880
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
407✔
881
    write_attribute(file_id, "openmc_version", VERSION);
407✔
882
#ifdef GIT_SHA1
883
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
884
#endif
885

886
    // Write data to file
887
    write_dataset(file_id, "current_batch", simulation::current_batch);
407✔
888
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
407✔
889
    write_dataset(file_id, "current_generation", simulation::current_gen);
407✔
890
    write_dataset(file_id, "n_particles", settings::n_particles);
407✔
891
    switch (settings::run_mode) {
407!
892
    case RunMode::FIXED_SOURCE:
275✔
893
      write_dataset(file_id, "run_mode", "fixed source");
275✔
894
      break;
145✔
895
    case RunMode::EIGENVALUE:
132✔
896
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
897
      break;
72✔
UNCOV
898
    case RunMode::PARTICLE:
×
UNCOV
899
      write_dataset(file_id, "run_mode", "particle restart");
×
900
      break;
901
    default:
902
      break;
903
    }
904
    write_dataset(file_id, "id", id());
407✔
905
    write_dataset(file_id, "type", type().pdg_number());
407✔
906

907
    // Get source site data for the particle that got lost
908
    int64_t i = current_work();
407✔
909
    SourceSite site;
407✔
910
    if (settings::run_mode == RunMode::EIGENVALUE) {
407✔
911
      site = simulation::source_bank[i];
132✔
912
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
275✔
913
               settings::use_shared_secondary_bank &&
275!
914
               i < simulation::shared_secondary_bank_read.size()) {
55!
UNCOV
915
      site = simulation::shared_secondary_bank_read[i];
×
916
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
275!
917
      // Re-sample using the same seed used to generate the source particle.
918
      // current_work() is 0-indexed, compute_particle_id expects 1-indexed.
919
      int64_t id = compute_transport_seed(compute_particle_id(i + 1));
275✔
920
      uint64_t seed = init_seed(id, STREAM_SOURCE);
275✔
921
      site = sample_external_source(&seed);
275✔
922
    }
923
    write_dataset(file_id, "weight", site.wgt);
407✔
924
    write_dataset(file_id, "energy", site.E);
407✔
925
    write_dataset(file_id, "xyz", site.r);
407✔
926
    write_dataset(file_id, "uvw", site.u);
407✔
927
    write_dataset(file_id, "time", site.time);
407✔
928

929
    // Close file
930
    file_close(file_id);
407✔
931
  } // #pragma omp critical
932
}
407✔
933

934
void Particle::update_neutron_xs(
2,147,483,647✔
935
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
936
{
937
  // Get microscopic cross section cache
938
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
939

940
  // If the cache doesn't match, recalculate micro xs
941
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
942
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
943
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
944
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
945

946
    // If NCrystal is being used, update micro cross section cache
947
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
948
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
949
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
950
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
951
    }
952
  }
953
}
2,147,483,647✔
954

955
//==============================================================================
956
// Non-method functions
957
//==============================================================================
958
void add_surf_source_to_bank(Particle& p, const Surface& surf)
2,147,483,647✔
959
{
960
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
961
      simulation::surf_source_bank.full()) {
2,147,483,647✔
962
    return;
2,147,483,647✔
963
  }
964

965
  // If a cell/cellfrom/cellto parameter is defined
966
  if (settings::ssw_cell_id != C_NONE) {
337,079✔
967

968
    // Retrieve cell index and storage type
969
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,434✔
970

971
    if (surf.bc_) {
254,434✔
972
      // Leave if cellto with vacuum boundary condition
973
      if (surf.bc_->type() == "vacuum" &&
298,918✔
974
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
975
        return;
976
      }
977

978
      // Leave if other boundary condition than vacuum
979
      if (surf.bc_->type() != "vacuum") {
274,648✔
980
        return;
981
      }
982
    }
983

984
    // Check if the cell of interest has been exited
985
    bool exited = false;
986
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,667✔
987
      if (p.cell_last(i) == cell_idx) {
207,728✔
988
        exited = true;
73,763✔
989
      }
990
    }
991

992
    // Check if the cell of interest has been entered
993
    bool entered = false;
994
    for (int i = 0; i < p.n_coord(); ++i) {
297,969✔
995
      if (p.coord(i).cell() == cell_idx) {
172,030✔
996
        entered = true;
57,516✔
997
      }
998
    }
999

1000
    // Vacuum boundary conditions: return if cell is not exited
1001
    if (surf.bc_) {
125,939✔
1002
      if (surf.bc_->type() == "vacuum" && !exited) {
41,928!
1003
        return;
1004
      }
1005
    } else {
1006

1007
      // If we both enter and exit the cell of interest
1008
      if (entered && exited) {
104,975✔
1009
        return;
1010
      }
1011

1012
      // If we did not enter nor exit the cell of interest
1013
      if (!entered && !exited) {
77,772✔
1014
        return;
1015
      }
1016

1017
      // If cellfrom and the cell before crossing is not the cell of
1018
      // interest
1019
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,273✔
1020
        return;
1021
      }
1022

1023
      // If cellto and the cell after crossing is not the cell of interest
1024
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,731✔
1025
        return;
1026
      }
1027
    }
1028
  }
1029

1030
  SourceSite site;
129,653✔
1031
  site.r = p.r();
129,653✔
1032
  site.u = p.u();
129,653✔
1033
  site.E = p.E();
129,653✔
1034
  site.time = p.time();
129,653✔
1035
  site.wgt = p.wgt();
129,653✔
1036
  site.delayed_group = p.delayed_group();
129,653✔
1037
  site.surf_id = surf.id_;
129,653✔
1038
  site.particle = p.type();
129,653✔
1039
  site.parent_id = p.id();
129,653✔
1040
  site.progeny_id = p.n_progeny();
129,653✔
1041
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1042
}
1043

1044
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc