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

openmc-dev / openmc / 22010122371

14 Feb 2026 03:14AM UTC coverage: 81.582% (-0.1%) from 81.73%
22010122371

push

github

web-flow
Store atomic mass in ParticleType. (#3765)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

16999 of 23629 branches covered (71.94%)

Branch coverage included in aggregate %.

6 of 7 new or added lines in 2 files covered. (85.71%)

302 existing lines in 25 files now uncovered.

56042 of 65902 relevant lines covered (85.04%)

42116893.57 hits per line

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

84.62
/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 (type().pdg_number()) {
1,870,003,116✔
52
    case PDG_NEUTRON:
1,807,847,341✔
53
      mass = MASS_NEUTRON_EV;
1,807,847,341✔
54
    case PDG_ELECTRON:
1,851,964,437✔
55
    case PDG_POSITRON:
56
      mass = MASS_ELECTRON_EV;
1,851,964,437✔
57
    default:
1,870,003,116✔
58
      mass = this->type().mass() * AMU_EV;
1,870,003,116✔
59
    }
60

61
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
62
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,870,003,116✔
63
           (this->E() + mass);
1,870,003,116✔
64
  } else {
65
    auto& macro_xs = data::mg.macro_xs_[this->material()];
1,688,676,066✔
66
    int macro_t = this->mg_xs_cache().t;
1,688,676,066✔
67
    int macro_a = macro_xs.get_angle_index(this->u());
1,688,676,066✔
68
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
1,688,676,066✔
69
                   nullptr, nullptr, macro_t, macro_a);
1,688,676,066✔
70
  }
71
}
72

73
bool Particle::create_secondary(
91,991,304✔
74
  double wgt, Direction u, double E, ParticleType type)
75
{
76
  // If energy is below cutoff for this particle, don't create secondary
77
  // particle
78
  int idx = type.transport_index();
91,991,304✔
79
  if (idx == C_NONE) {
91,991,304!
80
    return false;
×
81
  }
82
  if (E < settings::energy_cutoff[idx]) {
91,991,304✔
83
    return false;
43,992,516✔
84
  }
85

86
  // Increment number of secondaries created (for ParticleProductionFilter)
87
  n_secondaries()++;
47,998,788✔
88

89
  auto& bank = secondary_bank().emplace_back();
47,998,788✔
90
  bank.particle = type;
47,998,788✔
91
  bank.wgt = wgt;
47,998,788✔
92
  bank.r = r();
47,998,788✔
93
  bank.u = u;
47,998,788✔
94
  bank.E = settings::run_CE ? E : g();
47,998,788!
95
  bank.time = time();
47,998,788✔
96
  bank_second_E() += bank.E;
47,998,788✔
97
  return true;
47,998,788✔
98
}
99

100
void Particle::split(double wgt)
3,390,275✔
101
{
102
  auto& bank = secondary_bank().emplace_back();
3,390,275✔
103
  bank.particle = type();
3,390,275✔
104
  bank.wgt = wgt;
3,390,275✔
105
  bank.r = r();
3,390,275✔
106
  bank.u = u();
3,390,275✔
107
  bank.E = settings::run_CE ? E() : g();
3,390,275✔
108
  bank.time = time();
3,390,275✔
109

110
  // Convert signed index to a signed surface ID
111
  if (surface() == SURFACE_NONE) {
3,390,275!
112
    bank.surf_id = SURFACE_NONE;
3,390,275✔
113
  } else {
UNCOV
114
    int surf_id = model::surfaces[surface_index()]->id_;
×
UNCOV
115
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
×
116
  }
117
}
3,390,275✔
118

119
void Particle::from_source(const SourceSite* src)
196,506,287✔
120
{
121
  // Reset some attributes
122
  clear();
196,506,287✔
123
  surface() = SURFACE_NONE;
196,506,287✔
124
  cell_born() = C_NONE;
196,506,287✔
125
  material() = C_NONE;
196,506,287✔
126
  n_collision() = 0;
196,506,287✔
127
  fission() = false;
196,506,287✔
128
  zero_flux_derivs();
196,506,287✔
129
  lifetime() = 0.0;
196,506,287✔
130
#ifdef OPENMC_DAGMC_ENABLED
131
  history().reset();
132
#endif
133

134
  // Copy attributes from source bank site
135
  type() = src->particle;
196,506,287✔
136
  wgt() = src->wgt;
196,506,287✔
137
  wgt_last() = src->wgt;
196,506,287✔
138
  r() = src->r;
196,506,287✔
139
  u() = src->u;
196,506,287✔
140
  r_born() = src->r;
196,506,287✔
141
  r_last_current() = src->r;
196,506,287✔
142
  r_last() = src->r;
196,506,287✔
143
  u_last() = src->u;
196,506,287✔
144
  if (settings::run_CE) {
196,506,287✔
145
    E() = src->E;
101,685,644✔
146
    g() = 0;
101,685,644✔
147
  } else {
148
    g() = static_cast<int>(src->E);
94,820,643✔
149
    g_last() = static_cast<int>(src->E);
94,820,643✔
150
    E() = data::mg.energy_bin_avg_[g()];
94,820,643✔
151
  }
152
  E_last() = E();
196,506,287✔
153
  time() = src->time;
196,506,287✔
154
  time_last() = src->time;
196,506,287✔
155
  parent_nuclide() = src->parent_nuclide;
196,506,287✔
156
  delayed_group() = src->delayed_group;
196,506,287✔
157

158
  // Convert signed surface ID to signed index
159
  if (src->surf_id != SURFACE_NONE) {
196,506,287✔
160
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
90,000✔
161
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
90,000!
162
  }
163
}
196,506,287✔
164

165
void Particle::event_calculate_xs()
2,147,483,647✔
166
{
167
  // Set the random number stream
168
  stream() = STREAM_TRACKING;
2,147,483,647✔
169

170
  // Store pre-collision particle properties
171
  wgt_last() = wgt();
2,147,483,647✔
172
  E_last() = E();
2,147,483,647✔
173
  u_last() = u();
2,147,483,647✔
174
  r_last() = r();
2,147,483,647✔
175
  time_last() = time();
2,147,483,647✔
176

177
  // Reset event variables
178
  event() = TallyEvent::KILL;
2,147,483,647✔
179
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
180
  event_mt() = REACTION_NONE;
2,147,483,647✔
181

182
  // If the cell hasn't been determined based on the particle's location,
183
  // initiate a search for the current cell. This generally happens at the
184
  // beginning of the history and again for any secondary particles
185
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
186
    if (!exhaustive_find_cell(*this)) {
189,439,496!
187
      mark_as_lost(
×
188
        "Could not find the cell containing particle " + std::to_string(id()));
×
189
      return;
×
190
    }
191

192
    // Set birth cell attribute
193
    if (cell_born() == C_NONE)
189,439,496!
194
      cell_born() = lowest_coord().cell();
189,439,496✔
195

196
    // Initialize last cells from current cell
197
    for (int j = 0; j < n_coord(); ++j) {
393,168,146✔
198
      cell_last(j) = coord(j).cell();
203,728,650✔
199
    }
200
    n_coord_last() = n_coord();
189,439,496✔
201
  }
202

203
  // Write particle track.
204
  if (write_track())
2,147,483,647✔
205
    write_particle_track(*this);
8,251✔
206

207
  if (settings::check_overlaps)
2,147,483,647!
208
    check_cell_overlap(*this);
×
209

210
  // Calculate microscopic and macroscopic cross sections
211
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
212
    if (settings::run_CE) {
2,147,483,647✔
213
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,060,897,771✔
214
          density_mult() != density_mult_last()) {
304,836,471✔
215
        // If the material is the same as the last material and the
216
        // temperature hasn't changed, we don't need to lookup cross
217
        // sections again.
218
        model::materials[material()]->calculate_xs(*this);
1,451,232,677✔
219
      }
220
    } else {
221
      // Get the MG data; unlike the CE case above, we have to re-calculate
222
      // cross sections for every collision since the cross sections may
223
      // be angle-dependent
224
      data::mg.macro_xs_[material()].calculate_xs(*this);
1,688,676,066✔
225

226
      // Update the particle's group while we know we are multi-group
227
      g_last() = g();
1,688,676,066✔
228
    }
229
  } else {
230
    macro_xs().total = 0.0;
91,485,457✔
231
    macro_xs().absorption = 0.0;
91,485,457✔
232
    macro_xs().fission = 0.0;
91,485,457✔
233
    macro_xs().nu_fission = 0.0;
91,485,457✔
234
  }
235
}
236

237
void Particle::event_advance()
2,147,483,647✔
238
{
239
  // Find the distance to the nearest boundary
240
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
241

242
  // Sample a distance to collision
243
  if (type() == ParticleType::electron() ||
2,147,483,647✔
244
      type() == ParticleType::positron()) {
2,147,483,647✔
245
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
44,117,096!
246
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
247
    collision_distance() = INFINITY;
91,485,457✔
248
  } else {
249
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
250
  }
251

252
  double speed = this->speed();
2,147,483,647✔
253
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
254
  double distance_cutoff =
255
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
256

257
  // Select smaller of the three distances
258
  double distance =
259
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
260

261
  // Advance particle in space and time
262
  this->move_distance(distance);
2,147,483,647✔
263
  double dt = distance / speed;
2,147,483,647✔
264
  this->time() += dt;
2,147,483,647✔
265
  this->lifetime() += dt;
2,147,483,647✔
266

267
  // Score timed track-length tallies
268
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
269
    score_timed_tracklength_tally(*this, distance);
2,968,623✔
270
  }
271

272
  // Score track-length tallies
273
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
274
    score_tracklength_tally(*this, distance);
1,394,490,100✔
275
  }
276

277
  // Score track-length estimate of k-eff
278
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
279
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
280
  }
281

282
  // Score flux derivative accumulators for differential tallies.
283
  if (!model::active_tallies.empty()) {
2,147,483,647✔
284
    score_track_derivative(*this, distance);
1,532,504,691✔
285
  }
286

287
  // Set particle weight to zero if it hit the time boundary
288
  if (distance == distance_cutoff) {
2,147,483,647✔
289
    wgt() = 0.0;
184,032✔
290
  }
291
}
2,147,483,647✔
292

293
void Particle::event_cross_surface()
1,970,411,126✔
294
{
295
  // Saving previous cell data
296
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
297
    cell_last(j) = coord(j).cell();
2,147,483,647✔
298
  }
299
  n_coord_last() = n_coord();
1,970,411,126✔
300

301
  // Set surface that particle is on and adjust coordinate levels
302
  surface() = boundary().surface();
1,970,411,126✔
303
  n_coord() = boundary().coord_level();
1,970,411,126✔
304

305
  if (boundary().lattice_translation()[0] != 0 ||
1,970,411,126✔
306
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
307
      boundary().lattice_translation()[2] != 0) {
1,520,735,050✔
308
    // Particle crosses lattice boundary
309

310
    bool verbose = settings::verbosity >= 10 || trace();
603,937,244!
311
    cross_lattice(*this, boundary(), verbose);
603,937,244✔
312
    event() = TallyEvent::LATTICE;
603,937,244✔
313
  } else {
314
    // Particle crosses surface
315
    const auto& surf {model::surfaces[surface_index()].get()};
1,366,473,882✔
316
    // If BC, add particle to surface source before crossing surface
317
    if (surf->surf_source_ && surf->bc_) {
1,366,473,882✔
318
      add_surf_source_to_bank(*this, *surf);
588,513,214✔
319
    }
320
    this->cross_surface(*surf);
1,366,473,882✔
321
    // If no BC, add particle to surface source after crossing surface
322
    if (surf->surf_source_ && !surf->bc_) {
1,366,473,875✔
323
      add_surf_source_to_bank(*this, *surf);
776,961,848✔
324
    }
325
    if (settings::weight_window_checkpoint_surface) {
1,366,473,875✔
326
      apply_weight_windows(*this);
54✔
327
    }
328
    event() = TallyEvent::SURFACE;
1,366,473,875✔
329
  }
330
  // Score cell to cell partial currents
331
  if (!model::active_surface_tallies.empty()) {
1,970,411,119✔
332
    score_surface_tally(*this, model::active_surface_tallies);
28,573,173✔
333
  }
334
}
1,970,411,119✔
335

336
void Particle::event_collide()
2,147,483,647✔
337
{
338

339
  // Score collision estimate of keff
340
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
341
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
1,749,777,100✔
342
  }
343

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

348
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
349
    score_surface_tally(*this, model::active_meshsurf_tallies);
51,626,394✔
350

351
  // Clear surface component
352
  surface() = SURFACE_NONE;
2,147,483,647✔
353

354
  if (settings::run_CE) {
2,147,483,647✔
355
    collision(*this);
871,126,609✔
356
  } else {
357
    collision_mg(*this);
1,458,867,663✔
358
  }
359

360
  // Collision track feature to recording particle interaction
361
  if (settings::collision_track) {
2,147,483,647✔
362
    collision_track_record(*this);
122,489✔
363
  }
364

365
  // Score collision estimator tallies -- this is done after a collision
366
  // has occurred rather than before because we need information on the
367
  // outgoing energy for any tallies with an outgoing energy filter
368
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
369
    score_collision_tally(*this);
87,139,349✔
370
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
371
    if (settings::run_CE) {
332,017,677✔
372
      score_analog_tally_ce(*this);
331,029,099✔
373
    } else {
374
      score_analog_tally_mg(*this);
988,578✔
375
    }
376
  }
377

378
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
379
    pht_collision_energy();
1,656✔
380
  }
381

382
  // Reset banked weight during collision
383
  n_bank() = 0;
2,147,483,647✔
384
  bank_second_E() = 0.0;
2,147,483,647✔
385
  wgt_bank() = 0.0;
2,147,483,647✔
386

387
  // Clear number of secondaries in this collision. This is
388
  // distinct from the number of created neutrons n_bank() above!
389
  n_secondaries() = 0;
2,147,483,647✔
390

391
  zero_delayed_bank();
2,147,483,647✔
392

393
  // Reset fission logical
394
  fission() = false;
2,147,483,647✔
395

396
  // Save coordinates for tallying purposes
397
  r_last_current() = r();
2,147,483,647✔
398

399
  // Set last material to none since cross sections will need to be
400
  // re-evaluated
401
  material_last() = C_NONE;
2,147,483,647✔
402

403
  // Set all directions to base level -- right now, after a collision, only
404
  // the base level directions are changed
405
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
406
    if (coord(j + 1).rotated()) {
131,711,705✔
407
      // If next level is rotated, apply rotation matrix
408
      const auto& m {model::cells[coord(j).cell()]->rotation_};
8,530,866✔
409
      const auto& u {coord(j).u()};
8,530,866✔
410
      coord(j + 1).u() = u.rotate(m);
8,530,866✔
411
    } else {
412
      // Otherwise, copy this level's direction
413
      coord(j + 1).u() = coord(j).u();
123,180,839✔
414
    }
415
  }
416

417
  // Score flux derivative accumulators for differential tallies.
418
  if (!model::active_tallies.empty())
2,147,483,647✔
419
    score_collision_derivative(*this);
761,379,626✔
420

421
#ifdef OPENMC_DAGMC_ENABLED
422
  history().reset();
423
#endif
424
}
2,147,483,647✔
425

426
void Particle::event_revive_from_secondary()
2,147,483,647✔
427
{
428
  // If particle has too many events, display warning and kill it
429
  ++n_event();
2,147,483,647✔
430
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
431
    warning("Particle " + std::to_string(id()) +
×
432
            " underwent maximum number of events.");
433
    wgt() = 0.0;
×
434
  }
435

436
  // Check for secondary particles if this particle is dead
437
  if (!alive()) {
2,147,483,647✔
438
    // Write final position for this particle
439
    if (write_track()) {
189,438,984✔
440
      write_particle_track(*this);
4,976✔
441
    }
442

443
    // If no secondary particles, break out of event loop
444
    if (secondary_bank().empty())
189,438,984✔
445
      return;
137,938,211✔
446

447
    from_source(&secondary_bank().back());
51,500,773✔
448
    secondary_bank().pop_back();
51,500,773✔
449
    n_event() = 0;
51,500,773✔
450
    bank_second_E() = 0.0;
51,500,773✔
451

452
    // Subtract secondary particle energy from interim pulse-height results
453
    if (!model::active_pulse_height_tallies.empty() &&
51,513,454✔
454
        this->type().is_photon()) {
12,681✔
455
      // Since the birth cell of the particle has not been set we
456
      // have to determine it before the energy of the secondary particle can be
457
      // removed from the pulse-height of this cell.
458
      if (lowest_coord().cell() == C_NONE) {
495!
459
        bool verbose = settings::verbosity >= 10 || trace();
495!
460
        if (!exhaustive_find_cell(*this, verbose)) {
495!
461
          mark_as_lost("Could not find the cell containing particle " +
×
462
                       std::to_string(id()));
×
463
          return;
×
464
        }
465
        // Set birth cell attribute
466
        if (cell_born() == C_NONE)
495!
467
          cell_born() = lowest_coord().cell();
495✔
468

469
        // Initialize last cells from current cell
470
        for (int j = 0; j < n_coord(); ++j) {
990✔
471
          cell_last(j) = coord(j).cell();
495✔
472
        }
473
        n_coord_last() = n_coord();
495✔
474
      }
475
      pht_secondary_particles();
495✔
476
    }
477

478
    // Enter new particle in particle track file
479
    if (write_track())
51,500,773✔
480
      add_particle_track(*this);
4,166✔
481
  }
482
}
483

484
void Particle::event_death()
137,939,211✔
485
{
486
#ifdef OPENMC_DAGMC_ENABLED
487
  history().reset();
488
#endif
489

490
  // Finish particle track output.
491
  if (write_track()) {
137,939,211✔
492
    finalize_particle_track(*this);
810✔
493
  }
494

495
// Contribute tally reduction variables to global accumulator
496
#pragma omp atomic
77,531,118✔
497
  global_tally_absorption += keff_tally_absorption();
137,939,211✔
498
#pragma omp atomic
77,131,290✔
499
  global_tally_collision += keff_tally_collision();
137,939,211✔
500
#pragma omp atomic
77,073,417✔
501
  global_tally_tracklength += keff_tally_tracklength();
137,939,211✔
502
#pragma omp atomic
76,784,402✔
503
  global_tally_leakage += keff_tally_leakage();
137,939,211✔
504

505
  // Reset particle tallies once accumulated
506
  keff_tally_absorption() = 0.0;
137,939,211✔
507
  keff_tally_collision() = 0.0;
137,939,211✔
508
  keff_tally_tracklength() = 0.0;
137,939,211✔
509
  keff_tally_leakage() = 0.0;
137,939,211✔
510

511
  if (!model::active_pulse_height_tallies.empty()) {
137,939,211✔
512
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
4,500✔
513
  }
514

515
  // Record the number of progeny created by this particle.
516
  // This data will be used to efficiently sort the fission bank.
517
  if (settings::run_mode == RunMode::EIGENVALUE) {
137,939,211✔
518
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
115,656,800✔
519
    simulation::progeny_per_particle[offset] = n_progeny();
115,656,800✔
520
  }
521
}
137,939,211✔
522

523
void Particle::pht_collision_energy()
1,656✔
524
{
525
  // Adds the energy particles lose in a collision to the pulse-height
526

527
  // determine index of cell in pulse_height_cells
528
  auto it = std::find(model::pulse_height_cells.begin(),
1,656✔
529
    model::pulse_height_cells.end(), lowest_coord().cell());
1,656✔
530

531
  if (it != model::pulse_height_cells.end()) {
1,656!
532
    int index = std::distance(model::pulse_height_cells.begin(), it);
1,656✔
533
    pht_storage()[index] += E_last() - E();
1,656✔
534

535
    // If the energy of the particle is below the cutoff, it will not be sampled
536
    // so its energy is added to the pulse-height in the cell
537
    int photon = ParticleType::photon().transport_index();
1,656✔
538
    if (E() < settings::energy_cutoff[photon]) {
1,656✔
539
      pht_storage()[index] += E();
675✔
540
    }
541
  }
542
}
1,656✔
543

544
void Particle::pht_secondary_particles()
495✔
545
{
546
  // Removes the energy of secondary produced particles from the pulse-height
547

548
  // determine index of cell in pulse_height_cells
549
  auto it = std::find(model::pulse_height_cells.begin(),
495✔
550
    model::pulse_height_cells.end(), cell_born());
495✔
551

552
  if (it != model::pulse_height_cells.end()) {
495!
553
    int index = std::distance(model::pulse_height_cells.begin(), it);
495✔
554
    pht_storage()[index] -= E();
495✔
555
  }
556
}
495✔
557

558
void Particle::cross_surface(const Surface& surf)
1,368,007,416✔
559
{
560

561
  if (settings::verbosity >= 10 || trace()) {
1,368,007,416✔
562
    write_message(1, "    Crossing surface {}", surf.id_);
27✔
563
  }
564

565
// if we're crossing a CSG surface, make sure the DAG history is reset
566
#ifdef OPENMC_DAGMC_ENABLED
567
  if (surf.geom_type() == GeometryType::CSG)
568
    history().reset();
569
#endif
570

571
  // Handle any applicable boundary conditions.
572
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,956,903,912!
573
      settings::run_mode != RunMode::VOLUME) {
588,896,496✔
574
    surf.bc_->handle_particle(*this, surf);
588,798,360✔
575
    return;
588,798,360✔
576
  }
577

578
  // ==========================================================================
579
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
580

581
#ifdef OPENMC_DAGMC_ENABLED
582
  // in DAGMC, we know what the next cell should be
583
  if (surf.geom_type() == GeometryType::DAG) {
584
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
585
                       lowest_coord().universe()) -
586
                     1;
587
    // save material, temperature, and density multiplier
588
    material_last() = material();
589
    sqrtkT_last() = sqrtkT();
590
    density_mult_last() = density_mult();
591
    // set new cell value
592
    lowest_coord().cell() = i_cell;
593
    auto& cell = model::cells[i_cell];
594

595
    cell_instance() = 0;
596
    if (cell->distribcell_index_ >= 0)
597
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
598

599
    material() = cell->material(cell_instance());
600
    sqrtkT() = cell->sqrtkT(cell_instance());
601
    density_mult() = cell->density_mult(cell_instance());
602
    return;
603
  }
604
#endif
605

606
  bool verbose = settings::verbosity >= 10 || trace();
779,209,056!
607
  if (neighbor_list_find_cell(*this, verbose)) {
779,209,056✔
608
    return;
779,184,587✔
609
  }
610

611
  // ==========================================================================
612
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
613

614
  // Remove lower coordinate levels
615
  n_coord() = 1;
24,469✔
616
  bool found = exhaustive_find_cell(*this, verbose);
24,469✔
617

618
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
24,469!
619
    // If a cell is still not found, there are two possible causes: 1) there is
620
    // a void in the model, and 2) the particle hit a surface at a tangent. If
621
    // the particle is really traveling tangent to a surface, if we move it
622
    // forward a tiny bit it should fix the problem.
623

624
    surface() = SURFACE_NONE;
4,741✔
625
    n_coord() = 1;
4,741✔
626
    r() += TINY_BIT * u();
4,741✔
627

628
    // Couldn't find next cell anywhere! This probably means there is an actual
629
    // undefined region in the geometry.
630

631
    if (!exhaustive_find_cell(*this, verbose)) {
4,741!
632
      mark_as_lost("After particle " + std::to_string(id()) +
14,216✔
633
                   " crossed surface " + std::to_string(surf.id_) +
18,950✔
634
                   " it could not be located in any cell and it did not leak.");
635
      return;
4,734✔
636
    }
637
  }
638
}
639

640
void Particle::cross_vacuum_bc(const Surface& surf)
28,584,453✔
641
{
642
  // Score any surface current tallies -- note that the particle is moved
643
  // forward slightly so that if the mesh boundary is on the surface, it is
644
  // still processed
645

646
  if (!model::active_meshsurf_tallies.empty()) {
28,584,453✔
647
    // TODO: Find a better solution to score surface currents than
648
    // physically moving the particle forward slightly
649

650
    r() += TINY_BIT * u();
766,818✔
651
    score_surface_tally(*this, model::active_meshsurf_tallies);
766,818✔
652
  }
653

654
  // Score to global leakage tally
655
  keff_tally_leakage() += wgt();
28,584,453✔
656

657
  // Kill the particle
658
  wgt() = 0.0;
28,584,453✔
659

660
  // Display message
661
  if (settings::verbosity >= 10 || trace()) {
28,584,453!
662
    write_message(1, "    Leaked out of surface {}", surf.id_);
9✔
663
  }
664
}
28,584,453✔
665

666
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
559,198,046✔
667
{
668
  // Do not handle reflective boundary conditions on lower universes
669
  if (n_coord() != 1) {
559,198,046!
670
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
671
                 " off surface in a lower universe.");
672
    return;
×
673
  }
674

675
  // Score surface currents since reflection causes the direction of the
676
  // particle to change. For surface filters, we need to score the tallies
677
  // twice, once before the particle's surface attribute has changed and
678
  // once after. For mesh surface filters, we need to artificially move
679
  // the particle slightly back in case the surface crossing is coincident
680
  // with a mesh boundary
681

682
  if (!model::active_surface_tallies.empty()) {
559,198,046✔
683
    score_surface_tally(*this, model::active_surface_tallies);
233,199✔
684
  }
685

686
  if (!model::active_meshsurf_tallies.empty()) {
559,198,046✔
687
    Position r {this->r()};
38,360,853✔
688
    this->r() -= TINY_BIT * u();
38,360,853✔
689
    score_surface_tally(*this, model::active_meshsurf_tallies);
38,360,853✔
690
    this->r() = r;
38,360,853✔
691
  }
692

693
  // Set the new particle direction
694
  u() = new_u;
559,198,046✔
695

696
  // Reassign particle's cell and surface
697
  coord(0).cell() = cell_last(0);
559,198,046✔
698
  surface() = -surface();
559,198,046✔
699

700
  // If a reflective surface is coincident with a lattice or universe
701
  // boundary, it is necessary to redetermine the particle's coordinates in
702
  // the lower universes.
703
  // (unless we're using a dagmc model, which has exactly one universe)
704
  n_coord() = 1;
559,198,046✔
705
  if (surf.geom_type() != GeometryType::DAG &&
1,118,396,092!
706
      !neighbor_list_find_cell(*this)) {
559,198,046!
707
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
708
                 std::to_string(surf.id_) + ".");
×
709
    return;
×
710
  }
711

712
  // Set previous coordinate going slightly past surface crossing
713
  r_last_current() = r() + TINY_BIT * u();
559,198,046✔
714

715
  // Diagnostic message
716
  if (settings::verbosity >= 10 || trace()) {
559,198,046!
717
    write_message(1, "    Reflected from surface {}", surf.id_);
×
718
  }
719
}
720

721
void Particle::cross_periodic_bc(
1,838,515✔
722
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
723
{
724
  // Do not handle periodic boundary conditions on lower universes
725
  if (n_coord() != 1) {
1,838,515!
726
    mark_as_lost(
×
727
      "Cannot transfer particle " + std::to_string(id()) +
×
728
      " across surface in a lower universe. Boundary conditions must be "
729
      "applied to root universe.");
730
    return;
×
731
  }
732

733
  // Score surface currents since reflection causes the direction of the
734
  // particle to change -- artificially move the particle slightly back in
735
  // case the surface crossing is coincident with a mesh boundary
736
  if (!model::active_meshsurf_tallies.empty()) {
1,838,515!
737
    Position r {this->r()};
×
738
    this->r() -= TINY_BIT * u();
×
739
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
740
    this->r() = r;
×
741
  }
742

743
  // Adjust the particle's location and direction.
744
  r() = new_r;
1,838,515✔
745
  u() = new_u;
1,838,515✔
746

747
  // Reassign particle's surface
748
  surface() = new_surface;
1,838,515✔
749

750
  // Figure out what cell particle is in now
751
  n_coord() = 1;
1,838,515✔
752

753
  if (!neighbor_list_find_cell(*this)) {
1,838,515!
754
    mark_as_lost("Couldn't find particle after hitting periodic "
×
755
                 "boundary on surface " +
×
756
                 std::to_string(surf.id_) + ".");
×
757
    return;
×
758
  }
759

760
  // Set previous coordinate going slightly past surface crossing
761
  r_last_current() = r() + TINY_BIT * u();
1,838,515✔
762

763
  // Diagnostic message
764
  if (settings::verbosity >= 10 || trace()) {
1,838,515!
765
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
766
  }
767
}
768

769
void Particle::mark_as_lost(const char* message)
4,741✔
770
{
771
  // Print warning and write lost particle file
772
  warning(message);
4,741✔
773
  if (settings::max_write_lost_particles < 0 ||
4,741✔
774
      simulation::n_lost_particles < settings::max_write_lost_particles) {
4,500✔
775
    write_restart();
301✔
776
  }
777
  // Increment number of lost particles
778
  wgt() = 0.0;
4,741✔
779
#pragma omp atomic
2,625✔
780
  simulation::n_lost_particles += 1;
2,116✔
781

782
  // Count the total number of simulated particles (on this processor)
783
  auto n = simulation::current_batch * settings::gen_per_batch *
4,741✔
784
           simulation::work_per_rank;
785

786
  // Abort the simulation if the maximum number of lost particles has been
787
  // reached
788
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
4,741✔
789
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
7!
790
    fatal_error("Maximum number of lost particles has been reached.");
7✔
791
  }
792
}
4,734✔
793

794
void Particle::write_restart() const
301✔
795
{
796
  // Dont write another restart file if in particle restart mode
797
  if (settings::run_mode == RunMode::PARTICLE)
301✔
798
    return;
18✔
799

800
  // Set up file name
801
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
802
    simulation::current_batch, id());
517✔
803

804
#pragma omp critical(WriteParticleRestart)
300✔
805
  {
806
    // Create file
807
    hid_t file_id = file_open(filename, 'w');
283✔
808

809
    // Write filetype and version info
810
    write_attribute(file_id, "filetype", "particle restart");
283✔
811
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
283✔
812
    write_attribute(file_id, "openmc_version", VERSION);
283✔
813
#ifdef GIT_SHA1
814
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
815
#endif
816

817
    // Write data to file
818
    write_dataset(file_id, "current_batch", simulation::current_batch);
283✔
819
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
283✔
820
    write_dataset(file_id, "current_generation", simulation::current_gen);
283✔
821
    write_dataset(file_id, "n_particles", settings::n_particles);
283✔
822
    switch (settings::run_mode) {
283!
823
    case RunMode::FIXED_SOURCE:
175✔
824
      write_dataset(file_id, "run_mode", "fixed source");
175✔
825
      break;
175✔
826
    case RunMode::EIGENVALUE:
108✔
827
      write_dataset(file_id, "run_mode", "eigenvalue");
108✔
828
      break;
108✔
829
    case RunMode::PARTICLE:
×
830
      write_dataset(file_id, "run_mode", "particle restart");
×
831
      break;
×
832
    default:
×
833
      break;
×
834
    }
835
    write_dataset(file_id, "id", id());
283✔
836
    write_dataset(file_id, "type", type().pdg_number());
283✔
837

838
    int64_t i = current_work();
283✔
839
    if (settings::run_mode == RunMode::EIGENVALUE) {
283✔
840
      // take source data from primary bank for eigenvalue simulation
841
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
108✔
842
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
108✔
843
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
108✔
844
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
108✔
845
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
108✔
846
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
175!
847
      // re-sample using rng random number seed used to generate source particle
848
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
175✔
849
                     settings::n_particles +
175✔
850
                   simulation::work_index[mpi::rank] + i;
175✔
851
      uint64_t seed = init_seed(id, STREAM_SOURCE);
175✔
852
      // re-sample source site
853
      auto site = sample_external_source(&seed);
175✔
854
      write_dataset(file_id, "weight", site.wgt);
175✔
855
      write_dataset(file_id, "energy", site.E);
175✔
856
      write_dataset(file_id, "xyz", site.r);
175✔
857
      write_dataset(file_id, "uvw", site.u);
175✔
858
      write_dataset(file_id, "time", site.time);
175✔
859
    }
860

861
    // Close file
862
    file_close(file_id);
283✔
863
  } // #pragma omp critical
864
}
283✔
865

866
void Particle::update_neutron_xs(
2,147,483,647✔
867
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
868
{
869
  // Get microscopic cross section cache
870
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
871

872
  // If the cache doesn't match, recalculate micro xs
873
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
874
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
875
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
876
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
877

878
    // If NCrystal is being used, update micro cross section cache
879
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
880
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
881
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
9,015,507✔
882
      ncrystal_update_micro(ncrystal_xs, micro);
9,015,507✔
883
    }
884
  }
885
}
2,147,483,647✔
886

887
//==============================================================================
888
// Non-method functions
889
//==============================================================================
890
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,365,475,062✔
891
{
892
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
893
      simulation::surf_source_bank.full()) {
1,050,249,129✔
894
    return;
1,365,373,303✔
895
  }
896

897
  // If a cell/cellfrom/cellto parameter is defined
898
  if (settings::ssw_cell_id != C_NONE) {
263,321✔
899

900
    // Retrieve cell index and storage type
901
    int cell_idx = model::cell_map[settings::ssw_cell_id];
197,193✔
902

903
    if (surf.bc_) {
197,193✔
904
      // Leave if cellto with vacuum boundary condition
905
      if (surf.bc_->type() == "vacuum" &&
143,588!
906
          settings::ssw_cell_type == SSWCellType::To) {
25,250✔
907
        return;
9,008✔
908
      }
909

910
      // Leave if other boundary condition than vacuum
911
      if (surf.bc_->type() != "vacuum") {
109,330✔
912
        return;
93,088✔
913
      }
914
    }
915

916
    // Check if the cell of interest has been exited
917
    bool exited = false;
95,097✔
918
    for (int i = 0; i < p.n_coord_last(); ++i) {
255,493✔
919
      if (p.cell_last(i) == cell_idx) {
160,396✔
920
        exited = true;
57,278✔
921
      }
922
    }
923

924
    // Check if the cell of interest has been entered
925
    bool entered = false;
95,097✔
926
    for (int i = 0; i < p.n_coord(); ++i) {
227,047✔
927
      if (p.coord(i).cell() == cell_idx) {
131,950✔
928
        entered = true;
45,088✔
929
      }
930
    }
931

932
    // Vacuum boundary conditions: return if cell is not exited
933
    if (surf.bc_) {
95,097✔
934
      if (surf.bc_->type() == "vacuum" && !exited) {
16,242!
935
        return;
11,142✔
936
      }
937
    } else {
938

939
      // If we both enter and exit the cell of interest
940
      if (entered && exited) {
78,855✔
941
        return;
21,891✔
942
      }
943

944
      // If we did not enter nor exit the cell of interest
945
      if (!entered && !exited) {
56,964✔
946
        return;
8,580✔
947
      }
948

949
      // If cellfrom and the cell before crossing is not the cell of
950
      // interest
951
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
48,384✔
952
        return;
8,986✔
953
      }
954

955
      // If cellto and the cell after crossing is not the cell of interest
956
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
39,398✔
957
        return;
8,867✔
958
      }
959
    }
960
  }
961

962
  SourceSite site;
101,759✔
963
  site.r = p.r();
101,759✔
964
  site.u = p.u();
101,759✔
965
  site.E = p.E();
101,759✔
966
  site.time = p.time();
101,759✔
967
  site.wgt = p.wgt();
101,759✔
968
  site.delayed_group = p.delayed_group();
101,759✔
969
  site.surf_id = surf.id_;
101,759✔
970
  site.particle = p.type();
101,759✔
971
  site.parent_id = p.id();
101,759✔
972
  site.progeny_id = p.n_progeny();
101,759✔
973
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
101,759✔
974
}
975

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