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

openmc-dev / openmc / 30105316381

24 Jul 2026 03:26PM UTC coverage: 81.423% (+0.07%) from 81.354%
30105316381

Pull #3959

github

web-flow
Merge 87681ceb6 into 01790598d
Pull Request #3959: Fix coupled external source rate and transfer rate with destination material

18382 of 26610 branches covered (69.08%)

Branch coverage included in aggregate %.

30 of 31 new or added lines in 1 file covered. (96.77%)

1266 existing lines in 43 files now uncovered.

60041 of 69705 relevant lines covered (86.14%)

73826495.57 hits per line

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

87.35
/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
4,852,426,688✔
48
{
49
  if (settings::run_CE) {
4,852,426,688✔
50
    // Determine mass in eV/c^2
51
    double mass = this->mass();
4,004,359,982✔
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)) /
4,004,359,982✔
55
           (this->E() + mass);
4,004,359,982✔
56
  } else {
57
    auto mat = this->material();
2,082,832,565✔
58
    if (mat == MATERIAL_VOID)
2,082,832,565!
59
      return 1.0 / data::mg.default_inverse_velocity_[this->g()];
×
60
    auto& macro_xs = data::mg.macro_xs_[mat];
2,082,832,565✔
61
    int macro_t = this->mg_xs_cache().t;
2,082,832,565✔
62
    int macro_a = macro_xs.get_angle_index(this->u());
2,082,832,565✔
63
    return 1.0 / macro_xs.get_xs(
4,040,967,797✔
64
                   MgxsType::INVERSE_VELOCITY, this->g(), macro_t, macro_a);
2,082,832,565✔
65
  }
66
}
67

68
double Particle::mass() const
4,004,359,982✔
69
{
70
  switch (type().pdg_number()) {
4,004,359,982✔
71
  case PDG_NEUTRON:
72
    return MASS_NEUTRON_EV;
73
  case PDG_ELECTRON:
96,970,704✔
74
  case PDG_POSITRON:
96,970,704✔
75
    return MASS_ELECTRON_EV;
96,970,704✔
76
  default:
46,104,764✔
77
    return this->type().mass() * AMU_EV;
46,104,764✔
78
  }
79
}
80

81
bool Particle::create_secondary(
201,209,288✔
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();
201,209,288✔
87
  if (idx == C_NONE) {
201,209,288!
88
    return false;
89
  }
90
  if (E < settings::energy_cutoff[idx]) {
201,209,288✔
91
    return false;
92
  }
93

94
  // Increment number of secondaries created (for ParticleProductionFilter)
95
  n_secondaries()++;
104,690,006✔
96

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

113
  local_secondary_bank().emplace_back(bank);
104,690,006✔
114
  return true;
115
}
116

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

127
  // Convert signed index to a signed surface ID
128
  if (surface() == SURFACE_NONE) {
18,042,521✔
129
    bank.surf_id = SURFACE_NONE;
17,500,448✔
130
  } else {
131
    int surf_id = model::surfaces[surface_index()]->id_;
542,073✔
132
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
542,073✔
133
  }
134

135
  bank.wgt_born = wgt_born();
18,042,521✔
136
  bank.wgt_ww_born = wgt_ww_born();
18,042,521✔
137
  bank.n_split = n_split();
18,042,521✔
138
  bank.parent_id = current_work();
18,042,521✔
139
  if (settings::use_shared_secondary_bank) {
18,042,521✔
140
    bank.progeny_id = n_progeny()++;
12,381,415✔
141
  }
142

143
  local_secondary_bank().emplace_back(bank);
18,042,521✔
144
}
18,042,521✔
145

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

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

185
  // Convert signed surface ID to signed index
186
  if (src->surf_id != SURFACE_NONE) {
311,332,177✔
187
    auto it = model::surface_map.find(std::abs(src->surf_id));
655,868!
188
    if (it != model::surface_map.end()) {
655,868!
189
      int index_plus_one = it->second + 1;
655,868✔
190
      surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
655,868✔
191
    }
192
  }
193

194
  wgt_born() = src->wgt_born;
311,332,177✔
195
  wgt_ww_born() = src->wgt_ww_born;
311,332,177✔
196
  n_split() = src->n_split;
311,332,177✔
197
}
311,332,177✔
198

199
void Particle::event_calculate_xs()
4,849,931,537✔
200
{
201
  // Set the random number stream
202
  stream() = STREAM_TRACKING;
4,849,931,537✔
203

204
  // Store pre-collision particle properties
205
  wgt_last() = wgt();
4,849,931,537✔
206
  E_last() = E();
4,849,931,537✔
207
  u_last() = u();
4,849,931,537✔
208
  r_last() = r();
4,849,931,537✔
209
  time_last() = time();
4,849,931,537✔
210

211
  // Reset event variables
212
  event() = TallyEvent::KILL;
4,849,931,537✔
213
  event_nuclide() = NUCLIDE_NONE;
4,849,931,537✔
214
  event_mt() = REACTION_NONE;
4,849,931,537✔
215

216
  // If the cell hasn't been determined based on the particle's location,
217
  // initiate a search for the current cell. This generally happens at the
218
  // beginning of the history and again for any secondary particles
219
  if (lowest_coord().cell() == C_NONE) {
4,849,931,537✔
220
    if (!exhaustive_find_cell(*this)) {
301,363,609!
UNCOV
221
      mark_as_lost(
×
UNCOV
222
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
223
      return;
×
224
    }
225

226
    // Set birth cell attribute
227
    if (cell_born() == C_NONE)
301,363,609!
228
      cell_born() = lowest_coord().cell();
301,363,609✔
229

230
    // Initialize last cells from current cell
231
    for (int j = 0; j < n_coord(); ++j) {
620,330,058✔
232
      cell_last(j) = coord(j).cell();
318,966,449✔
233
    }
234
    n_coord_last() = n_coord();
301,363,609✔
235
  }
236

237
  // Write particle track.
238
  if (write_track())
4,849,931,537✔
239
    write_particle_track(*this);
10,309✔
240

241
  if (settings::check_overlaps)
4,849,931,537!
UNCOV
242
    check_cell_overlap(*this);
×
243

244
  // Calculate microscopic and macroscopic cross sections
245
  if (material() != MATERIAL_VOID) {
4,849,931,537✔
246
    if (settings::run_CE) {
4,839,606,206✔
247
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
3,922,112,286✔
248
          density_mult() != density_mult_last()) {
917,554,382✔
249
        // If the material is the same as the last material and the
250
        // temperature hasn't changed, we don't need to lookup cross
251
        // sections again.
252
        model::materials[material()]->calculate_xs(*this);
3,004,567,496✔
253
      }
254
    } else {
255
      // Get the MG data; unlike the CE case above, we have to re-calculate
256
      // cross sections for every collision since the cross sections may
257
      // be angle-dependent
258
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,082,832,565✔
259

260
      // Update the particle's group while we know we are multi-group
261
      g_last() = g();
2,082,832,565✔
262
    }
263
  } else {
264
    macro_xs().total = 0.0;
113,592,369✔
265
    macro_xs().absorption = 0.0;
113,592,369✔
266
    macro_xs().fission = 0.0;
113,592,369✔
267
    macro_xs().nu_fission = 0.0;
113,592,369✔
268
  }
269
}
270

271
void Particle::event_advance()
4,849,931,537✔
272
{
273
  // Find the distance to the nearest boundary
274
  boundary() = distance_to_boundary(*this);
4,849,931,537✔
275

276
  // Sample a distance to collision
277
  if (type() == ParticleType::electron() ||
4,849,931,537✔
278
      type() == ParticleType::positron()) {
4,841,134,196✔
279
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
193,941,408!
280
  } else if (macro_xs().total == 0.0) {
4,841,116,302✔
281
    collision_distance() = INFINITY;
113,592,369✔
282
  } else {
283
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
4,830,790,971✔
284
  }
285

286
  double speed = this->speed();
4,849,931,537✔
287
  double time_cutoff = settings::time_cutoff[type().transport_index()];
4,849,931,537✔
288
  double distance_cutoff =
4,849,931,537✔
289
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
4,849,931,537✔
290

291
  // Select smaller of the three distances
292
  double distance =
4,849,931,537✔
293
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
4,849,931,537✔
294

295
  // Advance particle in space and time
296
  this->move_distance(distance);
4,849,931,537✔
297
  double dt = distance / speed;
4,849,931,537✔
298
  this->time() += dt;
4,849,931,537✔
299
  this->lifetime() += dt;
4,849,931,537✔
300

301
  // Score timed track-length tallies
302
  if (!model::active_timed_tracklength_tallies.empty()) {
4,849,931,537✔
303
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
304
  }
305

306
  // Score track-length tallies
307
  if (!model::active_tracklength_tallies.empty()) {
4,849,931,537✔
308
    score_tracklength_tally(*this, distance);
3,193,605,245✔
309
  }
310

311
  // Score track-length estimate of k-eff
312
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
4,849,931,537✔
313
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
4,353,736,718✔
314
  }
315

316
  // Score flux derivative accumulators for differential tallies.
317
  if (!model::active_tallies.empty()) {
4,849,931,537✔
318
    score_track_derivative(*this, distance);
3,364,997,570✔
319
  }
320

321
  // Set particle weight to zero if it hit the time boundary
322
  if (distance == distance_cutoff) {
4,849,931,537✔
323
    wgt() = 0.0;
224,928✔
324
  }
325
}
4,849,931,537✔
326

327
void Particle::event_cross_surface()
3,710,699,360✔
328
{
329
  // Saving previous cell data
330
  for (int j = 0; j < n_coord(); ++j) {
5,253,672,951✔
331
    cell_last(j) = coord(j).cell();
4,917,366,258✔
332
  }
333
  n_coord_last() = n_coord();
3,710,699,360✔
334

335
  // Set surface that particle is on and adjust coordinate levels
336
  surface() = boundary().surface();
3,710,699,360✔
337
  n_coord() = boundary().coord_level();
3,710,699,360✔
338

339
  if (boundary().lattice_translation()[0] != 0 ||
3,710,699,360✔
340
      boundary().lattice_translation()[1] != 0 ||
3,710,699,360✔
341
      boundary().lattice_translation()[2] != 0) {
3,102,741,096✔
342
    // Particle crosses lattice boundary
343

344
    int i_lattice = coord(boundary().coord_level() - 1).lattice();
813,765,249!
345
    bool verbose = settings::verbosity >= 10 || trace();
813,765,249!
346
    cross_lattice(*this, boundary(), verbose);
813,765,249✔
347
    event() = TallyEvent::LATTICE;
813,765,249✔
348

349
    // Score cell to cell partial currents
350
    if (!model::active_surface_tallies.empty()) {
813,765,249✔
351
      auto& lat {*model::lattices[i_lattice]};
55✔
352
      bool is_valid;
55✔
353
      Direction normal =
55✔
354
        lat.get_normal(boundary().lattice_translation(), is_valid);
55✔
355
      if (is_valid) {
55!
356
        normal /= normal.norm();
55✔
357
        score_surface_tally(*this, model::active_surface_tallies, normal);
55✔
358
      }
359
    }
360

361
  } else {
362

363
    const auto& surf {*model::surfaces[surface_index()].get()};
2,896,934,111✔
364

365
    // Particle crosses surface
366
    // If BC, add particle to surface source before crossing surface
367
    if (surf.surf_source_ && surf.bc_) {
2,896,934,111✔
368
      add_surf_source_to_bank(*this, surf);
1,016,140,993✔
369
    }
370
    this->cross_surface(surf);
2,896,934,111✔
371
    // If no BC, add particle to surface source after crossing surface
372
    if (surf.surf_source_ && !surf.bc_) {
2,896,934,102✔
373
      add_surf_source_to_bank(*this, surf);
1,879,555,282✔
374
    }
375
    if (settings::weight_window_checkpoint_surface) {
2,896,934,102✔
376
      apply_weight_windows(*this);
32,393,943✔
377
    }
378
    event() = TallyEvent::SURFACE;
2,896,934,102✔
379

380
    // Score cell to cell partial currents
381
    if (!model::active_surface_tallies.empty()) {
2,896,934,102✔
382
      Direction normal = surf.normal(r());
34,931,622✔
383
      normal /= normal.norm();
34,931,622✔
384
      score_surface_tally(*this, model::active_surface_tallies, normal);
34,931,622✔
385
    }
386
  }
387
}
3,710,699,351✔
388

389
void Particle::event_collide()
3,426,614,780✔
390
{
391

392
  // Score collision estimate of keff
393
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
3,426,614,780✔
394
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,336,320,437✔
395
  }
396

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

401
  if (!model::active_meshsurf_tallies.empty())
3,426,614,780✔
402
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
403

404
  // Clear surface component
405
  surface() = SURFACE_NONE;
3,426,614,780✔
406

407
  if (settings::run_CE) {
3,426,614,780✔
408
    collision(*this);
1,625,470,006✔
409
  } else {
410
    collision_mg(*this);
1,801,144,774✔
411
  }
412

413
  // Collision track feature to recording particle interaction
414
  if (settings::collision_track) {
3,426,614,780✔
415
    collision_track_record(*this);
728,673✔
416
  }
417

418
  // Score collision estimator tallies -- this is done after a collision
419
  // has occurred rather than before because we need information on the
420
  // outgoing energy for any tallies with an outgoing energy filter
421
  if (!model::active_collision_tallies.empty())
3,426,614,780✔
422
    score_collision_tally(*this);
114,042,093✔
423
  if (!model::active_analog_tallies.empty()) {
3,426,614,780✔
424
    if (settings::run_CE) {
498,783,711✔
425
      score_analog_tally_ce(*this);
497,575,449✔
426
    } else {
427
      score_analog_tally_mg(*this);
1,208,262✔
428
    }
429
  }
430

431
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
3,426,614,780✔
432
    pht_collision_energy();
101,629✔
433
  }
434

435
  // Reset banked weight during collision
436
  n_bank() = 0;
3,426,614,780✔
437
  bank_second_E() = 0.0;
3,426,614,780✔
438
  wgt_bank() = 0.0;
3,426,614,780✔
439

440
  // Clear number of secondaries in this collision. This is
441
  // distinct from the number of created neutrons n_bank() above!
442
  n_secondaries() = 0;
3,426,614,780✔
443

444
  zero_delayed_bank();
3,426,614,780✔
445

446
  // Reset fission logical
447
  fission() = false;
3,426,614,780✔
448

449
  // Save coordinates for tallying purposes
450
  r_last_current() = r();
3,426,614,780✔
451

452
  // Set last material to none since cross sections will need to be
453
  // re-evaluated
454
  material_last() = C_NONE;
3,426,614,780✔
455

456
  // Set all directions to base level -- right now, after a collision, only
457
  // the base level directions are changed
458
  for (int j = 0; j < n_coord() - 1; ++j) {
3,724,937,962✔
459
    if (coord(j + 1).rotated()) {
298,323,182✔
460
      // If next level is rotated, apply rotation matrix
461
      const auto& m {model::cells[coord(j).cell()]->rotation_};
11,724,229✔
462
      const auto& u {coord(j).u()};
11,724,229✔
463
      coord(j + 1).u() = u.rotate(m);
11,724,229✔
464
    } else {
465
      // Otherwise, copy this level's direction
466
      coord(j + 1).u() = coord(j).u();
286,598,953✔
467
    }
468
  }
469

470
  // Score flux derivative accumulators for differential tallies.
471
  if (!model::active_tallies.empty())
3,426,614,780✔
472
    score_collision_derivative(*this);
1,468,284,286✔
473

474
#ifdef OPENMC_DAGMC_ENABLED
475
  history().reset();
313,693,021✔
476
#endif
477
}
3,426,614,780✔
478

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

488
  from_source(&site);
123,746,724✔
489

490
  n_event() = 0;
123,746,724✔
491
  if (!settings::use_shared_secondary_bank) {
123,746,724✔
492
    n_tracks()++;
92,720,474✔
493
  }
494
  bank_second_E() = 0.0;
123,746,724✔
495

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

515
      // Initialize last cells from current cell
516
      for (int j = 0; j < n_coord(); ++j) {
66,066✔
517
        cell_last(j) = coord(j).cell();
33,033✔
518
      }
519
      n_coord_last() = n_coord();
33,033✔
520
    }
521
    pht_secondary_particles();
33,033✔
522
  }
523

524
  // Enter new particle in particle track file
525
  if (write_track())
123,746,724✔
526
    add_particle_track(*this);
5,234✔
527
}
528

529
void Particle::event_check_limit_and_revive()
4,849,931,536✔
530
{
531
  // If particle has too many events, display warning and kill it
532
  n_event()++;
4,849,931,536✔
533
  if (n_event() == settings::max_particle_events) {
4,849,931,536!
UNCOV
534
    warning("Particle " + std::to_string(id()) +
×
535
            " underwent maximum number of events.");
UNCOV
536
    wgt() = 0.0;
×
537
  }
538

539
  // In non-shared-secondary mode, revive from local secondary bank
540
  if (!alive() && !settings::use_shared_secondary_bank &&
4,849,931,536✔
541
      !local_secondary_bank().empty()) {
269,580,542✔
542
    SourceSite& site = local_secondary_bank().back();
92,720,474✔
543
    event_revive_from_secondary(site);
92,720,474✔
544
    local_secondary_bank().pop_back();
92,720,474✔
545
  }
546
}
4,849,931,536✔
547

548
void Particle::event_death()
208,676,159✔
549
{
550
#ifdef OPENMC_DAGMC_ENABLED
551
  history().reset();
19,053,353✔
552
#endif
553

554
  // Finish particle track output.
555
  if (write_track()) {
208,676,159✔
556
    write_particle_track(*this);
1,010✔
557
    finalize_particle_track(*this);
1,010✔
558
  }
559

560
  // Contribute tally reduction variables to global accumulator
561
  const auto k_absorption = keff_tally_absorption();
208,676,159✔
562
  const auto k_collision = keff_tally_collision();
208,676,159✔
563
  const auto k_tracklength = keff_tally_tracklength();
208,676,159✔
564
  const auto leakage = keff_tally_leakage();
208,676,159✔
565

566
  if (settings::run_mode == RunMode::EIGENVALUE) {
208,676,159✔
567
    if (k_absorption != 0.0) {
149,937,000✔
568
#pragma omp atomic
73,841,482✔
569
      global_tally_absorption += k_absorption;
60,665,518✔
570
    }
571
    if (k_collision != 0.0) {
149,937,000✔
572
#pragma omp atomic
78,353,640✔
573
      global_tally_collision += k_collision;
65,034,301✔
574
    }
575
    if (k_tracklength != 0.0) {
149,937,000✔
576
#pragma omp atomic
81,995,147✔
577
      global_tally_tracklength += k_tracklength;
68,109,415✔
578
    }
579
  }
580
  if (leakage != 0.0) {
208,676,159✔
581
#pragma omp atomic
20,750,200✔
582
    global_tally_leakage += leakage;
16,913,826✔
583
  }
584

585
  // Reset particle tallies once accumulated
586
  keff_tally_absorption() = 0.0;
208,676,159✔
587
  keff_tally_collision() = 0.0;
208,676,159✔
588
  keff_tally_tracklength() = 0.0;
208,676,159✔
589
  keff_tally_leakage() = 0.0;
208,676,159✔
590

591
  if (!model::active_pulse_height_tallies.empty()) {
208,676,159✔
592
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
143,000✔
593
  }
594

595
  // Accumulate track count for this particle history
596
  if (!settings::use_shared_secondary_bank) {
208,676,159✔
597
#pragma omp atomic
96,550,248✔
598
    simulation::simulation_tracks_completed += n_tracks();
176,861,068✔
599
  }
600

601
  // Record the number of progeny created by this particle.
602
  // This data will be used to efficiently sort the fission bank.
603
  if (settings::run_mode == RunMode::EIGENVALUE ||
208,676,159✔
604
      settings::use_shared_secondary_bank) {
605
    simulation::progeny_per_particle[current_work()] = n_progeny();
181,752,091✔
606
  }
607
}
208,676,159✔
608

609
void Particle::pht_collision_energy()
101,629✔
610
{
611
  // Adds the energy particles lose in a collision to the pulse-height
612

613
  // determine index of cell in pulse_height_cells
614
  auto it = std::find(model::pulse_height_cells.begin(),
101,629✔
615
    model::pulse_height_cells.end(), lowest_coord().cell());
101,629!
616

617
  if (it != model::pulse_height_cells.end()) {
101,629!
618
    int index = std::distance(model::pulse_height_cells.begin(), it);
101,629✔
619
    pht_storage()[index] += E_last() - E();
101,629✔
620

621
    // If the energy of the particle is below the cutoff, it will not be sampled
622
    // so its energy is added to the pulse-height in the cell
623
    int photon = ParticleType::photon().transport_index();
101,629✔
624
    if (E() < settings::energy_cutoff[photon]) {
101,629✔
625
      pht_storage()[index] += E();
44,836✔
626
    }
627
  }
628
}
101,629✔
629

630
void Particle::pht_secondary_particles()
33,033✔
631
{
632
  // Removes the energy of secondary produced particles from the pulse-height
633

634
  // determine index of cell in pulse_height_cells
635
  auto it = std::find(model::pulse_height_cells.begin(),
33,033✔
636
    model::pulse_height_cells.end(), cell_born());
33,033!
637

638
  if (it != model::pulse_height_cells.end()) {
33,033!
639
    int index = std::distance(model::pulse_height_cells.begin(), it);
33,033✔
640
    pht_storage()[index] -= E();
33,033✔
641
  }
642
}
33,033✔
643

644
void Particle::cross_surface(const Surface& surf)
2,898,884,431✔
645
{
646

647
  if (settings::verbosity >= 10 || trace()) {
2,898,884,431✔
648
    write_message(1, "    Crossing surface {}", surf.id_);
88✔
649
  }
650

651
// if we're crossing a CSG surface, make sure the DAG history is reset
652
#ifdef OPENMC_DAGMC_ENABLED
653
  if (surf.geom_type() == GeometryType::CSG)
264,223,669✔
654
    history().reset();
264,166,085✔
655
#endif
656

657
  // Handle any applicable boundary conditions.
658
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,898,884,431!
659
      settings::run_mode != RunMode::VOLUME) {
660
    surf.bc_->handle_particle(*this, surf);
1,016,493,101✔
661
    return;
1,016,493,101✔
662
  }
663

664
  // ==========================================================================
665
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
666

667
#ifdef OPENMC_DAGMC_ENABLED
668
  // in DAGMC, we know what the next cell should be
669
  if (surf.geom_type() == GeometryType::DAG) {
171,373,138✔
670
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,664✔
671
                       lowest_coord().universe()) -
46,664✔
672
                     1;
46,664✔
673
    // save material, temperature, and density multiplier
674
    material_last() = material();
46,664✔
675
    sqrtkT_last() = sqrtkT();
46,664✔
676
    density_mult_last() = density_mult();
46,664✔
677
    // set new cell value
678
    lowest_coord().cell() = i_cell;
46,664✔
679
    auto& cell = model::cells[i_cell];
46,664✔
680

681
    cell_instance() = 0;
46,664✔
682
    if (cell->distribcell_index_ >= 0)
46,664✔
683
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,640✔
684

685
    material() = cell->material(cell_instance());
46,664!
686
    sqrtkT() = cell->sqrtkT(cell_instance());
46,664!
687
    density_mult() = cell->density_mult(cell_instance());
46,664✔
688
    return;
46,664✔
689
  }
690
#endif
691

692
  bool verbose = settings::verbosity >= 10 || trace();
1,882,344,666!
693
  if (neighbor_list_find_cell(*this, verbose)) {
1,882,344,666✔
694
    return;
695
  }
696

697
  // ==========================================================================
698
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
699

700
  // Remove lower coordinate levels
701
  n_coord() = 1;
29,977✔
702
  bool found = exhaustive_find_cell(*this, verbose);
29,977✔
703

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

710
    surface() = SURFACE_NONE;
5,865✔
711
    n_coord() = 1;
5,865✔
712
    r() += TINY_BIT * u();
5,865✔
713

714
    // Couldn't find next cell anywhere! This probably means there is an actual
715
    // undefined region in the geometry.
716

717
    if (!exhaustive_find_cell(*this, verbose)) {
5,865!
718
      mark_as_lost("After particle " + std::to_string(id()) +
17,586✔
719
                   " crossed surface " + std::to_string(surf.id_) +
17,586✔
720
                   " it could not be located in any cell and it did not leak.");
721
      return;
5,856✔
722
    }
723
  }
724
}
725

726
void Particle::cross_vacuum_bc(const Surface& surf)
38,655,065✔
727
{
728
  // Score any surface current tallies -- note that the particle is moved
729
  // forward slightly so that if the mesh boundary is on the surface, it is
730
  // still processed
731

732
  if (!model::active_meshsurf_tallies.empty()) {
38,655,065✔
733
    // TODO: Find a better solution to score surface currents than
734
    // physically moving the particle forward slightly
735

736
    r() += TINY_BIT * u();
937,233✔
737
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,233✔
738
  }
739

740
  // Score to global leakage tally
741
  keff_tally_leakage() += wgt();
38,655,065✔
742

743
  // Kill the particle
744
  wgt() = 0.0;
38,655,065✔
745

746
  // Display message
747
  if (settings::verbosity >= 10 || trace()) {
38,655,065!
748
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
749
  }
750
}
38,655,065✔
751

752
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
976,598,660✔
753
{
754
  // Do not handle reflective boundary conditions on lower universes
755
  if (n_coord() != 1) {
976,598,660!
UNCOV
756
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
757
                 " off surface in a lower universe.");
UNCOV
758
    return;
×
759
  }
760

761
  // Score surface currents since reflection causes the direction of the
762
  // particle to change. For surface filters, we need to score the tallies
763
  // twice, once before the particle's surface attribute has changed and
764
  // once after. For mesh surface filters, we need to artificially move
765
  // the particle slightly back in case the surface crossing is coincident
766
  // with a mesh boundary
767

768
  if (!model::active_surface_tallies.empty()) {
976,598,660✔
769
    Direction normal = surf.normal(r());
285,021✔
770
    normal /= normal.norm();
285,021✔
771
    score_surface_tally(*this, model::active_surface_tallies, normal);
285,021✔
772
  }
773

774
  if (!model::active_meshsurf_tallies.empty()) {
976,598,660✔
775
    Position r {this->r()};
46,885,487✔
776
    this->r() -= TINY_BIT * u();
46,885,487✔
777
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
778
    this->r() = r;
46,885,487✔
779
  }
780

781
  // Set the new particle direction
782
  u() = new_u;
976,598,660✔
783

784
  // Reassign particle's cell and surface
785
  coord(0).cell() = cell_last(0);
976,598,660✔
786
  surface() = -surface();
976,598,660✔
787

788
  // If a reflective surface is coincident with a lattice or universe
789
  // boundary, it is necessary to redetermine the particle's coordinates in
790
  // the lower universes.
791
  // (unless we're using a dagmc model, which has exactly one universe)
792
  n_coord() = 1;
976,598,660✔
793
  if (surf.geom_type() != GeometryType::DAG &&
1,953,194,562!
794
      !neighbor_list_find_cell(*this)) {
976,595,902✔
UNCOV
795
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
796
                 std::to_string(surf.id_) + ".");
×
UNCOV
797
    return;
×
798
  }
799

800
  // Set previous coordinate going slightly past surface crossing
801
  r_last_current() = r() + TINY_BIT * u();
976,598,660✔
802

803
  // Diagnostic message
804
  if (settings::verbosity >= 10 || trace()) {
976,598,660!
UNCOV
805
    write_message(1, "    Reflected from surface {}", surf.id_);
×
806
  }
807
}
808

809
void Particle::cross_periodic_bc(
2,244,842✔
810
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
811
{
812
  // Do not handle periodic boundary conditions on lower universes
813
  if (n_coord() != 1) {
2,244,842!
UNCOV
814
    mark_as_lost(
×
815
      "Cannot transfer particle " + std::to_string(id()) +
×
816
      " across surface in a lower universe. Boundary conditions must be "
817
      "applied to root universe.");
UNCOV
818
    return;
×
819
  }
820

821
  // Score surface currents since reflection causes the direction of the
822
  // particle to change -- artificially move the particle slightly back in
823
  // case the surface crossing is coincident with a mesh boundary
824
  if (!model::active_meshsurf_tallies.empty()) {
2,244,842!
825
    Position r {this->r()};
×
UNCOV
826
    this->r() -= TINY_BIT * u();
×
UNCOV
827
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
828
    this->r() = r;
×
829
  }
830

831
  // Adjust the particle's location and direction.
832
  r() = new_r;
2,244,842✔
833
  u() = new_u;
2,244,842✔
834

835
  // Reassign particle's surface
836
  surface() = new_surface;
2,244,842✔
837

838
  // Figure out what cell particle is in now
839
  n_coord() = 1;
2,244,842✔
840

841
  if (!neighbor_list_find_cell(*this)) {
2,244,842!
842
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
843
                 "boundary on surface " +
×
UNCOV
844
                 std::to_string(surf.id_) + ".");
×
UNCOV
845
    return;
×
846
  }
847

848
  // Set previous coordinate going slightly past surface crossing
849
  r_last_current() = r() + TINY_BIT * u();
2,244,842✔
850

851
  // Diagnostic message
852
  if (settings::verbosity >= 10 || trace()) {
2,244,842!
UNCOV
853
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
854
  }
855
}
856

857
void Particle::mark_as_lost(const char* message)
5,865✔
858
{
859
  // Print warning and write lost particle file
860
  warning(message);
5,865✔
861
  if (settings::max_write_lost_particles < 0 ||
5,865✔
862
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
863
    write_restart();
440✔
864
  }
865
  // Increment number of lost particles
866
  wgt() = 0.0;
5,865✔
867
#pragma omp atomic
3,190✔
868
  simulation::n_lost_particles += 1;
2,675✔
869

870
  // Count the total number of simulated particles (on this processor)
871
  auto n = simulation::current_batch * settings::gen_per_batch *
5,865✔
872
           simulation::work_per_rank;
873

874
  // Abort the simulation if the maximum number of lost particles has been
875
  // reached
876
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,865✔
877
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
878
    fatal_error("Maximum number of lost particles has been reached.");
9✔
879
  }
880
}
5,856✔
881

882
void Particle::write_restart() const
440✔
883
{
884
  // Dont write another restart file if in particle restart mode
885
  if (settings::run_mode == RunMode::PARTICLE)
440✔
886
    return;
33✔
887

888
  // Set up file name
889
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
407✔
890
    simulation::current_batch, id());
407✔
891

892
#pragma omp critical(WriteParticleRestart)
217✔
893
  {
407✔
894
    // Create file
895
    hid_t file_id = file_open(filename, 'w');
407✔
896

897
    // Write filetype and version info
898
    write_attribute(file_id, "filetype", "particle restart");
407✔
899
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
407✔
900
    write_attribute(file_id, "openmc_version", VERSION);
407✔
901
#ifdef GIT_SHA1
902
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
903
#endif
904

905
    // Write data to file
906
    write_dataset(file_id, "current_batch", simulation::current_batch);
407✔
907
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
407✔
908
    write_dataset(file_id, "current_generation", simulation::current_gen);
407✔
909
    write_dataset(file_id, "n_particles", settings::n_particles);
407✔
910
    switch (settings::run_mode) {
407!
911
    case RunMode::FIXED_SOURCE:
275✔
912
      write_dataset(file_id, "run_mode", "fixed source");
275✔
913
      break;
145✔
914
    case RunMode::EIGENVALUE:
132✔
915
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
916
      break;
72✔
UNCOV
917
    case RunMode::PARTICLE:
×
UNCOV
918
      write_dataset(file_id, "run_mode", "particle restart");
×
919
      break;
920
    default:
921
      break;
922
    }
923
    write_dataset(file_id, "id", id());
407✔
924
    write_dataset(file_id, "type", type().pdg_number());
407✔
925

926
    // Get source site data for the particle that got lost
927
    int64_t i = current_work();
407✔
928
    SourceSite site;
407✔
929
    if (settings::run_mode == RunMode::EIGENVALUE) {
407✔
930
      site = simulation::source_bank[i];
132✔
931
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
275✔
932
               settings::use_shared_secondary_bank &&
275!
933
               i < simulation::shared_secondary_bank_read.size()) {
55!
UNCOV
934
      site = simulation::shared_secondary_bank_read[i];
×
935
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
275!
936
      // Re-sample using the same seed used to generate the source particle.
937
      // current_work() is 0-indexed, compute_particle_id expects 1-indexed.
938
      int64_t id = compute_transport_seed(compute_particle_id(i + 1));
275✔
939
      uint64_t seed = init_seed(id, STREAM_SOURCE);
275✔
940
      site = sample_external_source(&seed);
275✔
941
    }
942
    write_dataset(file_id, "weight", site.wgt);
407✔
943
    write_dataset(file_id, "energy", site.E);
407✔
944
    write_dataset(file_id, "xyz", site.r);
407✔
945
    write_dataset(file_id, "uvw", site.u);
407✔
946
    write_dataset(file_id, "time", site.time);
407✔
947

948
    // Close file
949
    file_close(file_id);
407✔
950
  } // #pragma omp critical
951
}
407✔
952

953
void Particle::update_neutron_xs(
5,588,645,460✔
954
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
955
{
956
  // Get microscopic cross section cache
957
  auto& micro = this->neutron_xs(i_nuclide);
5,588,645,460✔
958

959
  // If the cache doesn't match, recalculate micro xs
960
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
4,494,548,322✔
961
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
6,060,344,908✔
962
      ncrystal_xs != micro.ncrystal_xs) {
4,443,505,844!
963
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
5,125,798,120✔
964

965
    // If NCrystal is being used, update micro cross section cache
966
    micro.ncrystal_xs = ncrystal_xs;
5,125,798,120✔
967
    if (ncrystal_xs >= 0.0) {
5,125,798,120✔
968
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
969
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
970
    }
971
  }
972
}
5,588,645,460✔
973

974
//==============================================================================
975
// Non-method functions
976
//==============================================================================
977
void add_surf_source_to_bank(Particle& p, const Surface& surf)
2,895,696,275✔
978
{
979
  if (simulation::current_batch <= settings::n_inactive ||
2,895,696,275✔
980
      simulation::surf_source_bank.full()) {
2,225,841,952✔
981
    return;
2,895,566,621✔
982
  }
983

984
  // If a cell/cellfrom/cellto parameter is defined
985
  if (settings::ssw_cell_id != C_NONE) {
337,079✔
986

987
    // Retrieve cell index and storage type
988
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,433✔
989

990
    if (surf.bc_) {
254,433✔
991
      // Leave if cellto with vacuum boundary condition
992
      if (surf.bc_->type() == "vacuum" &&
298,916✔
993
          settings::ssw_cell_type == SSWCellType::To) {
33,098✔
994
        return;
995
      }
996

997
      // Leave if other boundary condition than vacuum
998
      if (surf.bc_->type() != "vacuum") {
274,646✔
999
        return;
1000
      }
1001
    }
1002

1003
    // Check if the cell of interest has been exited
1004
    bool exited = false;
1005
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,665✔
1006
      if (p.cell_last(i) == cell_idx) {
207,727✔
1007
        exited = true;
73,762✔
1008
      }
1009
    }
1010

1011
    // Check if the cell of interest has been entered
1012
    bool entered = false;
1013
    for (int i = 0; i < p.n_coord(); ++i) {
297,967✔
1014
      if (p.coord(i).cell() == cell_idx) {
172,029✔
1015
        entered = true;
57,517✔
1016
      }
1017
    }
1018

1019
    // Vacuum boundary conditions: return if cell is not exited
1020
    if (surf.bc_) {
125,938✔
1021
      if (surf.bc_->type() == "vacuum" && !exited) {
41,926!
1022
        return;
1023
      }
1024
    } else {
1025

1026
      // If we both enter and exit the cell of interest
1027
      if (entered && exited) {
104,975✔
1028
        return;
1029
      }
1030

1031
      // If we did not enter nor exit the cell of interest
1032
      if (!entered && !exited) {
77,772✔
1033
        return;
1034
      }
1035

1036
      // If cellfrom and the cell before crossing is not the cell of
1037
      // interest
1038
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,273✔
1039
        return;
1040
      }
1041

1042
      // If cellto and the cell after crossing is not the cell of interest
1043
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,730✔
1044
        return;
1045
      }
1046
    }
1047
  }
1048

1049
  SourceSite site;
129,654✔
1050
  site.r = p.r();
129,654✔
1051
  site.u = p.u();
129,654✔
1052
  site.E = p.E();
129,654✔
1053
  site.time = p.time();
129,654✔
1054
  site.wgt = p.wgt();
129,654✔
1055
  site.delayed_group = p.delayed_group();
129,654✔
1056
  site.surf_id = surf.id_;
129,654✔
1057
  site.particle = p.type();
129,654✔
1058
  site.parent_id = p.id();
129,654✔
1059
  site.progeny_id = p.n_progeny();
129,654✔
1060
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,654✔
1061
}
1062

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

© 2026 Coveralls, Inc