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

openmc-dev / openmc / 28915011462

08 Jul 2026 03:20AM UTC coverage: 81.35% (+0.09%) from 81.265%
28915011462

Pull #3965

github

web-flow
Merge 37d15f655 into 868450626
Pull Request #3965: MGXS Bootstrapping

18221 of 26401 branches covered (69.02%)

Branch coverage included in aggregate %.

78 of 78 new or added lines in 5 files covered. (100.0%)

246 existing lines in 12 files now uncovered.

59469 of 69100 relevant lines covered (86.06%)

49958902.13 hits per line

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

87.2
/src/particle.cpp
1
#include "openmc/particle.h"
2

3
#include <algorithm> // copy, min
4
#include <cmath>     // log, abs
5

6
#include <fmt/core.h>
7

8
#include "openmc/bank.h"
9
#include "openmc/capi.h"
10
#include "openmc/cell.h"
11
#include "openmc/collision_track.h"
12
#include "openmc/constants.h"
13
#include "openmc/dagmc.h"
14
#include "openmc/error.h"
15
#include "openmc/geometry.h"
16
#include "openmc/hdf5_interface.h"
17
#include "openmc/lattice.h"
18
#include "openmc/material.h"
19
#include "openmc/message_passing.h"
20
#include "openmc/mgxs_interface.h"
21
#include "openmc/nuclide.h"
22
#include "openmc/particle_data.h"
23
#include "openmc/photon.h"
24
#include "openmc/physics.h"
25
#include "openmc/physics_mg.h"
26
#include "openmc/random_lcg.h"
27
#include "openmc/settings.h"
28
#include "openmc/simulation.h"
29
#include "openmc/source.h"
30
#include "openmc/surface.h"
31
#include "openmc/tallies/derivative.h"
32
#include "openmc/tallies/tally.h"
33
#include "openmc/tallies/tally_scoring.h"
34
#include "openmc/track_output.h"
35
#include "openmc/weight_windows.h"
36

37
#ifdef OPENMC_DAGMC_ENABLED
38
#include "DagMC.hpp"
39
#endif
40

41
namespace openmc {
42

43
//==============================================================================
44
// Particle implementation
45
//==============================================================================
46

47
double Particle::speed() const
2,147,483,647✔
48
{
49
  if (settings::run_CE) {
2,147,483,647✔
50
    // Determine mass in eV/c^2
51
    double mass = this->mass();
2,147,483,647✔
52

53
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
54
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,147,483,647✔
55
           (this->E() + mass);
2,147,483,647✔
56
  } else {
57
    auto mat = this->material();
2,082,832,565✔
58
    if (mat == MATERIAL_VOID)
2,082,832,565!
59
      return 1.0 / data::mg.default_inverse_velocity_[this->g()];
×
60
    auto& macro_xs = data::mg.macro_xs_[mat];
2,082,832,565✔
61
    int macro_t = this->mg_xs_cache().t;
2,082,832,565✔
62
    int macro_a = macro_xs.get_angle_index(this->u());
2,082,832,565✔
63
    return 1.0 / macro_xs.get_xs(
2,147,483,647✔
64
                   MgxsType::INVERSE_VELOCITY, this->g(), macro_t, macro_a);
2,082,832,565✔
65
  }
66
}
67

68
double Particle::mass() const
2,147,483,647✔
69
{
70
  switch (type().pdg_number()) {
2,147,483,647✔
71
  case PDG_NEUTRON:
72
    return MASS_NEUTRON_EV;
73
  case PDG_ELECTRON:
98,511,318✔
74
  case PDG_POSITRON:
98,511,318✔
75
    return MASS_ELECTRON_EV;
98,511,318✔
76
  default:
46,839,919✔
77
    return this->type().mass() * AMU_EV;
46,839,919✔
78
  }
79
}
80

81
bool Particle::create_secondary(
204,320,470✔
82
  double wgt, Direction u, double E, ParticleType type)
83
{
84
  // If energy is below cutoff for this particle, don't create secondary
85
  // particle
86
  int idx = type.transport_index();
204,320,470✔
87
  if (idx == C_NONE) {
204,320,470!
88
    return false;
89
  }
90
  if (E < settings::energy_cutoff[idx]) {
204,320,470✔
91
    return false;
92
  }
93

94
  // Increment number of secondaries created (for ParticleProductionFilter)
95
  n_secondaries()++;
106,255,220✔
96

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

113
  local_secondary_bank().emplace_back(bank);
106,255,220✔
114
  return true;
115
}
116

117
void Particle::split(double wgt)
18,042,521✔
118
{
119
  SourceSite bank;
18,042,521✔
120
  bank.particle = type();
18,042,521✔
121
  bank.wgt = wgt;
18,042,521✔
122
  bank.r = r();
18,042,521✔
123
  bank.u = u();
18,042,521✔
124
  bank.E = settings::run_CE ? E() : g();
18,042,521✔
125
  bank.time = time();
18,042,521✔
126

127
  // Convert signed index to a signed surface ID
128
  if (surface() == SURFACE_NONE) {
18,042,521✔
129
    bank.surf_id = SURFACE_NONE;
17,500,448✔
130
  } else {
131
    int surf_id = model::surfaces[surface_index()]->id_;
542,073✔
132
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
542,073✔
133
  }
134

135
  bank.wgt_born = wgt_born();
18,042,521✔
136
  bank.wgt_ww_born = wgt_ww_born();
18,042,521✔
137
  bank.n_split = n_split();
18,042,521✔
138
  bank.parent_id = current_work();
18,042,521✔
139
  if (settings::use_shared_secondary_bank) {
18,042,521✔
140
    bank.progeny_id = n_progeny()++;
12,381,415✔
141
  }
142

143
  local_secondary_bank().emplace_back(bank);
18,042,521✔
144
}
18,042,521✔
145

146
void Particle::from_source(const SourceSite* src)
313,400,380✔
147
{
148
  // Reset some attributes
149
  clear();
313,400,380✔
150
  surface() = SURFACE_NONE;
313,400,380✔
151
  cell_born() = C_NONE;
313,400,380✔
152
  material() = C_NONE;
313,400,380✔
153
  n_collision() = 0;
313,400,380✔
154
  fission() = false;
313,400,380✔
155
  zero_flux_derivs();
313,400,380✔
156
  lifetime() = 0.0;
313,400,380✔
157
#ifdef OPENMC_DAGMC_ENABLED
158
  history().reset();
28,650,314✔
159
#endif
160

161
  // Copy attributes from source bank site
162
  type() = src->particle;
313,400,380✔
163
  wgt() = src->wgt;
313,400,380✔
164
  wgt_last() = src->wgt;
313,400,380✔
165
  r() = src->r;
313,400,380✔
166
  u() = src->u;
313,400,380✔
167
  r_born() = src->r;
313,400,380✔
168
  r_last_current() = src->r;
313,400,380✔
169
  r_last() = src->r;
313,400,380✔
170
  u_last() = src->u;
313,400,380✔
171
  if (settings::run_CE) {
313,400,380✔
172
    E() = src->E;
195,654,516✔
173
    g() = 0;
195,654,516✔
174
  } else {
175
    g() = static_cast<int>(src->E);
117,745,864✔
176
    g_last() = static_cast<int>(src->E);
117,745,864✔
177
    E() = data::mg.energy_bin_avg_[g()];
117,745,864✔
178
  }
179
  E_last() = E();
313,400,380✔
180
  time() = src->time;
313,400,380✔
181
  time_last() = src->time;
313,400,380✔
182
  parent_nuclide() = src->parent_nuclide;
313,400,380✔
183
  delayed_group() = src->delayed_group;
313,400,380✔
184

185
  // Convert signed surface ID to signed index
186
  if (src->surf_id != SURFACE_NONE) {
313,400,380✔
187
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
652,073✔
188
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
652,073✔
189
  }
190

191
  wgt_born() = src->wgt_born;
313,400,380✔
192
  wgt_ww_born() = src->wgt_ww_born;
313,400,380✔
193
  n_split() = src->n_split;
313,400,380✔
194
}
313,400,380✔
195

196
void Particle::event_calculate_xs()
2,147,483,647✔
197
{
198
  // Set the random number stream
199
  stream() = STREAM_TRACKING;
2,147,483,647✔
200

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

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

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

223
    // Set birth cell attribute
224
    if (cell_born() == C_NONE)
303,461,677!
225
      cell_born() = lowest_coord().cell();
303,461,677✔
226

227
    // Initialize last cells from current cell
228
    for (int j = 0; j < n_coord(); ++j) {
624,526,194✔
229
      cell_last(j) = coord(j).cell();
321,064,517✔
230
    }
231
    n_coord_last() = n_coord();
303,461,677✔
232
  }
233

234
  // Write particle track.
235
  if (write_track())
2,147,483,647✔
236
    write_particle_track(*this);
10,320✔
237

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

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

257
      // Update the particle's group while we know we are multi-group
258
      g_last() = g();
2,082,832,565✔
259
    }
260
  } else {
261
    macro_xs().total = 0.0;
113,581,257✔
262
    macro_xs().absorption = 0.0;
113,581,257✔
263
    macro_xs().fission = 0.0;
113,581,257✔
264
    macro_xs().nu_fission = 0.0;
113,581,257✔
265
  }
266
}
267

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

273
  // Sample a distance to collision
274
  if (type() == ParticleType::electron() ||
2,147,483,647✔
275
      type() == ParticleType::positron()) {
2,147,483,647✔
276
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
197,022,636!
277
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
278
    collision_distance() = INFINITY;
113,581,257✔
279
  } else {
280
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
281
  }
282

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

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

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

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

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

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

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

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

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

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

336
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
337
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
338
      boundary().lattice_translation()[2] != 0) {
2,147,483,647✔
339
    // Particle crosses lattice boundary
340

341
    int i_lattice = coord(boundary().coord_level() - 1).lattice();
813,765,148!
342
    bool verbose = settings::verbosity >= 10 || trace();
813,765,148!
343
    cross_lattice(*this, boundary(), verbose);
813,765,148✔
344
    event() = TallyEvent::LATTICE;
813,765,148✔
345

346
    // Score cell to cell partial currents
347
    if (!model::active_surface_tallies.empty()) {
813,765,148✔
348
      auto& lat {*model::lattices[i_lattice]};
55✔
349
      bool is_valid;
55✔
350
      Direction normal =
55✔
351
        lat.get_normal(boundary().lattice_translation(), is_valid);
55✔
352
      if (is_valid) {
55!
353
        normal /= normal.norm();
55✔
354
        score_surface_tally(*this, model::active_surface_tallies, normal);
55✔
355
      }
356
    }
357

358
  } else {
359

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

362
    // Particle crosses surface
363
    // If BC, add particle to surface source before crossing surface
364
    if (surf.surf_source_ && surf.bc_) {
2,147,483,647✔
365
      add_surf_source_to_bank(*this, surf);
1,015,149,973✔
366
    }
367
    this->cross_surface(surf);
2,147,483,647✔
368
    // If no BC, add particle to surface source after crossing surface
369
    if (surf.surf_source_ && !surf.bc_) {
2,147,483,647✔
370
      add_surf_source_to_bank(*this, surf);
1,877,337,066✔
371
    }
372
    if (settings::weight_window_checkpoint_surface) {
2,147,483,647✔
373
      apply_weight_windows(*this);
32,393,943✔
374
    }
375
    event() = TallyEvent::SURFACE;
2,147,483,647✔
376

377
    // Score cell to cell partial currents
378
    if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
379
      Direction normal = surf.normal(r());
34,931,622✔
380
      normal /= normal.norm();
34,931,622✔
381
      score_surface_tally(*this, model::active_surface_tallies, normal);
34,931,622✔
382
    }
383
  }
384
}
2,147,483,647✔
385

386
void Particle::event_collide()
2,147,483,647✔
387
{
388

389
  // Score collision estimate of keff
390
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
391
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,147,483,647✔
392
  }
393

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

398
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
399
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
400

401
  // Clear surface component
402
  surface() = SURFACE_NONE;
2,147,483,647✔
403

404
  if (settings::run_CE) {
2,147,483,647✔
405
    collision(*this);
1,632,240,616✔
406
  } else {
407
    collision_mg(*this);
1,801,144,774✔
408
  }
409

410
  // Collision track feature to recording particle interaction
411
  if (settings::collision_track) {
2,147,483,647✔
412
    collision_track_record(*this);
728,673✔
413
  }
414

415
  // Score collision estimator tallies -- this is done after a collision
416
  // has occurred rather than before because we need information on the
417
  // outgoing energy for any tallies with an outgoing energy filter
418
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
419
    score_collision_tally(*this);
114,043,139✔
420
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
421
    if (settings::run_CE) {
498,783,711✔
422
      score_analog_tally_ce(*this);
497,575,449✔
423
    } else {
424
      score_analog_tally_mg(*this);
1,208,262✔
425
    }
426
  }
427

428
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
429
    pht_collision_energy();
8,668✔
430
  }
431

432
  // Reset banked weight during collision
433
  n_bank() = 0;
2,147,483,647✔
434
  bank_second_E() = 0.0;
2,147,483,647✔
435
  wgt_bank() = 0.0;
2,147,483,647✔
436

437
  // Clear number of secondaries in this collision. This is
438
  // distinct from the number of created neutrons n_bank() above!
439
  n_secondaries() = 0;
2,147,483,647✔
440

441
  zero_delayed_bank();
2,147,483,647✔
442

443
  // Reset fission logical
444
  fission() = false;
2,147,483,647✔
445

446
  // Save coordinates for tallying purposes
447
  r_last_current() = r();
2,147,483,647✔
448

449
  // Set last material to none since cross sections will need to be
450
  // re-evaluated
451
  material_last() = C_NONE;
2,147,483,647✔
452

453
  // Set all directions to base level -- right now, after a collision, only
454
  // the base level directions are changed
455
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
456
    if (coord(j + 1).rotated()) {
298,323,182✔
457
      // If next level is rotated, apply rotation matrix
458
      const auto& m {model::cells[coord(j).cell()]->rotation_};
11,724,229✔
459
      const auto& u {coord(j).u()};
11,724,229✔
460
      coord(j + 1).u() = u.rotate(m);
11,724,229✔
461
    } else {
462
      // Otherwise, copy this level's direction
463
      coord(j + 1).u() = coord(j).u();
286,598,953✔
464
    }
465
  }
466

467
  // Score flux derivative accumulators for differential tallies.
468
  if (!model::active_tallies.empty())
2,147,483,647✔
469
    score_collision_derivative(*this);
1,471,971,332✔
470

471
#ifdef OPENMC_DAGMC_ENABLED
472
  history().reset();
314,151,023✔
473
#endif
474
}
2,147,483,647✔
475

476
void Particle::event_revive_from_secondary(const SourceSite& site)
125,311,938✔
477
{
478
  // Write final position for the previous track (skip if this is a freshly
479
  // constructed particle with no prior track, e.g., Phase 2 of shared
480
  // secondary transport)
481
  if (write_track() && n_event() > 0) {
125,311,938!
482
    write_particle_track(*this);
5,234✔
483
  }
484

485
  from_source(&site);
125,311,938✔
486

487
  n_event() = 0;
125,311,938✔
488
  if (!settings::use_shared_secondary_bank) {
125,311,938✔
489
    n_tracks()++;
94,285,688✔
490
  }
491
  bank_second_E() = 0.0;
125,311,938✔
492

493
  // Subtract secondary particle energy from interim pulse-height results.
494
  // In shared secondary mode, this subtraction was already done on the parent
495
  // particle during create_secondary(), so skip it here.
496
  if (!settings::use_shared_secondary_bank &&
219,597,626✔
497
      !model::active_pulse_height_tallies.empty() && this->type().is_photon()) {
125,311,938✔
498
    // Since the birth cell of the particle has not been set we
499
    // have to determine it before the energy of the secondary particle can be
500
    // removed from the pulse-height of this cell.
501
    if (lowest_coord().cell() == C_NONE) {
3,168!
502
      bool verbose = settings::verbosity >= 10 || trace();
3,168!
503
      if (!exhaustive_find_cell(*this, verbose)) {
3,168!
504
        mark_as_lost("Could not find the cell containing particle " +
×
505
                     std::to_string(id()));
×
UNCOV
506
        return;
×
507
      }
508
      // Set birth cell attribute
509
      if (cell_born() == C_NONE)
3,168!
510
        cell_born() = lowest_coord().cell();
3,168✔
511

512
      // Initialize last cells from current cell
513
      for (int j = 0; j < n_coord(); ++j) {
6,336✔
514
        cell_last(j) = coord(j).cell();
3,168✔
515
      }
516
      n_coord_last() = n_coord();
3,168✔
517
    }
518
    pht_secondary_particles();
3,168✔
519
  }
520

521
  // Enter new particle in particle track file
522
  if (write_track())
125,311,938✔
523
    add_particle_track(*this);
5,234✔
524
}
525

526
void Particle::event_check_limit_and_revive()
2,147,483,647✔
527
{
528
  // If particle has too many events, display warning and kill it
529
  n_event()++;
2,147,483,647✔
530
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
UNCOV
531
    warning("Particle " + std::to_string(id()) +
×
532
            " underwent maximum number of events.");
UNCOV
533
    wgt() = 0.0;
×
534
  }
535

536
  // In non-shared-secondary mode, revive from local secondary bank
537
  if (!alive() && !settings::use_shared_secondary_bank &&
2,147,483,647✔
538
      !local_secondary_bank().empty()) {
271,648,745✔
539
    SourceSite& site = local_secondary_bank().back();
94,285,688✔
540
    event_revive_from_secondary(site);
94,285,688✔
541
    local_secondary_bank().pop_back();
94,285,688✔
542
  }
543
}
2,147,483,647✔
544

545
void Particle::event_death()
209,179,148✔
546
{
547
#ifdef OPENMC_DAGMC_ENABLED
548
  history().reset();
19,096,352✔
549
#endif
550

551
  // Finish particle track output.
552
  if (write_track()) {
209,179,148✔
553
    write_particle_track(*this);
1,010✔
554
    finalize_particle_track(*this);
1,010✔
555
  }
556

557
// Contribute tally reduction variables to global accumulator
558
#pragma omp atomic
114,806,347✔
559
  global_tally_absorption += keff_tally_absorption();
209,179,148✔
560
#pragma omp atomic
114,975,646✔
561
  global_tally_collision += keff_tally_collision();
209,179,148✔
562
#pragma omp atomic
115,094,161✔
563
  global_tally_tracklength += keff_tally_tracklength();
209,179,148✔
564
#pragma omp atomic
114,383,899✔
565
  global_tally_leakage += keff_tally_leakage();
209,179,148✔
566

567
  // Reset particle tallies once accumulated
568
  keff_tally_absorption() = 0.0;
209,179,148✔
569
  keff_tally_collision() = 0.0;
209,179,148✔
570
  keff_tally_tracklength() = 0.0;
209,179,148✔
571
  keff_tally_leakage() = 0.0;
209,179,148✔
572

573
  if (!model::active_pulse_height_tallies.empty()) {
209,179,148✔
574
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
33,000✔
575
  }
576

577
  // Accumulate track count for this particle history
578
  if (!settings::use_shared_secondary_bank) {
209,179,148✔
579
#pragma omp atomic
96,808,242✔
580
    simulation::simulation_tracks_completed += n_tracks();
177,364,057✔
581
  }
582

583
  // Record the number of progeny created by this particle.
584
  // This data will be used to efficiently sort the fission bank.
585
  if (settings::run_mode == RunMode::EIGENVALUE ||
209,179,148✔
586
      settings::use_shared_secondary_bank) {
587
    simulation::progeny_per_particle[current_work()] = n_progeny();
181,719,091✔
588
  }
589
}
209,179,148✔
590

591
void Particle::pht_collision_energy()
8,668✔
592
{
593
  // Adds the energy particles lose in a collision to the pulse-height
594

595
  // determine index of cell in pulse_height_cells
596
  auto it = std::find(model::pulse_height_cells.begin(),
8,668✔
597
    model::pulse_height_cells.end(), lowest_coord().cell());
8,668!
598

599
  if (it != model::pulse_height_cells.end()) {
8,668!
600
    int index = std::distance(model::pulse_height_cells.begin(), it);
8,668✔
601
    pht_storage()[index] += E_last() - E();
8,668✔
602

603
    // If the energy of the particle is below the cutoff, it will not be sampled
604
    // so its energy is added to the pulse-height in the cell
605
    int photon = ParticleType::photon().transport_index();
8,668✔
606
    if (E() < settings::energy_cutoff[photon]) {
8,668✔
607
      pht_storage()[index] += E();
3,740✔
608
    }
609
  }
610
}
8,668✔
611

612
void Particle::pht_secondary_particles()
3,168✔
613
{
614
  // Removes the energy of secondary produced particles from the pulse-height
615

616
  // determine index of cell in pulse_height_cells
617
  auto it = std::find(model::pulse_height_cells.begin(),
3,168✔
618
    model::pulse_height_cells.end(), cell_born());
3,168!
619

620
  if (it != model::pulse_height_cells.end()) {
3,168!
621
    int index = std::distance(model::pulse_height_cells.begin(), it);
3,168✔
622
    pht_storage()[index] -= E();
3,168✔
623
  }
624
}
3,168✔
625

626
void Particle::cross_surface(const Surface& surf)
2,147,483,647✔
627
{
628

629
  if (settings::verbosity >= 10 || trace()) {
2,147,483,647✔
630
    write_message(1, "    Crossing surface {}", surf.id_);
88✔
631
  }
632

633
// if we're crossing a CSG surface, make sure the DAG history is reset
634
#ifdef OPENMC_DAGMC_ENABLED
635
  if (surf.geom_type() == GeometryType::CSG)
263,910,744✔
636
    history().reset();
263,853,160✔
637
#endif
638

639
  // Handle any applicable boundary conditions.
640
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
641
      settings::run_mode != RunMode::VOLUME) {
642
    surf.bc_->handle_particle(*this, surf);
1,015,502,081✔
643
    return;
1,015,502,081✔
644
  }
645

646
  // ==========================================================================
647
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
648

649
#ifdef OPENMC_DAGMC_ENABLED
650
  // in DAGMC, we know what the next cell should be
651
  if (surf.geom_type() == GeometryType::DAG) {
171,151,730✔
652
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,664✔
653
                       lowest_coord().universe()) -
46,664✔
654
                     1;
46,664✔
655
    // save material, temperature, and density multiplier
656
    material_last() = material();
46,664✔
657
    sqrtkT_last() = sqrtkT();
46,664✔
658
    density_mult_last() = density_mult();
46,664✔
659
    // set new cell value
660
    lowest_coord().cell() = i_cell;
46,664✔
661
    auto& cell = model::cells[i_cell];
46,664✔
662

663
    cell_instance() = 0;
46,664✔
664
    if (cell->distribcell_index_ >= 0)
46,664✔
665
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,640✔
666

667
    material() = cell->material(cell_instance());
46,664!
668
    sqrtkT() = cell->sqrtkT(cell_instance());
46,664!
669
    density_mult() = cell->density_mult(cell_instance());
46,664✔
670
    return;
46,664✔
671
  }
672
#endif
673

674
  bool verbose = settings::verbosity >= 10 || trace();
1,880,087,354!
675
  if (neighbor_list_find_cell(*this, verbose)) {
1,880,087,354✔
676
    return;
677
  }
678

679
  // ==========================================================================
680
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
681

682
  // Remove lower coordinate levels
683
  n_coord() = 1;
29,977✔
684
  bool found = exhaustive_find_cell(*this, verbose);
29,977✔
685

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

692
    surface() = SURFACE_NONE;
5,865✔
693
    n_coord() = 1;
5,865✔
694
    r() += TINY_BIT * u();
5,865✔
695

696
    // Couldn't find next cell anywhere! This probably means there is an actual
697
    // undefined region in the geometry.
698

699
    if (!exhaustive_find_cell(*this, verbose)) {
5,865!
700
      mark_as_lost("After particle " + std::to_string(id()) +
17,586✔
701
                   " crossed surface " + std::to_string(surf.id_) +
17,586✔
702
                   " it could not be located in any cell and it did not leak.");
703
      return;
5,856✔
704
    }
705
  }
706
}
707

708
void Particle::cross_vacuum_bc(const Surface& surf)
38,998,785✔
709
{
710
  // Score any surface current tallies -- note that the particle is moved
711
  // forward slightly so that if the mesh boundary is on the surface, it is
712
  // still processed
713

714
  if (!model::active_meshsurf_tallies.empty()) {
38,998,785✔
715
    // TODO: Find a better solution to score surface currents than
716
    // physically moving the particle forward slightly
717

718
    r() += TINY_BIT * u();
937,222✔
719
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
720
  }
721

722
  // Score to global leakage tally
723
  keff_tally_leakage() += wgt();
38,998,785✔
724

725
  // Kill the particle
726
  wgt() = 0.0;
38,998,785✔
727

728
  // Display message
729
  if (settings::verbosity >= 10 || trace()) {
38,998,785!
730
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
731
  }
732
}
38,998,785✔
733

734
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
975,263,920✔
735
{
736
  // Do not handle reflective boundary conditions on lower universes
737
  if (n_coord() != 1) {
975,263,920!
UNCOV
738
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
739
                 " off surface in a lower universe.");
UNCOV
740
    return;
×
741
  }
742

743
  // Score surface currents since reflection causes the direction of the
744
  // particle to change. For surface filters, we need to score the tallies
745
  // twice, once before the particle's surface attribute has changed and
746
  // once after. For mesh surface filters, we need to artificially move
747
  // the particle slightly back in case the surface crossing is coincident
748
  // with a mesh boundary
749

750
  if (!model::active_surface_tallies.empty()) {
975,263,920✔
751
    Direction normal = surf.normal(r());
285,021✔
752
    normal /= normal.norm();
285,021✔
753
    score_surface_tally(*this, model::active_surface_tallies, normal);
285,021✔
754
  }
755

756
  if (!model::active_meshsurf_tallies.empty()) {
975,263,920✔
757
    Position r {this->r()};
46,885,487✔
758
    this->r() -= TINY_BIT * u();
46,885,487✔
759
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
760
    this->r() = r;
46,885,487✔
761
  }
762

763
  // Set the new particle direction
764
  u() = new_u;
975,263,920✔
765

766
  // Reassign particle's cell and surface
767
  coord(0).cell() = cell_last(0);
975,263,920✔
768
  surface() = -surface();
975,263,920✔
769

770
  // If a reflective surface is coincident with a lattice or universe
771
  // boundary, it is necessary to redetermine the particle's coordinates in
772
  // the lower universes.
773
  // (unless we're using a dagmc model, which has exactly one universe)
774
  n_coord() = 1;
975,263,920✔
775
  if (surf.geom_type() != GeometryType::DAG &&
1,950,525,082!
776
      !neighbor_list_find_cell(*this)) {
975,261,162✔
777
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
778
                 std::to_string(surf.id_) + ".");
×
UNCOV
779
    return;
×
780
  }
781

782
  // Set previous coordinate going slightly past surface crossing
783
  r_last_current() = r() + TINY_BIT * u();
975,263,920✔
784

785
  // Diagnostic message
786
  if (settings::verbosity >= 10 || trace()) {
975,263,920!
UNCOV
787
    write_message(1, "    Reflected from surface {}", surf.id_);
×
788
  }
789
}
790

791
void Particle::cross_periodic_bc(
2,244,842✔
792
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
793
{
794
  // Do not handle periodic boundary conditions on lower universes
795
  if (n_coord() != 1) {
2,244,842!
796
    mark_as_lost(
×
UNCOV
797
      "Cannot transfer particle " + std::to_string(id()) +
×
798
      " across surface in a lower universe. Boundary conditions must be "
799
      "applied to root universe.");
UNCOV
800
    return;
×
801
  }
802

803
  // Score surface currents since reflection causes the direction of the
804
  // particle to change -- artificially move the particle slightly back in
805
  // case the surface crossing is coincident with a mesh boundary
806
  if (!model::active_meshsurf_tallies.empty()) {
2,244,842!
807
    Position r {this->r()};
×
808
    this->r() -= TINY_BIT * u();
×
809
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
810
    this->r() = r;
×
811
  }
812

813
  // Adjust the particle's location and direction.
814
  r() = new_r;
2,244,842✔
815
  u() = new_u;
2,244,842✔
816

817
  // Reassign particle's surface
818
  surface() = new_surface;
2,244,842✔
819

820
  // Figure out what cell particle is in now
821
  n_coord() = 1;
2,244,842✔
822

823
  if (!neighbor_list_find_cell(*this)) {
2,244,842!
824
    mark_as_lost("Couldn't find particle after hitting periodic "
×
825
                 "boundary on surface " +
×
826
                 std::to_string(surf.id_) + ".");
×
UNCOV
827
    return;
×
828
  }
829

830
  // Set previous coordinate going slightly past surface crossing
831
  r_last_current() = r() + TINY_BIT * u();
2,244,842✔
832

833
  // Diagnostic message
834
  if (settings::verbosity >= 10 || trace()) {
2,244,842!
UNCOV
835
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
836
  }
837
}
838

839
void Particle::mark_as_lost(const char* message)
5,865✔
840
{
841
  // Print warning and write lost particle file
842
  warning(message);
5,865✔
843
  if (settings::max_write_lost_particles < 0 ||
5,865✔
844
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
845
    write_restart();
440✔
846
  }
847
  // Increment number of lost particles
848
  wgt() = 0.0;
5,865✔
849
#pragma omp atomic
3,190✔
850
  simulation::n_lost_particles += 1;
2,675✔
851

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

856
  // Abort the simulation if the maximum number of lost particles has been
857
  // reached
858
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,865✔
859
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
860
    fatal_error("Maximum number of lost particles has been reached.");
9✔
861
  }
862
}
5,856✔
863

864
void Particle::write_restart() const
440✔
865
{
866
  // Dont write another restart file if in particle restart mode
867
  if (settings::run_mode == RunMode::PARTICLE)
440✔
868
    return;
33✔
869

870
  // Set up file name
871
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
407✔
872
    simulation::current_batch, id());
407✔
873

874
#pragma omp critical(WriteParticleRestart)
217✔
875
  {
407✔
876
    // Create file
877
    hid_t file_id = file_open(filename, 'w');
407✔
878

879
    // Write filetype and version info
880
    write_attribute(file_id, "filetype", "particle restart");
407✔
881
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
407✔
882
    write_attribute(file_id, "openmc_version", VERSION);
407✔
883
#ifdef GIT_SHA1
884
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
885
#endif
886

887
    // Write data to file
888
    write_dataset(file_id, "current_batch", simulation::current_batch);
407✔
889
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
407✔
890
    write_dataset(file_id, "current_generation", simulation::current_gen);
407✔
891
    write_dataset(file_id, "n_particles", settings::n_particles);
407✔
892
    switch (settings::run_mode) {
407!
893
    case RunMode::FIXED_SOURCE:
275✔
894
      write_dataset(file_id, "run_mode", "fixed source");
275✔
895
      break;
145✔
896
    case RunMode::EIGENVALUE:
132✔
897
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
898
      break;
72✔
899
    case RunMode::PARTICLE:
×
UNCOV
900
      write_dataset(file_id, "run_mode", "particle restart");
×
901
      break;
902
    default:
903
      break;
904
    }
905
    write_dataset(file_id, "id", id());
407✔
906
    write_dataset(file_id, "type", type().pdg_number());
407✔
907

908
    // Get source site data for the particle that got lost
909
    int64_t i = current_work();
407✔
910
    SourceSite site;
407✔
911
    if (settings::run_mode == RunMode::EIGENVALUE) {
407✔
912
      site = simulation::source_bank[i];
132✔
913
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
275✔
914
               settings::use_shared_secondary_bank &&
275!
915
               i < simulation::shared_secondary_bank_read.size()) {
55!
UNCOV
916
      site = simulation::shared_secondary_bank_read[i];
×
917
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
275!
918
      // Re-sample using the same seed used to generate the source particle.
919
      // current_work() is 0-indexed, compute_particle_id expects 1-indexed.
920
      int64_t id = compute_transport_seed(compute_particle_id(i + 1));
275✔
921
      uint64_t seed = init_seed(id, STREAM_SOURCE);
275✔
922
      site = sample_external_source(&seed);
275✔
923
    }
924
    write_dataset(file_id, "weight", site.wgt);
407✔
925
    write_dataset(file_id, "energy", site.E);
407✔
926
    write_dataset(file_id, "xyz", site.r);
407✔
927
    write_dataset(file_id, "uvw", site.u);
407✔
928
    write_dataset(file_id, "time", site.time);
407✔
929

930
    // Close file
931
    file_close(file_id);
407✔
932
  } // #pragma omp critical
933
}
407✔
934

935
void Particle::update_neutron_xs(
2,147,483,647✔
936
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
937
{
938
  // Get microscopic cross section cache
939
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
940

941
  // If the cache doesn't match, recalculate micro xs
942
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
943
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
944
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
945
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
946

947
    // If NCrystal is being used, update micro cross section cache
948
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
949
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
950
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
951
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
952
    }
953
  }
954
}
2,147,483,647✔
955

956
//==============================================================================
957
// Non-method functions
958
//==============================================================================
959
void add_surf_source_to_bank(Particle& p, const Surface& surf)
2,147,483,647✔
960
{
961
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
962
      simulation::surf_source_bank.full()) {
2,147,483,647✔
963
    return;
2,147,483,647✔
964
  }
965

966
  // If a cell/cellfrom/cellto parameter is defined
967
  if (settings::ssw_cell_id != C_NONE) {
337,079✔
968

969
    // Retrieve cell index and storage type
970
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,434✔
971

972
    if (surf.bc_) {
254,434✔
973
      // Leave if cellto with vacuum boundary condition
974
      if (surf.bc_->type() == "vacuum" &&
298,916✔
975
          settings::ssw_cell_type == SSWCellType::To) {
33,098✔
976
        return;
977
      }
978

979
      // Leave if other boundary condition than vacuum
980
      if (surf.bc_->type() != "vacuum") {
274,646✔
981
        return;
982
      }
983
    }
984

985
    // Check if the cell of interest has been exited
986
    bool exited = false;
987
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,667✔
988
      if (p.cell_last(i) == cell_idx) {
207,728✔
989
        exited = true;
73,764✔
990
      }
991
    }
992

993
    // Check if the cell of interest has been entered
994
    bool entered = false;
995
    for (int i = 0; i < p.n_coord(); ++i) {
297,969✔
996
      if (p.coord(i).cell() == cell_idx) {
172,030✔
997
        entered = true;
57,517✔
998
      }
999
    }
1000

1001
    // Vacuum boundary conditions: return if cell is not exited
1002
    if (surf.bc_) {
125,939✔
1003
      if (surf.bc_->type() == "vacuum" && !exited) {
41,926!
1004
        return;
1005
      }
1006
    } else {
1007

1008
      // If we both enter and exit the cell of interest
1009
      if (entered && exited) {
104,976✔
1010
        return;
1011
      }
1012

1013
      // If we did not enter nor exit the cell of interest
1014
      if (!entered && !exited) {
77,773✔
1015
        return;
1016
      }
1017

1018
      // If cellfrom and the cell before crossing is not the cell of
1019
      // interest
1020
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,275✔
1021
        return;
1022
      }
1023

1024
      // If cellto and the cell after crossing is not the cell of interest
1025
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,732✔
1026
        return;
1027
      }
1028
    }
1029
  }
1030

1031
  SourceSite site;
129,653✔
1032
  site.r = p.r();
129,653✔
1033
  site.u = p.u();
129,653✔
1034
  site.E = p.E();
129,653✔
1035
  site.time = p.time();
129,653✔
1036
  site.wgt = p.wgt();
129,653✔
1037
  site.delayed_group = p.delayed_group();
129,653✔
1038
  site.surf_id = surf.id_;
129,653✔
1039
  site.particle = p.type();
129,653✔
1040
  site.parent_id = p.id();
129,653✔
1041
  site.progeny_id = p.n_progeny();
129,653✔
1042
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1043
}
1044

1045
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc