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

openmc-dev / openmc / 25218672962

01 May 2026 02:43PM UTC coverage: 81.452% (+0.1%) from 81.326%
25218672962

Pull #3863

github

web-flow
Merge bf4da9a8a into 368ea069c
Pull Request #3863: Shared Secondary Particle Bank

17907 of 25811 branches covered (69.38%)

Branch coverage included in aggregate %.

415 of 427 new or added lines in 17 files covered. (97.19%)

1149 existing lines in 27 files now uncovered.

58842 of 68415 relevant lines covered (86.01%)

48738312.94 hits per line

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

85.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:
86,180,406✔
74
  case PDG_POSITRON:
86,180,406✔
75
    return MASS_ELECTRON_EV;
86,180,406✔
76
  default:
39,642,288✔
77
    return this->type().mass() * AMU_EV;
39,642,288✔
78
  }
79
}
80

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

94
  // Increment number of secondaries created (for ParticleProductionFilter)
95
  n_secondaries()++;
93,385,606✔
96

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

113
  // In shared secondary mode, subtract secondary photon energy from parent's
114
  // pulse-height storage now, since the secondary will be transported as a
115
  // separate Particle object and won't have access to the parent's pht_storage.
116
  if (settings::use_shared_secondary_bank &&
108,756,808✔
117
      !model::active_pulse_height_tallies.empty() && type.is_photon()) {
93,385,606!
NEW
118
    auto it = std::find(model::pulse_height_cells.begin(),
×
NEW
119
      model::pulse_height_cells.end(), lowest_coord().cell());
×
UNCOV
120
    if (it != model::pulse_height_cells.end()) {
×
UNCOV
121
      int index = std::distance(model::pulse_height_cells.begin(), it);
×
UNCOV
122
      pht_storage()[index] -= bank.E;
×
123
    }
124
  }
125

126
  local_secondary_bank().emplace_back(bank);
93,385,606✔
127
  return true;
128
}
129

130
void Particle::split(double wgt)
10,351,858✔
131
{
132
  SourceSite bank;
10,351,858✔
133
  bank.particle = type();
10,351,858✔
134
  bank.wgt = wgt;
10,351,858✔
135
  bank.r = r();
10,351,858✔
136
  bank.u = u();
10,351,858✔
137
  bank.E = settings::run_CE ? E() : g();
10,351,858✔
138
  bank.time = time();
10,351,858✔
139

140
  // Convert signed index to a signed surface ID
141
  if (surface() == SURFACE_NONE) {
10,351,858✔
142
    bank.surf_id = SURFACE_NONE;
10,347,986✔
143
  } else {
144
    int surf_id = model::surfaces[surface_index()]->id_;
3,872✔
145
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
3,872✔
146
  }
147

148
  bank.wgt_born = wgt_born();
10,351,858✔
149
  bank.wgt_ww_born = wgt_ww_born();
10,351,858✔
150
  bank.n_split = n_split();
10,351,858✔
151
  bank.parent_id = current_work();
10,351,858✔
152
  if (settings::use_shared_secondary_bank) {
10,351,858✔
153
    bank.progeny_id = n_progeny()++;
5,183,682✔
154
  }
155

156
  local_secondary_bank().emplace_back(bank);
10,351,858✔
157
}
10,351,858✔
158

159
void Particle::from_source(const SourceSite* src)
291,592,977✔
160
{
161
  // Reset some attributes
162
  clear();
291,592,977✔
163
  surface() = SURFACE_NONE;
291,592,977✔
164
  cell_born() = C_NONE;
291,592,977✔
165
  material() = C_NONE;
291,592,977✔
166
  n_collision() = 0;
291,592,977✔
167
  fission() = false;
291,592,977✔
168
  zero_flux_derivs();
291,592,977✔
169
  lifetime() = 0.0;
291,592,977✔
170
#ifdef OPENMC_DAGMC_ENABLED
171
  history().reset();
26,670,066✔
172
#endif
173

174
  // Copy attributes from source bank site
175
  type() = src->particle;
291,592,977✔
176
  wgt() = src->wgt;
291,592,977✔
177
  wgt_last() = src->wgt;
291,592,977✔
178
  r() = src->r;
291,592,977✔
179
  u() = src->u;
291,592,977✔
180
  r_born() = src->r;
291,592,977✔
181
  r_last_current() = src->r;
291,592,977✔
182
  r_last() = src->r;
291,592,977✔
183
  u_last() = src->u;
291,592,977✔
184
  if (settings::run_CE) {
291,592,977✔
185
    E() = src->E;
174,738,113✔
186
    g() = 0;
174,738,113✔
187
  } else {
188
    g() = static_cast<int>(src->E);
116,854,864✔
189
    g_last() = static_cast<int>(src->E);
116,854,864✔
190
    E() = data::mg.energy_bin_avg_[g()];
116,854,864✔
191
  }
192
  E_last() = E();
291,592,977✔
193
  time() = src->time;
291,592,977✔
194
  time_last() = src->time;
291,592,977✔
195
  parent_nuclide() = src->parent_nuclide;
291,592,977✔
196
  delayed_group() = src->delayed_group;
291,592,977✔
197

198
  // Convert signed surface ID to signed index
199
  if (src->surf_id != SURFACE_NONE) {
291,592,977✔
200
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
113,872✔
201
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
113,872✔
202
  }
203

204
  wgt_born() = src->wgt_born;
291,592,977✔
205
  wgt_ww_born() = src->wgt_ww_born;
291,592,977✔
206
  n_split() = src->n_split;
291,592,977✔
207
}
291,592,977✔
208

209
void Particle::event_calculate_xs()
2,147,483,647✔
210
{
211
  // Set the random number stream
212
  stream() = STREAM_TRACKING;
2,147,483,647✔
213

214
  // Store pre-collision particle properties
215
  wgt_last() = wgt();
2,147,483,647✔
216
  E_last() = E();
2,147,483,647✔
217
  u_last() = u();
2,147,483,647✔
218
  r_last() = r();
2,147,483,647✔
219
  time_last() = time();
2,147,483,647✔
220

221
  // Reset event variables
222
  event() = TallyEvent::KILL;
2,147,483,647✔
223
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
224
  event_mt() = REACTION_NONE;
2,147,483,647✔
225

226
  // If the cell hasn't been determined based on the particle's location,
227
  // initiate a search for the current cell. This generally happens at the
228
  // beginning of the history and again for any secondary particles
229
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
230
    if (!exhaustive_find_cell(*this)) {
282,535,022!
UNCOV
231
      mark_as_lost(
×
UNCOV
232
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
233
      return;
×
234
    }
235

236
    // Set birth cell attribute
237
    if (cell_born() == C_NONE)
282,535,022!
238
      cell_born() = lowest_coord().cell();
282,535,022✔
239

240
    // Initialize last cells from current cell
241
    for (int j = 0; j < n_coord(); ++j) {
582,465,463✔
242
      cell_last(j) = coord(j).cell();
299,930,441✔
243
    }
244
    n_coord_last() = n_coord();
282,535,022✔
245
  }
246

247
  // Write particle track.
248
  if (write_track())
2,147,483,647✔
249
    write_particle_track(*this);
10,313✔
250

251
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
252
    check_cell_overlap(*this);
×
253

254
  // Calculate microscopic and macroscopic cross sections
255
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
256
    if (settings::run_CE) {
2,147,483,647✔
257
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
258
          density_mult() != density_mult_last()) {
904,071,173✔
259
        // If the material is the same as the last material and the
260
        // temperature hasn't changed, we don't need to lookup cross
261
        // sections again.
262
        model::materials[material()]->calculate_xs(*this);
2,147,483,647✔
263
      }
264
    } else {
265
      // Get the MG data; unlike the CE case above, we have to re-calculate
266
      // cross sections for every collision since the cross sections may
267
      // be angle-dependent
268
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,081,363,801✔
269

270
      // Update the particle's group while we know we are multi-group
271
      g_last() = g();
2,081,363,801✔
272
    }
273
  } else {
274
    macro_xs().total = 0.0;
111,895,122✔
275
    macro_xs().absorption = 0.0;
111,895,122✔
276
    macro_xs().fission = 0.0;
111,895,122✔
277
    macro_xs().nu_fission = 0.0;
111,895,122✔
278
  }
279
}
280

281
void Particle::event_advance()
2,147,483,647✔
282
{
283
  // Find the distance to the nearest boundary
284
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
285

286
  // Sample a distance to collision
287
  if (type() == ParticleType::electron() ||
2,147,483,647✔
288
      type() == ParticleType::positron()) {
2,147,483,647✔
289
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
172,360,812!
290
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
291
    collision_distance() = INFINITY;
111,895,122✔
292
  } else {
293
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
294
  }
295

296
  double speed = this->speed();
2,147,483,647✔
297
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
298
  double distance_cutoff =
2,147,483,647✔
299
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
300

301
  // Select smaller of the three distances
302
  double distance =
2,147,483,647✔
303
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
304

305
  // Advance particle in space and time
306
  this->move_distance(distance);
2,147,483,647✔
307
  double dt = distance / speed;
2,147,483,647✔
308
  this->time() += dt;
2,147,483,647✔
309
  this->lifetime() += dt;
2,147,483,647✔
310

311
  // Score timed track-length tallies
312
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
313
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
314
  }
315

316
  // Score track-length tallies
317
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
318
    score_tracklength_tally(*this, distance);
2,147,483,647✔
319
  }
320

321
  // Score track-length estimate of k-eff
322
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
323
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
324
  }
325

326
  // Score flux derivative accumulators for differential tallies.
327
  if (!model::active_tallies.empty()) {
2,147,483,647✔
328
    score_track_derivative(*this, distance);
2,147,483,647✔
329
  }
330

331
  // Set particle weight to zero if it hit the time boundary
332
  if (distance == distance_cutoff) {
2,147,483,647✔
333
    wgt() = 0.0;
224,928✔
334
  }
335
}
2,147,483,647✔
336

337
void Particle::event_cross_surface()
2,147,483,647✔
338
{
339
  // Saving previous cell data
340
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
341
    cell_last(j) = coord(j).cell();
2,147,483,647✔
342
  }
343
  n_coord_last() = n_coord();
2,147,483,647✔
344

345
  // Set surface that particle is on and adjust coordinate levels
346
  surface() = boundary().surface();
2,147,483,647✔
347
  n_coord() = boundary().coord_level();
2,147,483,647✔
348

349
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
350
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
351
      boundary().lattice_translation()[2] != 0) {
2,147,483,647✔
352
    // Particle crosses lattice boundary
353

354
    bool verbose = settings::verbosity >= 10 || trace();
801,265,648!
355
    cross_lattice(*this, boundary(), verbose);
801,265,648✔
356
    event() = TallyEvent::LATTICE;
801,265,648✔
357

358
    // Score cell to cell partial currents
359
    if (!model::active_surface_tallies.empty()) {
801,265,648!
UNCOV
360
      auto& lat {*model::lattices[lowest_coord().lattice()]};
×
UNCOV
361
      bool is_valid;
×
UNCOV
362
      Direction normal =
×
UNCOV
363
        lat.get_normal(boundary().lattice_translation(), is_valid);
×
UNCOV
364
      if (is_valid) {
×
UNCOV
365
        normal /= normal.norm();
×
UNCOV
366
        score_surface_tally(*this, model::active_surface_tallies, normal);
×
367
      }
368
    }
369

370
  } else {
371

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

374
    // Particle crosses surface
375
    // If BC, add particle to surface source before crossing surface
376
    if (surf.surf_source_ && surf.bc_) {
2,147,483,647✔
377
      add_surf_source_to_bank(*this, surf);
1,008,709,119✔
378
    }
379
    this->cross_surface(surf);
2,147,483,647✔
380
    // If no BC, add particle to surface source after crossing surface
381
    if (surf.surf_source_ && !surf.bc_) {
2,147,483,647✔
382
      add_surf_source_to_bank(*this, surf);
1,853,283,576✔
383
    }
384
    if (settings::weight_window_checkpoint_surface) {
2,147,483,647✔
385
      apply_weight_windows(*this);
173,985✔
386
    }
387
    event() = TallyEvent::SURFACE;
2,147,483,647✔
388

389
    // Score cell to cell partial currents
390
    if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
391
      Direction normal = surf.normal(r());
34,931,567✔
392
      normal /= normal.norm();
34,931,567✔
393
      score_surface_tally(*this, model::active_surface_tallies, normal);
34,931,567✔
394
    }
395
  }
396
}
2,147,483,647✔
397

398
void Particle::event_collide()
2,147,483,647✔
399
{
400

401
  // Score collision estimate of keff
402
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
403
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,147,483,647✔
404
  }
405

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

410
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
411
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
412

413
  // Clear surface component
414
  surface() = SURFACE_NONE;
2,147,483,647✔
415

416
  if (settings::run_CE) {
2,147,483,647✔
417
    collision(*this);
1,462,242,958✔
418
  } else {
419
    collision_mg(*this);
1,800,818,030✔
420
  }
421

422
  // Collision track feature to recording particle interaction
423
  if (settings::collision_track) {
2,147,483,647✔
424
    collision_track_record(*this);
150,087✔
425
  }
426

427
  // Score collision estimator tallies -- this is done after a collision
428
  // has occurred rather than before because we need information on the
429
  // outgoing energy for any tallies with an outgoing energy filter
430
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
431
    score_collision_tally(*this);
108,960,852✔
432
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
433
    if (settings::run_CE) {
406,059,376✔
434
      score_analog_tally_ce(*this);
404,851,114✔
435
    } else {
436
      score_analog_tally_mg(*this);
1,208,262✔
437
    }
438
  }
439

440
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
441
    pht_collision_energy();
8,096✔
442
  }
443

444
  // Reset banked weight during collision
445
  n_bank() = 0;
2,147,483,647✔
446
  bank_second_E() = 0.0;
2,147,483,647✔
447
  wgt_bank() = 0.0;
2,147,483,647✔
448

449
  // Clear number of secondaries in this collision. This is
450
  // distinct from the number of created neutrons n_bank() above!
451
  n_secondaries() = 0;
2,147,483,647✔
452

453
  zero_delayed_bank();
2,147,483,647✔
454

455
  // Reset fission logical
456
  fission() = false;
2,147,483,647✔
457

458
  // Save coordinates for tallying purposes
459
  r_last_current() = r();
2,147,483,647✔
460

461
  // Set last material to none since cross sections will need to be
462
  // re-evaluated
463
  material_last() = C_NONE;
2,147,483,647✔
464

465
  // Set all directions to base level -- right now, after a collision, only
466
  // the base level directions are changed
467
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
468
    if (coord(j + 1).rotated()) {
286,650,778✔
469
      // If next level is rotated, apply rotation matrix
470
      const auto& m {model::cells[coord(j).cell()]->rotation_};
11,724,229✔
471
      const auto& u {coord(j).u()};
11,724,229✔
472
      coord(j + 1).u() = u.rotate(m);
11,724,229✔
473
    } else {
474
      // Otherwise, copy this level's direction
475
      coord(j + 1).u() = coord(j).u();
274,926,549✔
476
    }
477
  }
478

479
  // Score flux derivative accumulators for differential tallies.
480
  if (!model::active_tallies.empty())
2,147,483,647✔
481
    score_collision_derivative(*this);
1,300,634,074✔
482

483
#ifdef OPENMC_DAGMC_ENABLED
484
  history().reset();
298,418,539✔
485
#endif
486
}
2,147,483,647✔
487

488
void Particle::event_revive_from_secondary(const SourceSite& site)
104,751,661✔
489
{
490
  // Write final position for the previous track (skip if this is a freshly
491
  // constructed particle with no prior track, e.g., Phase 2 of shared
492
  // secondary transport)
493
  if (write_track() && n_event() > 0) {
104,751,661!
494
    write_particle_track(*this);
5,234✔
495
  }
496

497
  from_source(&site);
104,751,661✔
498

499
  n_event() = 0;
104,751,661✔
500
  if (!settings::use_shared_secondary_bank) {
104,751,661✔
501
    n_tracks()++;
83,391,115✔
502
  }
503
  bank_second_E() = 0.0;
104,751,661✔
504

505
  // Subtract secondary particle energy from interim pulse-height results.
506
  // In shared secondary mode, this subtraction was already done on the parent
507
  // particle during create_secondary(), so skip it here.
508
  if (!settings::use_shared_secondary_bank &&
188,142,776✔
509
      !model::active_pulse_height_tallies.empty() && this->type().is_photon()) {
104,751,661✔
510
    // Since the birth cell of the particle has not been set we
511
    // have to determine it before the energy of the secondary particle can be
512
    // removed from the pulse-height of this cell.
513
    if (lowest_coord().cell() == C_NONE) {
2,420!
514
      bool verbose = settings::verbosity >= 10 || trace();
2,420!
515
      if (!exhaustive_find_cell(*this, verbose)) {
2,420!
NEW
516
        mark_as_lost("Could not find the cell containing particle " +
×
NEW
517
                     std::to_string(id()));
×
NEW
518
        return;
×
519
      }
520
      // Set birth cell attribute
521
      if (cell_born() == C_NONE)
2,420!
522
        cell_born() = lowest_coord().cell();
2,420✔
523

524
      // Initialize last cells from current cell
525
      for (int j = 0; j < n_coord(); ++j) {
4,840✔
526
        cell_last(j) = coord(j).cell();
2,420✔
527
      }
528
      n_coord_last() = n_coord();
2,420✔
529
    }
530
    pht_secondary_particles();
2,420✔
531
  }
532

533
  // Enter new particle in particle track file
534
  if (write_track())
104,751,661✔
535
    add_particle_track(*this);
5,234✔
536
}
537

538
void Particle::event_check_limit_and_revive()
2,147,483,647✔
539
{
540
  // If particle has too many events, display warning and kill it
541
  n_event()++;
2,147,483,647✔
542
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
NEW
543
    warning("Particle " + std::to_string(id()) +
×
544
            " underwent maximum number of events.");
NEW
545
    wgt() = 0.0;
×
546
  }
547

548
  // In non-shared-secondary mode, revive from local secondary bank
549
  if (!alive() && !settings::use_shared_secondary_bank &&
2,147,483,647✔
550
      !local_secondary_bank().empty()) {
260,391,391✔
551
    SourceSite& site = local_secondary_bank().back();
83,391,115✔
552
    event_revive_from_secondary(site);
83,391,115✔
553
    local_secondary_bank().pop_back();
83,391,115✔
554
  }
555
}
2,147,483,647✔
556

557
void Particle::event_death()
199,146,318✔
558
{
559
#ifdef OPENMC_DAGMC_ENABLED
560
  history().reset();
18,184,051✔
561
#endif
562

563
  // Finish particle track output.
564
  if (write_track()) {
199,146,318✔
565
    write_particle_track(*this);
1,010✔
566
    finalize_particle_track(*this);
1,010✔
567
  }
568

569
// Contribute tally reduction variables to global accumulator
570
#pragma omp atomic
109,307,189✔
571
  global_tally_absorption += keff_tally_absorption();
199,146,318✔
572
#pragma omp atomic
108,920,787✔
573
  global_tally_collision += keff_tally_collision();
199,146,318✔
574
#pragma omp atomic
108,997,585✔
575
  global_tally_tracklength += keff_tally_tracklength();
199,146,318✔
576
#pragma omp atomic
109,025,865✔
577
  global_tally_leakage += keff_tally_leakage();
199,146,318✔
578

579
  // Reset particle tallies once accumulated
580
  keff_tally_absorption() = 0.0;
199,146,318✔
581
  keff_tally_collision() = 0.0;
199,146,318✔
582
  keff_tally_tracklength() = 0.0;
199,146,318✔
583
  keff_tally_leakage() = 0.0;
199,146,318✔
584

585
  if (!model::active_pulse_height_tallies.empty()) {
199,146,318✔
586
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
22,000✔
587
  }
588

589
  // Accumulate track count for this particle history
590
  if (!settings::use_shared_secondary_bank) {
199,146,318✔
591
#pragma omp atomic
96,640,116✔
592
    simulation::simulation_tracks_completed += n_tracks();
177,001,276✔
593
  }
594

595
  // Record the number of progeny created by this particle.
596
  // This data will be used to efficiently sort the fission bank.
597
  if (settings::run_mode == RunMode::EIGENVALUE ||
199,146,318✔
598
      settings::use_shared_secondary_bank) {
599
    simulation::progeny_per_particle[current_work()] = n_progeny();
172,069,742✔
600
  }
601
}
199,146,318✔
602

603
void Particle::pht_collision_energy()
8,096✔
604
{
605
  // Adds the energy particles lose in a collision to the pulse-height
606

607
  // determine index of cell in pulse_height_cells
608
  auto it = std::find(model::pulse_height_cells.begin(),
8,096✔
609
    model::pulse_height_cells.end(), lowest_coord().cell());
8,096!
610

611
  if (it != model::pulse_height_cells.end()) {
8,096!
612
    int index = std::distance(model::pulse_height_cells.begin(), it);
8,096✔
613
    pht_storage()[index] += E_last() - E();
8,096✔
614

615
    // If the energy of the particle is below the cutoff, it will not be sampled
616
    // so its energy is added to the pulse-height in the cell
617
    int photon = ParticleType::photon().transport_index();
8,096✔
618
    if (E() < settings::energy_cutoff[photon]) {
8,096✔
619
      pht_storage()[index] += E();
3,300✔
620
    }
621
  }
622
}
8,096✔
623

624
void Particle::pht_secondary_particles()
2,420✔
625
{
626
  // Removes the energy of secondary produced particles from the pulse-height
627

628
  // determine index of cell in pulse_height_cells
629
  auto it = std::find(model::pulse_height_cells.begin(),
2,420✔
630
    model::pulse_height_cells.end(), cell_born());
2,420!
631

632
  if (it != model::pulse_height_cells.end()) {
2,420!
633
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,420✔
634
    pht_storage()[index] -= E();
2,420✔
635
  }
636
}
2,420✔
637

638
void Particle::cross_surface(const Surface& surf)
2,147,483,647✔
639
{
640

641
  if (settings::verbosity >= 10 || trace()) {
2,147,483,647✔
642
    write_message(1, "    Crossing surface {}", surf.id_);
88✔
643
  }
644

645
// if we're crossing a CSG surface, make sure the DAG history is reset
646
#ifdef OPENMC_DAGMC_ENABLED
647
  if (surf.geom_type() == GeometryType::CSG)
260,853,559✔
648
    history().reset();
260,795,877✔
649
#endif
650

651
  // Handle any applicable boundary conditions.
652
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
653
      settings::run_mode != RunMode::VOLUME) {
654
    surf.bc_->handle_particle(*this, surf);
1,009,061,227✔
655
    return;
1,009,061,227✔
656
  }
657

658
  // ==========================================================================
659
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
660

661
#ifdef OPENMC_DAGMC_ENABLED
662
  // in DAGMC, we know what the next cell should be
663
  if (surf.geom_type() == GeometryType::DAG) {
168,759,031✔
664
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,742✔
665
                       lowest_coord().universe()) -
46,742✔
666
                     1;
46,742✔
667
    // save material, temperature, and density multiplier
668
    material_last() = material();
46,742✔
669
    sqrtkT_last() = sqrtkT();
46,742✔
670
    density_mult_last() = density_mult();
46,742✔
671
    // set new cell value
672
    lowest_coord().cell() = i_cell;
46,742✔
673
    auto& cell = model::cells[i_cell];
46,742✔
674

675
    cell_instance() = 0;
46,742✔
676
    if (cell->distribcell_index_ >= 0)
46,742✔
677
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,718✔
678

679
    material() = cell->material(cell_instance());
46,742!
680
    sqrtkT() = cell->sqrtkT(cell_instance());
46,742!
681
    density_mult() = cell->density_mult(cell_instance());
46,742✔
682
    return;
46,742✔
683
  }
684
#endif
685

686
  bool verbose = settings::verbosity >= 10 || trace();
1,856,098,034!
687
  if (neighbor_list_find_cell(*this, verbose)) {
1,856,098,034✔
688
    return;
689
  }
690

691
  // ==========================================================================
692
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
693

694
  // Remove lower coordinate levels
695
  n_coord() = 1;
29,977✔
696
  bool found = exhaustive_find_cell(*this, verbose);
29,977✔
697

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

704
    surface() = SURFACE_NONE;
5,865✔
705
    n_coord() = 1;
5,865✔
706
    r() += TINY_BIT * u();
5,865✔
707

708
    // Couldn't find next cell anywhere! This probably means there is an actual
709
    // undefined region in the geometry.
710

711
    if (!exhaustive_find_cell(*this, verbose)) {
5,865!
712
      mark_as_lost("After particle " + std::to_string(id()) +
17,586✔
713
                   " crossed surface " + std::to_string(surf.id_) +
17,586✔
714
                   " it could not be located in any cell and it did not leak.");
715
      return;
5,856✔
716
    }
717
  }
718
}
719

720
void Particle::cross_vacuum_bc(const Surface& surf)
37,290,466✔
721
{
722
  // Score any surface current tallies -- note that the particle is moved
723
  // forward slightly so that if the mesh boundary is on the surface, it is
724
  // still processed
725

726
  if (!model::active_meshsurf_tallies.empty()) {
37,290,466✔
727
    // TODO: Find a better solution to score surface currents than
728
    // physically moving the particle forward slightly
729

730
    r() += TINY_BIT * u();
937,222✔
731
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
732
  }
733

734
  // Score to global leakage tally
735
  keff_tally_leakage() += wgt();
37,290,466✔
736

737
  // Kill the particle
738
  wgt() = 0.0;
37,290,466✔
739

740
  // Display message
741
  if (settings::verbosity >= 10 || trace()) {
37,290,466!
742
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
743
  }
744
}
37,290,466✔
745

746
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
970,530,432✔
747
{
748
  // Do not handle reflective boundary conditions on lower universes
749
  if (n_coord() != 1) {
970,530,432!
UNCOV
750
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
751
                 " off surface in a lower universe.");
UNCOV
752
    return;
×
753
  }
754

755
  // Score surface currents since reflection causes the direction of the
756
  // particle to change. For surface filters, we need to score the tallies
757
  // twice, once before the particle's surface attribute has changed and
758
  // once after. For mesh surface filters, we need to artificially move
759
  // the particle slightly back in case the surface crossing is coincident
760
  // with a mesh boundary
761

762
  if (!model::active_surface_tallies.empty()) {
970,530,432✔
763
    Direction normal = surf.normal(r());
285,021✔
764
    normal /= normal.norm();
285,021✔
765
    score_surface_tally(*this, model::active_surface_tallies, normal);
285,021✔
766
  }
767

768
  if (!model::active_meshsurf_tallies.empty()) {
970,530,432✔
769
    Position r {this->r()};
46,885,487✔
770
    this->r() -= TINY_BIT * u();
46,885,487✔
771
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
772
    this->r() = r;
46,885,487✔
773
  }
774

775
  // Set the new particle direction
776
  u() = new_u;
970,530,432✔
777

778
  // Reassign particle's cell and surface
779
  coord(0).cell() = cell_last(0);
970,530,432✔
780
  surface() = -surface();
970,530,432✔
781

782
  // If a reflective surface is coincident with a lattice or universe
783
  // boundary, it is necessary to redetermine the particle's coordinates in
784
  // the lower universes.
785
  // (unless we're using a dagmc model, which has exactly one universe)
786
  n_coord() = 1;
970,530,432✔
787
  if (surf.geom_type() != GeometryType::DAG &&
1,941,058,106!
788
      !neighbor_list_find_cell(*this)) {
970,527,674✔
UNCOV
789
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
790
                 std::to_string(surf.id_) + ".");
×
UNCOV
791
    return;
×
792
  }
793

794
  // Set previous coordinate going slightly past surface crossing
795
  r_last_current() = r() + TINY_BIT * u();
970,530,432✔
796

797
  // Diagnostic message
798
  if (settings::verbosity >= 10 || trace()) {
970,530,432!
UNCOV
799
    write_message(1, "    Reflected from surface {}", surf.id_);
×
800
  }
801
}
802

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

815
  // Score surface currents since reflection causes the direction of the
816
  // particle to change -- artificially move the particle slightly back in
817
  // case the surface crossing is coincident with a mesh boundary
818
  if (!model::active_meshsurf_tallies.empty()) {
2,245,795!
UNCOV
819
    Position r {this->r()};
×
UNCOV
820
    this->r() -= TINY_BIT * u();
×
UNCOV
821
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
822
    this->r() = r;
×
823
  }
824

825
  // Adjust the particle's location and direction.
826
  r() = new_r;
2,245,795✔
827
  u() = new_u;
2,245,795✔
828

829
  // Reassign particle's surface
830
  surface() = new_surface;
2,245,795✔
831

832
  // Figure out what cell particle is in now
833
  n_coord() = 1;
2,245,795✔
834

835
  if (!neighbor_list_find_cell(*this)) {
2,245,795!
UNCOV
836
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
837
                 "boundary on surface " +
×
UNCOV
838
                 std::to_string(surf.id_) + ".");
×
UNCOV
839
    return;
×
840
  }
841

842
  // Set previous coordinate going slightly past surface crossing
843
  r_last_current() = r() + TINY_BIT * u();
2,245,795✔
844

845
  // Diagnostic message
846
  if (settings::verbosity >= 10 || trace()) {
2,245,795!
UNCOV
847
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
848
  }
849
}
850

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

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

868
  // Abort the simulation if the maximum number of lost particles has been
869
  // reached
870
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,865✔
871
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
872
    fatal_error("Maximum number of lost particles has been reached.");
9✔
873
  }
874
}
5,856✔
875

876
void Particle::write_restart() const
440✔
877
{
878
  // Dont write another restart file if in particle restart mode
879
  if (settings::run_mode == RunMode::PARTICLE)
440✔
880
    return;
33✔
881

882
  // Set up file name
883
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
407✔
884
    simulation::current_batch, id());
407✔
885

886
#pragma omp critical(WriteParticleRestart)
217✔
887
  {
407✔
888
    // Create file
889
    hid_t file_id = file_open(filename, 'w');
407✔
890

891
    // Write filetype and version info
892
    write_attribute(file_id, "filetype", "particle restart");
407✔
893
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
407✔
894
    write_attribute(file_id, "openmc_version", VERSION);
407✔
895
#ifdef GIT_SHA1
896
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
897
#endif
898

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

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

942
    // Close file
943
    file_close(file_id);
407✔
944
  } // #pragma omp critical
945
}
407✔
946

947
void Particle::update_neutron_xs(
2,147,483,647✔
948
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
949
{
950
  // Get microscopic cross section cache
951
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
952

953
  // If the cache doesn't match, recalculate micro xs
954
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
955
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
956
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
957
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
958

959
    // If NCrystal is being used, update micro cross section cache
960
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
961
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
962
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
963
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
964
    }
965
  }
966
}
2,147,483,647✔
967

968
//==============================================================================
969
// Non-method functions
970
//==============================================================================
971
void add_surf_source_to_bank(Particle& p, const Surface& surf)
2,147,483,647✔
972
{
973
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
974
      simulation::surf_source_bank.full()) {
2,147,483,647✔
975
    return;
2,147,483,647✔
976
  }
977

978
  // If a cell/cellfrom/cellto parameter is defined
979
  if (settings::ssw_cell_id != C_NONE) {
337,081✔
980

981
    // Retrieve cell index and storage type
982
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,436✔
983

984
    if (surf.bc_) {
254,436✔
985
      // Leave if cellto with vacuum boundary condition
986
      if (surf.bc_->type() == "vacuum" &&
298,918✔
987
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
988
        return;
989
      }
990

991
      // Leave if other boundary condition than vacuum
992
      if (surf.bc_->type() != "vacuum") {
274,648✔
993
        return;
994
      }
995
    }
996

997
    // Check if the cell of interest has been exited
998
    bool exited = false;
999
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,671✔
1000
      if (p.cell_last(i) == cell_idx) {
207,730✔
1001
        exited = true;
73,764✔
1002
      }
1003
    }
1004

1005
    // Check if the cell of interest has been entered
1006
    bool entered = false;
1007
    for (int i = 0; i < p.n_coord(); ++i) {
297,973✔
1008
      if (p.coord(i).cell() == cell_idx) {
172,032✔
1009
        entered = true;
57,517✔
1010
      }
1011
    }
1012

1013
    // Vacuum boundary conditions: return if cell is not exited
1014
    if (surf.bc_) {
125,941✔
1015
      if (surf.bc_->type() == "vacuum" && !exited) {
41,928!
1016
        return;
1017
      }
1018
    } else {
1019

1020
      // If we both enter and exit the cell of interest
1021
      if (entered && exited) {
104,977✔
1022
        return;
1023
      }
1024

1025
      // If we did not enter nor exit the cell of interest
1026
      if (!entered && !exited) {
77,774✔
1027
        return;
1028
      }
1029

1030
      // If cellfrom and the cell before crossing is not the cell of
1031
      // interest
1032
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,275✔
1033
        return;
1034
      }
1035

1036
      // If cellto and the cell after crossing is not the cell of interest
1037
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,732✔
1038
        return;
1039
      }
1040
    }
1041
  }
1042

1043
  SourceSite site;
129,653✔
1044
  site.r = p.r();
129,653✔
1045
  site.u = p.u();
129,653✔
1046
  site.E = p.E();
129,653✔
1047
  site.time = p.time();
129,653✔
1048
  site.wgt = p.wgt();
129,653✔
1049
  site.delayed_group = p.delayed_group();
129,653✔
1050
  site.surf_id = surf.id_;
129,653✔
1051
  site.particle = p.type();
129,653✔
1052
  site.parent_id = p.id();
129,653✔
1053
  site.progeny_id = p.n_progeny();
129,653✔
1054
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1055
}
1056

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