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

openmc-dev / openmc / 21498346812

29 Jan 2026 11:22PM UTC coverage: 81.303% (-0.7%) from 81.953%
21498346812

Pull #3757

github

web-flow
Merge 00995505f into f7a734189
Pull Request #3757: Testing point detectors

17285 of 24400 branches covered (70.84%)

Branch coverage included in aggregate %.

103 of 504 new or added lines in 26 files covered. (20.44%)

3 existing lines in 2 files now uncovered.

55851 of 65555 relevant lines covered (85.2%)

43756726.79 hits per line

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

82.43
/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::mass() const
2,115,230,772✔
47
{
48
  // Determine mass in eV/c^2
49
  switch (this->type()) {
2,115,230,772!
50
  case ParticleType::neutron:
2,039,955,432✔
51
    return MASS_NEUTRON_EV;
2,039,955,432✔
52
  case ParticleType::photon:
21,807,414✔
53
    return 0.0;
21,807,414✔
54
  case ParticleType::electron:
53,467,926✔
55
  case ParticleType::positron:
56
    return MASS_ELECTRON_EV;
53,467,926✔
57
  }
NEW
58
  UNREACHABLE();
×
59
}
60

61
double Particle::speed() const
2,147,483,647✔
62
{
63
  if (settings::run_CE) {
2,147,483,647✔
64
    double mass = this->mass();
2,115,230,772✔
65
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
66
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,115,230,772✔
67
           (this->E() + mass);
2,115,230,772✔
68
  } else {
69
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
70
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
71
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
72
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
73
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
74
  }
75
}
76

77
bool Particle::create_secondary(
111,535,615✔
78
  double wgt, Direction u, double E, ParticleType type)
79
{
80
  // If energy is below cutoff for this particle, don't create secondary
81
  // particle
82
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
111,535,615✔
83
    return false;
53,314,974✔
84
  }
85

86
  auto& bank = secondary_bank().emplace_back();
58,220,641✔
87
  bank.particle = type;
58,220,641✔
88
  bank.wgt = wgt;
58,220,641✔
89
  bank.r = r();
58,220,641✔
90
  bank.u = u;
58,220,641✔
91
  bank.E = settings::run_CE ? E : g();
58,220,641!
92
  bank.time = time();
58,220,641✔
93
  bank_second_E() += bank.E;
58,220,641✔
94
  return true;
58,220,641✔
95
}
96

97
void Particle::split(double wgt)
4,087,987✔
98
{
99
  auto& bank = secondary_bank().emplace_back();
4,087,987✔
100
  bank.particle = type();
4,087,987✔
101
  bank.wgt = wgt;
4,087,987✔
102
  bank.r = r();
4,087,987✔
103
  bank.u = u();
4,087,987✔
104
  bank.E = settings::run_CE ? E() : g();
4,087,987✔
105
  bank.time = time();
4,087,987✔
106

107
  // Convert signed index to a signed surface ID
108
  if (surface() == SURFACE_NONE) {
4,087,987✔
109
    bank.surf_id = SURFACE_NONE;
4,087,651✔
110
  } else {
111
    int surf_id = model::surfaces[surface_index()]->id_;
336✔
112
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
336!
113
  }
114
}
4,087,987✔
115

116
void Particle::from_source(const SourceSite* src)
238,072,639✔
117
{
118
  // Reset some attributes
119
  clear();
238,072,639✔
120
  surface() = SURFACE_NONE;
238,072,639✔
121
  cell_born() = C_NONE;
238,072,639✔
122
  material() = C_NONE;
238,072,639✔
123
  n_collision() = 0;
238,072,639✔
124
  fission() = false;
238,072,639✔
125
  zero_flux_derivs();
238,072,639✔
126
  lifetime() = 0.0;
238,072,639✔
127
#ifdef OPENMC_DAGMC_ENABLED
128
  history().reset();
21,803,549✔
129
#endif
130

131
  // Copy attributes from source bank site
132
  type() = src->particle;
238,072,639✔
133
  wgt() = src->wgt;
238,072,639✔
134
  wgt_last() = src->wgt;
238,072,639✔
135
  r() = src->r;
238,072,639✔
136
  u() = src->u;
238,072,639✔
137
  r_born() = src->r;
238,072,639✔
138
  r_last_current() = src->r;
238,072,639✔
139
  r_last() = src->r;
238,072,639✔
140
  u_last() = src->u;
238,072,639✔
141
  if (settings::run_CE) {
238,072,639✔
142
    E() = src->E;
122,334,022✔
143
    g() = 0;
122,334,022✔
144
  } else {
145
    g() = static_cast<int>(src->E);
115,738,617✔
146
    g_last() = static_cast<int>(src->E);
115,738,617✔
147
    E() = data::mg.energy_bin_avg_[g()];
115,738,617✔
148
  }
149
  E_last() = E();
238,072,639✔
150
  time() = src->time;
238,072,639✔
151
  time_last() = src->time;
238,072,639✔
152
  parent_nuclide() = src->parent_nuclide;
238,072,639✔
153
  delayed_group() = src->delayed_group;
238,072,639✔
154

155
  // Convert signed surface ID to signed index
156
  if (src->surf_id != SURFACE_NONE) {
238,072,639✔
157
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,336✔
158
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,336!
159
  }
160
}
238,072,639✔
161

NEW
162
void Particle::initialize_pseudoparticle(
×
163
  Particle& p, Direction u_new, double E_new)
164
{
165
  // Reset some attributes
NEW
166
  clear();
×
NEW
167
  surface() = SURFACE_NONE;
×
NEW
168
  cell_born() = C_NONE;
×
NEW
169
  material() = C_NONE;
×
NEW
170
  n_collision() = 0;
×
NEW
171
  fission() = false;
×
NEW
172
  zero_flux_derivs();
×
NEW
173
  lifetime() = 0.0;
×
174

175
  // Copy attributes from particle
NEW
176
  type() = p.type();
×
NEW
177
  wgt() = p.wgt();
×
NEW
178
  wgt_last() = p.wgt();
×
NEW
179
  r() = p.r();
×
NEW
180
  u() = u_new;
×
NEW
181
  r_born() = p.r();
×
NEW
182
  r_last_current() = p.r();
×
NEW
183
  r_last() = p.r();
×
NEW
184
  u_last() = p.u();
×
NEW
185
  if (settings::run_CE) {
×
NEW
186
    E() = E_new;
×
NEW
187
    g() = 0;
×
188
  } else {
NEW
189
    g() = static_cast<int>(E_new);
×
NEW
190
    g_last() = static_cast<int>(E_new);
×
NEW
191
    E() = data::mg.energy_bin_avg_[g()];
×
192
  }
NEW
193
  E_last() = E();
×
NEW
194
  time() = p.time();
×
NEW
195
  time_last() = p.time();
×
NEW
196
}
×
197

198
void Particle::event_calculate_xs(bool is_pseudo)
2,147,483,647✔
199
{
200
  // Set the random number stream
201
  stream() = is_pseudo ? STREAM_NEXT_EVENT : STREAM_TRACKING;
2,147,483,647!
202

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

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

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

225
    // Set birth cell attribute
226
    if (cell_born() == C_NONE)
229,588,730!
227
      cell_born() = lowest_coord().cell();
229,588,730✔
228

229
    // Initialize last cells from current cell
230
    for (int j = 0; j < n_coord(); ++j) {
476,202,238✔
231
      cell_last(j) = coord(j).cell();
246,613,508✔
232
    }
233
    n_coord_last() = n_coord();
229,588,730✔
234
  }
235

236
  // Write particle track.
237
  if (write_track() && !is_pseudo)
2,147,483,647!
238
    write_particle_track(*this);
10,817✔
239

240
  if (settings::check_overlaps)
2,147,483,647!
241
    check_cell_overlap(*this);
×
242

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

259
      // Update the particle's group while we know we are multi-group
260
      g_last() = g();
2,063,937,414✔
261
    }
262
  } else {
263
    macro_xs().total = 0.0;
111,825,089✔
264
    macro_xs().absorption = 0.0;
111,825,089✔
265
    macro_xs().fission = 0.0;
111,825,089✔
266
    macro_xs().nu_fission = 0.0;
111,825,089✔
267
  }
268
}
269

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

275
  // Sample a distance to collision
276
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
277
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
53,467,926!
278
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
279
    collision_distance() = INFINITY;
111,825,089✔
280
  } else {
281
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
282
  }
283

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

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

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

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

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

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

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

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

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

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

338
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
339
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
340
      boundary().lattice_translation()[2] != 0) {
1,695,538,106✔
341
    // Particle crosses lattice boundary
342

343
    bool verbose = settings::verbosity >= 10 || trace();
732,435,834!
344
    cross_lattice(*this, boundary(), verbose);
732,435,834✔
345
    event() = TallyEvent::LATTICE;
732,435,834✔
346
  } else {
347
    // Particle crosses surface
348
    const auto& surf {model::surfaces[surface_index()].get()};
1,506,996,210✔
349
    // If BC, add particle to surface source before crossing surface
350
    if (surf->surf_source_ && surf->bc_ && !is_pseudo) {
1,506,996,210!
351
      add_surf_source_to_bank(*this, *surf);
688,536,942✔
352
    }
353
    this->cross_surface(*surf);
1,506,996,210✔
354
    // If no BC, add particle to surface source after crossing surface
355
    if (surf->surf_source_ && !surf->bc_ && !is_pseudo) {
1,506,996,201!
356
      add_surf_source_to_bank(*this, *surf);
817,221,432✔
357
    }
358
    if (settings::weight_window_checkpoint_surface && !is_pseudo) {
1,506,996,201!
359
      apply_weight_windows(*this);
10,738!
360
    }
361
    event() = TallyEvent::SURFACE;
1,506,996,201✔
362
  }
363
  // Score cell to cell partial currents
364
  if (!model::active_surface_tallies.empty() && !is_pseudo) {
2,147,483,647!
365
    score_surface_tally(*this, model::active_surface_tallies);
34,922,767✔
366
  }
367
}
2,147,483,647✔
368

369
void Particle::event_collide()
2,147,483,647✔
370
{
371
  // Score collision estimate of keff
372
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
373
      type() == ParticleType::neutron) {
2,147,483,647✔
374
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,125,060,607✔
375
  }
376

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

381
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
382
    score_surface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
383

384
  // Clear surface component
385
  surface() = SURFACE_NONE;
2,147,483,647✔
386

387
  if (settings::run_CE) {
2,147,483,647✔
388
    collision(*this);
944,999,881✔
389
  } else {
390
    collision_mg(*this);
1,783,060,477✔
391
  }
392

393
  // Collision track feature to recording particle interaction
394
  if (settings::collision_track) {
2,147,483,647✔
395
    collision_track_record(*this);
150,087✔
396
  }
397

398
  // Score collision estimator tallies -- this is done after a collision
399
  // has occurred rather than before because we need information on the
400
  // outgoing energy for any tallies with an outgoing energy filter
401
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
402
    score_collision_tally(*this);
107,061,064✔
403
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
404
    if (settings::run_CE) {
291,821,708✔
405
      score_analog_tally_ce(*this);
290,613,446✔
406
    } else {
407
      score_analog_tally_mg(*this);
1,208,262✔
408
    }
409
  }
410

411
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
412
      type() == ParticleType::photon) {
16,918✔
413
    pht_collision_energy();
2,024✔
414
  }
415

416
  // Reset banked weight during collision
417
  n_bank() = 0;
2,147,483,647✔
418
  bank_second_E() = 0.0;
2,147,483,647✔
419
  wgt_bank() = 0.0;
2,147,483,647✔
420
  zero_delayed_bank();
2,147,483,647✔
421

422
  // Reset fission logical
423
  fission() = false;
2,147,483,647✔
424

425
  // Save coordinates for tallying purposes
426
  r_last_current() = r();
2,147,483,647✔
427

428
  // Set last material to none since cross sections will need to be
429
  // re-evaluated
430
  material_last() = C_NONE;
2,147,483,647✔
431

432
  // Set all directions to base level -- right now, after a collision, only
433
  // the base level directions are changed
434
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
435
    if (coord(j + 1).rotated()) {
143,198,604✔
436
      // If next level is rotated, apply rotation matrix
437
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
438
      const auto& u {coord(j).u()};
10,426,614✔
439
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
440
    } else {
441
      // Otherwise, copy this level's direction
442
      coord(j + 1).u() = coord(j).u();
132,771,990✔
443
    }
444
  }
445

446
  // Score flux derivative accumulators for differential tallies.
447
  if (!model::active_tallies.empty())
2,147,483,647✔
448
    score_collision_derivative(*this);
817,355,006✔
449

450
#ifdef OPENMC_DAGMC_ENABLED
451
  history().reset();
250,284,912✔
452
#endif
453
}
2,147,483,647✔
454

455
void Particle::event_revive_from_secondary()
2,147,483,647✔
456
{
457
  // If particle has too many events, display warning and kill it
458
  ++n_event();
2,147,483,647✔
459
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
460
    warning("Particle " + std::to_string(id()) +
×
461
            " underwent maximum number of events.");
462
    wgt() = 0.0;
×
463
  }
464

465
  // Check for secondary particles if this particle is dead
466
  if (!alive()) {
2,147,483,647✔
467
    // Write final position for this particle
468
    if (write_track()) {
229,588,324✔
469
      write_particle_track(*this);
6,676✔
470
    }
471

472
    // If no secondary particles, break out of event loop
473
    if (secondary_bank().empty())
229,588,324✔
474
      return;
167,076,177✔
475

476
    from_source(&secondary_bank().back());
62,512,147✔
477
    secondary_bank().pop_back();
62,512,147✔
478
    n_event() = 0;
62,512,147✔
479
    bank_second_E() = 0.0;
62,512,147✔
480

481
    // Subtract secondary particle energy from interim pulse-height results
482
    if (!model::active_pulse_height_tallies.empty() &&
62,527,646✔
483
        this->type() == ParticleType::photon) {
15,499✔
484
      // Since the birth cell of the particle has not been set we
485
      // have to determine it before the energy of the secondary particle can be
486
      // removed from the pulse-height of this cell.
487
      if (lowest_coord().cell() == C_NONE) {
605!
488
        bool verbose = settings::verbosity >= 10 || trace();
605!
489
        if (!exhaustive_find_cell(*this, verbose)) {
605!
490
          mark_as_lost("Could not find the cell containing particle " +
×
491
                       std::to_string(id()));
×
492
          return;
×
493
        }
494
        // Set birth cell attribute
495
        if (cell_born() == C_NONE)
605!
496
          cell_born() = lowest_coord().cell();
605✔
497

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

507
    // Enter new particle in particle track file
508
    if (write_track())
62,512,147✔
509
      add_particle_track(*this);
5,606✔
510
  }
511
}
512

513
void Particle::event_death()
167,077,177✔
514
{
515
#ifdef OPENMC_DAGMC_ENABLED
516
  history().reset();
15,264,231✔
517
#endif
518

519
  // Finish particle track output.
520
  if (write_track()) {
167,077,177✔
521
    finalize_particle_track(*this);
1,070✔
522
  }
523

524
// Contribute tally reduction variables to global accumulator
525
#pragma omp atomic
92,063,461✔
526
  global_tally_absorption += keff_tally_absorption();
167,077,177✔
527
#pragma omp atomic
92,029,347✔
528
  global_tally_collision += keff_tally_collision();
167,077,177✔
529
#pragma omp atomic
91,661,461✔
530
  global_tally_tracklength += keff_tally_tracklength();
167,077,177✔
531
#pragma omp atomic
91,392,529✔
532
  global_tally_leakage += keff_tally_leakage();
167,077,177✔
533

534
  // Reset particle tallies once accumulated
535
  keff_tally_absorption() = 0.0;
167,077,177✔
536
  keff_tally_collision() = 0.0;
167,077,177✔
537
  keff_tally_tracklength() = 0.0;
167,077,177✔
538
  keff_tally_leakage() = 0.0;
167,077,177✔
539

540
  if (!model::active_pulse_height_tallies.empty()) {
167,077,177✔
541
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
542
  }
543

544
  // Record the number of progeny created by this particle.
545
  // This data will be used to efficiently sort the fission bank.
546
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,077,177✔
547
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
140,925,796✔
548
    simulation::progeny_per_particle[offset] = n_progeny();
140,925,796✔
549
  }
550
}
167,077,177✔
551

552
void Particle::pht_collision_energy()
2,024✔
553
{
554
  // Adds the energy particles lose in a collision to the pulse-height
555

556
  // determine index of cell in pulse_height_cells
557
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
558
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
559

560
  if (it != model::pulse_height_cells.end()) {
2,024!
561
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
562
    pht_storage()[index] += E_last() - E();
2,024✔
563

564
    // If the energy of the particle is below the cutoff, it will not be sampled
565
    // so its energy is added to the pulse-height in the cell
566
    int photon = static_cast<int>(ParticleType::photon);
2,024✔
567
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
568
      pht_storage()[index] += E();
825✔
569
    }
570
  }
571
}
2,024✔
572

573
void Particle::pht_secondary_particles()
605✔
574
{
575
  // Removes the energy of secondary produced particles from the pulse-height
576

577
  // determine index of cell in pulse_height_cells
578
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
579
    model::pulse_height_cells.end(), cell_born());
605✔
580

581
  if (it != model::pulse_height_cells.end()) {
605!
582
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
583
    pht_storage()[index] -= E();
605✔
584
  }
585
}
605✔
586

587
void Particle::cross_surface(const Surface& surf)
1,508,866,852✔
588
{
589

590
  if (settings::verbosity >= 10 || trace()) {
1,508,866,852✔
591
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
592
  }
593

594
// if we're crossing a CSG surface, make sure the DAG history is reset
595
#ifdef OPENMC_DAGMC_ENABLED
596
  if (surf.geom_type() == GeometryType::CSG)
137,902,112✔
597
    history().reset();
137,846,993✔
598
#endif
599

600
  // Handle any applicable boundary conditions.
601
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
602
      settings::run_mode != RunMode::VOLUME) {
689,008,994✔
603
    surf.bc_->handle_particle(*this, surf);
688,889,050✔
604
    return;
688,889,050✔
605
  }
606

607
  // ==========================================================================
608
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
609

610
#ifdef OPENMC_DAGMC_ENABLED
611
  // in DAGMC, we know what the next cell should be
612
  if (surf.geom_type() == GeometryType::DAG) {
74,831,648✔
613
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
44,310✔
614
                       lowest_coord().universe()) -
44,310✔
615
                     1;
44,310✔
616
    // save material, temperature, and density multiplier
617
    material_last() = material();
44,310✔
618
    sqrtkT_last() = sqrtkT();
44,310✔
619
    density_mult_last() = density_mult();
44,310✔
620
    // set new cell value
621
    lowest_coord().cell() = i_cell;
44,310✔
622
    auto& cell = model::cells[i_cell];
44,310✔
623

624
    cell_instance() = 0;
44,310✔
625
    if (cell->distribcell_index_ >= 0)
44,310✔
626
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
43,286✔
627

628
    material() = cell->material(cell_instance());
44,310✔
629
    sqrtkT() = cell->sqrtkT(cell_instance());
44,310✔
630
    density_mult() = cell->density_mult(cell_instance());
44,310✔
631
    return;
44,310✔
632
  }
633
#endif
634

635
  bool verbose = settings::verbosity >= 10 || trace();
819,933,492!
636
  if (neighbor_list_find_cell(*this, verbose)) {
819,933,492✔
637
    return;
819,903,581✔
638
  }
639

640
  // ==========================================================================
641
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
642

643
  // Remove lower coordinate levels
644
  n_coord() = 1;
29,911✔
645
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
646

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

653
    surface() = SURFACE_NONE;
5,799✔
654
    n_coord() = 1;
5,799✔
655
    r() += TINY_BIT * u();
5,799✔
656

657
    // Couldn't find next cell anywhere! This probably means there is an actual
658
    // undefined region in the geometry.
659

660
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
661
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
662
                   " crossed surface " + std::to_string(surf.id_) +
23,178✔
663
                   " it could not be located in any cell and it did not leak.");
664
      return;
5,790✔
665
    }
666
  }
667
}
668

669
void Particle::cross_vacuum_bc(const Surface& surf)
35,010,490✔
670
{
671
  // Score any surface current tallies -- note that the particle is moved
672
  // forward slightly so that if the mesh boundary is on the surface, it is
673
  // still processed
674

675
  if (!model::active_meshsurf_tallies.empty()) {
35,010,490✔
676
    // TODO: Find a better solution to score surface currents than
677
    // physically moving the particle forward slightly
678

679
    r() += TINY_BIT * u();
937,222✔
680
    score_surface_tally(*this, model::active_meshsurf_tallies);
937,222✔
681
  }
682

683
  // Score to global leakage tally
684
  keff_tally_leakage() += wgt();
35,010,490✔
685

686
  // Kill the particle
687
  wgt() = 0.0;
35,010,490✔
688

689
  // Display message
690
  if (settings::verbosity >= 10 || trace()) {
35,010,490!
691
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
692
  }
693
}
35,010,490✔
694

695
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
652,640,010✔
696
{
697
  // Do not handle reflective boundary conditions on lower universes
698
  if (n_coord() != 1) {
652,640,010!
699
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
700
                 " off surface in a lower universe.");
701
    return;
×
702
  }
703

704
  // Score surface currents since reflection causes the direction of the
705
  // particle to change. For surface filters, we need to score the tallies
706
  // twice, once before the particle's surface attribute has changed and
707
  // once after. For mesh surface filters, we need to artificially move
708
  // the particle slightly back in case the surface crossing is coincident
709
  // with a mesh boundary
710

711
  if (!model::active_surface_tallies.empty()) {
652,640,010✔
712
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
713
  }
714

715
  if (!model::active_meshsurf_tallies.empty()) {
652,640,010✔
716
    Position r {this->r()};
46,885,487✔
717
    this->r() -= TINY_BIT * u();
46,885,487✔
718
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
719
    this->r() = r;
46,885,487✔
720
  }
721

722
  // Set the new particle direction
723
  u() = new_u;
652,640,010✔
724

725
  // Reassign particle's cell and surface
726
  coord(0).cell() = cell_last(0);
652,640,010✔
727
  surface() = -surface();
652,640,010✔
728

729
  // If a reflective surface is coincident with a lattice or universe
730
  // boundary, it is necessary to redetermine the particle's coordinates in
731
  // the lower universes.
732
  // (unless we're using a dagmc model, which has exactly one universe)
733
  n_coord() = 1;
652,640,010✔
734
  if (surf.geom_type() != GeometryType::DAG &&
1,305,277,262!
735
      !neighbor_list_find_cell(*this)) {
652,637,252!
736
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
737
                 std::to_string(surf.id_) + ".");
×
738
    return;
×
739
  }
740

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

744
  // Diagnostic message
745
  if (settings::verbosity >= 10 || trace()) {
652,640,010!
746
    write_message(1, "    Reflected from surface {}", surf.id_);
×
747
  }
748
}
749

750
void Particle::cross_periodic_bc(
2,244,016✔
751
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
752
{
753
  // Do not handle periodic boundary conditions on lower universes
754
  if (n_coord() != 1) {
2,244,016!
755
    mark_as_lost(
×
756
      "Cannot transfer particle " + std::to_string(id()) +
×
757
      " across surface in a lower universe. Boundary conditions must be "
758
      "applied to root universe.");
759
    return;
×
760
  }
761

762
  // Score surface currents since reflection causes the direction of the
763
  // particle to change -- artificially move the particle slightly back in
764
  // case the surface crossing is coincident with a mesh boundary
765
  if (!model::active_meshsurf_tallies.empty()) {
2,244,016!
766
    Position r {this->r()};
×
767
    this->r() -= TINY_BIT * u();
×
768
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
769
    this->r() = r;
×
770
  }
771

772
  // Adjust the particle's location and direction.
773
  r() = new_r;
2,244,016✔
774
  u() = new_u;
2,244,016✔
775

776
  // Reassign particle's surface
777
  surface() = new_surface;
2,244,016✔
778

779
  // Figure out what cell particle is in now
780
  n_coord() = 1;
2,244,016✔
781

782
  if (!neighbor_list_find_cell(*this)) {
2,244,016!
783
    mark_as_lost("Couldn't find particle after hitting periodic "
×
784
                 "boundary on surface " +
×
785
                 std::to_string(surf.id_) + ".");
×
786
    return;
×
787
  }
788

789
  // Set previous coordinate going slightly past surface crossing
790
  r_last_current() = r() + TINY_BIT * u();
2,244,016✔
791

792
  // Diagnostic message
793
  if (settings::verbosity >= 10 || trace()) {
2,244,016!
794
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
795
  }
796
}
797

798
void Particle::mark_as_lost(const char* message)
5,809✔
799
{
800
  // Print warning and write lost particle file
801
  warning(message);
5,809✔
802
  if (settings::max_write_lost_particles < 0 ||
5,809✔
803
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
804
    write_restart();
389✔
805
  }
806
  // Increment number of lost particles
807
  wgt() = 0.0;
5,809✔
808
#pragma omp atomic
3,164✔
809
  simulation::n_lost_particles += 1;
2,645✔
810

811
  // Count the total number of simulated particles (on this processor)
812
  auto n = simulation::current_batch * settings::gen_per_batch *
5,809✔
813
           simulation::work_per_rank;
814

815
  // Abort the simulation if the maximum number of lost particles has been
816
  // reached
817
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,809✔
818
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
10!
819
    fatal_error("Maximum number of lost particles has been reached.");
10✔
820
  }
821
}
5,799✔
822

823
void Particle::write_restart() const
389✔
824
{
825
  // Dont write another restart file if in particle restart mode
826
  if (settings::run_mode == RunMode::PARTICLE)
389✔
827
    return;
22✔
828

829
  // Set up file name
830
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
831
    simulation::current_batch, id());
685✔
832

833
#pragma omp critical(WriteParticleRestart)
394✔
834
  {
835
    // Create file
836
    hid_t file_id = file_open(filename, 'w');
367✔
837

838
    // Write filetype and version info
839
    write_attribute(file_id, "filetype", "particle restart");
367✔
840
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
367✔
841
    write_attribute(file_id, "openmc_version", VERSION);
367✔
842
#ifdef GIT_SHA1
843
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
844
#endif
845

846
    // Write data to file
847
    write_dataset(file_id, "current_batch", simulation::current_batch);
367✔
848
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
367✔
849
    write_dataset(file_id, "current_generation", simulation::current_gen);
367✔
850
    write_dataset(file_id, "n_particles", settings::n_particles);
367✔
851
    switch (settings::run_mode) {
367!
852
    case RunMode::FIXED_SOURCE:
225✔
853
      write_dataset(file_id, "run_mode", "fixed source");
225✔
854
      break;
225✔
855
    case RunMode::EIGENVALUE:
142✔
856
      write_dataset(file_id, "run_mode", "eigenvalue");
142✔
857
      break;
142✔
858
    case RunMode::PARTICLE:
×
859
      write_dataset(file_id, "run_mode", "particle restart");
×
860
      break;
×
861
    default:
×
862
      break;
×
863
    }
864
    write_dataset(file_id, "id", id());
367✔
865
    write_dataset(file_id, "type", static_cast<int>(type()));
367✔
866

867
    int64_t i = current_work();
367✔
868
    if (settings::run_mode == RunMode::EIGENVALUE) {
367✔
869
      // take source data from primary bank for eigenvalue simulation
870
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
142✔
871
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
142✔
872
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
142✔
873
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
142✔
874
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
142✔
875
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
225!
876
      // re-sample using rng random number seed used to generate source particle
877
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
225✔
878
                     settings::n_particles +
225✔
879
                   simulation::work_index[mpi::rank] + i;
225✔
880
      uint64_t seed = init_seed(id, STREAM_SOURCE);
225✔
881
      // re-sample source site
882
      auto site = sample_external_source(&seed);
225✔
883
      write_dataset(file_id, "weight", site.wgt);
225✔
884
      write_dataset(file_id, "energy", site.E);
225✔
885
      write_dataset(file_id, "xyz", site.r);
225✔
886
      write_dataset(file_id, "uvw", site.u);
225✔
887
      write_dataset(file_id, "time", site.time);
225✔
888
    }
889

890
    // Close file
891
    file_close(file_id);
367✔
892
  } // #pragma omp critical
893
}
367✔
894

895
void Particle::update_neutron_xs(
2,147,483,647✔
896
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
897
{
898
  // Get microscopic cross section cache
899
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
900

901
  // If the cache doesn't match, recalculate micro xs
902
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
903
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
904
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
905
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
906

907
    // If NCrystal is being used, update micro cross section cache
908
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
909
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
910
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
911
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
912
    }
913
  }
914
}
2,147,483,647✔
915

916
//==============================================================================
917
// Non-method functions
918
//==============================================================================
919

920
std::string particle_type_to_str(ParticleType type)
3,130,197✔
921
{
922
  switch (type) {
3,130,197!
923
  case ParticleType::neutron:
2,399,940✔
924
    return "neutron";
2,399,940✔
925
  case ParticleType::photon:
729,993✔
926
    return "photon";
729,993✔
927
  case ParticleType::electron:
132✔
928
    return "electron";
132✔
929
  case ParticleType::positron:
132✔
930
    return "positron";
132✔
931
  }
932
  UNREACHABLE();
×
933
}
934

935
ParticleType str_to_particle_type(std::string str)
3,316,792✔
936
{
937
  if (str == "neutron") {
3,316,792✔
938
    return ParticleType::neutron;
774,663✔
939
  } else if (str == "photon") {
2,542,129✔
940
    return ParticleType::photon;
2,542,043✔
941
  } else if (str == "electron") {
86✔
942
    return ParticleType::electron;
43✔
943
  } else if (str == "positron") {
43!
944
    return ParticleType::positron;
43✔
945
  } else {
946
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
947
  }
948
}
949

950
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,505,758,374✔
951
{
952
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
953
      simulation::surf_source_bank.full()) {
1,178,686,372✔
954
    return;
1,505,628,721✔
955
  }
956

957
  // If a cell/cellfrom/cellto parameter is defined
958
  if (settings::ssw_cell_id != C_NONE) {
337,077✔
959

960
    // Retrieve cell index and storage type
961
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,432✔
962

963
    if (surf.bc_) {
254,432✔
964
      // Leave if cellto with vacuum boundary condition
965
      if (surf.bc_->type() == "vacuum" &&
182,554!
966
          settings::ssw_cell_type == SSWCellType::To) {
33,097✔
967
        return;
12,135✔
968
      }
969

970
      // Leave if other boundary condition than vacuum
971
      if (surf.bc_->type() != "vacuum") {
137,322✔
972
        return;
116,360✔
973
      }
974
    }
975

976
    // Check if the cell of interest has been exited
977
    bool exited = false;
125,937✔
978
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,663✔
979
      if (p.cell_last(i) == cell_idx) {
207,726✔
980
        exited = true;
73,762✔
981
      }
982
    }
983

984
    // Check if the cell of interest has been entered
985
    bool entered = false;
125,937✔
986
    for (int i = 0; i < p.n_coord(); ++i) {
297,965✔
987
      if (p.coord(i).cell() == cell_idx) {
172,028✔
988
        entered = true;
57,517✔
989
      }
990
    }
991

992
    // Vacuum boundary conditions: return if cell is not exited
993
    if (surf.bc_) {
125,937✔
994
      if (surf.bc_->type() == "vacuum" && !exited) {
20,962!
995
        return;
14,662✔
996
      }
997
    } else {
998

999
      // If we both enter and exit the cell of interest
1000
      if (entered && exited) {
104,975✔
1001
        return;
27,203✔
1002
      }
1003

1004
      // If we did not enter nor exit the cell of interest
1005
      if (!entered && !exited) {
77,772✔
1006
        return;
13,499✔
1007
      }
1008

1009
      // If cellfrom and the cell before crossing is not the cell of
1010
      // interest
1011
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,273✔
1012
        return;
11,543✔
1013
      }
1014

1015
      // If cellto and the cell after crossing is not the cell of interest
1016
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,730✔
1017
        return;
12,022✔
1018
      }
1019
    }
1020
  }
1021

1022
  SourceSite site;
129,653✔
1023
  site.r = p.r();
129,653✔
1024
  site.u = p.u();
129,653✔
1025
  site.E = p.E();
129,653✔
1026
  site.time = p.time();
129,653✔
1027
  site.wgt = p.wgt();
129,653✔
1028
  site.delayed_group = p.delayed_group();
129,653✔
1029
  site.surf_id = surf.id_;
129,653✔
1030
  site.particle = p.type();
129,653✔
1031
  site.parent_id = p.id();
129,653✔
1032
  site.progeny_id = p.n_progeny();
129,653✔
1033
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1034
}
1035

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