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

openmc-dev / openmc / 22596289416

02 Mar 2026 09:22PM UTC coverage: 80.951% (-0.6%) from 81.508%
22596289416

Pull #3757

github

web-flow
Merge d60b97b21 into 823b4c96c
Pull Request #3757: Testing point detectors

17543 of 25514 branches covered (68.76%)

Branch coverage included in aggregate %.

117 of 510 new or added lines in 26 files covered. (22.94%)

22 existing lines in 3 files now uncovered.

57759 of 67508 relevant lines covered (85.56%)

44598697.25 hits per line

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

83.55
/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,147,483,647✔
47
{
48
  // Determine mass in eV/c^2
49
  switch (type().pdg_number()) {
2,147,483,647✔
50
  case PDG_NEUTRON:
51
    return MASS_NEUTRON_EV;
52
  case PDG_ELECTRON:
53,917,013✔
53
  case PDG_POSITRON:
53,917,013✔
54
    return MASS_ELECTRON_EV;
53,917,013✔
55
  default:
22,048,390✔
56
    return this->type().mass() * AMU_EV;
22,048,390✔
57
  }
58
}
59

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

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

89
  // Increment number of secondaries created (for ParticleProductionFilter)
90
  n_secondaries()++;
58,670,709✔
91

92
  auto& bank = secondary_bank().emplace_back();
58,670,709✔
93
  bank.particle = type;
58,670,709✔
94
  bank.wgt = wgt;
58,670,709✔
95
  bank.r = r();
58,670,709!
96
  bank.u = u;
58,670,709✔
97
  bank.E = settings::run_CE ? E : g();
58,670,709!
98
  bank.time = time();
58,670,709✔
99
  bank_second_E() += bank.E;
58,670,709✔
100
  return true;
58,670,709✔
101
}
102

103
void Particle::split(double wgt)
4,249,826✔
104
{
105
  auto& bank = secondary_bank().emplace_back();
4,249,826✔
106
  bank.particle = type();
4,249,826✔
107
  bank.wgt = wgt;
4,249,826✔
108
  bank.r = r();
4,249,826✔
109
  bank.u = u();
4,249,826✔
110
  bank.E = settings::run_CE ? E() : g();
4,249,826✔
111
  bank.time = time();
4,249,826✔
112

113
  // Convert signed index to a signed surface ID
114
  if (surface() == SURFACE_NONE) {
4,249,826✔
115
    bank.surf_id = SURFACE_NONE;
4,249,281✔
116
  } else {
117
    int surf_id = model::surfaces[surface_index()]->id_;
545✔
118
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
545✔
119
  }
120
}
4,249,826✔
121

122
void Particle::from_source(const SourceSite* src)
240,482,938✔
123
{
124
  // Reset some attributes
125
  clear();
240,482,938✔
126
  surface() = SURFACE_NONE;
240,482,938✔
127
  cell_born() = C_NONE;
240,482,938✔
128
  material() = C_NONE;
240,482,938✔
129
  n_collision() = 0;
240,482,938✔
130
  fission() = false;
240,482,938✔
131
  zero_flux_derivs();
240,482,938✔
132
  lifetime() = 0.0;
240,482,938✔
133
#ifdef OPENMC_DAGMC_ENABLED
134
  history().reset();
22,023,242✔
135
#endif
136

137
  // Copy attributes from source bank site
138
  type() = src->particle;
240,482,938✔
139
  wgt() = src->wgt;
240,482,938✔
140
  wgt_last() = src->wgt;
240,482,938✔
141
  r() = src->r;
240,482,938✔
142
  u() = src->u;
240,482,938✔
143
  r_born() = src->r;
240,482,938✔
144
  r_last_current() = src->r;
240,482,938✔
145
  r_last() = src->r;
240,482,938✔
146
  u_last() = src->u;
240,482,938✔
147
  if (settings::run_CE) {
240,482,938✔
148
    E() = src->E;
124,557,321✔
149
    g() = 0;
124,557,321✔
150
  } else {
151
    g() = static_cast<int>(src->E);
115,925,617✔
152
    g_last() = static_cast<int>(src->E);
115,925,617✔
153
    E() = data::mg.energy_bin_avg_[g()];
115,925,617✔
154
  }
155
  E_last() = E();
240,482,938✔
156
  time() = src->time;
240,482,938✔
157
  time_last() = src->time;
240,482,938✔
158
  parent_nuclide() = src->parent_nuclide;
240,482,938✔
159
  delayed_group() = src->delayed_group;
240,482,938✔
160

161
  // Convert signed surface ID to signed index
162
  if (src->surf_id != SURFACE_NONE) {
240,482,938✔
163
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,545✔
164
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,545✔
165
  }
166
}
240,482,938✔
167

NEW
168
void Particle::initialize_pseudoparticle(
×
169
  Particle& p, Direction u_new, double E_new)
170
{
171
  // Reset some attributes
NEW
172
  clear();
×
NEW
173
  surface() = SURFACE_NONE;
×
NEW
174
  cell_born() = C_NONE;
×
NEW
175
  material() = C_NONE;
×
NEW
176
  n_collision() = 0;
×
NEW
177
  fission() = false;
×
NEW
178
  zero_flux_derivs();
×
NEW
179
  lifetime() = 0.0;
×
180

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

204
void Particle::event_calculate_xs(bool is_pseudo)
2,147,483,647✔
205
{
206
  // Set the random number stream
207
  stream() = is_pseudo ? STREAM_NEXT_EVENT : STREAM_TRACKING;
2,147,483,647!
208

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

216
  // Reset event variables
217
  event() = TallyEvent::KILL;
2,147,483,647✔
218
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
219
  event_mt() = REACTION_NONE;
2,147,483,647✔
220

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

231
    // Set birth cell attribute
232
    if (cell_born() == C_NONE)
231,812,029!
233
      cell_born() = lowest_coord().cell();
231,812,029✔
234

235
    // Initialize last cells from current cell
236
    for (int j = 0; j < n_coord(); ++j) {
481,095,970✔
237
      cell_last(j) = coord(j).cell();
249,283,941✔
238
    }
239
    n_coord_last() = n_coord();
231,812,029✔
240
  }
241

242
  // Write particle track.
243
  if (write_track() && !is_pseudo)
2,147,483,647!
244
    write_particle_track(*this);
10,309✔
245

246
  if (settings::check_overlaps)
2,147,483,647!
247
    check_cell_overlap(*this);
×
248

249
  // Calculate microscopic and macroscopic cross sections
250
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
251
    if (settings::run_CE) {
2,147,483,647✔
252
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
253
          density_mult() != density_mult_last()) {
385,347,289✔
254
        // If the material is the same as the last material and the
255
        // temperature hasn't changed, we don't need to lookup cross
256
        // sections again.
257
        model::materials[material()]->calculate_xs(*this);
1,780,229,415✔
258
      }
259
    } else {
260
      // Get the MG data; unlike the CE case above, we have to re-calculate
261
      // cross sections for every collision since the cross sections may
262
      // be angle-dependent
263
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,063,937,414✔
264

265
      // Update the particle's group while we know we are multi-group
266
      g_last() = g();
2,063,937,414✔
267
    }
268
  } else {
269
    macro_xs().total = 0.0;
111,829,724✔
270
    macro_xs().absorption = 0.0;
111,829,724✔
271
    macro_xs().fission = 0.0;
111,829,724✔
272
    macro_xs().nu_fission = 0.0;
111,829,724✔
273
  }
274
}
275

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

281
  // Sample a distance to collision
282
  if (type() == ParticleType::electron() ||
2,147,483,647✔
283
      type() == ParticleType::positron()) {
2,147,483,647✔
284
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
107,834,026!
285
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
286
    collision_distance() = INFINITY;
111,829,724✔
287
  } else {
288
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
289
  }
290

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

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

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

306
  // Score timed track-length tallies
307
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
308
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
309
  }
310

311
  // Score track-length tallies
312
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
313
    score_tracklength_tally(*this, distance);
1,722,253,288✔
314
  }
315

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

321
  // Score flux derivative accumulators for differential tallies.
322
  if (!model::active_tallies.empty()) {
2,147,483,647✔
323
    score_track_derivative(*this, distance);
1,892,015,340✔
324
  }
325

326
  // Set particle weight to zero if it hit the time boundary
327
  if (distance == distance_cutoff) {
2,147,483,647✔
328
    wgt() = 0.0;
224,928✔
329
  }
330
}
2,147,483,647✔
331

332
void Particle::event_cross_surface(bool is_pseudo)
2,147,483,647✔
333
{
334
  // Saving previous cell data
335
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
336
    cell_last(j) = coord(j).cell();
2,147,483,647✔
337
  }
338
  n_coord_last() = n_coord();
2,147,483,647✔
339

340
  // Set surface that particle is on and adjust coordinate levels
341
  surface() = boundary().surface();
2,147,483,647✔
342
  n_coord() = boundary().coord_level();
2,147,483,647✔
343

344
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
345
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
346
      boundary().lattice_translation()[2] != 0) {
1,860,010,270✔
347
    // Particle crosses lattice boundary
348

349
    bool verbose = settings::verbosity >= 10 || trace();
750,250,830!
350
    cross_lattice(*this, boundary(), verbose);
750,250,830✔
351
    event() = TallyEvent::LATTICE;
750,250,830✔
352
  } else {
353
    // Particle crosses surface
354
    const auto& surf {model::surfaces[surface_index()].get()};
1,671,468,397✔
355
    // If BC, add particle to surface source before crossing surface
356
    if (surf->surf_source_ && surf->bc_ && !is_pseudo) {
1,671,468,397!
357
      add_surf_source_to_bank(*this, *surf);
720,229,983✔
358
    }
359
    this->cross_surface(*surf);
1,671,468,397✔
360
    // If no BC, add particle to surface source after crossing surface
361
    if (surf->surf_source_ && !surf->bc_ && !is_pseudo) {
1,671,468,388!
362
      add_surf_source_to_bank(*this, *surf);
950,000,578✔
363
    }
364
    if (settings::weight_window_checkpoint_surface && !is_pseudo) {
1,671,468,388!
365
      apply_weight_windows(*this);
74,912✔
366
    }
367
    event() = TallyEvent::SURFACE;
1,671,468,388✔
368
  }
369
  // Score cell to cell partial currents
370
  if (!model::active_surface_tallies.empty() && !is_pseudo) {
2,147,483,647!
371
    score_surface_tally(*this, model::active_surface_tallies);
34,922,767✔
372
  }
373
}
2,147,483,647✔
374

375
void Particle::event_collide()
2,147,483,647✔
376
{
377

378
  // Score collision estimate of keff
379
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
380
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,139,011,038✔
381
  }
382

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

387
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
388
    score_surface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
389

390
  // Clear surface component
391
  surface() = SURFACE_NONE;
2,147,483,647✔
392

393
  if (settings::run_CE) {
2,147,483,647✔
394
    collision(*this);
1,070,992,750✔
395
  } else {
396
    collision_mg(*this);
1,783,060,477✔
397
  }
398

399
  // Collision track feature to recording particle interaction
400
  if (settings::collision_track) {
2,147,483,647✔
401
    collision_track_record(*this);
150,087✔
402
  }
403

404
  // Score collision estimator tallies -- this is done after a collision
405
  // has occurred rather than before because we need information on the
406
  // outgoing energy for any tallies with an outgoing energy filter
407
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
408
    score_collision_tally(*this);
107,367,326✔
409
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
410
    if (settings::run_CE) {
406,034,945✔
411
      score_analog_tally_ce(*this);
404,826,683✔
412
    } else {
413
      score_analog_tally_mg(*this);
1,208,262✔
414
    }
415
  }
416

417
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
418
    pht_collision_energy();
2,024✔
419
  }
420

421
  // Reset banked weight during collision
422
  n_bank() = 0;
2,147,483,647✔
423
  bank_second_E() = 0.0;
2,147,483,647✔
424
  wgt_bank() = 0.0;
2,147,483,647✔
425

426
  // Clear number of secondaries in this collision. This is
427
  // distinct from the number of created neutrons n_bank() above!
428
  n_secondaries() = 0;
2,147,483,647✔
429

430
  zero_delayed_bank();
2,147,483,647✔
431

432
  // Reset fission logical
433
  fission() = false;
2,147,483,647✔
434

435
  // Save coordinates for tallying purposes
436
  r_last_current() = r();
2,147,483,647✔
437

438
  // Set last material to none since cross sections will need to be
439
  // re-evaluated
440
  material_last() = C_NONE;
2,147,483,647✔
441

442
  // Set all directions to base level -- right now, after a collision, only
443
  // the base level directions are changed
444
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
445
    if (coord(j + 1).rotated()) {
161,247,365✔
446
      // If next level is rotated, apply rotation matrix
447
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
448
      const auto& u {coord(j).u()};
10,426,614✔
449
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
450
    } else {
451
      // Otherwise, copy this level's direction
452
      coord(j + 1).u() = coord(j).u();
150,820,751✔
453
    }
454
  }
455

456
  // Score flux derivative accumulators for differential tallies.
457
  if (!model::active_tallies.empty())
2,147,483,647✔
458
    score_collision_derivative(*this);
936,582,995✔
459

460
#ifdef OPENMC_DAGMC_ENABLED
461
  history().reset();
261,515,247✔
462
#endif
463
}
2,147,483,647✔
464

465
void Particle::event_revive_from_secondary()
2,147,483,647✔
466
{
467
  // If particle has too many events, display warning and kill it
468
  ++n_event();
2,147,483,647✔
469
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
470
    warning("Particle " + std::to_string(id()) +
×
471
            " underwent maximum number of events.");
472
    wgt() = 0.0;
×
473
  }
474

475
  // Check for secondary particles if this particle is dead
476
  if (!alive()) {
2,147,483,647✔
477
    // Write final position for this particle
478
    if (write_track()) {
231,811,625✔
479
      write_particle_track(*this);
6,244✔
480
    }
481

482
    // If no secondary particles, break out of event loop
483
    if (secondary_bank().empty())
231,811,625✔
484
      return;
485

486
    from_source(&secondary_bank().back());
63,124,054✔
487
    secondary_bank().pop_back();
63,124,054✔
488
    n_event() = 0;
63,124,054✔
489
    bank_second_E() = 0.0;
63,124,054✔
490

491
    // Subtract secondary particle energy from interim pulse-height results
492
    if (!model::active_pulse_height_tallies.empty() &&
63,124,054✔
493
        this->type().is_photon()) {
15,499✔
494
      // Since the birth cell of the particle has not been set we
495
      // have to determine it before the energy of the secondary particle can be
496
      // removed from the pulse-height of this cell.
497
      if (lowest_coord().cell() == C_NONE) {
605!
498
        bool verbose = settings::verbosity >= 10 || trace();
605!
499
        if (!exhaustive_find_cell(*this, verbose)) {
605!
500
          mark_as_lost("Could not find the cell containing particle " +
×
501
                       std::to_string(id()));
×
502
          return;
×
503
        }
504
        // Set birth cell attribute
505
        if (cell_born() == C_NONE)
605!
506
          cell_born() = lowest_coord().cell();
605✔
507

508
        // Initialize last cells from current cell
509
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
510
          cell_last(j) = coord(j).cell();
605✔
511
        }
512
        n_coord_last() = n_coord();
605✔
513
      }
514
      pht_secondary_particles();
605✔
515
    }
516

517
    // Enter new particle in particle track file
518
    if (write_track())
63,124,054✔
519
      add_particle_track(*this);
5,234✔
520
  }
521
}
522

523
void Particle::event_death()
168,688,571✔
524
{
525
#ifdef OPENMC_DAGMC_ENABLED
526
  history().reset();
15,411,985✔
527
#endif
528

529
  // Finish particle track output.
530
  if (write_track()) {
168,688,571✔
531
    finalize_particle_track(*this);
1,010✔
532
  }
533

534
// Contribute tally reduction variables to global accumulator
535
#pragma omp atomic
92,894,001✔
536
  global_tally_absorption += keff_tally_absorption();
168,688,571✔
537
#pragma omp atomic
92,975,592✔
538
  global_tally_collision += keff_tally_collision();
168,688,571✔
539
#pragma omp atomic
93,213,629✔
540
  global_tally_tracklength += keff_tally_tracklength();
168,688,571✔
541
#pragma omp atomic
92,321,270✔
542
  global_tally_leakage += keff_tally_leakage();
168,688,571✔
543

544
  // Reset particle tallies once accumulated
545
  keff_tally_absorption() = 0.0;
168,688,571✔
546
  keff_tally_collision() = 0.0;
168,688,571✔
547
  keff_tally_tracklength() = 0.0;
168,688,571✔
548
  keff_tally_leakage() = 0.0;
168,688,571✔
549

550
  if (!model::active_pulse_height_tallies.empty()) {
168,688,571✔
551
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
552
  }
553

554
  // Record the number of progeny created by this particle.
555
  // This data will be used to efficiently sort the fission bank.
556
  if (settings::run_mode == RunMode::EIGENVALUE) {
168,688,571✔
557
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
141,424,700✔
558
    simulation::progeny_per_particle[offset] = n_progeny();
141,424,700✔
559
  }
560
}
168,688,571✔
561

562
void Particle::pht_collision_energy()
2,024✔
563
{
564
  // Adds the energy particles lose in a collision to the pulse-height
565

566
  // determine index of cell in pulse_height_cells
567
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
568
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024!
569

570
  if (it != model::pulse_height_cells.end()) {
2,024!
571
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
572
    pht_storage()[index] += E_last() - E();
2,024✔
573

574
    // If the energy of the particle is below the cutoff, it will not be sampled
575
    // so its energy is added to the pulse-height in the cell
576
    int photon = ParticleType::photon().transport_index();
2,024✔
577
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
578
      pht_storage()[index] += E();
825✔
579
    }
580
  }
581
}
2,024✔
582

583
void Particle::pht_secondary_particles()
605✔
584
{
585
  // Removes the energy of secondary produced particles from the pulse-height
586

587
  // determine index of cell in pulse_height_cells
588
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
589
    model::pulse_height_cells.end(), cell_born());
605!
590

591
  if (it != model::pulse_height_cells.end()) {
605!
592
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
593
    pht_storage()[index] -= E();
605✔
594
  }
595
}
605✔
596

597
void Particle::cross_surface(const Surface& surf)
1,673,319,863✔
598
{
599

600
  if (settings::verbosity >= 10 || trace()) {
1,673,319,863✔
601
    write_message(1, "    Crossing surface {}", surf.id_);
66✔
602
  }
603

604
// if we're crossing a CSG surface, make sure the DAG history is reset
605
#ifdef OPENMC_DAGMC_ENABLED
606
  if (surf.geom_type() == GeometryType::CSG)
152,796,651✔
607
    history().reset();
152,739,492✔
608
#endif
609

610
  // Handle any applicable boundary conditions.
611
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,673,319,863!
612
      settings::run_mode != RunMode::VOLUME) {
613
    surf.bc_->handle_particle(*this, surf);
720,582,091✔
614
    return;
720,582,091✔
615
  }
616

617
  // ==========================================================================
618
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
619

620
#ifdef OPENMC_DAGMC_ENABLED
621
  // in DAGMC, we know what the next cell should be
622
  if (surf.geom_type() == GeometryType::DAG) {
86,845,868✔
623
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,350✔
624
                       lowest_coord().universe()) -
46,350✔
625
                     1;
46,350✔
626
    // save material, temperature, and density multiplier
627
    material_last() = material();
46,350✔
628
    sqrtkT_last() = sqrtkT();
46,350✔
629
    density_mult_last() = density_mult();
46,350✔
630
    // set new cell value
631
    lowest_coord().cell() = i_cell;
46,350✔
632
    auto& cell = model::cells[i_cell];
46,350✔
633

634
    cell_instance() = 0;
46,350✔
635
    if (cell->distribcell_index_ >= 0)
46,350✔
636
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,326✔
637

638
    material() = cell->material(cell_instance());
46,350!
639
    sqrtkT() = cell->sqrtkT(cell_instance());
46,350!
640
    density_mult() = cell->density_mult(cell_instance());
46,350✔
641
    return;
46,350✔
642
  }
643
#endif
644

645
  bool verbose = settings::verbosity >= 10 || trace();
952,691,422!
646
  if (neighbor_list_find_cell(*this, verbose)) {
952,691,422✔
647
    return;
648
  }
649

650
  // ==========================================================================
651
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
652

653
  // Remove lower coordinate levels
654
  n_coord() = 1;
29,911✔
655
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
656

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

663
    surface() = SURFACE_NONE;
5,799✔
664
    n_coord() = 1;
5,799✔
665
    r() += TINY_BIT * u();
5,799✔
666

667
    // Couldn't find next cell anywhere! This probably means there is an actual
668
    // undefined region in the geometry.
669

670
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
671
      mark_as_lost("After particle " + std::to_string(id()) +
23,178✔
672
                   " crossed surface " + std::to_string(surf.id_) +
17,388✔
673
                   " it could not be located in any cell and it did not leak.");
674
      return;
5,790✔
675
    }
676
  }
677
}
678

679
void Particle::cross_vacuum_bc(const Surface& surf)
35,021,851✔
680
{
681
  // Score any surface current tallies -- note that the particle is moved
682
  // forward slightly so that if the mesh boundary is on the surface, it is
683
  // still processed
684

685
  if (!model::active_meshsurf_tallies.empty()) {
35,021,851✔
686
    // TODO: Find a better solution to score surface currents than
687
    // physically moving the particle forward slightly
688

689
    r() += TINY_BIT * u();
937,222✔
690
    score_surface_tally(*this, model::active_meshsurf_tallies);
937,222✔
691
  }
692

693
  // Score to global leakage tally
694
  keff_tally_leakage() += wgt();
35,021,851✔
695

696
  // Kill the particle
697
  wgt() = 0.0;
35,021,851✔
698

699
  // Display message
700
  if (settings::verbosity >= 10 || trace()) {
35,021,851!
701
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
702
  }
703
}
35,021,851✔
704

705
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
684,318,903✔
706
{
707
  // Do not handle reflective boundary conditions on lower universes
708
  if (n_coord() != 1) {
684,318,903!
709
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
710
                 " off surface in a lower universe.");
711
    return;
×
712
  }
713

714
  // Score surface currents since reflection causes the direction of the
715
  // particle to change. For surface filters, we need to score the tallies
716
  // twice, once before the particle's surface attribute has changed and
717
  // once after. For mesh surface filters, we need to artificially move
718
  // the particle slightly back in case the surface crossing is coincident
719
  // with a mesh boundary
720

721
  if (!model::active_surface_tallies.empty()) {
684,318,903✔
722
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
723
  }
724

725
  if (!model::active_meshsurf_tallies.empty()) {
684,318,903✔
726
    Position r {this->r()};
46,885,487✔
727
    this->r() -= TINY_BIT * u();
46,885,487✔
728
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
729
    this->r() = r;
46,885,487✔
730
  }
731

732
  // Set the new particle direction
733
  u() = new_u;
684,318,903✔
734

735
  // Reassign particle's cell and surface
736
  coord(0).cell() = cell_last(0);
684,318,903✔
737
  surface() = -surface();
684,318,903✔
738

739
  // If a reflective surface is coincident with a lattice or universe
740
  // boundary, it is necessary to redetermine the particle's coordinates in
741
  // the lower universes.
742
  // (unless we're using a dagmc model, which has exactly one universe)
743
  n_coord() = 1;
684,318,903✔
744
  if (surf.geom_type() != GeometryType::DAG &&
1,368,635,048!
745
      !neighbor_list_find_cell(*this)) {
684,316,145✔
746
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
747
                 std::to_string(surf.id_) + ".");
×
748
    return;
×
749
  }
750

751
  // Set previous coordinate going slightly past surface crossing
752
  r_last_current() = r() + TINY_BIT * u();
684,318,903✔
753

754
  // Diagnostic message
755
  if (settings::verbosity >= 10 || trace()) {
684,318,903!
756
    write_message(1, "    Reflected from surface {}", surf.id_);
×
757
  }
758
}
759

760
void Particle::cross_periodic_bc(
2,246,803✔
761
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
762
{
763
  // Do not handle periodic boundary conditions on lower universes
764
  if (n_coord() != 1) {
2,246,803!
765
    mark_as_lost(
×
766
      "Cannot transfer particle " + std::to_string(id()) +
×
767
      " across surface in a lower universe. Boundary conditions must be "
768
      "applied to root universe.");
769
    return;
×
770
  }
771

772
  // Score surface currents since reflection causes the direction of the
773
  // particle to change -- artificially move the particle slightly back in
774
  // case the surface crossing is coincident with a mesh boundary
775
  if (!model::active_meshsurf_tallies.empty()) {
2,246,803!
776
    Position r {this->r()};
×
777
    this->r() -= TINY_BIT * u();
×
778
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
779
    this->r() = r;
×
780
  }
781

782
  // Adjust the particle's location and direction.
783
  r() = new_r;
2,246,803✔
784
  u() = new_u;
2,246,803✔
785

786
  // Reassign particle's surface
787
  surface() = new_surface;
2,246,803✔
788

789
  // Figure out what cell particle is in now
790
  n_coord() = 1;
2,246,803✔
791

792
  if (!neighbor_list_find_cell(*this)) {
2,246,803!
793
    mark_as_lost("Couldn't find particle after hitting periodic "
×
794
                 "boundary on surface " +
×
795
                 std::to_string(surf.id_) + ".");
×
796
    return;
×
797
  }
798

799
  // Set previous coordinate going slightly past surface crossing
800
  r_last_current() = r() + TINY_BIT * u();
2,246,803✔
801

802
  // Diagnostic message
803
  if (settings::verbosity >= 10 || trace()) {
2,246,803!
804
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
805
  }
806
}
807

808
void Particle::mark_as_lost(const char* message)
5,799✔
809
{
810
  // Print warning and write lost particle file
811
  warning(message);
5,799✔
812
  if (settings::max_write_lost_particles < 0 ||
5,799✔
813
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
814
    write_restart();
374✔
815
  }
816
  // Increment number of lost particles
817
  wgt() = 0.0;
5,799✔
818
#pragma omp atomic
3,154✔
819
  simulation::n_lost_particles += 1;
2,645✔
820

821
  // Count the total number of simulated particles (on this processor)
822
  auto n = simulation::current_batch * settings::gen_per_batch *
5,799✔
823
           simulation::work_per_rank;
824

825
  // Abort the simulation if the maximum number of lost particles has been
826
  // reached
827
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
828
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
829
    fatal_error("Maximum number of lost particles has been reached.");
9✔
830
  }
831
}
5,790✔
832

833
void Particle::write_restart() const
374✔
834
{
835
  // Dont write another restart file if in particle restart mode
836
  if (settings::run_mode == RunMode::PARTICLE)
374✔
837
    return;
22✔
838

839
  // Set up file name
840
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
352✔
841
    simulation::current_batch, id());
352✔
842

843
#pragma omp critical(WriteParticleRestart)
187✔
844
  {
352✔
845
    // Create file
846
    hid_t file_id = file_open(filename, 'w');
352✔
847

848
    // Write filetype and version info
849
    write_attribute(file_id, "filetype", "particle restart");
352✔
850
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
352✔
851
    write_attribute(file_id, "openmc_version", VERSION);
352✔
852
#ifdef GIT_SHA1
853
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
854
#endif
855

856
    // Write data to file
857
    write_dataset(file_id, "current_batch", simulation::current_batch);
352✔
858
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
352✔
859
    write_dataset(file_id, "current_generation", simulation::current_gen);
352✔
860
    write_dataset(file_id, "n_particles", settings::n_particles);
352✔
861
    switch (settings::run_mode) {
352!
862
    case RunMode::FIXED_SOURCE:
220✔
863
      write_dataset(file_id, "run_mode", "fixed source");
220✔
864
      break;
115✔
865
    case RunMode::EIGENVALUE:
132✔
866
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
867
      break;
72✔
868
    case RunMode::PARTICLE:
×
869
      write_dataset(file_id, "run_mode", "particle restart");
×
870
      break;
871
    default:
872
      break;
873
    }
874
    write_dataset(file_id, "id", id());
352✔
875
    write_dataset(file_id, "type", type().pdg_number());
352✔
876

877
    int64_t i = current_work();
352✔
878
    if (settings::run_mode == RunMode::EIGENVALUE) {
352✔
879
      // take source data from primary bank for eigenvalue simulation
880
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
881
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
882
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
883
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
884
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
885
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
220!
886
      // re-sample using rng random number seed used to generate source particle
887
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
220✔
888
                     settings::n_particles +
220✔
889
                   simulation::work_index[mpi::rank] + i;
220✔
890
      uint64_t seed = init_seed(id, STREAM_SOURCE);
220✔
891
      // re-sample source site
892
      auto site = sample_external_source(&seed);
220✔
893
      write_dataset(file_id, "weight", site.wgt);
220✔
894
      write_dataset(file_id, "energy", site.E);
220✔
895
      write_dataset(file_id, "xyz", site.r);
220✔
896
      write_dataset(file_id, "uvw", site.u);
220✔
897
      write_dataset(file_id, "time", site.time);
220✔
898
    }
899

900
    // Close file
901
    file_close(file_id);
352✔
902
  } // #pragma omp critical
903
}
352✔
904

905
void Particle::update_neutron_xs(
2,147,483,647✔
906
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
907
{
908
  // Get microscopic cross section cache
909
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
910

911
  // If the cache doesn't match, recalculate micro xs
912
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
913
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
914
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
915
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
916

917
    // If NCrystal is being used, update micro cross section cache
918
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
919
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
920
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
921
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
922
    }
923
  }
924
}
2,147,483,647✔
925

926
//==============================================================================
927
// Non-method functions
928
//==============================================================================
929
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,670,230,561✔
930
{
931
  if (simulation::current_batch <= settings::n_inactive ||
1,670,230,561✔
932
      simulation::surf_source_bank.full()) {
1,284,795,371✔
933
    return;
1,670,100,908✔
934
  }
935

936
  // If a cell/cellfrom/cellto parameter is defined
937
  if (settings::ssw_cell_id != C_NONE) {
337,076✔
938

939
    // Retrieve cell index and storage type
940
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,431✔
941

942
    if (surf.bc_) {
254,431✔
943
      // Leave if cellto with vacuum boundary condition
944
      if (surf.bc_->type() == "vacuum" &&
298,914✔
945
          settings::ssw_cell_type == SSWCellType::To) {
33,097✔
946
        return;
947
      }
948

949
      // Leave if other boundary condition than vacuum
950
      if (surf.bc_->type() != "vacuum") {
274,644✔
951
        return;
952
      }
953
    }
954

955
    // Check if the cell of interest has been exited
956
    bool exited = false;
957
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,661✔
958
      if (p.cell_last(i) == cell_idx) {
207,725✔
959
        exited = true;
73,763✔
960
      }
961
    }
962

963
    // Check if the cell of interest has been entered
964
    bool entered = false;
965
    for (int i = 0; i < p.n_coord(); ++i) {
297,963✔
966
      if (p.coord(i).cell() == cell_idx) {
172,027✔
967
        entered = true;
57,516✔
968
      }
969
    }
970

971
    // Vacuum boundary conditions: return if cell is not exited
972
    if (surf.bc_) {
125,936✔
973
      if (surf.bc_->type() == "vacuum" && !exited) {
41,924!
974
        return;
975
      }
976
    } else {
977

978
      // If we both enter and exit the cell of interest
979
      if (entered && exited) {
104,974✔
980
        return;
981
      }
982

983
      // If we did not enter nor exit the cell of interest
984
      if (!entered && !exited) {
77,771✔
985
        return;
986
      }
987

988
      // If cellfrom and the cell before crossing is not the cell of
989
      // interest
990
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,273✔
991
        return;
992
      }
993

994
      // If cellto and the cell after crossing is not the cell of interest
995
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,731✔
996
        return;
997
      }
998
    }
999
  }
1000

1001
  SourceSite site;
129,653✔
1002
  site.r = p.r();
129,653✔
1003
  site.u = p.u();
129,653✔
1004
  site.E = p.E();
129,653✔
1005
  site.time = p.time();
129,653✔
1006
  site.wgt = p.wgt();
129,653✔
1007
  site.delayed_group = p.delayed_group();
129,653✔
1008
  site.surf_id = surf.id_;
129,653✔
1009
  site.particle = p.type();
129,653✔
1010
  site.parent_id = p.id();
129,653✔
1011
  site.progeny_id = p.n_progeny();
129,653✔
1012
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1013
}
1014

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