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

openmc-dev / openmc / 30662130446

31 Jul 2026 08:14PM UTC coverage: 81.463% (+0.06%) from 81.4%
30662130446

Pull #3934

github

web-flow
Merge c44d91937 into a8152672b
Pull Request #3934: Fix virtual surface crossing

18514 of 26799 branches covered (69.08%)

Branch coverage included in aggregate %.

23 of 23 new or added lines in 1 file covered. (100.0%)

1004 existing lines in 27 files now uncovered.

60272 of 69915 relevant lines covered (86.21%)

50336961.16 hits per line

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

87.36
/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:
94,466,474✔
74
  case PDG_POSITRON:
94,466,474✔
75
    return MASS_ELECTRON_EV;
94,466,474✔
76
  default:
43,153,120✔
77
    return this->type().mass() * AMU_EV;
43,153,120✔
78
  }
79
}
80

81
bool Particle::create_secondary(
196,103,042✔
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();
196,103,042✔
87
  if (idx == C_NONE) {
196,103,042!
88
    return false;
89
  }
90
  if (E < settings::energy_cutoff[idx]) {
196,103,042✔
91
    return false;
92
  }
93

94
  // Increment number of secondaries created (for ParticleProductionFilter)
95
  n_secondaries()++;
102,497,780✔
96

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

113
  local_secondary_bank().emplace_back(bank);
102,497,780✔
114
  return true;
115
}
116

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

127
  // Convert signed index to a signed surface ID
128
  if (surface() == SURFACE_NONE) {
19,708,834✔
129
    bank.surf_id = SURFACE_NONE;
19,443,400✔
130
  } else {
131
    int surf_id = model::surfaces[surface_index()]->id_;
265,434✔
132
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
265,434✔
133
  }
134

135
  bank.wgt_born = wgt_born();
19,708,834✔
136
  bank.wgt_ww_born = wgt_ww_born();
19,708,834✔
137
  bank.n_split = n_split();
19,708,834✔
138
  bank.n_collision = n_collision();
19,708,834✔
139
  bank.parent_id = current_work();
19,708,834✔
140
  if (settings::use_shared_secondary_bank) {
19,708,834✔
141
    bank.progeny_id = n_progeny()++;
15,003,716✔
142
  }
143

144
  local_secondary_bank().emplace_back(bank);
19,708,834✔
145
}
19,708,834✔
146

147
void Particle::from_source(const SourceSite* src)
311,137,916✔
148
{
149
  // Reset some attributes
150
  clear();
311,137,916✔
151
  surface() = SURFACE_NONE;
311,137,916✔
152
  cell_born() = C_NONE;
311,137,916✔
153
  material() = C_NONE;
311,137,916✔
154
  n_collision() = src->n_collision;
311,137,916✔
155
  fission() = false;
311,137,916✔
156
  zero_flux_derivs();
311,137,916✔
157
  lifetime() = 0.0;
311,137,916✔
158
#ifdef OPENMC_DAGMC_ENABLED
159
  history().reset();
28,448,488✔
160
#endif
161

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

186
  // Convert signed surface ID to signed index
187
  if (src->surf_id != SURFACE_NONE) {
311,137,916✔
188
    auto it = model::surface_map.find(std::abs(src->surf_id));
379,229!
189
    if (it != model::surface_map.end()) {
379,229!
190
      int index_plus_one = it->second + 1;
379,229✔
191
      surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
379,229✔
192
    }
193
  }
194

195
  wgt_born() = src->wgt_born;
311,137,916✔
196
  wgt_ww_born() = src->wgt_ww_born;
311,137,916✔
197
  n_split() = src->n_split;
311,137,916✔
198
}
311,137,916✔
199

200
void Particle::event_calculate_xs()
2,147,483,647✔
201
{
202
  // Set the random number stream
203
  stream() = STREAM_TRACKING;
2,147,483,647✔
204

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

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

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

227
    // Set birth cell attribute
228
    if (cell_born() == C_NONE)
301,169,524!
229
      cell_born() = lowest_coord().cell();
301,169,524✔
230

231
    // Initialize last cells from current cell
232
    for (int j = 0; j < n_coord(); ++j) {
619,942,034✔
233
      cell_last(j) = coord(j).cell();
318,772,510✔
234
    }
235
    n_coord_last() = n_coord();
301,169,524✔
236
  }
237

238
  // Write particle track.
239
  if (write_track())
2,147,483,647✔
240
    write_particle_track(*this);
9,228✔
241

242
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
243
    check_cell_overlap(*this);
×
244

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

261
      // Update the particle's group while we know we are multi-group
262
      g_last() = g();
2,082,832,565✔
263
    }
264
  } else {
265
    macro_xs().total = 0.0;
113,928,588✔
266
    macro_xs().absorption = 0.0;
113,928,588✔
267
    macro_xs().fission = 0.0;
113,928,588✔
268
    macro_xs().nu_fission = 0.0;
113,928,588✔
269
  }
270
}
271

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

277
  // Sample a distance to collision
278
  if (type() == ParticleType::electron() ||
2,147,483,647✔
279
      type() == ParticleType::positron()) {
2,147,483,647✔
280
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
188,932,948!
281
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
282
    collision_distance() = INFINITY;
113,928,588✔
283
  } else {
284
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
285
  }
286

287
  double speed = this->speed();
2,147,483,647✔
288
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
289
  double distance_cutoff =
2,147,483,647✔
290
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
291

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

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

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

307
  // Score track-length tallies
308
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
309
    score_tracklength_tally(*this, distance);
2,147,483,647✔
310
  }
311

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

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

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

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

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

340
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
341
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
342
      boundary().lattice_translation()[2] != 0) {
2,147,483,647✔
343
    // Particle crosses lattice boundary
344

345
    int i_lattice = coord(boundary().coord_level() - 1).lattice();
813,765,074!
346
    bool verbose = settings::verbosity >= 10 || trace();
813,765,074!
347
    cross_lattice(*this, boundary(), verbose);
813,765,074✔
348
    event() = TallyEvent::LATTICE;
813,765,074✔
349

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

362
  } else {
363

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

366
    // Particle crosses surface
367
    // If BC, add particle to surface source before crossing surface
368
    if (surf.surf_source_ && surf.bc_) {
2,147,483,647✔
369
      add_surf_source_to_bank(*this, surf);
1,016,484,759✔
370
    }
371
    this->cross_surface(surf);
2,147,483,647✔
372
    // If no BC, add particle to surface source after crossing surface
373
    if (surf.surf_source_ && !surf.bc_) {
2,147,483,647✔
374
      add_surf_source_to_bank(*this, surf);
1,855,422,564✔
375
    }
376
    if (settings::weight_window_checkpoint_surface) {
2,147,483,647✔
377
      apply_weight_windows(*this);
13,167,527✔
378
    }
379
    event() = TallyEvent::SURFACE;
2,147,483,647✔
380

381
    // Score cell to cell partial currents
382
    if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
383
      Direction normal = surf.normal(r());
34,934,064✔
384
      normal /= normal.norm();
34,934,064✔
385
      score_surface_tally(*this, model::active_surface_tallies, normal);
34,934,064✔
386
    }
387
  }
388
}
2,147,483,647✔
389

390
void Particle::event_collide()
2,147,483,647✔
391
{
392

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

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

402
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
403
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,095,989✔
404

405
  // Clear surface component
406
  surface() = SURFACE_NONE;
2,147,483,647✔
407

408
  if (settings::run_CE) {
2,147,483,647✔
409
    collision(*this);
1,692,868,141✔
410
  } else {
411
    collision_mg(*this);
1,801,144,774✔
412
  }
413

414
  // Collision track feature to recording particle interaction
415
  if (settings::collision_track) {
2,147,483,647✔
416
    collision_track_record(*this);
712,910✔
417
  }
418

419
  // Score collision estimator tallies -- this is done after a collision
420
  // has occurred rather than before because we need information on the
421
  // outgoing energy for any tallies with an outgoing energy filter
422
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
423
    score_collision_tally(*this);
101,470,912✔
424
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
425
    if (settings::run_CE) {
528,915,626✔
426
      score_analog_tally_ce(*this);
527,707,364✔
427
    } else {
428
      score_analog_tally_mg(*this);
1,208,262✔
429
    }
430
  }
431

432
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
433
    pht_collision_energy();
102,179✔
434
  }
435

436
  // Reset banked weight during collision
437
  n_bank() = 0;
2,147,483,647✔
438
  bank_second_E() = 0.0;
2,147,483,647✔
439
  wgt_bank() = 0.0;
2,147,483,647✔
440

441
  // Clear number of secondaries in this collision. This is
442
  // distinct from the number of created neutrons n_bank() above!
443
  n_secondaries() = 0;
2,147,483,647✔
444

445
  zero_delayed_bank();
2,147,483,647✔
446

447
  // Reset fission logical
448
  fission() = false;
2,147,483,647✔
449

450
  // Save coordinates for tallying purposes
451
  r_last_current() = r();
2,147,483,647✔
452

453
  // Set last material to none since cross sections will need to be
454
  // re-evaluated
455
  material_last() = C_NONE;
2,147,483,647✔
456

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

471
  // Score flux derivative accumulators for differential tallies.
472
  if (!model::active_tallies.empty())
2,147,483,647✔
473
    score_collision_derivative(*this);
1,536,031,095✔
474

475
#ifdef OPENMC_DAGMC_ENABLED
476
  history().reset();
319,673,135✔
477
#endif
478
}
2,147,483,647✔
479

480
void Particle::event_revive_from_secondary(const SourceSite& site)
123,221,363✔
481
{
482
  // Write final position for the previous track (skip if this is a freshly
483
  // constructed particle with no prior track, e.g., Phase 2 of shared
484
  // secondary transport)
485
  if (write_track() && n_event() > 0) {
123,221,363!
486
    write_particle_track(*this);
4,238✔
487
  }
488

489
  from_source(&site);
123,221,363✔
490

491
  n_event() = 0;
123,221,363✔
492
  if (!settings::use_shared_secondary_bank) {
123,221,363✔
493
    n_tracks()++;
79,152,765✔
494
  }
495
  bank_second_E() = 0.0;
123,221,363✔
496

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

516
      // Initialize last cells from current cell
517
      for (int j = 0; j < n_coord(); ++j) {
65,714✔
518
        cell_last(j) = coord(j).cell();
32,857✔
519
      }
520
      n_coord_last() = n_coord();
32,857✔
521
    }
522
    pht_secondary_particles();
32,857✔
523
  }
524

525
  // Enter new particle in particle track file
526
  if (write_track())
123,221,363✔
527
    add_particle_track(*this);
4,238✔
528
}
529

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

540
  // In non-shared-secondary mode, revive from local secondary bank
541
  if (!alive() && !settings::use_shared_secondary_bank &&
2,147,483,647✔
542
      !local_secondary_bank().empty()) {
256,233,933✔
543
    SourceSite& site = local_secondary_bank().back();
79,152,765✔
544
    event_revive_from_secondary(site);
79,152,765✔
545
    local_secondary_bank().pop_back();
79,152,765✔
546
  }
547
}
2,147,483,647✔
548

549
void Particle::event_death()
222,049,607✔
550
{
551
#ifdef OPENMC_DAGMC_ENABLED
552
  history().reset();
20,269,121✔
553
#endif
554

555
  // Finish particle track output.
556
  if (write_track()) {
222,049,607✔
557
    write_particle_track(*this);
1,010✔
558
    finalize_particle_track(*this);
1,010✔
559
  }
560

561
  // Contribute tally reduction variables to global accumulator
562
  const auto k_absorption = keff_tally_absorption();
222,049,607✔
563
  const auto k_collision = keff_tally_collision();
222,049,607✔
564
  const auto k_tracklength = keff_tally_tracklength();
222,049,607✔
565
  const auto leakage = keff_tally_leakage();
222,049,607✔
566

567
  if (settings::run_mode == RunMode::EIGENVALUE) {
222,049,607✔
568
    if (k_absorption != 0.0) {
149,937,000✔
569
#pragma omp atomic
73,495,784✔
570
      global_tally_absorption += k_absorption;
60,666,438✔
571
    }
572
    if (k_collision != 0.0) {
149,937,000✔
573
#pragma omp atomic
78,471,627✔
574
      global_tally_collision += k_collision;
65,034,971✔
575
    }
576
    if (k_tracklength != 0.0) {
149,937,000✔
577
#pragma omp atomic
82,251,231✔
578
      global_tally_tracklength += k_tracklength;
68,109,415✔
579
    }
580
  }
581
  if (leakage != 0.0) {
222,049,607✔
582
#pragma omp atomic
21,247,934✔
583
    global_tally_leakage += leakage;
17,076,645✔
584
  }
585

586
  // Reset particle tallies once accumulated
587
  keff_tally_absorption() = 0.0;
222,049,607✔
588
  keff_tally_collision() = 0.0;
222,049,607✔
589
  keff_tally_tracklength() = 0.0;
222,049,607✔
590
  keff_tally_leakage() = 0.0;
222,049,607✔
591

592
  if (!model::active_pulse_height_tallies.empty()) {
222,049,607✔
593
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
143,000✔
594
  }
595

596
  // Accumulate track count for this particle history
597
  if (!settings::use_shared_secondary_bank) {
222,049,607✔
598
#pragma omp atomic
96,670,848✔
599
    simulation::simulation_tracks_completed += n_tracks();
177,082,168✔
600
  }
601

602
  // Record the number of progeny created by this particle.
603
  // This data will be used to efficiently sort the fission bank.
604
  if (settings::run_mode == RunMode::EIGENVALUE ||
222,049,607✔
605
      settings::use_shared_secondary_bank) {
606
    simulation::progeny_per_particle[current_work()] = n_progeny();
194,904,439✔
607
  }
608
}
222,049,607✔
609

610
void Particle::pht_collision_energy()
102,179✔
611
{
612
  // Adds the energy particles lose in a collision to the pulse-height
613

614
  // determine index of cell in pulse_height_cells
615
  auto it = std::find(model::pulse_height_cells.begin(),
102,179✔
616
    model::pulse_height_cells.end(), lowest_coord().cell());
102,179!
617

618
  if (it != model::pulse_height_cells.end()) {
102,179!
619
    int index = std::distance(model::pulse_height_cells.begin(), it);
102,179✔
620
    pht_storage()[index] += E_last() - E();
102,179✔
621

622
    // If the energy of the particle is below the cutoff, it will not be sampled
623
    // so its energy is added to the pulse-height in the cell
624
    int photon = ParticleType::photon().transport_index();
102,179✔
625
    if (E() < settings::energy_cutoff[photon]) {
102,179✔
626
      pht_storage()[index] += E();
44,506✔
627
    }
628
  }
629
}
102,179✔
630

631
void Particle::pht_secondary_particles()
32,857✔
632
{
633
  // Removes the energy of secondary produced particles from the pulse-height
634

635
  // determine index of cell in pulse_height_cells
636
  auto it = std::find(model::pulse_height_cells.begin(),
32,857✔
637
    model::pulse_height_cells.end(), cell_born());
32,857!
638

639
  if (it != model::pulse_height_cells.end()) {
32,857!
640
    int index = std::distance(model::pulse_height_cells.begin(), it);
32,857✔
641
    pht_storage()[index] -= E();
32,857✔
642
  }
643
}
32,857✔
644

645
void Particle::cross_surface(const Surface& surf)
2,147,483,647✔
646
{
647

648
  if (settings::verbosity >= 10 || trace()) {
2,147,483,647✔
649
    write_message(1, "    Crossing surface {}", surf.id_);
88✔
650
  }
651

652
// if we're crossing a CSG surface, make sure the DAG history is reset
653
#ifdef OPENMC_DAGMC_ENABLED
654
  if (surf.geom_type() == GeometryType::CSG)
261,791,942✔
655
    history().reset();
261,734,306✔
656
#endif
657

658
  // Handle any applicable boundary conditions.
659
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
660
      settings::run_mode != RunMode::VOLUME) {
661
    surf.bc_->handle_particle(*this, surf);
1,016,831,756✔
662
    return;
1,016,831,756✔
663
  }
664

665
  // ==========================================================================
666
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
667

668
#ifdef OPENMC_DAGMC_ENABLED
669
  // in DAGMC, we know what the next cell should be
670
  if (surf.geom_type() == GeometryType::DAG) {
168,908,899✔
671
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,716✔
672
                       lowest_coord().universe()) -
46,716✔
673
                     1;
46,716✔
674
    // save material, temperature, and density multiplier
675
    material_last() = material();
46,716✔
676
    sqrtkT_last() = sqrtkT();
46,716✔
677
    density_mult_last() = density_mult();
46,716✔
678
    // set new cell value
679
    lowest_coord().cell() = i_cell;
46,716✔
680
    auto& cell = model::cells[i_cell];
46,716✔
681

682
    cell_instance() = 0;
46,716✔
683
    if (cell->distribcell_index_ >= 0)
46,716✔
684
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,692✔
685

686
    material() = cell->material(cell_instance());
46,716!
687
    sqrtkT() = cell->sqrtkT(cell_instance());
46,716!
688
    density_mult() = cell->density_mult(cell_instance());
46,716✔
689
    return;
46,716✔
690
  }
691
#endif
692

693
  bool verbose = settings::verbosity >= 10 || trace();
1,858,025,246!
694
  if (neighbor_list_find_cell(*this, verbose)) {
1,858,025,246✔
695
    return;
696
  }
697

698
  // ==========================================================================
699
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
700

701
  // Remove lower coordinate levels
702
  n_coord() = 1;
29,977✔
703
  bool found = exhaustive_find_cell(*this, verbose);
29,977✔
704

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

711
    surface() = SURFACE_NONE;
5,865✔
712
    n_coord() = 1;
5,865✔
713
    r() += TINY_BIT * u();
5,865✔
714

715
    // Couldn't find next cell anywhere! This probably means there is an actual
716
    // undefined region in the geometry.
717

718
    if (!exhaustive_find_cell(*this, verbose)) {
5,865!
719
      mark_as_lost("After particle " + std::to_string(id()) +
17,586✔
720
                   " crossed surface " + std::to_string(surf.id_) +
17,586✔
721
                   " it could not be located in any cell and it did not leak.");
722
      return;
5,856✔
723
    }
724
  }
725
}
726

727
void Particle::cross_vacuum_bc(const Surface& surf)
39,006,238✔
728
{
729
  // Score any surface current tallies -- note that the particle is moved
730
  // forward slightly so that if the mesh boundary is on the surface, it is
731
  // still processed
732

733
  if (!model::active_meshsurf_tallies.empty()) {
39,006,238✔
734
    // TODO: Find a better solution to score surface currents than
735
    // physically moving the particle forward slightly
736

737
    r() += TINY_BIT * u();
936,210✔
738
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
936,210✔
739
  }
740

741
  // Score to global leakage tally
742
  keff_tally_leakage() += wgt();
39,006,238✔
743

744
  // Kill the particle
745
  wgt() = 0.0;
39,006,238✔
746

747
  // Display message
748
  if (settings::verbosity >= 10 || trace()) {
39,006,238!
749
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
750
  }
751
}
39,006,238✔
752

753
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
976,587,302✔
754
{
755
  // Do not handle reflective boundary conditions on lower universes
756
  if (n_coord() != 1) {
976,587,302!
UNCOV
757
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
758
                 " off surface in a lower universe.");
UNCOV
759
    return;
×
760
  }
761

762
  // Score surface currents since reflection causes the direction of the
763
  // particle to change. For surface filters, we need to score the tallies
764
  // twice, once before the particle's surface attribute has changed and
765
  // once after. For mesh surface filters, we need to artificially move
766
  // the particle slightly back in case the surface crossing is coincident
767
  // with a mesh boundary
768

769
  if (!model::active_surface_tallies.empty()) {
976,587,302✔
770
    Direction normal = surf.normal(r());
285,021✔
771
    normal /= normal.norm();
285,021✔
772
    score_surface_tally(*this, model::active_surface_tallies, normal);
285,021✔
773
  }
774

775
  if (!model::active_meshsurf_tallies.empty()) {
976,587,302✔
776
    Position r {this->r()};
46,882,979✔
777
    this->r() -= TINY_BIT * u();
46,882,979✔
778
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,882,979✔
779
    this->r() = r;
46,882,979✔
780
  }
781

782
  // Set the new particle direction
783
  u() = new_u;
976,587,302✔
784

785
  // Reassign particle's cell and surface
786
  coord(0).cell() = cell_last(0);
976,587,302✔
787
  surface() = -surface();
976,587,302✔
788

789
  // If a reflective surface is coincident with a lattice or universe
790
  // boundary, it is necessary to redetermine the particle's coordinates in
791
  // the lower universes.
792
  // (unless we're using a dagmc model, which has exactly one universe)
793
  n_coord() = 1;
976,587,302✔
794
  if (surf.geom_type() != GeometryType::DAG &&
1,953,171,846!
795
      !neighbor_list_find_cell(*this)) {
976,584,544✔
UNCOV
796
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
797
                 std::to_string(surf.id_) + ".");
×
UNCOV
798
    return;
×
799
  }
800

801
  // Set previous coordinate going slightly past surface crossing
802
  r_last_current() = r() + TINY_BIT * u();
976,587,302✔
803

804
  // Diagnostic message
805
  if (settings::verbosity >= 10 || trace()) {
976,587,302!
UNCOV
806
    write_message(1, "    Reflected from surface {}", surf.id_);
×
807
  }
808
}
809

810
void Particle::cross_periodic_bc(
2,243,682✔
811
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
812
{
813
  // Do not handle periodic boundary conditions on lower universes
814
  if (n_coord() != 1) {
2,243,682!
815
    mark_as_lost(
×
UNCOV
816
      "Cannot transfer particle " + std::to_string(id()) +
×
817
      " across surface in a lower universe. Boundary conditions must be "
818
      "applied to root universe.");
UNCOV
819
    return;
×
820
  }
821

822
  // Score surface currents since reflection causes the direction of the
823
  // particle to change -- artificially move the particle slightly back in
824
  // case the surface crossing is coincident with a mesh boundary
825
  if (!model::active_meshsurf_tallies.empty()) {
2,243,682!
UNCOV
826
    Position r {this->r()};
×
UNCOV
827
    this->r() -= TINY_BIT * u();
×
UNCOV
828
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
829
    this->r() = r;
×
830
  }
831

832
  // Adjust the particle's location and direction.
833
  r() = new_r;
2,243,682✔
834
  u() = new_u;
2,243,682✔
835

836
  // Reassign particle's surface
837
  surface() = new_surface;
2,243,682✔
838

839
  // Figure out what cell particle is in now
840
  n_coord() = 1;
2,243,682✔
841

842
  if (!neighbor_list_find_cell(*this)) {
2,243,682!
UNCOV
843
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
844
                 "boundary on surface " +
×
UNCOV
845
                 std::to_string(surf.id_) + ".");
×
UNCOV
846
    return;
×
847
  }
848

849
  // Set previous coordinate going slightly past surface crossing
850
  r_last_current() = r() + TINY_BIT * u();
2,243,682✔
851

852
  // Diagnostic message
853
  if (settings::verbosity >= 10 || trace()) {
2,243,682!
UNCOV
854
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
855
  }
856
}
857

858
void Particle::mark_as_lost(const char* message)
5,865✔
859
{
860
  // Print warning and write lost particle file
861
  warning(message);
5,865✔
862
  if (settings::max_write_lost_particles < 0 ||
5,865✔
863
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
864
    write_restart();
440✔
865
  }
866
  // Increment number of lost particles
867
  wgt() = 0.0;
5,865✔
868
#pragma omp atomic
3,190✔
869
  simulation::n_lost_particles += 1;
2,675✔
870

871
  // Count the total number of simulated particles (on this processor)
872
  auto n = simulation::current_batch * settings::gen_per_batch *
5,865✔
873
           simulation::work_per_rank;
874

875
  // Abort the simulation if the maximum number of lost particles has been
876
  // reached
877
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,865✔
878
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
879
    fatal_error("Maximum number of lost particles has been reached.");
9✔
880
  }
881
}
5,856✔
882

883
void Particle::write_restart() const
440✔
884
{
885
  // Dont write another restart file if in particle restart mode
886
  if (settings::run_mode == RunMode::PARTICLE)
440✔
887
    return;
33✔
888

889
  // Set up file name
890
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
407✔
891
    simulation::current_batch, id());
407✔
892

893
#pragma omp critical(WriteParticleRestart)
217✔
894
  {
407✔
895
    // Create file
896
    hid_t file_id = file_open(filename, 'w');
407✔
897

898
    // Write filetype and version info
899
    write_attribute(file_id, "filetype", "particle restart");
407✔
900
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
407✔
901
    write_attribute(file_id, "openmc_version", VERSION);
407✔
902
#ifdef GIT_SHA1
903
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
904
#endif
905

906
    // Write data to file
907
    write_dataset(file_id, "current_batch", simulation::current_batch);
407✔
908
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
407✔
909
    write_dataset(file_id, "current_generation", simulation::current_gen);
407✔
910
    write_dataset(file_id, "n_particles", settings::n_particles);
407✔
911
    switch (settings::run_mode) {
407!
912
    case RunMode::FIXED_SOURCE:
275✔
913
      write_dataset(file_id, "run_mode", "fixed source");
275✔
914
      break;
145✔
915
    case RunMode::EIGENVALUE:
132✔
916
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
917
      break;
72✔
UNCOV
918
    case RunMode::PARTICLE:
×
UNCOV
919
      write_dataset(file_id, "run_mode", "particle restart");
×
920
      break;
921
    default:
922
      break;
923
    }
924
    write_dataset(file_id, "id", id());
407✔
925
    write_dataset(file_id, "type", type().pdg_number());
407✔
926

927
    // Get source site data for the particle that got lost
928
    int64_t i = current_work();
407✔
929
    SourceSite site;
407✔
930
    if (settings::run_mode == RunMode::EIGENVALUE) {
407✔
931
      site = simulation::source_bank[i];
132✔
932
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
275✔
933
               settings::use_shared_secondary_bank &&
275!
934
               i < simulation::shared_secondary_bank_read.size()) {
55!
UNCOV
935
      site = simulation::shared_secondary_bank_read[i];
×
936
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
275!
937
      // Re-sample using the same seed used to generate the source particle.
938
      // current_work() is 0-indexed, compute_particle_id expects 1-indexed.
939
      int64_t id = compute_transport_seed(compute_particle_id(i + 1));
275✔
940
      uint64_t seed = init_seed(id, STREAM_SOURCE);
275✔
941
      site = sample_external_source(&seed);
275✔
942
    }
943
    write_dataset(file_id, "weight", site.wgt);
407✔
944
    write_dataset(file_id, "energy", site.E);
407✔
945
    write_dataset(file_id, "xyz", site.r);
407✔
946
    write_dataset(file_id, "uvw", site.u);
407✔
947
    write_dataset(file_id, "time", site.time);
407✔
948

949
    // Close file
950
    file_close(file_id);
407✔
951
  } // #pragma omp critical
952
}
407✔
953

954
void Particle::update_neutron_xs(
2,147,483,647✔
955
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
956
{
957
  // Get microscopic cross section cache
958
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
959

960
  // If the cache doesn't match, recalculate micro xs
961
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
962
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
963
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
964
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
965

966
    // If NCrystal is being used, update micro cross section cache
967
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
968
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
969
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
970
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
971
    }
972
  }
973
}
2,147,483,647✔
974

975
//==============================================================================
976
// Non-method functions
977
//==============================================================================
978
void add_surf_source_to_bank(Particle& p, const Surface& surf)
2,147,483,647✔
979
{
980
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
981
      simulation::surf_source_bank.full()) {
2,147,483,647✔
982
    return;
2,147,483,647✔
983
  }
984

985
  // If a cell/cellfrom/cellto parameter is defined
986
  if (settings::ssw_cell_id != C_NONE) {
304,422✔
987

988
    // Retrieve cell index and storage type
989
    int cell_idx = model::cell_map[settings::ssw_cell_id];
222,357✔
990

991
    if (surf.bc_) {
222,357✔
992
      // Leave if cellto with vacuum boundary condition
993
      if (surf.bc_->type() == "vacuum" &&
284,576✔
994
          settings::ssw_cell_type == SSWCellType::To) {
32,878✔
995
        return;
996
      }
997

998
      // Leave if other boundary condition than vacuum
999
      if (surf.bc_->type() != "vacuum") {
260,246✔
1000
        return;
1001
      }
1002
    }
1003

1004
    // Check if the cell of interest has been exited
1005
    bool exited = false;
1006
    for (int i = 0; i < p.n_coord_last(); ++i) {
268,747✔
1007
      if (p.cell_last(i) == cell_idx) {
167,965✔
1008
        exited = true;
59,528✔
1009
      }
1010
    }
1011

1012
    // Check if the cell of interest has been entered
1013
    bool entered = false;
1014
    for (int i = 0; i < p.n_coord(); ++i) {
233,631✔
1015
      if (p.coord(i).cell() == cell_idx) {
132,849✔
1016
        entered = true;
43,894✔
1017
      }
1018
    }
1019

1020
    // Vacuum boundary conditions: return if cell is not exited
1021
    if (surf.bc_) {
100,782✔
1022
      if (surf.bc_->type() == "vacuum" && !exited) {
41,426!
1023
        return;
1024
      }
1025
    } else {
1026

1027
      // If we both enter and exit the cell of interest
1028
      if (entered && exited) {
80,069✔
1029
        return;
1030
      }
1031

1032
      // If we did not enter nor exit the cell of interest
1033
      if (!entered && !exited) {
66,552✔
1034
        return;
1035
      }
1036

1037
      // If cellfrom and the cell before crossing is not the cell of
1038
      // interest
1039
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,788✔
1040
        return;
1041
      }
1042

1043
      // If cellto and the cell after crossing is not the cell of interest
1044
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,314✔
1045
        return;
1046
      }
1047
    }
1048
  }
1049

1050
  SourceSite site;
128,645✔
1051
  site.r = p.r();
128,645✔
1052
  site.u = p.u();
128,645✔
1053
  site.E = p.E();
128,645✔
1054
  site.time = p.time();
128,645✔
1055
  site.wgt = p.wgt();
128,645✔
1056
  site.delayed_group = p.delayed_group();
128,645✔
1057
  site.surf_id = surf.id_;
128,645✔
1058
  site.particle = p.type();
128,645✔
1059
  site.parent_id = p.id();
128,645✔
1060
  site.progeny_id = p.n_progeny();
128,645✔
1061
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
128,645✔
1062
}
1063

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