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

openmc-dev / openmc / 23020451435

12 Mar 2026 07:39PM UTC coverage: 81.638% (+0.07%) from 81.566%
23020451435

Pull #3863

github

web-flow
Merge 5541c0bf0 into 27522fe85
Pull Request #3863: Shared Secondary Particle Bank

17761 of 25507 branches covered (69.63%)

Branch coverage included in aggregate %.

418 of 435 new or added lines in 17 files covered. (96.09%)

10 existing lines in 4 files now uncovered.

58266 of 67620 relevant lines covered (86.17%)

46325054.24 hits per line

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

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

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

6
#include <fmt/core.h>
7

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

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

40
namespace openmc {
41

42
//==============================================================================
43
// Particle implementation
44
//==============================================================================
45

46
double Particle::speed() const
2,147,483,647✔
47
{
48
  if (settings::run_CE) {
2,147,483,647✔
49
    // Determine mass in eV/c^2
50
    double mass;
2,147,483,647✔
51
    switch (type().pdg_number()) {
2,147,483,647✔
52
    case PDG_NEUTRON:
53
      mass = MASS_NEUTRON_EV;
54
    case PDG_ELECTRON:
55
    case PDG_POSITRON:
56
      mass = MASS_ELECTRON_EV;
2,147,483,647✔
57
    default:
2,147,483,647✔
58
      mass = this->type().mass() * AMU_EV;
2,147,483,647✔
59
    }
60

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

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

86
  // Increment number of secondaries created (for ParticleProductionFilter)
87
  n_secondaries()++;
93,371,477✔
88

89
  SourceSite bank;
93,371,477✔
90
  bank.particle = type;
93,371,477✔
91
  bank.wgt = wgt;
93,371,477✔
92
  bank.r = r();
93,371,477!
93
  bank.u = u;
93,371,477✔
94
  bank.E = settings::run_CE ? E : g();
93,371,477!
95
  bank.time = time();
93,371,477✔
96
  bank_second_E() += bank.E;
93,371,477✔
97
  bank.parent_id = current_work();
93,371,477✔
98
  if (settings::use_shared_secondary_bank) {
93,371,477✔
99
    bank.progeny_id = n_progeny()++;
15,371,202✔
100
  }
101
  bank.wgt_born = wgt_born();
93,371,477✔
102
  bank.wgt_ww_born = wgt_ww_born();
93,371,477✔
103
  bank.n_split = n_split();
93,371,477✔
104

105
  // In shared secondary mode, subtract secondary photon energy from parent's
106
  // pulse-height storage now, since the secondary will be transported as a
107
  // separate Particle object and won't have access to the parent's pht_storage.
108
  if (settings::use_shared_secondary_bank &&
108,742,679✔
109
      !model::active_pulse_height_tallies.empty() && type.is_photon()) {
93,371,477!
NEW
110
    auto it = std::find(model::pulse_height_cells.begin(),
×
NEW
111
      model::pulse_height_cells.end(), lowest_coord().cell());
×
NEW
112
    if (it != model::pulse_height_cells.end()) {
×
NEW
113
      int index = std::distance(model::pulse_height_cells.begin(), it);
×
NEW
114
      pht_storage()[index] -= bank.E;
×
115
    }
116
  }
117

118
  local_secondary_bank().emplace_back(bank);
93,371,477✔
119
  return true;
120
}
121

122
void Particle::split(double wgt)
10,347,378✔
123
{
124
  SourceSite bank;
10,347,378✔
125
  bank.particle = type();
10,347,378✔
126
  bank.wgt = wgt;
10,347,378✔
127
  bank.r = r();
10,347,378✔
128
  bank.u = u();
10,347,378✔
129
  bank.E = settings::run_CE ? E() : g();
10,347,378✔
130
  bank.time = time();
10,347,378✔
131

132
  // Convert signed index to a signed surface ID
133
  if (surface() == SURFACE_NONE) {
10,347,378✔
134
    bank.surf_id = SURFACE_NONE;
10,343,506✔
135
  } else {
136
    int surf_id = model::surfaces[surface_index()]->id_;
3,872✔
137
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
3,872✔
138
  }
139

140
  bank.wgt_born = wgt_born();
10,347,378✔
141
  bank.wgt_ww_born = wgt_ww_born();
10,347,378✔
142
  bank.n_split = n_split();
10,347,378✔
143
  bank.parent_id = current_work();
10,347,378✔
144
  if (settings::use_shared_secondary_bank) {
10,347,378✔
145
    bank.progeny_id = n_progeny()++;
5,177,213✔
146
  }
147

148
  local_secondary_bank().emplace_back(bank);
10,347,378✔
149
}
10,347,378✔
150

151
void Particle::from_source(const SourceSite* src)
282,512,796✔
152
{
153
  // Reset some attributes
154
  clear();
282,512,796✔
155
  surface() = SURFACE_NONE;
282,512,796✔
156
  cell_born() = C_NONE;
282,512,796✔
157
  material() = C_NONE;
282,512,796✔
158
  n_collision() = 0;
282,512,796✔
159
  fission() = false;
282,512,796✔
160
  zero_flux_derivs();
282,512,796✔
161
  lifetime() = 0.0;
282,512,796✔
162
#ifdef OPENMC_DAGMC_ENABLED
163
  history().reset();
25,845,134✔
164
#endif
165

166
  // Copy attributes from source bank site
167
  type() = src->particle;
282,512,796✔
168
  wgt() = src->wgt;
282,512,796✔
169
  wgt_last() = src->wgt;
282,512,796✔
170
  r() = src->r;
282,512,796✔
171
  u() = src->u;
282,512,796✔
172
  r_born() = src->r;
282,512,796✔
173
  r_last_current() = src->r;
282,512,796✔
174
  r_last() = src->r;
282,512,796✔
175
  u_last() = src->u;
282,512,796✔
176
  if (settings::run_CE) {
282,512,796✔
177
    E() = src->E;
165,823,262✔
178
    g() = 0;
165,823,262✔
179
  } else {
180
    g() = static_cast<int>(src->E);
116,689,534✔
181
    g_last() = static_cast<int>(src->E);
116,689,534✔
182
    E() = data::mg.energy_bin_avg_[g()];
116,689,534✔
183
  }
184
  E_last() = E();
282,512,796✔
185
  time() = src->time;
282,512,796✔
186
  time_last() = src->time;
282,512,796✔
187
  parent_nuclide() = src->parent_nuclide;
282,512,796✔
188
  delayed_group() = src->delayed_group;
282,512,796✔
189

190
  // Convert signed surface ID to signed index
191
  if (src->surf_id != SURFACE_NONE) {
282,512,796✔
192
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
113,872✔
193
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
113,872✔
194
  }
195

196
  wgt_born() = src->wgt_born;
282,512,796✔
197
  wgt_ww_born() = src->wgt_ww_born;
282,512,796✔
198
  n_split() = src->n_split;
282,512,796✔
199
}
282,512,796✔
200

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

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

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

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

228
    // Set birth cell attribute
229
    if (cell_born() == C_NONE)
273,840,083!
230
      cell_born() = lowest_coord().cell();
273,840,083✔
231

232
    // Initialize last cells from current cell
233
    for (int j = 0; j < n_coord(); ++j) {
565,075,585✔
234
      cell_last(j) = coord(j).cell();
291,235,502✔
235
    }
236
    n_coord_last() = n_coord();
273,840,083✔
237
  }
238

239
  // Write particle track.
240
  if (write_track())
2,147,483,647✔
241
    write_particle_track(*this);
10,309✔
242

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

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

262
      // Update the particle's group while we know we are multi-group
263
      g_last() = g();
2,081,363,471✔
264
    }
265
  } else {
266
    macro_xs().total = 0.0;
111,862,093✔
267
    macro_xs().absorption = 0.0;
111,862,093✔
268
    macro_xs().fission = 0.0;
111,862,093✔
269
    macro_xs().nu_fission = 0.0;
111,862,093✔
270
  }
271
}
272

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

278
  // Sample a distance to collision
279
  if (type() == ParticleType::electron() ||
2,147,483,647✔
280
      type() == ParticleType::positron()) {
2,147,483,647✔
281
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
172,373,148!
282
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
283
    collision_distance() = INFINITY;
111,862,093✔
284
  } else {
285
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
286
  }
287

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

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

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

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

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

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

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

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

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

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

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

343
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
344
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
345
      boundary().lattice_translation()[2] != 0) {
1,861,009,496✔
346
    // Particle crosses lattice boundary
347

348
    bool verbose = settings::verbosity >= 10 || trace();
749,891,384!
349
    cross_lattice(*this, boundary(), verbose);
749,891,384✔
350
    event() = TallyEvent::LATTICE;
749,891,384✔
351
  } else {
352
    // Particle crosses surface
353
    // If BC, add particle to surface source before crossing surface
354
    if (surf.surf_source_ && surf.bc_) {
1,672,569,226✔
355
      add_surf_source_to_bank(*this, surf);
720,441,020✔
356
    }
357
    this->cross_surface(surf);
1,672,569,226✔
358
    // If no BC, add particle to surface source after crossing surface
359
    if (surf.surf_source_ && !surf.bc_) {
1,672,569,217✔
360
      add_surf_source_to_bank(*this, surf);
950,890,370✔
361
    }
362
    if (settings::weight_window_checkpoint_surface) {
1,672,569,217✔
363
      apply_weight_windows(*this);
173,985✔
364
    }
365
    event() = TallyEvent::SURFACE;
1,672,569,217✔
366
  }
367
  // Score cell to cell partial currents
368
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
369
    score_surface_tally(*this, model::active_surface_tallies, surf);
34,931,567✔
370
  }
371
}
2,147,483,647✔
372

373
void Particle::event_collide()
2,147,483,647✔
374
{
375

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

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

385
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
386
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
387

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

391
  if (settings::run_CE) {
2,147,483,647✔
392
    collision(*this);
1,261,107,495✔
393
  } else {
394
    collision_mg(*this);
1,800,818,030✔
395
  }
396

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

402
  // Score collision estimator tallies -- this is done after a collision
403
  // has occurred rather than before because we need information on the
404
  // outgoing energy for any tallies with an outgoing energy filter
405
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
406
    score_collision_tally(*this);
108,967,600✔
407
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
408
    if (settings::run_CE) {
406,059,376✔
409
      score_analog_tally_ce(*this);
404,851,114✔
410
    } else {
411
      score_analog_tally_mg(*this);
1,208,262✔
412
    }
413
  }
414

415
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
416
    pht_collision_energy();
8,096✔
417
  }
418

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

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

428
  zero_delayed_bank();
2,147,483,647✔
429

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

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

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

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

454
  // Score flux derivative accumulators for differential tallies.
455
  if (!model::active_tallies.empty())
2,147,483,647✔
456
    score_collision_derivative(*this);
1,143,545,130✔
457

458
#ifdef OPENMC_DAGMC_ENABLED
459
  history().reset();
280,475,271✔
460
#endif
461
}
2,147,483,647✔
462

463
void Particle::event_revive_from_secondary(SourceSite& site)
104,733,052✔
464
{
465
  // Write final position for the previous track (skip if this is a freshly
466
  // constructed particle with no prior track, e.g., Phase 2 of shared
467
  // secondary transport)
468
  if (write_track() && n_event() > 0) {
104,733,052!
469
    write_particle_track(*this);
5,234✔
470
  }
471

472
  from_source(&site);
104,733,052✔
473

474
  n_event() = 0;
104,733,052✔
475
  if (!settings::use_shared_secondary_bank) {
104,733,052✔
476
    n_tracks()++;
83,378,975✔
477
  }
478
  bank_second_E() = 0.0;
104,733,052✔
479

480
  // Subtract secondary particle energy from interim pulse-height results.
481
  // In shared secondary mode, this subtraction was already done on the parent
482
  // particle during create_secondary(), so skip it here.
483
  if (!settings::use_shared_secondary_bank &&
188,112,027✔
484
      !model::active_pulse_height_tallies.empty() && this->type().is_photon()) {
104,733,052✔
485
    // Since the birth cell of the particle has not been set we
486
    // have to determine it before the energy of the secondary particle can be
487
    // removed from the pulse-height of this cell.
488
    if (lowest_coord().cell() == C_NONE) {
2,420!
489
      bool verbose = settings::verbosity >= 10 || trace();
2,420!
490
      if (!exhaustive_find_cell(*this, verbose)) {
2,420!
NEW
491
        mark_as_lost("Could not find the cell containing particle " +
×
NEW
492
                     std::to_string(id()));
×
NEW
493
        return;
×
494
      }
495
      // Set birth cell attribute
496
      if (cell_born() == C_NONE)
2,420!
497
        cell_born() = lowest_coord().cell();
2,420✔
498

499
      // Initialize last cells from current cell
500
      for (int j = 0; j < n_coord(); ++j) {
4,840✔
501
        cell_last(j) = coord(j).cell();
2,420✔
502
      }
503
      n_coord_last() = n_coord();
2,420✔
504
    }
505
    pht_secondary_particles();
2,420✔
506
  }
507

508
  // Enter new particle in particle track file
509
  if (write_track())
104,733,052✔
510
    add_particle_track(*this);
5,234✔
511
}
512

513
void Particle::event_check_limit_and_revive()
2,147,483,647✔
514
{
515
  // If particle has too many events, display warning and kill it
516
  n_event()++;
2,147,483,647✔
517
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
NEW
518
    warning("Particle " + std::to_string(id()) +
×
519
            " underwent maximum number of events.");
NEW
520
    wgt() = 0.0;
×
521
  }
522

523
  // In non-shared-secondary mode, revive from local secondary bank
524
  if (!alive() && !settings::use_shared_secondary_bank &&
2,147,483,647✔
525
      !local_secondary_bank().empty()) {
251,702,921✔
526
    SourceSite& site = local_secondary_bank().back();
83,378,975✔
527
    event_revive_from_secondary(site);
83,378,975✔
528
    local_secondary_bank().pop_back();
83,378,975✔
529
  }
530
}
2,147,483,647✔
531

532
void Particle::event_death()
190,463,519✔
533
{
534
#ifdef OPENMC_DAGMC_ENABLED
535
  history().reset();
17,395,587✔
536
#endif
537

538
  // Finish particle track output.
539
  if (write_track()) {
190,463,519✔
540
    write_particle_track(*this);
1,010✔
541
    finalize_particle_track(*this);
1,010✔
542
  }
543

544
// Contribute tally reduction variables to global accumulator
545
#pragma omp atomic
104,729,703✔
546
  global_tally_absorption += keff_tally_absorption();
190,463,519✔
547
#pragma omp atomic
104,804,651✔
548
  global_tally_collision += keff_tally_collision();
190,463,519✔
549
#pragma omp atomic
104,550,688✔
550
  global_tally_tracklength += keff_tally_tracklength();
190,463,519✔
551
#pragma omp atomic
104,433,547✔
552
  global_tally_leakage += keff_tally_leakage();
190,463,519✔
553

554
  // Reset particle tallies once accumulated
555
  keff_tally_absorption() = 0.0;
190,463,519✔
556
  keff_tally_collision() = 0.0;
190,463,519✔
557
  keff_tally_tracklength() = 0.0;
190,463,519✔
558
  keff_tally_leakage() = 0.0;
190,463,519✔
559

560
  if (!model::active_pulse_height_tallies.empty()) {
190,463,519✔
561
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
22,000✔
562
  }
563

564
  // Accumulate track count for this particle history
565
  if (!settings::use_shared_secondary_bank) {
190,463,519✔
566
#pragma omp atomic
91,893,936✔
567
    simulation::simulation_tracks_completed += n_tracks();
168,324,946✔
568
  }
569

570
  // Record the number of progeny created by this particle.
571
  // This data will be used to efficiently sort the fission bank.
572
  if (settings::run_mode == RunMode::EIGENVALUE ||
190,463,519✔
573
      settings::use_shared_secondary_bank) {
574
    simulation::progeny_per_particle[current_work()] = n_progeny();
163,673,273✔
575
  }
576
}
190,463,519✔
577

578
void Particle::pht_collision_energy()
8,096✔
579
{
580
  // Adds the energy particles lose in a collision to the pulse-height
581

582
  // determine index of cell in pulse_height_cells
583
  auto it = std::find(model::pulse_height_cells.begin(),
8,096✔
584
    model::pulse_height_cells.end(), lowest_coord().cell());
8,096!
585

586
  if (it != model::pulse_height_cells.end()) {
8,096!
587
    int index = std::distance(model::pulse_height_cells.begin(), it);
8,096✔
588
    pht_storage()[index] += E_last() - E();
8,096✔
589

590
    // If the energy of the particle is below the cutoff, it will not be sampled
591
    // so its energy is added to the pulse-height in the cell
592
    int photon = ParticleType::photon().transport_index();
8,096✔
593
    if (E() < settings::energy_cutoff[photon]) {
8,096✔
594
      pht_storage()[index] += E();
3,300✔
595
    }
596
  }
597
}
8,096✔
598

599
void Particle::pht_secondary_particles()
2,420✔
600
{
601
  // Removes the energy of secondary produced particles from the pulse-height
602

603
  // determine index of cell in pulse_height_cells
604
  auto it = std::find(model::pulse_height_cells.begin(),
2,420✔
605
    model::pulse_height_cells.end(), cell_born());
2,420!
606

607
  if (it != model::pulse_height_cells.end()) {
2,420!
608
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,420✔
609
    pht_storage()[index] -= E();
2,420✔
610
  }
611
}
2,420✔
612

613
void Particle::cross_surface(const Surface& surf)
1,674,486,092✔
614
{
615

616
  if (settings::verbosity >= 10 || trace()) {
1,674,486,092✔
617
    write_message(1, "    Crossing surface {}", surf.id_);
88✔
618
  }
619

620
// if we're crossing a CSG surface, make sure the DAG history is reset
621
#ifdef OPENMC_DAGMC_ENABLED
622
  if (surf.geom_type() == GeometryType::CSG)
152,919,414✔
623
    history().reset();
152,861,732✔
624
#endif
625

626
  // Handle any applicable boundary conditions.
627
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,674,486,092!
628
      settings::run_mode != RunMode::VOLUME) {
629
    surf.bc_->handle_particle(*this, surf);
720,793,128✔
630
    return;
720,793,128✔
631
  }
632

633
  // ==========================================================================
634
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
635

636
#ifdef OPENMC_DAGMC_ENABLED
637
  // in DAGMC, we know what the next cell should be
638
  if (surf.geom_type() == GeometryType::DAG) {
86,951,082✔
639
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,742✔
640
                       lowest_coord().universe()) -
46,742✔
641
                     1;
46,742✔
642
    // save material, temperature, and density multiplier
643
    material_last() = material();
46,742✔
644
    sqrtkT_last() = sqrtkT();
46,742✔
645
    density_mult_last() = density_mult();
46,742✔
646
    // set new cell value
647
    lowest_coord().cell() = i_cell;
46,742✔
648
    auto& cell = model::cells[i_cell];
46,742✔
649

650
    cell_instance() = 0;
46,742✔
651
    if (cell->distribcell_index_ >= 0)
46,742✔
652
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,718✔
653

654
    material() = cell->material(cell_instance());
46,742!
655
    sqrtkT() = cell->sqrtkT(cell_instance());
46,742!
656
    density_mult() = cell->density_mult(cell_instance());
46,742✔
657
    return;
46,742✔
658
  }
659
#endif
660

661
  bool verbose = settings::verbosity >= 10 || trace();
953,646,222!
662
  if (neighbor_list_find_cell(*this, verbose)) {
953,646,222✔
663
    return;
664
  }
665

666
  // ==========================================================================
667
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
668

669
  // Remove lower coordinate levels
670
  n_coord() = 1;
29,977✔
671
  bool found = exhaustive_find_cell(*this, verbose);
29,977✔
672

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

679
    surface() = SURFACE_NONE;
5,865✔
680
    n_coord() = 1;
5,865✔
681
    r() += TINY_BIT * u();
5,865✔
682

683
    // Couldn't find next cell anywhere! This probably means there is an actual
684
    // undefined region in the geometry.
685

686
    if (!exhaustive_find_cell(*this, verbose)) {
5,865!
687
      mark_as_lost("After particle " + std::to_string(id()) +
17,586✔
688
                   " crossed surface " + std::to_string(surf.id_) +
17,586✔
689
                   " it could not be located in any cell and it did not leak.");
690
      return;
5,856✔
691
    }
692
  }
693
}
694

695
void Particle::cross_vacuum_bc(const Surface& surf)
35,136,208✔
696
{
697
  // Score any surface current tallies -- note that the particle is moved
698
  // forward slightly so that if the mesh boundary is on the surface, it is
699
  // still processed
700

701
  if (!model::active_meshsurf_tallies.empty()) {
35,136,208✔
702
    // TODO: Find a better solution to score surface currents than
703
    // physically moving the particle forward slightly
704

705
    r() += TINY_BIT * u();
937,222✔
706
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
707
  }
708

709
  // Score to global leakage tally
710
  keff_tally_leakage() += wgt();
35,136,208✔
711

712
  // Kill the particle
713
  wgt() = 0.0;
35,136,208✔
714

715
  // Display message
716
  if (settings::verbosity >= 10 || trace()) {
35,136,208!
717
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
718
  }
719
}
35,136,208✔
720

721
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
684,413,855✔
722
{
723
  // Do not handle reflective boundary conditions on lower universes
724
  if (n_coord() != 1) {
684,413,855!
725
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
726
                 " off surface in a lower universe.");
727
    return;
×
728
  }
729

730
  // Score surface currents since reflection causes the direction of the
731
  // particle to change. For surface filters, we need to score the tallies
732
  // twice, once before the particle's surface attribute has changed and
733
  // once after. For mesh surface filters, we need to artificially move
734
  // the particle slightly back in case the surface crossing is coincident
735
  // with a mesh boundary
736

737
  if (!model::active_surface_tallies.empty()) {
684,413,855✔
738
    score_surface_tally(*this, model::active_surface_tallies, surf);
285,021✔
739
  }
740

741
  if (!model::active_meshsurf_tallies.empty()) {
684,413,855✔
742
    Position r {this->r()};
46,885,487✔
743
    this->r() -= TINY_BIT * u();
46,885,487✔
744
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
745
    this->r() = r;
46,885,487✔
746
  }
747

748
  // Set the new particle direction
749
  u() = new_u;
684,413,855✔
750

751
  // Reassign particle's cell and surface
752
  coord(0).cell() = cell_last(0);
684,413,855✔
753
  surface() = -surface();
684,413,855✔
754

755
  // If a reflective surface is coincident with a lattice or universe
756
  // boundary, it is necessary to redetermine the particle's coordinates in
757
  // the lower universes.
758
  // (unless we're using a dagmc model, which has exactly one universe)
759
  n_coord() = 1;
684,413,855✔
760
  if (surf.geom_type() != GeometryType::DAG &&
1,368,824,952!
761
      !neighbor_list_find_cell(*this)) {
684,411,097✔
762
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
763
                 std::to_string(surf.id_) + ".");
×
764
    return;
×
765
  }
766

767
  // Set previous coordinate going slightly past surface crossing
768
  r_last_current() = r() + TINY_BIT * u();
684,413,855✔
769

770
  // Diagnostic message
771
  if (settings::verbosity >= 10 || trace()) {
684,413,855!
772
    write_message(1, "    Reflected from surface {}", surf.id_);
×
773
  }
774
}
775

776
void Particle::cross_periodic_bc(
2,248,531✔
777
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
778
{
779
  // Do not handle periodic boundary conditions on lower universes
780
  if (n_coord() != 1) {
2,248,531!
781
    mark_as_lost(
×
782
      "Cannot transfer particle " + std::to_string(id()) +
×
783
      " across surface in a lower universe. Boundary conditions must be "
784
      "applied to root universe.");
785
    return;
×
786
  }
787

788
  // Score surface currents since reflection causes the direction of the
789
  // particle to change -- artificially move the particle slightly back in
790
  // case the surface crossing is coincident with a mesh boundary
791
  if (!model::active_meshsurf_tallies.empty()) {
2,248,531!
792
    Position r {this->r()};
×
793
    this->r() -= TINY_BIT * u();
×
794
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
795
    this->r() = r;
×
796
  }
797

798
  // Adjust the particle's location and direction.
799
  r() = new_r;
2,248,531✔
800
  u() = new_u;
2,248,531✔
801

802
  // Reassign particle's surface
803
  surface() = new_surface;
2,248,531✔
804

805
  // Figure out what cell particle is in now
806
  n_coord() = 1;
2,248,531✔
807

808
  if (!neighbor_list_find_cell(*this)) {
2,248,531!
809
    mark_as_lost("Couldn't find particle after hitting periodic "
×
810
                 "boundary on surface " +
×
811
                 std::to_string(surf.id_) + ".");
×
812
    return;
×
813
  }
814

815
  // Set previous coordinate going slightly past surface crossing
816
  r_last_current() = r() + TINY_BIT * u();
2,248,531✔
817

818
  // Diagnostic message
819
  if (settings::verbosity >= 10 || trace()) {
2,248,531!
820
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
821
  }
822
}
823

824
void Particle::mark_as_lost(const char* message)
5,865✔
825
{
826
  // Print warning and write lost particle file
827
  warning(message);
5,865✔
828
  if (settings::max_write_lost_particles < 0 ||
5,865✔
829
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
830
    write_restart();
440✔
831
  }
832
  // Increment number of lost particles
833
  wgt() = 0.0;
5,865✔
834
#pragma omp atomic
3,190✔
835
  simulation::n_lost_particles += 1;
2,675✔
836

837
  // Count the total number of simulated particles (on this processor)
838
  auto n = simulation::current_batch * settings::gen_per_batch *
5,865✔
839
           simulation::work_per_rank;
840

841
  // Abort the simulation if the maximum number of lost particles has been
842
  // reached
843
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,865✔
844
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
845
    fatal_error("Maximum number of lost particles has been reached.");
9✔
846
  }
847
}
5,856✔
848

849
void Particle::write_restart() const
440✔
850
{
851
  // Dont write another restart file if in particle restart mode
852
  if (settings::run_mode == RunMode::PARTICLE)
440✔
853
    return;
33✔
854

855
  // Set up file name
856
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
407✔
857
    simulation::current_batch, id());
407✔
858

859
#pragma omp critical(WriteParticleRestart)
217✔
860
  {
407✔
861
    // Create file
862
    hid_t file_id = file_open(filename, 'w');
407✔
863

864
    // Write filetype and version info
865
    write_attribute(file_id, "filetype", "particle restart");
407✔
866
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
407✔
867
    write_attribute(file_id, "openmc_version", VERSION);
407✔
868
#ifdef GIT_SHA1
869
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
870
#endif
871

872
    // Write data to file
873
    write_dataset(file_id, "current_batch", simulation::current_batch);
407✔
874
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
407✔
875
    write_dataset(file_id, "current_generation", simulation::current_gen);
407✔
876
    write_dataset(file_id, "n_particles", settings::n_particles);
407✔
877
    switch (settings::run_mode) {
407!
878
    case RunMode::FIXED_SOURCE:
275✔
879
      write_dataset(file_id, "run_mode", "fixed source");
275✔
880
      break;
145✔
881
    case RunMode::EIGENVALUE:
132✔
882
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
883
      break;
72✔
884
    case RunMode::PARTICLE:
×
885
      write_dataset(file_id, "run_mode", "particle restart");
×
886
      break;
887
    default:
888
      break;
889
    }
890
    write_dataset(file_id, "id", id());
407✔
891
    write_dataset(file_id, "type", type().pdg_number());
407✔
892

893
    // Get source site data for the particle that got lost
894
    int64_t i = current_work();
407✔
895
    SourceSite site;
407✔
896
    if (settings::run_mode == RunMode::EIGENVALUE) {
407✔
897
      site = simulation::source_bank[i];
132✔
898
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
275✔
899
               settings::use_shared_secondary_bank &&
275!
900
               i < simulation::shared_secondary_bank_read.size()) {
55!
NEW
901
      site = simulation::shared_secondary_bank_read[i];
×
902
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
275!
903
      // Re-sample using the same seed used to generate the source particle.
904
      // current_work() is 0-indexed, compute_particle_id expects 1-indexed.
905
      int64_t id = compute_transport_seed(compute_particle_id(i + 1));
275✔
906
      uint64_t seed = init_seed(id, STREAM_SOURCE);
275✔
907
      site = sample_external_source(&seed);
275✔
908
    }
909
    write_dataset(file_id, "weight", site.wgt);
407✔
910
    write_dataset(file_id, "energy", site.E);
407✔
911
    write_dataset(file_id, "xyz", site.r);
407✔
912
    write_dataset(file_id, "uvw", site.u);
407✔
913
    write_dataset(file_id, "time", site.time);
407✔
914

915
    // Close file
916
    file_close(file_id);
407✔
917
  } // #pragma omp critical
918
}
407✔
919

920
void Particle::update_neutron_xs(
2,147,483,647✔
921
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
922
{
923
  // Get microscopic cross section cache
924
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
925

926
  // If the cache doesn't match, recalculate micro xs
927
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
928
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
929
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
930
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
931

932
    // If NCrystal is being used, update micro cross section cache
933
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
934
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
935
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
936
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
937
    }
938
  }
939
}
2,147,483,647✔
940

941
//==============================================================================
942
// Non-method functions
943
//==============================================================================
944
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,671,331,390✔
945
{
946
  if (simulation::current_batch <= settings::n_inactive ||
1,671,331,390✔
947
      simulation::surf_source_bank.full()) {
1,285,859,765✔
948
    return;
1,671,201,737✔
949
  }
950

951
  // If a cell/cellfrom/cellto parameter is defined
952
  if (settings::ssw_cell_id != C_NONE) {
337,079✔
953

954
    // Retrieve cell index and storage type
955
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,434✔
956

957
    if (surf.bc_) {
254,434✔
958
      // Leave if cellto with vacuum boundary condition
959
      if (surf.bc_->type() == "vacuum" &&
298,918✔
960
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
961
        return;
962
      }
963

964
      // Leave if other boundary condition than vacuum
965
      if (surf.bc_->type() != "vacuum") {
274,648✔
966
        return;
967
      }
968
    }
969

970
    // Check if the cell of interest has been exited
971
    bool exited = false;
972
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,667✔
973
      if (p.cell_last(i) == cell_idx) {
207,728✔
974
        exited = true;
73,764✔
975
      }
976
    }
977

978
    // Check if the cell of interest has been entered
979
    bool entered = false;
980
    for (int i = 0; i < p.n_coord(); ++i) {
297,969✔
981
      if (p.coord(i).cell() == cell_idx) {
172,030✔
982
        entered = true;
57,515✔
983
      }
984
    }
985

986
    // Vacuum boundary conditions: return if cell is not exited
987
    if (surf.bc_) {
125,939✔
988
      if (surf.bc_->type() == "vacuum" && !exited) {
41,928!
989
        return;
990
      }
991
    } else {
992

993
      // If we both enter and exit the cell of interest
994
      if (entered && exited) {
104,975✔
995
        return;
996
      }
997

998
      // If we did not enter nor exit the cell of interest
999
      if (!entered && !exited) {
77,772✔
1000
        return;
1001
      }
1002

1003
      // If cellfrom and the cell before crossing is not the cell of
1004
      // interest
1005
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,273✔
1006
        return;
1007
      }
1008

1009
      // If cellto and the cell after crossing is not the cell of interest
1010
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,732✔
1011
        return;
1012
      }
1013
    }
1014
  }
1015

1016
  SourceSite site;
129,653✔
1017
  site.r = p.r();
129,653✔
1018
  site.u = p.u();
129,653✔
1019
  site.E = p.E();
129,653✔
1020
  site.time = p.time();
129,653✔
1021
  site.wgt = p.wgt();
129,653✔
1022
  site.delayed_group = p.delayed_group();
129,653✔
1023
  site.surf_id = surf.id_;
129,653✔
1024
  site.particle = p.type();
129,653✔
1025
  site.parent_id = p.id();
129,653✔
1026
  site.progeny_id = p.n_progeny();
129,653✔
1027
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1028
}
1029

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