• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In
Build has been canceled!

openmc-dev / openmc / 21552992812

31 Jan 2026 11:54PM UTC coverage: 82.001% (+0.02%) from 81.979%
21552992812

Pull #3547

github

web-flow
Merge 6e8322eaa into 6041ee6ae
Pull Request #3547: Tally spectrum of secondary particles

17302 of 24061 branches covered (71.91%)

Branch coverage included in aggregate %.

69 of 71 new or added lines in 10 files covered. (97.18%)

640 existing lines in 11 files now uncovered.

55850 of 65148 relevant lines covered (85.73%)

49122667.73 hits per line

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

85.2
/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;
51
    switch (this->type()) {
2,147,483,647!
52
    case ParticleType::neutron:
2,127,011,927✔
53
      mass = MASS_NEUTRON_EV;
2,127,011,927✔
54
      break;
2,127,011,927✔
55
    case ParticleType::photon:
121,775,331✔
56
      mass = 0.0;
121,775,331✔
57
      break;
121,775,331✔
58
    case ParticleType::electron:
867,174,049✔
59
    case ParticleType::positron:
60
      mass = MASS_ELECTRON_EV;
867,174,049✔
61
      break;
867,174,049✔
62
    }
63
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
64
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,147,483,647✔
65
           (this->E() + mass);
2,147,483,647✔
66
  } else {
67
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
68
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
69
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
70
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
71
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
72
  }
73
}
74

75
bool Particle::create_secondary(
1,821,338,112✔
76
  double wgt, Direction u, double E, ParticleType type)
77
{
78
  // If energy is below cutoff for this particle, don't create secondary
79
  // particle
80
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
1,821,338,112✔
81
    return false;
865,991,745✔
82
  }
83

84
  auto& bank = secondary_bank().emplace_back();
955,346,367✔
85
  bank.particle = type;
955,346,367✔
86
  bank.wgt = wgt;
955,346,367✔
87
  bank.r = r();
955,346,367✔
88
  bank.u = u;
955,346,367✔
89
  bank.E = settings::run_CE ? E : g();
955,346,367!
90
  bank.time = time();
955,346,367✔
91
  bank_second_E() += bank.E;
955,346,367✔
92

93
  // Score tallies affected by secondary particles
94
  if (!model::active_particleout_analog_tallies.empty()) {
955,346,367✔
95
    // Create secondary particle for tallying purposes only
96
    Particle tmp;
897,135,734✔
97
    tmp.from_source(&bank);
897,135,734✔
98
    tmp.u_last() = this->u();
897,135,734✔
99
    tmp.r_last() = this->r();
897,135,734✔
100
    tmp.E_last() = this->E();
897,135,734✔
101
    tmp.type_last() = this->type();
897,135,734✔
102

103
    // Load geometry info
104
    if (!exhaustive_find_cell(tmp))
897,135,734!
NEW
105
      fatal_error("Cannot find temporary particle in model.");
×
106

107
    if (settings::run_CE) {
897,135,734!
108
      score_analog_tally_ce(tmp, model::active_particleout_analog_tallies);
897,135,734✔
109
    } else {
NEW
110
      score_analog_tally_mg(tmp, model::active_particleout_analog_tallies);
×
111
    }
112
  }
897,135,734✔
113
  return true;
955,346,367✔
114
}
115

116
void Particle::split(double wgt)
4,087,375✔
117
{
118
  auto& bank = secondary_bank().emplace_back();
4,087,375✔
119
  bank.particle = type();
4,087,375✔
120
  bank.wgt = wgt;
4,087,375✔
121
  bank.r = r();
4,087,375✔
122
  bank.u = u();
4,087,375✔
123
  bank.E = settings::run_CE ? E() : g();
4,087,375✔
124
  bank.time = time();
4,087,375✔
125

126
  // Convert signed index to a signed surface ID
127
  if (surface() == SURFACE_NONE) {
4,087,375✔
128
    bank.surf_id = SURFACE_NONE;
4,087,039✔
129
  } else {
130
    int surf_id = model::surfaces[surface_index()]->id_;
336✔
131
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
336!
132
  }
133
}
4,087,375✔
134

135
void Particle::from_source(const SourceSite* src)
2,034,180,117✔
136
{
137
  // Reset some attributes
138
  clear();
2,034,180,117✔
139
  surface() = SURFACE_NONE;
2,034,180,117✔
140
  cell_born() = C_NONE;
2,034,180,117✔
141
  material() = C_NONE;
2,034,180,117✔
142
  n_collision() = 0;
2,034,180,117✔
143
  fission() = false;
2,034,180,117✔
144
  zero_flux_derivs();
2,034,180,117✔
145
  lifetime() = 0.0;
2,034,180,117✔
146
#ifdef OPENMC_DAGMC_ENABLED
147
  history().reset();
185,085,925✔
148
#endif
149

150
  // Copy attributes from source bank site
151
  type() = src->particle;
2,034,180,117✔
152
  type_last() = src->particle;
2,034,180,117✔
153
  wgt() = src->wgt;
2,034,180,117✔
154
  wgt_last() = src->wgt;
2,034,180,117✔
155
  r() = src->r;
2,034,180,117✔
156
  u() = src->u;
2,034,180,117✔
157
  r_born() = src->r;
2,034,180,117✔
158
  r_last_current() = src->r;
2,034,180,117✔
159
  r_last() = src->r;
2,034,180,117✔
160
  u_last() = src->u;
2,034,180,117✔
161
  if (settings::run_CE) {
2,034,180,117✔
162
    E() = src->E;
1,918,441,500✔
163
    g() = 0;
1,918,441,500✔
164
  } else {
165
    g() = static_cast<int>(src->E);
115,738,617✔
166
    g_last() = static_cast<int>(src->E);
115,738,617✔
167
    E() = data::mg.energy_bin_avg_[g()];
115,738,617✔
168
  }
169
  E_last() = E();
2,034,180,117✔
170
  time() = src->time;
2,034,180,117✔
171
  time_last() = src->time;
2,034,180,117✔
172
  parent_nuclide() = src->parent_nuclide;
2,034,180,117✔
173
  delayed_group() = src->delayed_group;
2,034,180,117✔
174

175
  // Convert signed surface ID to signed index
176
  if (src->surf_id != SURFACE_NONE) {
2,034,180,117✔
177
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,336✔
178
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,336!
179
  }
180
}
2,034,180,117✔
181

182
void Particle::event_calculate_xs()
2,147,483,647✔
183
{
184
  // Set the random number stream
185
  stream() = STREAM_TRACKING;
2,147,483,647✔
186

187
  // Store pre-collision particle properties
188
  wgt_last() = wgt();
2,147,483,647✔
189
  E_last() = E();
2,147,483,647✔
190
  type_last() = type();
2,147,483,647✔
191
  u_last() = u();
2,147,483,647✔
192
  r_last() = r();
2,147,483,647✔
193
  time_last() = time();
2,147,483,647✔
194

195
  // Reset event variables
196
  event() = TallyEvent::KILL;
2,147,483,647✔
197
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
198
  event_mt() = REACTION_NONE;
2,147,483,647✔
199

200
  // If the cell hasn't been determined based on the particle's location,
201
  // initiate a search for the current cell. This generally happens at the
202
  // beginning of the history and again for any secondary particles
203
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
204
    if (!exhaustive_find_cell(*this)) {
1,128,560,474!
205
      mark_as_lost(
×
206
        "Could not find the cell containing particle " + std::to_string(id()));
×
207
      return;
×
208
    }
209

210
    // Set birth cell attribute
211
    if (cell_born() == C_NONE)
1,128,560,474!
212
      cell_born() = lowest_coord().cell();
1,128,560,474✔
213

214
    // Initialize last cells from current cell
215
    for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
216
      cell_last(j) = coord(j).cell();
1,145,585,246✔
217
    }
218
    n_coord_last() = n_coord();
1,128,560,474✔
219
  }
220

221
  // Write particle track.
222
  if (write_track())
2,147,483,647✔
223
    write_particle_track(*this);
10,816✔
224

225
  if (settings::check_overlaps)
2,147,483,647!
226
    check_cell_overlap(*this);
×
227

228
  // Calculate microscopic and macroscopic cross sections
229
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
230
    if (settings::run_CE) {
2,147,483,647✔
231
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
232
          density_mult() != density_mult_last()) {
365,033,226✔
233
        // If the material is the same as the last material and the
234
        // temperature hasn't changed, we don't need to lookup cross
235
        // sections again.
236
        model::materials[material()]->calculate_xs(*this);
2,147,483,647✔
237
      }
238
    } else {
239
      // Get the MG data; unlike the CE case above, we have to re-calculate
240
      // cross sections for every collision since the cross sections may
241
      // be angle-dependent
242
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,063,937,414✔
243

244
      // Update the particle's group while we know we are multi-group
245
      g_last() = g();
2,063,937,414✔
246
    }
247
  } else {
248
    macro_xs().total = 0.0;
111,825,046✔
249
    macro_xs().absorption = 0.0;
111,825,046✔
250
    macro_xs().fission = 0.0;
111,825,046✔
251
    macro_xs().nu_fission = 0.0;
111,825,046✔
252
  }
253
}
254

255
void Particle::event_advance()
2,147,483,647✔
256
{
257
  // Find the distance to the nearest boundary
258
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
259

260
  // Sample a distance to collision
261
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
262
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
867,174,049!
263
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
264
    collision_distance() = INFINITY;
111,825,046✔
265
  } else {
266
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
267
  }
268

269
  double speed = this->speed();
2,147,483,647✔
270
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
271
  double distance_cutoff =
272
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
273

274
  // Select smaller of the three distances
275
  double distance =
276
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
277

278
  // Advance particle in space and time
279
  this->move_distance(distance);
2,147,483,647✔
280
  double dt = distance / speed;
2,147,483,647✔
281
  this->time() += dt;
2,147,483,647✔
282
  this->lifetime() += dt;
2,147,483,647✔
283

284
  // Score timed track-length tallies
285
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
286
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
287
  }
288

289
  // Score track-length tallies
290
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
291
    score_tracklength_tally(*this, distance);
1,562,522,730✔
292
  }
293

294
  // Score track-length estimate of k-eff
295
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
296
      type() == ParticleType::neutron) {
2,147,483,647✔
297
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
298
  }
299

300
  // Score flux derivative accumulators for differential tallies.
301
  if (!model::active_tallies.empty()) {
2,147,483,647✔
302
    score_track_derivative(*this, distance);
2,147,483,647✔
303
  }
304

305
  // Set particle weight to zero if it hit the time boundary
306
  if (distance == distance_cutoff) {
2,147,483,647✔
307
    wgt() = 0.0;
224,928✔
308
  }
309
}
2,147,483,647✔
310

311
void Particle::event_cross_surface()
2,147,483,647✔
312
{
313
  // Saving previous cell data
314
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
315
    cell_last(j) = coord(j).cell();
2,147,483,647✔
316
  }
317
  n_coord_last() = n_coord();
2,147,483,647✔
318

319
  // Set surface that particle is on and adjust coordinate levels
320
  surface() = boundary().surface();
2,147,483,647✔
321
  n_coord() = boundary().coord_level();
2,147,483,647✔
322

323
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
324
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
325
      boundary().lattice_translation()[2] != 0) {
1,695,549,035✔
326
    // Particle crosses lattice boundary
327

328
    bool verbose = settings::verbosity >= 10 || trace();
732,435,769!
329
    cross_lattice(*this, boundary(), verbose);
732,435,769✔
330
    event() = TallyEvent::LATTICE;
732,435,769✔
331
  } else {
332
    // Particle crosses surface
333
    const auto& surf {model::surfaces[surface_index()].get()};
1,507,007,151✔
334
    // If BC, add particle to surface source before crossing surface
335
    if (surf->surf_source_ && surf->bc_) {
1,507,007,151✔
336
      add_surf_source_to_bank(*this, *surf);
688,547,744✔
337
    }
338
    this->cross_surface(*surf);
1,507,007,151✔
339
    // If no BC, add particle to surface source after crossing surface
340
    if (surf->surf_source_ && !surf->bc_) {
1,507,007,142✔
341
      add_surf_source_to_bank(*this, *surf);
817,221,571✔
342
    }
343
    if (settings::weight_window_checkpoint_surface) {
1,507,007,142✔
344
      apply_weight_windows(*this);
10,738!
345
    }
346
    event() = TallyEvent::SURFACE;
1,507,007,142✔
347
  }
348
  // Score cell to cell partial currents
349
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
350
    score_surface_tally(*this, model::active_surface_tallies);
34,922,767✔
351
  }
352
}
2,147,483,647✔
353

354
void Particle::event_collide()
2,147,483,647✔
355
{
356
  // Score collision estimate of keff
357
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
358
      type() == ParticleType::neutron) {
2,147,483,647✔
359
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,125,060,208✔
360
  }
361

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

366
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
367
    score_surface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
368

369
  // Clear surface component
370
  surface() = SURFACE_NONE;
2,147,483,647✔
371

372
  if (settings::run_CE) {
2,147,483,647✔
373
    collision(*this);
1,945,719,531✔
374
  } else {
375
    collision_mg(*this);
1,783,060,477✔
376
  }
377

378
  // Collision track feature to recording particle interaction
379
  if (settings::collision_track) {
2,147,483,647✔
380
    collision_track_record(*this);
150,087✔
381
  }
382

383
  // Score collision estimator tallies -- this is done after a collision
384
  // has occurred rather than before because we need information on the
385
  // outgoing energy for any tallies with an outgoing energy filter
386
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
387
    score_collision_tally(*this);
107,049,793✔
388
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
389
    if (settings::run_CE) {
1,293,763,561✔
390
      score_analog_tally_ce(*this, model::active_analog_tallies);
1,292,555,299✔
391
    } else {
392
      score_analog_tally_mg(*this, model::active_analog_tallies);
1,208,262✔
393
    }
394
  }
395

396
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
397
      type() == ParticleType::photon) {
16,918✔
398
    pht_collision_energy();
2,024✔
399
  }
400

401
  // Reset banked weight during collision
402
  n_bank() = 0;
2,147,483,647✔
403
  bank_second_E() = 0.0;
2,147,483,647✔
404
  wgt_bank() = 0.0;
2,147,483,647✔
405
  zero_delayed_bank();
2,147,483,647✔
406

407
  // Reset fission logical
408
  fission() = false;
2,147,483,647✔
409

410
  // Save coordinates for tallying purposes
411
  r_last_current() = r();
2,147,483,647✔
412

413
  // Set last material to none since cross sections will need to be
414
  // re-evaluated
415
  material_last() = C_NONE;
2,147,483,647✔
416

417
  // Set all directions to base level -- right now, after a collision, only
418
  // the base level directions are changed
419
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
420
    if (coord(j + 1).rotated()) {
143,197,821✔
421
      // If next level is rotated, apply rotation matrix
422
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
423
      const auto& u {coord(j).u()};
10,426,614✔
424
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
425
    } else {
426
      // Otherwise, copy this level's direction
427
      coord(j + 1).u() = coord(j).u();
132,771,207✔
428
    }
429
  }
430

431
  // Score flux derivative accumulators for differential tallies.
432
  if (!model::active_tallies.empty())
2,147,483,647✔
433
    score_collision_derivative(*this);
1,818,075,055✔
434

435
#ifdef OPENMC_DAGMC_ENABLED
436
  history().reset();
341,126,064✔
437
#endif
438
}
2,147,483,647✔
439

440
void Particle::event_revive_from_secondary()
2,147,483,647✔
441
{
442
  // If particle has too many events, display warning and kill it
443
  ++n_event();
2,147,483,647✔
444
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
445
    warning("Particle " + std::to_string(id()) +
×
446
            " underwent maximum number of events.");
447
    wgt() = 0.0;
×
448
  }
449

450
  // Check for secondary particles if this particle is dead
451
  if (!alive()) {
2,147,483,647✔
452
    // Write final position for this particle
453
    if (write_track()) {
1,128,560,067✔
454
      write_particle_track(*this);
6,678✔
455
    }
456

457
    // If no secondary particles, break out of event loop
458
    if (secondary_bank().empty())
1,128,560,067✔
459
      return;
168,176,192✔
460

461
    from_source(&secondary_bank().back());
960,383,875✔
462
    secondary_bank().pop_back();
960,383,875✔
463
    n_event() = 0;
960,383,875✔
464
    bank_second_E() = 0.0;
960,383,875✔
465

466
    // Subtract secondary particle energy from interim pulse-height results
467
    if (!model::active_pulse_height_tallies.empty() &&
960,399,374✔
468
        this->type() == ParticleType::photon) {
15,499✔
469
      // Since the birth cell of the particle has not been set we
470
      // have to determine it before the energy of the secondary particle can be
471
      // removed from the pulse-height of this cell.
472
      if (lowest_coord().cell() == C_NONE) {
605!
473
        bool verbose = settings::verbosity >= 10 || trace();
605!
474
        if (!exhaustive_find_cell(*this, verbose)) {
605!
475
          mark_as_lost("Could not find the cell containing particle " +
×
476
                       std::to_string(id()));
×
477
          return;
×
478
        }
479
        // Set birth cell attribute
480
        if (cell_born() == C_NONE)
605!
481
          cell_born() = lowest_coord().cell();
605✔
482

483
        // Initialize last cells from current cell
484
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
485
          cell_last(j) = coord(j).cell();
605✔
486
        }
487
        n_coord_last() = n_coord();
605✔
488
      }
489
      pht_secondary_particles();
605✔
490
    }
491

492
    // Enter new particle in particle track file
493
    if (write_track())
960,383,875✔
494
      add_particle_track(*this);
5,608✔
495
  }
496
}
497

498
void Particle::event_death()
168,177,192✔
499
{
500
#ifdef OPENMC_DAGMC_ENABLED
501
  history().reset();
15,364,246✔
502
#endif
503

504
  // Finish particle track output.
505
  if (write_track()) {
168,177,192✔
506
    finalize_particle_track(*this);
1,070✔
507
  }
508

509
// Contribute tally reduction variables to global accumulator
510
#pragma omp atomic
92,604,408✔
511
  global_tally_absorption += keff_tally_absorption();
168,177,192✔
512
#pragma omp atomic
93,115,533✔
513
  global_tally_collision += keff_tally_collision();
168,177,192✔
514
#pragma omp atomic
92,217,736✔
515
  global_tally_tracklength += keff_tally_tracklength();
168,177,192✔
516
#pragma omp atomic
91,941,709✔
517
  global_tally_leakage += keff_tally_leakage();
168,177,192✔
518

519
  // Reset particle tallies once accumulated
520
  keff_tally_absorption() = 0.0;
168,177,192✔
521
  keff_tally_collision() = 0.0;
168,177,192✔
522
  keff_tally_tracklength() = 0.0;
168,177,192✔
523
  keff_tally_leakage() = 0.0;
168,177,192✔
524

525
  if (!model::active_pulse_height_tallies.empty()) {
168,177,192✔
526
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
527
  }
528

529
  // Record the number of progeny created by this particle.
530
  // This data will be used to efficiently sort the fission bank.
531
  if (settings::run_mode == RunMode::EIGENVALUE) {
168,177,192✔
532
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
140,925,811✔
533
    simulation::progeny_per_particle[offset] = n_progeny();
140,925,811✔
534
  }
535
}
168,177,192✔
536

537
void Particle::pht_collision_energy()
2,024✔
538
{
539
  // Adds the energy particles lose in a collision to the pulse-height
540

541
  // determine index of cell in pulse_height_cells
542
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
543
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
544

545
  if (it != model::pulse_height_cells.end()) {
2,024!
546
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
547
    pht_storage()[index] += E_last() - E();
2,024✔
548

549
    // If the energy of the particle is below the cutoff, it will not be sampled
550
    // so its energy is added to the pulse-height in the cell
551
    int photon = static_cast<int>(ParticleType::photon);
2,024✔
552
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
553
      pht_storage()[index] += E();
825✔
554
    }
555
  }
556
}
2,024✔
557

558
void Particle::pht_secondary_particles()
605✔
559
{
560
  // Removes the energy of secondary produced particles from the pulse-height
561

562
  // determine index of cell in pulse_height_cells
563
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
564
    model::pulse_height_cells.end(), cell_born());
605✔
565

566
  if (it != model::pulse_height_cells.end()) {
605!
567
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
568
    pht_storage()[index] -= E();
605✔
569
  }
570
}
605✔
571

572
void Particle::cross_surface(const Surface& surf)
1,508,853,697✔
573
{
574

575
  if (settings::verbosity >= 10 || trace()) {
1,508,853,697✔
576
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
577
  }
578

579
// if we're crossing a CSG surface, make sure the DAG history is reset
580
#ifdef OPENMC_DAGMC_ENABLED
581
  if (surf.geom_type() == GeometryType::CSG)
137,911,529✔
582
    history().reset();
137,856,399✔
583
#endif
584

585
  // Handle any applicable boundary conditions.
586
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
587
      settings::run_mode != RunMode::VOLUME) {
689,019,796✔
588
    surf.bc_->handle_particle(*this, surf);
688,899,852✔
589
    return;
688,899,852✔
590
  }
591

592
  // ==========================================================================
593
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
594

595
#ifdef OPENMC_DAGMC_ENABLED
596
  // in DAGMC, we know what the next cell should be
597
  if (surf.geom_type() == GeometryType::DAG) {
74,839,006✔
598
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
44,321✔
599
                       lowest_coord().universe()) -
44,321✔
600
                     1;
44,321✔
601
    // save material, temperature, and density multiplier
602
    material_last() = material();
44,321✔
603
    sqrtkT_last() = sqrtkT();
44,321✔
604
    density_mult_last() = density_mult();
44,321✔
605
    // set new cell value
606
    lowest_coord().cell() = i_cell;
44,321✔
607
    auto& cell = model::cells[i_cell];
44,321✔
608

609
    cell_instance() = 0;
44,321✔
610
    if (cell->distribcell_index_ >= 0)
44,321✔
611
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
43,297✔
612

613
    material() = cell->material(cell_instance());
44,321✔
614
    sqrtkT() = cell->sqrtkT(cell_instance());
44,321✔
615
    density_mult() = cell->density_mult(cell_instance());
44,321✔
616
    return;
44,321✔
617
  }
618
#endif
619

620
  bool verbose = settings::verbosity >= 10 || trace();
819,909,524!
621
  if (neighbor_list_find_cell(*this, verbose)) {
819,909,524✔
622
    return;
819,879,613✔
623
  }
624

625
  // ==========================================================================
626
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
627

628
  // Remove lower coordinate levels
629
  n_coord() = 1;
29,911✔
630
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
631

632
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
29,911!
633
    // If a cell is still not found, there are two possible causes: 1) there is
634
    // a void in the model, and 2) the particle hit a surface at a tangent. If
635
    // the particle is really traveling tangent to a surface, if we move it
636
    // forward a tiny bit it should fix the problem.
637

638
    surface() = SURFACE_NONE;
5,799✔
639
    n_coord() = 1;
5,799✔
640
    r() += TINY_BIT * u();
5,799✔
641

642
    // Couldn't find next cell anywhere! This probably means there is an actual
643
    // undefined region in the geometry.
644

645
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
646
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
647
                   " crossed surface " + std::to_string(surf.id_) +
23,178✔
648
                   " it could not be located in any cell and it did not leak.");
649
      return;
5,790✔
650
    }
651
  }
652
}
653

654
void Particle::cross_vacuum_bc(const Surface& surf)
35,021,034✔
655
{
656
  // Score any surface current tallies -- note that the particle is moved
657
  // forward slightly so that if the mesh boundary is on the surface, it is
658
  // still processed
659

660
  if (!model::active_meshsurf_tallies.empty()) {
35,021,034✔
661
    // TODO: Find a better solution to score surface currents than
662
    // physically moving the particle forward slightly
663

664
    r() += TINY_BIT * u();
937,222✔
665
    score_surface_tally(*this, model::active_meshsurf_tallies);
937,222✔
666
  }
667

668
  // Score to global leakage tally
669
  keff_tally_leakage() += wgt();
35,021,034✔
670

671
  // Kill the particle
672
  wgt() = 0.0;
35,021,034✔
673

674
  // Display message
675
  if (settings::verbosity >= 10 || trace()) {
35,021,034!
676
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
677
  }
678
}
35,021,034✔
679

680
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
652,640,010✔
681
{
682
  // Do not handle reflective boundary conditions on lower universes
683
  if (n_coord() != 1) {
652,640,010!
684
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
685
                 " off surface in a lower universe.");
686
    return;
×
687
  }
688

689
  // Score surface currents since reflection causes the direction of the
690
  // particle to change. For surface filters, we need to score the tallies
691
  // twice, once before the particle's surface attribute has changed and
692
  // once after. For mesh surface filters, we need to artificially move
693
  // the particle slightly back in case the surface crossing is coincident
694
  // with a mesh boundary
695

696
  if (!model::active_surface_tallies.empty()) {
652,640,010✔
697
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
698
  }
699

700
  if (!model::active_meshsurf_tallies.empty()) {
652,640,010✔
701
    Position r {this->r()};
46,885,487✔
702
    this->r() -= TINY_BIT * u();
46,885,487✔
703
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
704
    this->r() = r;
46,885,487✔
705
  }
706

707
  // Set the new particle direction
708
  u() = new_u;
652,640,010✔
709

710
  // Reassign particle's cell and surface
711
  coord(0).cell() = cell_last(0);
652,640,010✔
712
  surface() = -surface();
652,640,010✔
713

714
  // If a reflective surface is coincident with a lattice or universe
715
  // boundary, it is necessary to redetermine the particle's coordinates in
716
  // the lower universes.
717
  // (unless we're using a dagmc model, which has exactly one universe)
718
  n_coord() = 1;
652,640,010✔
719
  if (surf.geom_type() != GeometryType::DAG &&
1,305,277,262!
720
      !neighbor_list_find_cell(*this)) {
652,637,252!
721
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
722
                 std::to_string(surf.id_) + ".");
×
723
    return;
×
724
  }
725

726
  // Set previous coordinate going slightly past surface crossing
727
  r_last_current() = r() + TINY_BIT * u();
652,640,010✔
728

729
  // Diagnostic message
730
  if (settings::verbosity >= 10 || trace()) {
652,640,010!
731
    write_message(1, "    Reflected from surface {}", surf.id_);
×
732
  }
733
}
734

735
void Particle::cross_periodic_bc(
2,244,274✔
736
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
737
{
738
  // Do not handle periodic boundary conditions on lower universes
739
  if (n_coord() != 1) {
2,244,274!
740
    mark_as_lost(
×
741
      "Cannot transfer particle " + std::to_string(id()) +
×
742
      " across surface in a lower universe. Boundary conditions must be "
743
      "applied to root universe.");
744
    return;
×
745
  }
746

747
  // Score surface currents since reflection causes the direction of the
748
  // particle to change -- artificially move the particle slightly back in
749
  // case the surface crossing is coincident with a mesh boundary
750
  if (!model::active_meshsurf_tallies.empty()) {
2,244,274!
751
    Position r {this->r()};
×
752
    this->r() -= TINY_BIT * u();
×
753
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
754
    this->r() = r;
×
755
  }
756

757
  // Adjust the particle's location and direction.
758
  r() = new_r;
2,244,274✔
759
  u() = new_u;
2,244,274✔
760

761
  // Reassign particle's surface
762
  surface() = new_surface;
2,244,274✔
763

764
  // Figure out what cell particle is in now
765
  n_coord() = 1;
2,244,274✔
766

767
  if (!neighbor_list_find_cell(*this)) {
2,244,274!
768
    mark_as_lost("Couldn't find particle after hitting periodic "
×
769
                 "boundary on surface " +
×
770
                 std::to_string(surf.id_) + ".");
×
771
    return;
×
772
  }
773

774
  // Set previous coordinate going slightly past surface crossing
775
  r_last_current() = r() + TINY_BIT * u();
2,244,274✔
776

777
  // Diagnostic message
778
  if (settings::verbosity >= 10 || trace()) {
2,244,274!
779
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
780
  }
781
}
782

783
void Particle::mark_as_lost(const char* message)
5,820✔
784
{
785
  // Print warning and write lost particle file
786
  warning(message);
5,820✔
787
  if (settings::max_write_lost_particles < 0 ||
5,820✔
788
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
789
    write_restart();
400✔
790
  }
791
  // Increment number of lost particles
792
  wgt() = 0.0;
5,820✔
793
#pragma omp atomic
3,175✔
794
  simulation::n_lost_particles += 1;
2,645✔
795

796
  // Count the total number of simulated particles (on this processor)
797
  auto n = simulation::current_batch * settings::gen_per_batch *
5,820✔
798
           simulation::work_per_rank;
799

800
  // Abort the simulation if the maximum number of lost particles has been
801
  // reached
802
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,820✔
803
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
12!
804
    fatal_error("Maximum number of lost particles has been reached.");
12✔
805
  }
806
}
5,808✔
807

808
void Particle::write_restart() const
400✔
809
{
810
  // Dont write another restart file if in particle restart mode
811
  if (settings::run_mode == RunMode::PARTICLE)
400✔
812
    return;
22✔
813

814
  // Set up file name
815
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
816
    simulation::current_batch, id());
707✔
817

818
#pragma omp critical(WriteParticleRestart)
416✔
819
  {
820
    // Create file
821
    hid_t file_id = file_open(filename, 'w');
378✔
822

823
    // Write filetype and version info
824
    write_attribute(file_id, "filetype", "particle restart");
378✔
825
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
378✔
826
    write_attribute(file_id, "openmc_version", VERSION);
378✔
827
#ifdef GIT_SHA1
828
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
829
#endif
830

831
    // Write data to file
832
    write_dataset(file_id, "current_batch", simulation::current_batch);
378✔
833
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
378✔
834
    write_dataset(file_id, "current_generation", simulation::current_gen);
378✔
835
    write_dataset(file_id, "n_particles", settings::n_particles);
378✔
836
    switch (settings::run_mode) {
378!
837
    case RunMode::FIXED_SOURCE:
225✔
838
      write_dataset(file_id, "run_mode", "fixed source");
225✔
839
      break;
225✔
840
    case RunMode::EIGENVALUE:
153✔
841
      write_dataset(file_id, "run_mode", "eigenvalue");
153✔
842
      break;
153✔
843
    case RunMode::PARTICLE:
×
844
      write_dataset(file_id, "run_mode", "particle restart");
×
845
      break;
×
846
    default:
×
847
      break;
×
848
    }
849
    write_dataset(file_id, "id", id());
378✔
850
    write_dataset(file_id, "type", static_cast<int>(type()));
378✔
851

852
    int64_t i = current_work();
378✔
853
    if (settings::run_mode == RunMode::EIGENVALUE) {
378✔
854
      // take source data from primary bank for eigenvalue simulation
855
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
153✔
856
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
153✔
857
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
153✔
858
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
153✔
859
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
153✔
860
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
225!
861
      // re-sample using rng random number seed used to generate source particle
862
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
225✔
863
                     settings::n_particles +
225✔
864
                   simulation::work_index[mpi::rank] + i;
225✔
865
      uint64_t seed = init_seed(id, STREAM_SOURCE);
225✔
866
      // re-sample source site
867
      auto site = sample_external_source(&seed);
225✔
868
      write_dataset(file_id, "weight", site.wgt);
225✔
869
      write_dataset(file_id, "energy", site.E);
225✔
870
      write_dataset(file_id, "xyz", site.r);
225✔
871
      write_dataset(file_id, "uvw", site.u);
225✔
872
      write_dataset(file_id, "time", site.time);
225✔
873
    }
874

875
    // Close file
876
    file_close(file_id);
378✔
877
  } // #pragma omp critical
878
}
378✔
879

880
void Particle::update_neutron_xs(
2,147,483,647✔
881
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
882
{
883
  // Get microscopic cross section cache
884
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
885

886
  // If the cache doesn't match, recalculate micro xs
887
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
888
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
889
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
890
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
891

892
    // If NCrystal is being used, update micro cross section cache
893
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
894
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
895
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
896
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
897
    }
898
  }
899
}
2,147,483,647✔
900

901
//==============================================================================
902
// Non-method functions
903
//==============================================================================
904

905
std::string particle_type_to_str(ParticleType type)
3,130,241✔
906
{
907
  switch (type) {
3,130,241!
908
  case ParticleType::neutron:
2,399,962✔
909
    return "neutron";
2,399,962✔
910
  case ParticleType::photon:
730,015✔
911
    return "photon";
730,015✔
912
  case ParticleType::electron:
132✔
913
    return "electron";
132✔
914
  case ParticleType::positron:
132✔
915
    return "positron";
132✔
916
  }
917
  UNREACHABLE();
×
918
}
919

920
ParticleType str_to_particle_type(std::string str)
3,317,965✔
921
{
922
  if (str == "neutron") {
3,317,965✔
923
    return ParticleType::neutron;
775,577✔
924
  } else if (str == "photon") {
2,542,388✔
925
    return ParticleType::photon;
2,542,302✔
926
  } else if (str == "electron") {
86✔
927
    return ParticleType::electron;
43✔
928
  } else if (str == "positron") {
43!
929
    return ParticleType::positron;
43✔
930
  } else {
931
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
932
  }
933
}
934

935
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,505,769,315✔
936
{
937
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
938
      simulation::surf_source_bank.full()) {
1,178,697,302✔
939
    return;
1,505,639,662✔
940
  }
941

942
  // If a cell/cellfrom/cellto parameter is defined
943
  if (settings::ssw_cell_id != C_NONE) {
337,082✔
944

945
    // Retrieve cell index and storage type
946
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,437✔
947

948
    if (surf.bc_) {
254,437✔
949
      // Leave if cellto with vacuum boundary condition
950
      if (surf.bc_->type() == "vacuum" &&
182,558!
951
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
952
        return;
12,136✔
953
      }
954

955
      // Leave if other boundary condition than vacuum
956
      if (surf.bc_->type() != "vacuum") {
137,323✔
957
        return;
116,360✔
958
      }
959
    }
960

961
    // Check if the cell of interest has been exited
962
    bool exited = false;
125,941✔
963
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,671✔
964
      if (p.cell_last(i) == cell_idx) {
207,730✔
965
        exited = true;
73,765✔
966
      }
967
    }
968

969
    // Check if the cell of interest has been entered
970
    bool entered = false;
125,941✔
971
    for (int i = 0; i < p.n_coord(); ++i) {
297,973✔
972
      if (p.coord(i).cell() == cell_idx) {
172,032✔
973
        entered = true;
57,515✔
974
      }
975
    }
976

977
    // Vacuum boundary conditions: return if cell is not exited
978
    if (surf.bc_) {
125,941✔
979
      if (surf.bc_->type() == "vacuum" && !exited) {
20,963!
980
        return;
14,663✔
981
      }
982
    } else {
983

984
      // If we both enter and exit the cell of interest
985
      if (entered && exited) {
104,978✔
986
        return;
27,203✔
987
      }
988

989
      // If we did not enter nor exit the cell of interest
990
      if (!entered && !exited) {
77,775✔
991
        return;
13,501✔
992
      }
993

994
      // If cellfrom and the cell before crossing is not the cell of
995
      // interest
996
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,274✔
997
        return;
11,541✔
998
      }
999

1000
      // If cellto and the cell after crossing is not the cell of interest
1001
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,733✔
1002
        return;
12,025✔
1003
      }
1004
    }
1005
  }
1006

1007
  SourceSite site;
129,653✔
1008
  site.r = p.r();
129,653✔
1009
  site.u = p.u();
129,653✔
1010
  site.E = p.E();
129,653✔
1011
  site.time = p.time();
129,653✔
1012
  site.wgt = p.wgt();
129,653✔
1013
  site.delayed_group = p.delayed_group();
129,653✔
1014
  site.surf_id = surf.id_;
129,653✔
1015
  site.particle = p.type();
129,653✔
1016
  site.parent_id = p.id();
129,653✔
1017
  site.progeny_id = p.n_progeny();
129,653✔
1018
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1019
}
1020

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