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

openmc-dev / openmc / 23010841626

12 Mar 2026 03:50PM UTC coverage: 81.015% (-0.6%) from 81.566%
23010841626

Pull #3863

github

web-flow
Merge 954a87042 into ba94c5823
Pull Request #3863: Shared Secondary Particle Bank

16912 of 24191 branches covered (69.91%)

Branch coverage included in aggregate %.

323 of 429 new or added lines in 17 files covered. (75.29%)

577 existing lines in 39 files now uncovered.

56865 of 66875 relevant lines covered (85.03%)

32719674.03 hits per line

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

85.78
/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/material.h"
18
#include "openmc/message_passing.h"
19
#include "openmc/mgxs_interface.h"
20
#include "openmc/nuclide.h"
21
#include "openmc/particle_data.h"
22
#include "openmc/photon.h"
23
#include "openmc/physics.h"
24
#include "openmc/physics_mg.h"
25
#include "openmc/random_lcg.h"
26
#include "openmc/settings.h"
27
#include "openmc/simulation.h"
28
#include "openmc/source.h"
29
#include "openmc/surface.h"
30
#include "openmc/tallies/derivative.h"
31
#include "openmc/tallies/tally.h"
32
#include "openmc/tallies/tally_scoring.h"
33
#include "openmc/track_output.h"
34
#include "openmc/weight_windows.h"
35

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

40
namespace openmc {
41

42
//==============================================================================
43
// Particle implementation
44
//==============================================================================
45

46
double Particle::speed() const
2,147,483,647✔
47
{
48
  if (settings::run_CE) {
2,147,483,647✔
49
    // Determine mass in eV/c^2
50
    double mass;
1,358,789,566✔
51
    switch (type().pdg_number()) {
1,358,789,566✔
52
    case PDG_NEUTRON:
53
      mass = MASS_NEUTRON_EV;
54
    case PDG_ELECTRON:
55
    case PDG_POSITRON:
56
      mass = MASS_ELECTRON_EV;
1,358,789,566✔
57
    default:
1,358,789,566✔
58
      mass = this->type().mass() * AMU_EV;
1,358,789,566✔
59
    }
60

61
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
62
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,358,789,566✔
63
           (this->E() + mass);
1,358,789,566✔
64
  } else {
65
    auto& macro_xs = data::mg.macro_xs_[this->material()];
1,135,289,166✔
66
    int macro_t = this->mg_xs_cache().t;
1,135,289,166✔
67
    int macro_a = macro_xs.get_angle_index(this->u());
1,135,289,166✔
68
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
1,135,289,166✔
69
                   nullptr, nullptr, macro_t, macro_a);
1,135,289,166✔
70
  }
71
}
72

73
bool Particle::create_secondary(
104,560,093✔
74
  double wgt, Direction u, double E, ParticleType type)
75
{
76
  // If energy is below cutoff for this particle, don't create secondary
77
  // particle
78
  int idx = type.transport_index();
104,560,093✔
79
  if (idx == C_NONE) {
104,560,093!
80
    return false;
81
  }
82
  if (E < settings::energy_cutoff[idx]) {
104,560,093✔
83
    return false;
84
  }
85

86
  // Increment number of secondaries created (for ParticleProductionFilter)
87
  n_secondaries()++;
54,350,963✔
88

89
  SourceSite bank;
54,350,963✔
90
  bank.particle = type;
54,350,963✔
91
  bank.wgt = wgt;
54,350,963✔
92
  bank.r = r();
54,350,963!
93
  bank.u = u;
54,350,963✔
94
  bank.E = settings::run_CE ? E : g();
54,350,963!
95
  bank.time = time();
54,350,963✔
96
  bank_second_E() += bank.E;
54,350,963✔
97
  bank.parent_id = current_work();
54,350,963✔
98
  if (settings::use_shared_secondary_bank) {
54,350,963✔
99
    bank.progeny_id = n_progeny()++;
11,026,404✔
100
  }
101
  bank.wgt_born = wgt_born();
54,350,963✔
102
  bank.wgt_ww_born = wgt_ww_born();
54,350,963✔
103
  bank.n_split = n_split();
54,350,963✔
104

105
  // In shared secondary mode, subtract secondary photon energy from parent's
106
  // pulse-height storage now, since the secondary will be transported as a
107
  // separate Particle object and won't have access to the parent's pht_storage.
108
  if (settings::use_shared_secondary_bank &&
65,377,367✔
109
      !model::active_pulse_height_tallies.empty() && type.is_photon()) {
54,350,963!
NEW
110
    auto it = std::find(model::pulse_height_cells.begin(),
×
NEW
111
      model::pulse_height_cells.end(), lowest_coord().cell());
×
NEW
112
    if (it != model::pulse_height_cells.end()) {
×
NEW
113
      int index = std::distance(model::pulse_height_cells.begin(), it);
×
NEW
114
      pht_storage()[index] -= bank.E;
×
115
    }
116
  }
117

118
  local_secondary_bank().emplace_back(bank);
54,350,963✔
119
  return true;
120
}
121

122
void Particle::split(double wgt)
6,030,137✔
123
{
124
  SourceSite bank;
6,030,137✔
125
  bank.particle = type();
6,030,137✔
126
  bank.wgt = wgt;
6,030,137✔
127
  bank.r = r();
6,030,137✔
128
  bank.u = u();
6,030,137✔
129
  bank.E = settings::run_CE ? E() : g();
6,030,137✔
130
  bank.time = time();
6,030,137✔
131

132
  // Convert signed index to a signed surface ID
133
  if (surface() == SURFACE_NONE) {
6,030,137✔
134
    bank.surf_id = SURFACE_NONE;
6,028,217✔
135
  } else {
136
    int surf_id = model::surfaces[surface_index()]->id_;
1,920✔
137
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
1,920✔
138
  }
139

140
  bank.wgt_born = wgt_born();
6,030,137✔
141
  bank.wgt_ww_born = wgt_ww_born();
6,030,137✔
142
  bank.n_split = n_split();
6,030,137✔
143
  bank.parent_id = current_work();
6,030,137✔
144
  if (settings::use_shared_secondary_bank) {
6,030,137✔
145
    bank.progeny_id = n_progeny()++;
3,128,920✔
146
  }
147

148
  local_secondary_bank().emplace_back(bank);
6,030,137✔
149
}
6,030,137✔
150

151
void Particle::from_source(const SourceSite* src)
157,697,920✔
152
{
153
  // Reset some attributes
154
  clear();
157,697,920✔
155
  surface() = SURFACE_NONE;
157,697,920✔
156
  cell_born() = C_NONE;
157,697,920✔
157
  material() = C_NONE;
157,697,920✔
158
  n_collision() = 0;
157,697,920✔
159
  fission() = false;
157,697,920✔
160
  zero_flux_derivs();
157,697,920✔
161
  lifetime() = 0.0;
157,697,920✔
162
#ifdef OPENMC_DAGMC_ENABLED
163
  history().reset();
164
#endif
165

166
  // Copy attributes from source bank site
167
  type() = src->particle;
157,697,920✔
168
  wgt() = src->wgt;
157,697,920✔
169
  wgt_last() = src->wgt;
157,697,920✔
170
  r() = src->r;
157,697,920✔
171
  u() = src->u;
157,697,920✔
172
  r_born() = src->r;
157,697,920✔
173
  r_last_current() = src->r;
157,697,920✔
174
  r_last() = src->r;
157,697,920✔
175
  u_last() = src->u;
157,697,920✔
176
  if (settings::run_CE) {
157,697,920✔
177
    E() = src->E;
94,049,476✔
178
    g() = 0;
94,049,476✔
179
  } else {
180
    g() = static_cast<int>(src->E);
63,648,444✔
181
    g_last() = static_cast<int>(src->E);
63,648,444✔
182
    E() = data::mg.energy_bin_avg_[g()];
63,648,444✔
183
  }
184
  E_last() = E();
157,697,920✔
185
  time() = src->time;
157,697,920✔
186
  time_last() = src->time;
157,697,920✔
187
  parent_nuclide() = src->parent_nuclide;
157,697,920✔
188
  delayed_group() = src->delayed_group;
157,697,920✔
189

190
  // Convert signed surface ID to signed index
191
  if (src->surf_id != SURFACE_NONE) {
157,697,920✔
192
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
61,920✔
193
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
61,920✔
194
  }
195

196
  wgt_born() = src->wgt_born;
157,697,920✔
197
  wgt_ww_born() = src->wgt_ww_born;
157,697,920✔
198
  n_split() = src->n_split;
157,697,920✔
199
}
157,697,920✔
200

201
void Particle::event_calculate_xs()
2,147,483,647✔
202
{
203
  // Set the random number stream
204
  stream() = STREAM_TRACKING;
2,147,483,647✔
205

206
  // Store pre-collision particle properties
207
  wgt_last() = wgt();
2,147,483,647✔
208
  E_last() = E();
2,147,483,647✔
209
  u_last() = u();
2,147,483,647✔
210
  r_last() = r();
2,147,483,647✔
211
  time_last() = time();
2,147,483,647✔
212

213
  // Reset event variables
214
  event() = TallyEvent::KILL;
2,147,483,647✔
215
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
216
  event_mt() = REACTION_NONE;
2,147,483,647✔
217

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

228
    // Set birth cell attribute
229
    if (cell_born() == C_NONE)
152,967,742!
230
      cell_born() = lowest_coord().cell();
152,967,742✔
231

232
    // Initialize last cells from current cell
233
    for (int j = 0; j < n_coord(); ++j) {
315,430,004✔
234
      cell_last(j) = coord(j).cell();
162,462,262✔
235
    }
236
    n_coord_last() = n_coord();
152,967,742✔
237
  }
238

239
  // Write particle track.
240
  if (write_track())
2,147,483,647✔
241
    write_particle_track(*this);
5,013✔
242

243
  if (settings::check_overlaps)
2,147,483,647!
244
    check_cell_overlap(*this);
×
245

246
  // Calculate microscopic and macroscopic cross sections
247
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
248
    if (settings::run_CE) {
2,147,483,647✔
249
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
1,282,811,439✔
250
          density_mult() != density_mult_last()) {
203,242,619✔
251
        // If the material is the same as the last material and the
252
        // temperature hasn't changed, we don't need to lookup cross
253
        // sections again.
254
        model::materials[material()]->calculate_xs(*this);
1,079,574,052✔
255
      }
256
    } else {
257
      // Get the MG data; unlike the CE case above, we have to re-calculate
258
      // cross sections for every collision since the cross sections may
259
      // be angle-dependent
260
      data::mg.macro_xs_[material()].calculate_xs(*this);
1,135,289,166✔
261

262
      // Update the particle's group while we know we are multi-group
263
      g_last() = g();
1,135,289,166✔
264
    }
265
  } else {
266
    macro_xs().total = 0.0;
61,007,221✔
267
    macro_xs().absorption = 0.0;
61,007,221✔
268
    macro_xs().fission = 0.0;
61,007,221✔
269
    macro_xs().nu_fission = 0.0;
61,007,221✔
270
  }
271
}
272

273
void Particle::event_advance()
2,147,483,647✔
274
{
275
  // Find the distance to the nearest boundary
276
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
277

278
  // Sample a distance to collision
279
  if (type() == ParticleType::electron() ||
2,147,483,647✔
280
      type() == ParticleType::positron()) {
2,147,483,647✔
281
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
100,870,960!
282
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
283
    collision_distance() = INFINITY;
61,007,221✔
284
  } else {
285
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
286
  }
287

288
  double speed = this->speed();
2,147,483,647✔
289
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
290
  double distance_cutoff =
2,147,483,647✔
291
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
292

293
  // Select smaller of the three distances
294
  double distance =
2,147,483,647✔
295
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
296

297
  // Advance particle in space and time
298
  this->move_distance(distance);
2,147,483,647✔
299
  double dt = distance / speed;
2,147,483,647✔
300
  this->time() += dt;
2,147,483,647✔
301
  this->lifetime() += dt;
2,147,483,647✔
302

303
  // Score timed track-length tallies
304
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
305
    score_timed_tracklength_tally(*this, distance);
1,979,082✔
306
  }
307

308
  // Score track-length tallies
309
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
310
    score_tracklength_tally(*this, distance);
1,052,360,604✔
311
  }
312

313
  // Score track-length estimate of k-eff
314
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
315
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
1,899,570,289✔
316
  }
317

318
  // Score flux derivative accumulators for differential tallies.
319
  if (!model::active_tallies.empty()) {
2,147,483,647✔
320
    score_track_derivative(*this, distance);
1,142,638,392✔
321
  }
322

323
  // Set particle weight to zero if it hit the time boundary
324
  if (distance == distance_cutoff) {
2,147,483,647✔
325
    wgt() = 0.0;
122,688✔
326
  }
327
}
2,147,483,647✔
328

329
void Particle::event_cross_surface()
1,314,401,882✔
330
{
331
  // Saving previous cell data
332
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
333
    cell_last(j) = coord(j).cell();
2,147,483,647✔
334
  }
335
  n_coord_last() = n_coord();
1,314,401,882✔
336

337
  // Set surface that particle is on and adjust coordinate levels
338
  surface() = boundary().surface();
1,314,401,882✔
339
  n_coord() = boundary().coord_level();
1,314,401,882✔
340

341
  const auto& surf {*model::surfaces[surface_index()].get()};
1,314,401,882✔
342

343
  if (boundary().lattice_translation()[0] != 0 ||
1,314,401,882✔
344
      boundary().lattice_translation()[1] != 0 ||
1,314,401,882✔
345
      boundary().lattice_translation()[2] != 0) {
1,014,669,096✔
346
    // Particle crosses lattice boundary
347

348
    bool verbose = settings::verbosity >= 10 || trace();
402,517,112!
349
    cross_lattice(*this, boundary(), verbose);
402,517,112✔
350
    event() = TallyEvent::LATTICE;
402,517,112✔
351
  } else {
352
    // Particle crosses surface
353
    // If BC, add particle to surface source before crossing surface
354
    if (surf.surf_source_ && surf.bc_) {
911,884,770✔
355
      add_surf_source_to_bank(*this, surf);
392,666,208✔
356
    }
357
    this->cross_surface(surf);
911,884,770✔
358
    // If no BC, add particle to surface source after crossing surface
359
    if (surf.surf_source_ && !surf.bc_) {
911,884,764✔
360
      add_surf_source_to_bank(*this, surf);
518,517,696✔
361
    }
362
    if (settings::weight_window_checkpoint_surface) {
911,884,764✔
363
      apply_weight_windows(*this);
88,758✔
364
    }
365
    event() = TallyEvent::SURFACE;
911,884,764✔
366
  }
367
  // Score cell to cell partial currents
368
  if (!model::active_surface_tallies.empty()) {
1,314,401,876✔
369
    score_surface_tally(*this, model::active_surface_tallies, surf);
19,053,582✔
370
  }
371
}
1,314,401,876✔
372

373
void Particle::event_collide()
1,674,386,060✔
374
{
375

376
  // Score collision estimate of keff
377
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
1,674,386,060✔
378
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
1,167,096,926✔
379
  }
380

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

385
  if (!model::active_meshsurf_tallies.empty())
1,674,386,060✔
386
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
34,417,596✔
387

388
  // Clear surface component
389
  surface() = SURFACE_NONE;
1,674,386,060✔
390

391
  if (settings::run_CE) {
1,674,386,060✔
392
    collision(*this);
692,121,680✔
393
  } else {
394
    collision_mg(*this);
982,264,380✔
395
  }
396

397
  // Collision track feature to recording particle interaction
398
  if (settings::collision_track) {
1,674,386,060✔
399
    collision_track_record(*this);
82,794✔
400
  }
401

402
  // Score collision estimator tallies -- this is done after a collision
403
  // has occurred rather than before because we need information on the
404
  // outgoing energy for any tallies with an outgoing energy filter
405
  if (!model::active_collision_tallies.empty())
1,674,386,060✔
406
    score_collision_tally(*this);
63,838,437✔
407
  if (!model::active_analog_tallies.empty()) {
1,674,386,060✔
408
    if (settings::run_CE) {
221,358,444✔
409
      score_analog_tally_ce(*this);
220,699,392✔
410
    } else {
411
      score_analog_tally_mg(*this);
659,052✔
412
    }
413
  }
414

415
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
1,674,386,060✔
416
    pht_collision_energy();
4,416✔
417
  }
418

419
  // Reset banked weight during collision
420
  n_bank() = 0;
1,674,386,060✔
421
  bank_second_E() = 0.0;
1,674,386,060✔
422
  wgt_bank() = 0.0;
1,674,386,060✔
423

424
  // Clear number of secondaries in this collision. This is
425
  // distinct from the number of created neutrons n_bank() above!
426
  n_secondaries() = 0;
1,674,386,060✔
427

428
  zero_delayed_bank();
1,674,386,060✔
429

430
  // Reset fission logical
431
  fission() = false;
1,674,386,060✔
432

433
  // Save coordinates for tallying purposes
434
  r_last_current() = r();
1,674,386,060✔
435

436
  // Set last material to none since cross sections will need to be
437
  // re-evaluated
438
  material_last() = C_NONE;
1,674,386,060✔
439

440
  // Set all directions to base level -- right now, after a collision, only
441
  // the base level directions are changed
442
  for (int j = 0; j < n_coord() - 1; ++j) {
1,762,333,039✔
443
    if (coord(j + 1).rotated()) {
87,946,979✔
444
      // If next level is rotated, apply rotation matrix
445
      const auto& m {model::cells[coord(j).cell()]->rotation_};
5,687,244✔
446
      const auto& u {coord(j).u()};
5,687,244✔
447
      coord(j + 1).u() = u.rotate(m);
5,687,244✔
448
    } else {
449
      // Otherwise, copy this level's direction
450
      coord(j + 1).u() = coord(j).u();
82,259,735✔
451
    }
452
  }
453

454
  // Score flux derivative accumulators for differential tallies.
455
  if (!model::active_tallies.empty())
1,674,386,060✔
456
    score_collision_derivative(*this);
628,067,282✔
457

458
#ifdef OPENMC_DAGMC_ENABLED
459
  history().reset();
460
#endif
461
}
1,674,386,060✔
462

463
void Particle::event_revive_from_secondary(SourceSite& site)
60,823,480✔
464
{
465
  // Write final position for the previous track (skip if this is a freshly
466
  // constructed particle with no prior track, e.g., Phase 2 of shared
467
  // secondary transport)
468
  if (write_track() && n_event() > 0) {
60,823,480!
469
    write_particle_track(*this);
2,404✔
470
  }
471

472
  from_source(&site);
60,823,480✔
473

474
  n_event() = 0;
60,823,480✔
475
  if (!settings::use_shared_secondary_bank) {
60,823,480✔
476
    n_tracks()++;
46,228,704✔
477
  }
478
  bank_second_E() = 0.0;
60,823,480✔
479

480
  // Subtract secondary particle energy from interim pulse-height results.
481
  // In shared secondary mode, this subtraction was already done on the parent
482
  // particle during create_secondary(), so skip it here.
483
  if (!settings::use_shared_secondary_bank &&
107,052,184✔
484
      !model::active_pulse_height_tallies.empty() && this->type().is_photon()) {
60,823,480✔
485
    // Since the birth cell of the particle has not been set we
486
    // have to determine it before the energy of the secondary particle can be
487
    // removed from the pulse-height of this cell.
488
    if (lowest_coord().cell() == C_NONE) {
1,320!
489
      bool verbose = settings::verbosity >= 10 || trace();
1,320!
490
      if (!exhaustive_find_cell(*this, verbose)) {
1,320!
NEW
491
        mark_as_lost("Could not find the cell containing particle " +
×
NEW
492
                     std::to_string(id()));
×
NEW
493
        return;
×
494
      }
495
      // Set birth cell attribute
496
      if (cell_born() == C_NONE)
1,320!
497
        cell_born() = lowest_coord().cell();
1,320✔
498

499
      // Initialize last cells from current cell
500
      for (int j = 0; j < n_coord(); ++j) {
2,640✔
501
        cell_last(j) = coord(j).cell();
1,320✔
502
      }
503
      n_coord_last() = n_coord();
1,320✔
504
    }
505
    pht_secondary_particles();
1,320✔
506
  }
507

508
  // Enter new particle in particle track file
509
  if (write_track())
60,823,480✔
510
    add_particle_track(*this);
2,404✔
511
}
512

513
void Particle::event_check_limit_and_revive()
2,147,483,647✔
514
{
515
  // If particle has too many events, display warning and kill it
516
  n_event()++;
2,147,483,647✔
517
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
NEW
518
    warning("Particle " + std::to_string(id()) +
×
519
            " underwent maximum number of events.");
NEW
520
    wgt() = 0.0;
×
521
  }
522

523
  // In non-shared-secondary mode, revive from local secondary bank
524
  if (!alive() && !settings::use_shared_secondary_bank &&
2,147,483,647✔
525
      !local_secondary_bank().empty()) {
137,947,074✔
526
    SourceSite& site = local_secondary_bank().back();
46,228,704✔
527
    event_revive_from_secondary(site);
46,228,704✔
528
    local_secondary_bank().pop_back();
46,228,704✔
529
  }
530
}
2,147,483,647✔
531

532
void Particle::event_death()
106,740,352✔
533
{
534
#ifdef OPENMC_DAGMC_ENABLED
535
  history().reset();
536
#endif
537

538
  // Finish particle track output.
539
  if (write_track()) {
106,740,352✔
540
    write_particle_track(*this);
480✔
541
    finalize_particle_track(*this);
480✔
542
  }
543

544
// Contribute tally reduction variables to global accumulator
545
#pragma omp atomic
17,804,022✔
546
  global_tally_absorption += keff_tally_absorption();
106,740,352✔
547
#pragma omp atomic
17,804,461✔
548
  global_tally_collision += keff_tally_collision();
106,740,352✔
549
#pragma omp atomic
17,799,783✔
550
  global_tally_tracklength += keff_tally_tracklength();
106,740,352✔
551
#pragma omp atomic
17,798,144✔
552
  global_tally_leakage += keff_tally_leakage();
106,740,352✔
553

554
  // Reset particle tallies once accumulated
555
  keff_tally_absorption() = 0.0;
106,740,352✔
556
  keff_tally_collision() = 0.0;
106,740,352✔
557
  keff_tally_tracklength() = 0.0;
106,740,352✔
558
  keff_tally_leakage() = 0.0;
106,740,352✔
559

560
  if (!model::active_pulse_height_tallies.empty()) {
106,740,352✔
561
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
12,000✔
562
  }
563

564
  // Accumulate track count for this particle history
565
  if (!settings::use_shared_secondary_bank) {
106,740,352✔
566
#pragma omp atomic
15,287,135✔
567
    simulation::simulation_tracks_completed += n_tracks();
91,718,370✔
568
  }
569

570
  // Record the number of progeny created by this particle.
571
  // This data will be used to efficiently sort the fission bank.
572
  if (settings::run_mode == RunMode::EIGENVALUE ||
106,740,352✔
573
      settings::use_shared_secondary_bank) {
574
    simulation::progeny_per_particle[current_work()] = n_progeny();
92,227,182✔
575
  }
576
}
106,740,352✔
577

578
void Particle::pht_collision_energy()
4,416✔
579
{
580
  // Adds the energy particles lose in a collision to the pulse-height
581

582
  // determine index of cell in pulse_height_cells
583
  auto it = std::find(model::pulse_height_cells.begin(),
4,416✔
584
    model::pulse_height_cells.end(), lowest_coord().cell());
4,416!
585

586
  if (it != model::pulse_height_cells.end()) {
4,416!
587
    int index = std::distance(model::pulse_height_cells.begin(), it);
4,416✔
588
    pht_storage()[index] += E_last() - E();
4,416✔
589

590
    // If the energy of the particle is below the cutoff, it will not be sampled
591
    // so its energy is added to the pulse-height in the cell
592
    int photon = ParticleType::photon().transport_index();
4,416✔
593
    if (E() < settings::energy_cutoff[photon]) {
4,416✔
594
      pht_storage()[index] += E();
1,800✔
595
    }
596
  }
597
}
4,416✔
598

599
void Particle::pht_secondary_particles()
1,320✔
600
{
601
  // Removes the energy of secondary produced particles from the pulse-height
602

603
  // determine index of cell in pulse_height_cells
604
  auto it = std::find(model::pulse_height_cells.begin(),
1,320✔
605
    model::pulse_height_cells.end(), cell_born());
1,320!
606

607
  if (it != model::pulse_height_cells.end()) {
1,320!
608
    int index = std::distance(model::pulse_height_cells.begin(), it);
1,320✔
609
    pht_storage()[index] -= E();
1,320✔
610
  }
611
}
1,320✔
612

613
void Particle::cross_surface(const Surface& surf)
912,981,966✔
614
{
615

616
  if (settings::verbosity >= 10 || trace()) {
912,981,966✔
617
    write_message(1, "    Crossing surface {}", surf.id_);
48✔
618
  }
619

620
// if we're crossing a CSG surface, make sure the DAG history is reset
621
#ifdef OPENMC_DAGMC_ENABLED
622
  if (surf.geom_type() == GeometryType::CSG)
623
    history().reset();
624
#endif
625

626
  // Handle any applicable boundary conditions.
627
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
912,981,966!
628
      settings::run_mode != RunMode::VOLUME) {
629
    surf.bc_->handle_particle(*this, surf);
392,863,008✔
630
    return;
392,863,008✔
631
  }
632

633
  // ==========================================================================
634
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
635

636
#ifdef OPENMC_DAGMC_ENABLED
637
  // in DAGMC, we know what the next cell should be
638
  if (surf.geom_type() == GeometryType::DAG) {
639
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
640
                       lowest_coord().universe()) -
641
                     1;
642
    // save material, temperature, and density multiplier
643
    material_last() = material();
644
    sqrtkT_last() = sqrtkT();
645
    density_mult_last() = density_mult();
646
    // set new cell value
647
    lowest_coord().cell() = i_cell;
648
    auto& cell = model::cells[i_cell];
649

650
    cell_instance() = 0;
651
    if (cell->distribcell_index_ >= 0)
652
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
653

654
    material() = cell->material(cell_instance());
655
    sqrtkT() = cell->sqrtkT(cell_instance());
656
    density_mult() = cell->density_mult(cell_instance());
657
    return;
658
  }
659
#endif
660

661
  bool verbose = settings::verbosity >= 10 || trace();
520,118,958!
662
  if (neighbor_list_find_cell(*this, verbose)) {
520,118,958✔
663
    return;
664
  }
665

666
  // ==========================================================================
667
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
668

669
  // Remove lower coordinate levels
670
  n_coord() = 1;
16,362✔
671
  bool found = exhaustive_find_cell(*this, verbose);
16,362✔
672

673
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
16,362!
674
    // If a cell is still not found, there are two possible causes: 1) there is
675
    // a void in the model, and 2) the particle hit a surface at a tangent. If
676
    // the particle is really traveling tangent to a surface, if we move it
677
    // forward a tiny bit it should fix the problem.
678

679
    surface() = SURFACE_NONE;
3,210✔
680
    n_coord() = 1;
3,210✔
681
    r() += TINY_BIT * u();
3,210✔
682

683
    // Couldn't find next cell anywhere! This probably means there is an actual
684
    // undefined region in the geometry.
685

686
    if (!exhaustive_find_cell(*this, verbose)) {
3,210!
687
      mark_as_lost("After particle " + std::to_string(id()) +
9,624✔
688
                   " crossed surface " + std::to_string(surf.id_) +
9,624✔
689
                   " it could not be located in any cell and it did not leak.");
690
      return;
3,204✔
691
    }
692
  }
693
}
694

695
void Particle::cross_vacuum_bc(const Surface& surf)
19,005,147✔
696
{
697
  // Score any surface current tallies -- note that the particle is moved
698
  // forward slightly so that if the mesh boundary is on the surface, it is
699
  // still processed
700

701
  if (!model::active_meshsurf_tallies.empty()) {
19,005,147✔
702
    // TODO: Find a better solution to score surface currents than
703
    // physically moving the particle forward slightly
704

705
    r() += TINY_BIT * u();
511,212✔
706
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
511,212✔
707
  }
708

709
  // Score to global leakage tally
710
  keff_tally_leakage() += wgt();
19,005,147✔
711

712
  // Kill the particle
713
  wgt() = 0.0;
19,005,147✔
714

715
  // Display message
716
  if (settings::verbosity >= 10 || trace()) {
19,005,147!
717
    write_message(1, "    Leaked out of surface {}", surf.id_);
12✔
718
  }
719
}
19,005,147✔
720

721
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
373,177,480✔
722
{
723
  // Do not handle reflective boundary conditions on lower universes
724
  if (n_coord() != 1) {
373,177,480!
725
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
726
                 " off surface in a lower universe.");
727
    return;
×
728
  }
729

730
  // Score surface currents since reflection causes the direction of the
731
  // particle to change. For surface filters, we need to score the tallies
732
  // twice, once before the particle's surface attribute has changed and
733
  // once after. For mesh surface filters, we need to artificially move
734
  // the particle slightly back in case the surface crossing is coincident
735
  // with a mesh boundary
736

737
  if (!model::active_surface_tallies.empty()) {
373,177,480✔
738
    score_surface_tally(*this, model::active_surface_tallies, surf);
155,466✔
739
  }
740

741
  if (!model::active_meshsurf_tallies.empty()) {
373,177,480✔
742
    Position r {this->r()};
25,573,902✔
743
    this->r() -= TINY_BIT * u();
25,573,902✔
744
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
25,573,902✔
745
    this->r() = r;
25,573,902✔
746
  }
747

748
  // Set the new particle direction
749
  u() = new_u;
373,177,480✔
750

751
  // Reassign particle's cell and surface
752
  coord(0).cell() = cell_last(0);
373,177,480✔
753
  surface() = -surface();
373,177,480✔
754

755
  // If a reflective surface is coincident with a lattice or universe
756
  // boundary, it is necessary to redetermine the particle's coordinates in
757
  // the lower universes.
758
  // (unless we're using a dagmc model, which has exactly one universe)
759
  n_coord() = 1;
373,177,480✔
760
  if (surf.geom_type() != GeometryType::DAG &&
746,354,960!
761
      !neighbor_list_find_cell(*this)) {
373,177,480✔
762
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
763
                 std::to_string(surf.id_) + ".");
×
764
    return;
×
765
  }
766

767
  // Set previous coordinate going slightly past surface crossing
768
  r_last_current() = r() + TINY_BIT * u();
373,177,480✔
769

770
  // Diagnostic message
771
  if (settings::verbosity >= 10 || trace()) {
373,177,480!
772
    write_message(1, "    Reflected from surface {}", surf.id_);
×
773
  }
774
}
775

776
void Particle::cross_periodic_bc(
1,228,817✔
777
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
778
{
779
  // Do not handle periodic boundary conditions on lower universes
780
  if (n_coord() != 1) {
1,228,817!
781
    mark_as_lost(
×
782
      "Cannot transfer particle " + std::to_string(id()) +
×
783
      " across surface in a lower universe. Boundary conditions must be "
784
      "applied to root universe.");
785
    return;
×
786
  }
787

788
  // Score surface currents since reflection causes the direction of the
789
  // particle to change -- artificially move the particle slightly back in
790
  // case the surface crossing is coincident with a mesh boundary
791
  if (!model::active_meshsurf_tallies.empty()) {
1,228,817!
792
    Position r {this->r()};
×
793
    this->r() -= TINY_BIT * u();
×
794
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
795
    this->r() = r;
×
796
  }
797

798
  // Adjust the particle's location and direction.
799
  r() = new_r;
1,228,817✔
800
  u() = new_u;
1,228,817✔
801

802
  // Reassign particle's surface
803
  surface() = new_surface;
1,228,817✔
804

805
  // Figure out what cell particle is in now
806
  n_coord() = 1;
1,228,817✔
807

808
  if (!neighbor_list_find_cell(*this)) {
1,228,817!
809
    mark_as_lost("Couldn't find particle after hitting periodic "
×
810
                 "boundary on surface " +
×
811
                 std::to_string(surf.id_) + ".");
×
812
    return;
×
813
  }
814

815
  // Set previous coordinate going slightly past surface crossing
816
  r_last_current() = r() + TINY_BIT * u();
1,228,817✔
817

818
  // Diagnostic message
819
  if (settings::verbosity >= 10 || trace()) {
1,228,817!
820
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
821
  }
822
}
823

824
void Particle::mark_as_lost(const char* message)
3,210✔
825
{
826
  // Print warning and write lost particle file
827
  warning(message);
3,210✔
828
  if (settings::max_write_lost_particles < 0 ||
3,210✔
829
      simulation::n_lost_particles < settings::max_write_lost_particles) {
3,000✔
830
    write_restart();
245✔
831
  }
832
  // Increment number of lost particles
833
  wgt() = 0.0;
3,210✔
834
#pragma omp atomic
535✔
835
  simulation::n_lost_particles += 1;
2,675✔
836

837
  // Count the total number of simulated particles (on this processor)
838
  auto n = simulation::current_batch * settings::gen_per_batch *
3,210✔
839
           simulation::work_per_rank;
840

841
  // Abort the simulation if the maximum number of lost particles has been
842
  // reached
843
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
3,210✔
844
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
6!
845
    fatal_error("Maximum number of lost particles has been reached.");
6✔
846
  }
847
}
3,204✔
848

849
void Particle::write_restart() const
245✔
850
{
851
  // Dont write another restart file if in particle restart mode
852
  if (settings::run_mode == RunMode::PARTICLE)
245✔
853
    return;
18✔
854

855
  // Set up file name
856
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
227✔
857
    simulation::current_batch, id());
227✔
858

859
#pragma omp critical(WriteParticleRestart)
37✔
860
  {
227✔
861
    // Create file
862
    hid_t file_id = file_open(filename, 'w');
227✔
863

864
    // Write filetype and version info
865
    write_attribute(file_id, "filetype", "particle restart");
227✔
866
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
227✔
867
    write_attribute(file_id, "openmc_version", VERSION);
227✔
868
#ifdef GIT_SHA1
869
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
870
#endif
871

872
    // Write data to file
873
    write_dataset(file_id, "current_batch", simulation::current_batch);
227✔
874
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
227✔
875
    write_dataset(file_id, "current_generation", simulation::current_gen);
227✔
876
    write_dataset(file_id, "n_particles", settings::n_particles);
227✔
877
    switch (settings::run_mode) {
227!
878
    case RunMode::FIXED_SOURCE:
155✔
879
      write_dataset(file_id, "run_mode", "fixed source");
155✔
880
      break;
25✔
881
    case RunMode::EIGENVALUE:
72✔
882
      write_dataset(file_id, "run_mode", "eigenvalue");
72✔
883
      break;
12✔
884
    case RunMode::PARTICLE:
×
885
      write_dataset(file_id, "run_mode", "particle restart");
×
886
      break;
887
    default:
888
      break;
889
    }
890
    write_dataset(file_id, "id", id());
227✔
891
    write_dataset(file_id, "type", type().pdg_number());
227✔
892

893
    // Get source site data for the particle that got lost
894
    int64_t i = current_work();
227✔
895
    SourceSite site;
227✔
896
    if (settings::run_mode == RunMode::EIGENVALUE) {
227✔
897
      site = simulation::source_bank[i];
72✔
898
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
155✔
899
               settings::use_shared_secondary_bank &&
155!
900
               i < simulation::shared_secondary_bank_read.size()) {
30!
NEW
901
      site = simulation::shared_secondary_bank_read[i];
×
902
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
155!
903
      // Re-sample using the same seed used to generate the source particle.
904
      // current_work() is 0-indexed, compute_particle_id expects 1-indexed.
905
      int64_t id = compute_transport_seed(compute_particle_id(i + 1));
155✔
906
      uint64_t seed = init_seed(id, STREAM_SOURCE);
155✔
907
      site = sample_external_source(&seed);
155✔
908
    }
909
    write_dataset(file_id, "weight", site.wgt);
227✔
910
    write_dataset(file_id, "energy", site.E);
227✔
911
    write_dataset(file_id, "xyz", site.r);
227✔
912
    write_dataset(file_id, "uvw", site.u);
227✔
913
    write_dataset(file_id, "time", site.time);
227✔
914

915
    // Close file
916
    file_close(file_id);
227✔
917
  } // #pragma omp critical
918
}
227✔
919

920
void Particle::update_neutron_xs(
2,147,483,647✔
921
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
922
{
923
  // Get microscopic cross section cache
924
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
925

926
  // If the cache doesn't match, recalculate micro xs
927
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
1,530,071,256✔
928
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
929
      ncrystal_xs != micro.ncrystal_xs) {
1,468,777,652!
930
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
931

932
    // If NCrystal is being used, update micro cross section cache
933
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
934
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
935
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
6,010,338✔
936
      ncrystal_update_micro(ncrystal_xs, micro);
6,010,338✔
937
    }
938
  }
939
}
2,147,483,647✔
940

941
//==============================================================================
942
// Non-method functions
943
//==============================================================================
944
void add_surf_source_to_bank(Particle& p, const Surface& surf)
911,183,904✔
945
{
946
  if (simulation::current_batch <= settings::n_inactive ||
911,183,904✔
947
      simulation::surf_source_bank.full()) {
700,931,373✔
948
    return;
911,112,534✔
949
  }
950

951
  // If a cell/cellfrom/cellto parameter is defined
952
  if (settings::ssw_cell_id != C_NONE) {
191,266✔
953

954
    // Retrieve cell index and storage type
955
    int cell_idx = model::cell_map[settings::ssw_cell_id];
145,414✔
956

957
    if (surf.bc_) {
145,414✔
958
      // Leave if cellto with vacuum boundary condition
959
      if (surf.bc_->type() == "vacuum" &&
176,532✔
960
          settings::ssw_cell_type == SSWCellType::To) {
18,450✔
961
        return;
962
      }
963

964
      // Leave if other boundary condition than vacuum
965
      if (surf.bc_->type() != "vacuum") {
163,020✔
966
        return;
967
      }
968
    }
969

970
    // Check if the cell of interest has been exited
971
    bool exited = false;
972
    for (int i = 0; i < p.n_coord_last(); ++i) {
185,360✔
973
      if (p.cell_last(i) == cell_idx) {
116,518✔
974
        exited = true;
41,328✔
975
      }
976
    }
977

978
    // Check if the cell of interest has been entered
979
    bool entered = false;
980
    for (int i = 0; i < p.n_coord(); ++i) {
164,804✔
981
      if (p.coord(i).cell() == cell_idx) {
95,962✔
982
        entered = true;
32,710✔
983
      }
984
    }
985

986
    // Vacuum boundary conditions: return if cell is not exited
987
    if (surf.bc_) {
68,842✔
988
      if (surf.bc_->type() == "vacuum" && !exited) {
23,388!
989
        return;
990
      }
991
    } else {
992

993
      // If we both enter and exit the cell of interest
994
      if (entered && exited) {
57,148✔
995
        return;
996
      }
997

998
      // If we did not enter nor exit the cell of interest
999
      if (!entered && !exited) {
41,212✔
1000
        return;
1001
      }
1002

1003
      // If cellfrom and the cell before crossing is not the cell of
1004
      // interest
1005
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
34,966✔
1006
        return;
1007
      }
1008

1009
      // If cellto and the cell after crossing is not the cell of interest
1010
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
28,386✔
1011
        return;
1012
      }
1013
    }
1014
  }
1015

1016
  SourceSite site;
71,370✔
1017
  site.r = p.r();
71,370✔
1018
  site.u = p.u();
71,370✔
1019
  site.E = p.E();
71,370✔
1020
  site.time = p.time();
71,370✔
1021
  site.wgt = p.wgt();
71,370✔
1022
  site.delayed_group = p.delayed_group();
71,370✔
1023
  site.surf_id = surf.id_;
71,370✔
1024
  site.particle = p.type();
71,370✔
1025
  site.parent_id = p.id();
71,370✔
1026
  site.progeny_id = p.n_progeny();
71,370✔
1027
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
71,370✔
1028
}
1029

1030
} // 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