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

openmc-dev / openmc / 29141018921

11 Jul 2026 05:18AM UTC coverage: 81.299% (+0.02%) from 81.283%
29141018921

Pull #3957

github

web-flow
Merge aac381585 into 7256d5046
Pull Request #3957: Add chain parameter to Material.get_activity for half-life data

18212 of 26418 branches covered (68.94%)

Branch coverage included in aggregate %.

26 of 26 new or added lines in 3 files covered. (100.0%)

393 existing lines in 7 files now uncovered.

59410 of 69059 relevant lines covered (86.03%)

48494421.81 hits per line

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

87.45
/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:
95,835,062✔
74
  case PDG_POSITRON:
95,835,062✔
75
    return MASS_ELECTRON_EV;
95,835,062✔
76
  default:
44,611,846✔
77
    return this->type().mass() * AMU_EV;
44,611,846✔
78
  }
79
}
80

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

94
  // Increment number of secondaries created (for ParticleProductionFilter)
95
  n_secondaries()++;
103,584,800✔
96

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

113
  local_secondary_bank().emplace_back(bank);
103,584,800✔
114
  return true;
115
}
116

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

127
  // Convert signed index to a signed surface ID
128
  if (surface() == SURFACE_NONE) {
10,837,900✔
129
    bank.surf_id = SURFACE_NONE;
10,834,028✔
130
  } else {
131
    int surf_id = model::surfaces[surface_index()]->id_;
3,872✔
132
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
3,872✔
133
  }
134

135
  bank.wgt_born = wgt_born();
10,837,900✔
136
  bank.wgt_ww_born = wgt_ww_born();
10,837,900✔
137
  bank.n_split = n_split();
10,837,900✔
138
  bank.parent_id = current_work();
10,837,900✔
139
  if (settings::use_shared_secondary_bank) {
10,837,900✔
140
    bank.progeny_id = n_progeny()++;
5,192,960✔
141
  }
142

143
  local_secondary_bank().emplace_back(bank);
10,837,900✔
144
}
10,837,900✔
145

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

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

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

191
  wgt_born() = src->wgt_born;
302,501,049✔
192
  wgt_ww_born() = src->wgt_ww_born;
302,501,049✔
193
  n_split() = src->n_split;
302,501,049✔
194
}
302,501,049✔
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)) {
293,442,346!
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)
293,442,346!
225
      cell_born() = lowest_coord().cell();
293,442,346✔
226

227
    // Initialize last cells from current cell
228
    for (int j = 0; j < n_coord(); ++j) {
604,377,532✔
229
      cell_last(j) = coord(j).cell();
310,935,186✔
230
    }
231
    n_coord_last() = n_coord();
293,442,346✔
232
  }
233

234
  // Write particle track.
235
  if (write_track())
2,147,483,647✔
236
    write_particle_track(*this);
10,312✔
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()) {
902,527,296✔
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;
111,961,626✔
262
    macro_xs().absorption = 0.0;
111,961,626✔
263
    macro_xs().fission = 0.0;
111,961,626✔
264
    macro_xs().nu_fission = 0.0;
111,961,626✔
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;
191,670,124!
277
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
278
    collision_distance() = INFINITY;
111,961,626✔
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();
801,517,792!
342
    bool verbose = settings::verbosity >= 10 || trace();
801,517,792!
343
    cross_lattice(*this, boundary(), verbose);
801,517,792✔
344
    event() = TallyEvent::LATTICE;
801,517,792✔
345

346
    // Score cell to cell partial currents
347
    if (!model::active_surface_tallies.empty()) {
801,517,792✔
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,008,678,249✔
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,851,429,240✔
371
    }
372
    if (settings::weight_window_checkpoint_surface) {
2,147,483,647✔
373
      apply_weight_windows(*this);
174,249✔
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,486,733,807✔
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);
109,010,055✔
420
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
421
    if (settings::run_CE) {
406,229,898✔
422
      score_analog_tally_ce(*this);
405,021,636✔
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()) {
290,523,291✔
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();
278,799,062✔
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,326,459,732✔
470

471
#ifdef OPENMC_DAGMC_ENABLED
472
  history().reset();
300,395,054✔
473
#endif
474
}
2,147,483,647✔
475

476
void Particle::event_revive_from_secondary(const SourceSite& site)
115,436,897✔
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) {
115,436,897!
482
    write_particle_track(*this);
5,230✔
483
  }
484

485
  from_source(&site);
115,436,897✔
486

487
  n_event() = 0;
115,436,897✔
488
  if (!settings::use_shared_secondary_bank) {
115,436,897✔
489
    n_tracks()++;
94,062,665✔
490
  }
491
  bank_second_E() = 0.0;
115,436,897✔
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 &&
209,499,562✔
497
      !model::active_pulse_height_tallies.empty() && this->type().is_photon()) {
115,436,897✔
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()));
×
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())
115,436,897✔
523
    add_particle_track(*this);
5,230✔
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!
531
    warning("Particle " + std::to_string(id()) +
×
532
            " underwent maximum number of events.");
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,285,777✔
539
    SourceSite& site = local_secondary_bank().back();
94,062,665✔
540
    event_revive_from_secondary(site);
94,062,665✔
541
    local_secondary_bank().pop_back();
94,062,665✔
542
  }
543
}
2,147,483,647✔
544

545
void Particle::event_death()
199,382,840✔
546
{
547
#ifdef OPENMC_DAGMC_ENABLED
548
  history().reset();
18,196,739✔
549
#endif
550

551
  // Finish particle track output.
552
  if (write_track()) {
199,382,840✔
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
  const auto k_absorption = keff_tally_absorption();
199,382,840✔
559
  const auto k_collision = keff_tally_collision();
199,382,840✔
560
  const auto k_tracklength = keff_tally_tracklength();
199,382,840✔
561
  const auto leakage = keff_tally_leakage();
199,382,840✔
562

563
  if (settings::run_mode == RunMode::EIGENVALUE) {
199,382,840✔
564
    if (k_absorption != 0.0) {
149,904,000✔
565
#pragma omp atomic
73,167,641✔
566
      global_tally_absorption += k_absorption;
60,650,486✔
567
    }
568
    if (k_collision != 0.0) {
149,904,000✔
569
#pragma omp atomic
78,196,458✔
570
      global_tally_collision += k_collision;
65,018,950✔
571
    }
572
    if (k_tracklength != 0.0) {
149,904,000✔
573
#pragma omp atomic
81,949,399✔
574
      global_tally_tracklength += k_tracklength;
68,094,415✔
575
    }
576
  }
577
  if (leakage != 0.0) {
199,382,840✔
578
#pragma omp atomic
20,187,507✔
579
    global_tally_leakage += leakage;
16,323,420✔
580
  }
581

582
  // Reset particle tallies once accumulated
583
  keff_tally_absorption() = 0.0;
199,382,840✔
584
  keff_tally_collision() = 0.0;
199,382,840✔
585
  keff_tally_tracklength() = 0.0;
199,382,840✔
586
  keff_tally_leakage() = 0.0;
199,382,840✔
587

588
  if (!model::active_pulse_height_tallies.empty()) {
199,382,840✔
589
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
33,000✔
590
  }
591

592
  // Accumulate track count for this particle history
593
  if (!settings::use_shared_secondary_bank) {
199,382,840✔
594
#pragma omp atomic
96,748,272✔
595
    simulation::simulation_tracks_completed += n_tracks();
177,224,112✔
596
  }
597

598
  // Record the number of progeny created by this particle.
599
  // This data will be used to efficiently sort the fission bank.
600
  if (settings::run_mode == RunMode::EIGENVALUE ||
199,382,840✔
601
      settings::use_shared_secondary_bank) {
602
    simulation::progeny_per_particle[current_work()] = n_progeny();
172,062,728✔
603
  }
604
}
199,382,840✔
605

606
void Particle::pht_collision_energy()
8,668✔
607
{
608
  // Adds the energy particles lose in a collision to the pulse-height
609

610
  // determine index of cell in pulse_height_cells
611
  auto it = std::find(model::pulse_height_cells.begin(),
8,668✔
612
    model::pulse_height_cells.end(), lowest_coord().cell());
8,668!
613

614
  if (it != model::pulse_height_cells.end()) {
8,668!
615
    int index = std::distance(model::pulse_height_cells.begin(), it);
8,668✔
616
    pht_storage()[index] += E_last() - E();
8,668✔
617

618
    // If the energy of the particle is below the cutoff, it will not be sampled
619
    // so its energy is added to the pulse-height in the cell
620
    int photon = ParticleType::photon().transport_index();
8,668✔
621
    if (E() < settings::energy_cutoff[photon]) {
8,668✔
622
      pht_storage()[index] += E();
3,740✔
623
    }
624
  }
625
}
8,668✔
626

627
void Particle::pht_secondary_particles()
3,168✔
628
{
629
  // Removes the energy of secondary produced particles from the pulse-height
630

631
  // determine index of cell in pulse_height_cells
632
  auto it = std::find(model::pulse_height_cells.begin(),
3,168✔
633
    model::pulse_height_cells.end(), cell_born());
3,168!
634

635
  if (it != model::pulse_height_cells.end()) {
3,168!
636
    int index = std::distance(model::pulse_height_cells.begin(), it);
3,168✔
637
    pht_storage()[index] -= E();
3,168✔
638
  }
639
}
3,168✔
640

641
void Particle::cross_surface(const Surface& surf)
2,147,483,647✔
642
{
643

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

648
// if we're crossing a CSG surface, make sure the DAG history is reset
649
#ifdef OPENMC_DAGMC_ENABLED
650
  if (surf.geom_type() == GeometryType::CSG)
260,970,541✔
651
    history().reset();
260,912,859✔
652
#endif
653

654
  // Handle any applicable boundary conditions.
655
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
656
      settings::run_mode != RunMode::VOLUME) {
657
    surf.bc_->handle_particle(*this, surf);
1,009,030,357✔
658
    return;
1,009,030,357✔
659
  }
660

661
  // ==========================================================================
662
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
663

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

678
    cell_instance() = 0;
46,742✔
679
    if (cell->distribcell_index_ >= 0)
46,742✔
680
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,718✔
681

682
    material() = cell->material(cell_instance());
46,742!
683
    sqrtkT() = cell->sqrtkT(cell_instance());
46,742!
684
    density_mult() = cell->density_mult(cell_instance());
46,742✔
685
    return;
46,742✔
686
  }
687
#endif
688

689
  bool verbose = settings::verbosity >= 10 || trace();
1,854,240,962!
690
  if (neighbor_list_find_cell(*this, verbose)) {
1,854,240,962✔
691
    return;
692
  }
693

694
  // ==========================================================================
695
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
696

697
  // Remove lower coordinate levels
698
  n_coord() = 1;
29,977✔
699
  bool found = exhaustive_find_cell(*this, verbose);
29,977✔
700

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

707
    surface() = SURFACE_NONE;
5,865✔
708
    n_coord() = 1;
5,865✔
709
    r() += TINY_BIT * u();
5,865✔
710

711
    // Couldn't find next cell anywhere! This probably means there is an actual
712
    // undefined region in the geometry.
713

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

723
void Particle::cross_vacuum_bc(const Surface& surf)
37,357,265✔
724
{
725
  // Score any surface current tallies -- note that the particle is moved
726
  // forward slightly so that if the mesh boundary is on the surface, it is
727
  // still processed
728

729
  if (!model::active_meshsurf_tallies.empty()) {
37,357,265✔
730
    // TODO: Find a better solution to score surface currents than
731
    // physically moving the particle forward slightly
732

733
    r() += TINY_BIT * u();
937,222✔
734
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
735
  }
736

737
  // Score to global leakage tally
738
  keff_tally_leakage() += wgt();
37,357,265✔
739

740
  // Kill the particle
741
  wgt() = 0.0;
37,357,265✔
742

743
  // Display message
744
  if (settings::verbosity >= 10 || trace()) {
37,357,265!
745
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
746
  }
747
}
37,357,265✔
748

749
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
970,435,591✔
750
{
751
  // Do not handle reflective boundary conditions on lower universes
752
  if (n_coord() != 1) {
970,435,591!
UNCOV
753
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
754
                 " off surface in a lower universe.");
UNCOV
755
    return;
×
756
  }
757

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

765
  if (!model::active_surface_tallies.empty()) {
970,435,591✔
766
    Direction normal = surf.normal(r());
285,021✔
767
    normal /= normal.norm();
285,021✔
768
    score_surface_tally(*this, model::active_surface_tallies, normal);
285,021✔
769
  }
770

771
  if (!model::active_meshsurf_tallies.empty()) {
970,435,591✔
772
    Position r {this->r()};
46,885,487✔
773
    this->r() -= TINY_BIT * u();
46,885,487✔
774
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
775
    this->r() = r;
46,885,487✔
776
  }
777

778
  // Set the new particle direction
779
  u() = new_u;
970,435,591✔
780

781
  // Reassign particle's cell and surface
782
  coord(0).cell() = cell_last(0);
970,435,591✔
783
  surface() = -surface();
970,435,591✔
784

785
  // If a reflective surface is coincident with a lattice or universe
786
  // boundary, it is necessary to redetermine the particle's coordinates in
787
  // the lower universes.
788
  // (unless we're using a dagmc model, which has exactly one universe)
789
  n_coord() = 1;
970,435,591✔
790
  if (surf.geom_type() != GeometryType::DAG &&
1,940,868,424!
791
      !neighbor_list_find_cell(*this)) {
970,432,833✔
UNCOV
792
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
UNCOV
793
                 std::to_string(surf.id_) + ".");
×
UNCOV
794
    return;
×
795
  }
796

797
  // Set previous coordinate going slightly past surface crossing
798
  r_last_current() = r() + TINY_BIT * u();
970,435,591✔
799

800
  // Diagnostic message
801
  if (settings::verbosity >= 10 || trace()) {
970,435,591!
UNCOV
802
    write_message(1, "    Reflected from surface {}", surf.id_);
×
803
  }
804
}
805

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

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

828
  // Adjust the particle's location and direction.
829
  r() = new_r;
2,242,967✔
830
  u() = new_u;
2,242,967✔
831

832
  // Reassign particle's surface
833
  surface() = new_surface;
2,242,967✔
834

835
  // Figure out what cell particle is in now
836
  n_coord() = 1;
2,242,967✔
837

838
  if (!neighbor_list_find_cell(*this)) {
2,242,967!
UNCOV
839
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
840
                 "boundary on surface " +
×
UNCOV
841
                 std::to_string(surf.id_) + ".");
×
UNCOV
842
    return;
×
843
  }
844

845
  // Set previous coordinate going slightly past surface crossing
846
  r_last_current() = r() + TINY_BIT * u();
2,242,967✔
847

848
  // Diagnostic message
849
  if (settings::verbosity >= 10 || trace()) {
2,242,967!
UNCOV
850
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
851
  }
852
}
853

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

867
  // Count the total number of simulated particles (on this processor)
868
  auto n = simulation::current_batch * settings::gen_per_batch *
5,865✔
869
           simulation::work_per_rank;
870

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

879
void Particle::write_restart() const
440✔
880
{
881
  // Dont write another restart file if in particle restart mode
882
  if (settings::run_mode == RunMode::PARTICLE)
440✔
883
    return;
33✔
884

885
  // Set up file name
886
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
407✔
887
    simulation::current_batch, id());
407✔
888

889
#pragma omp critical(WriteParticleRestart)
217✔
890
  {
407✔
891
    // Create file
892
    hid_t file_id = file_open(filename, 'w');
407✔
893

894
    // Write filetype and version info
895
    write_attribute(file_id, "filetype", "particle restart");
407✔
896
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
407✔
897
    write_attribute(file_id, "openmc_version", VERSION);
407✔
898
#ifdef GIT_SHA1
899
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
900
#endif
901

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

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

945
    // Close file
946
    file_close(file_id);
407✔
947
  } // #pragma omp critical
948
}
407✔
949

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

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

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

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

981
  // If a cell/cellfrom/cellto parameter is defined
982
  if (settings::ssw_cell_id != C_NONE) {
337,080✔
983

984
    // Retrieve cell index and storage type
985
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,435✔
986

987
    if (surf.bc_) {
254,435✔
988
      // Leave if cellto with vacuum boundary condition
989
      if (surf.bc_->type() == "vacuum" &&
298,918✔
990
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
991
        return;
992
      }
993

994
      // Leave if other boundary condition than vacuum
995
      if (surf.bc_->type() != "vacuum") {
274,646✔
996
        return;
997
      }
998
    }
999

1000
    // Check if the cell of interest has been exited
1001
    bool exited = false;
1002
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,667✔
1003
      if (p.cell_last(i) == cell_idx) {
207,728✔
1004
        exited = true;
73,763✔
1005
      }
1006
    }
1007

1008
    // Check if the cell of interest has been entered
1009
    bool entered = false;
1010
    for (int i = 0; i < p.n_coord(); ++i) {
297,969✔
1011
      if (p.coord(i).cell() == cell_idx) {
172,030✔
1012
        entered = true;
57,516✔
1013
      }
1014
    }
1015

1016
    // Vacuum boundary conditions: return if cell is not exited
1017
    if (surf.bc_) {
125,939✔
1018
      if (surf.bc_->type() == "vacuum" && !exited) {
41,926!
1019
        return;
1020
      }
1021
    } else {
1022

1023
      // If we both enter and exit the cell of interest
1024
      if (entered && exited) {
104,976✔
1025
        return;
1026
      }
1027

1028
      // If we did not enter nor exit the cell of interest
1029
      if (!entered && !exited) {
77,773✔
1030
        return;
1031
      }
1032

1033
      // If cellfrom and the cell before crossing is not the cell of
1034
      // interest
1035
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,273✔
1036
        return;
1037
      }
1038

1039
      // If cellto and the cell after crossing is not the cell of interest
1040
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,731✔
1041
        return;
1042
      }
1043
    }
1044
  }
1045

1046
  SourceSite site;
129,653✔
1047
  site.r = p.r();
129,653✔
1048
  site.u = p.u();
129,653✔
1049
  site.E = p.E();
129,653✔
1050
  site.time = p.time();
129,653✔
1051
  site.wgt = p.wgt();
129,653✔
1052
  site.delayed_group = p.delayed_group();
129,653✔
1053
  site.surf_id = surf.id_;
129,653✔
1054
  site.particle = p.type();
129,653✔
1055
  site.parent_id = p.id();
129,653✔
1056
  site.progeny_id = p.n_progeny();
129,653✔
1057
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1058
}
1059

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