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

openmc-dev / openmc / 22553980355

01 Mar 2026 10:12PM UTC coverage: 81.417%. First build
22553980355

Pull #3843

github

web-flow
Merge fb6dcf7be into 83a7b36ad
Pull Request #3843: Implement cell importance variance reduction scheme.

17515 of 25275 branches covered (69.3%)

Branch coverage included in aggregate %.

54 of 117 new or added lines in 5 files covered. (46.15%)

57727 of 67141 relevant lines covered (85.98%)

45335662.04 hits per line

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

83.89
/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,063,937,414✔
66
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
67
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
68
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
69
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
70
  }
71
}
72

73
bool Particle::create_secondary(
112,437,805✔
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();
112,437,805✔
79
  if (idx == C_NONE) {
112,437,805!
80
    return false;
81
  }
82
  if (E < settings::energy_cutoff[idx]) {
112,437,805✔
83
    return false;
84
  }
85

86
  // Increment number of secondaries created (for ParticleProductionFilter)
87
  n_secondaries()++;
58,671,989✔
88

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

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

110
  // Convert signed index to a signed surface ID
111
  if (surface() == SURFACE_NONE) {
4,250,805✔
112
    bank.surf_id = SURFACE_NONE;
4,250,260✔
113
  } else {
114
    int surf_id = model::surfaces[surface_index()]->id_;
545✔
115
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
545✔
116
  }
117
}
4,250,805✔
118

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

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

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

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

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

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

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

192
    // Set birth cell attribute
193
    if (cell_born() == C_NONE)
231,814,288!
194
      cell_born() = lowest_coord().cell();
231,814,288✔
195

196
    // Initialize last cells from current cell
197
    for (int j = 0; j < n_coord(); ++j) {
481,100,488✔
198
      cell_last(j) = coord(j).cell();
249,286,200✔
199
    }
200
    n_coord_last() = n_coord();
231,814,288✔
201
  }
202

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

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

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

226
      // Update the particle's group while we know we are multi-group
227
      g_last() = g();
2,063,937,414✔
228
    }
229
  } else {
230
    macro_xs().total = 0.0;
111,829,771✔
231
    macro_xs().absorption = 0.0;
111,829,771✔
232
    macro_xs().fission = 0.0;
111,829,771✔
233
    macro_xs().nu_fission = 0.0;
111,829,771✔
234
  }
235
}
236

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

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

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

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

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

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

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

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

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

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

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

301
  if (simulation::cell_importances && material() != MATERIAL_VOID)
2,147,483,647!
NEW
302
    importance_last() = cell_importance_at_level(*this, n_coord() - 1);
×
303

304
  // Set surface that particle is on and adjust coordinate levels
305
  surface() = boundary().surface();
2,147,483,647✔
306
  n_coord() = boundary().coord_level();
2,147,483,647✔
307

308
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
309
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
310
      boundary().lattice_translation()[2] != 0) {
1,860,005,187✔
311
    // Particle crosses lattice boundary
312

313
    bool verbose = settings::verbosity >= 10 || trace();
750,250,877!
314
    cross_lattice(*this, boundary(), verbose);
750,250,877✔
315
    event() = TallyEvent::LATTICE;
750,250,877✔
316
  } else {
317
    // Particle crosses surface
318
    const auto& surf {model::surfaces[surface_index()].get()};
1,671,463,316✔
319
    // If BC, add particle to surface source before crossing surface
320
    if (surf->surf_source_ && surf->bc_) {
1,671,463,316✔
321
      add_surf_source_to_bank(*this, *surf);
720,224,890✔
322
    }
323
    this->cross_surface(*surf);
1,671,463,316✔
324
    double importance = cell_importance_at_level(*this, n_coord() - 1);
1,671,463,307✔
325
    if (importance == 0.0) {
1,671,463,307!
NEW
326
      wgt() = 0.0;
×
NEW
327
      return;
×
328
    }
329
    // If no BC, add particle to surface source after crossing surface
330
    if (surf->surf_source_ && !surf->bc_) {
1,671,463,307✔
331
      add_surf_source_to_bank(*this, *surf);
950,000,590✔
332
    }
333
    if (settings::weight_window_checkpoint_surface) {
1,671,463,307✔
334
      apply_weight_windows(*this);
74,912✔
335
    }
336
    if (simulation::cell_importances) {
1,671,463,307!
NEW
337
      if (importance != importance_last()) {
×
NEW
338
        if (importance < importance_last()) {
×
NEW
339
          if (importance_last() * prn(current_seed()) < importance) {
×
NEW
340
            wgt() *= importance_last() / importance;
×
341
          } else {
NEW
342
            wgt() = 0.;
×
NEW
343
            return;
×
344
          }
345
        } else {
346
          // do not further split the particle if above the limit
NEW
347
          if (n_split() >= settings::max_history_splits)
×
348
            return;
349

NEW
350
          double num_split = std::min(
×
NEW
351
            static_cast<int>(std::ceil(importance / importance_last())),
×
NEW
352
            settings::max_history_splits);
×
NEW
353
          n_split() += num_split;
×
354

355
          // Create secondaries and divide weight among all particles
NEW
356
          int i_split = std::round(num_split);
×
NEW
357
          for (int l = 0; l < i_split - 1; l++) {
×
NEW
358
            split(wgt() / num_split);
×
359
          }
360
          // remaining weight is applied to current particle
NEW
361
          wgt() /= num_split;
×
362
        }
363
      }
364
    }
365
    event() = TallyEvent::SURFACE;
1,671,463,307✔
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);
34,922,767✔
370
  }
371
}
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,010,968✔
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_surface_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,071,534,161✔
393
  } else {
394
    collision_mg(*this);
1,783,060,477✔
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);
107,369,684✔
407
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
408
    if (settings::run_CE) {
406,034,945✔
409
      score_analog_tally_ce(*this);
404,826,683✔
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();
2,024✔
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,247,365✔
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,820,751✔
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);
937,124,476✔
457

458
#ifdef OPENMC_DAGMC_ENABLED
459
  history().reset();
261,961,877✔
460
#endif
461
}
2,147,483,647✔
462

463
void Particle::event_revive_from_secondary()
2,147,483,647✔
464
{
465
  // If particle has too many events, display warning and kill it
466
  ++n_event();
2,147,483,647✔
467
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
468
    warning("Particle " + std::to_string(id()) +
×
469
            " underwent maximum number of events.");
470
    wgt() = 0.0;
×
471
  }
472

473
  // Check for secondary particles if this particle is dead
474
  if (!alive()) {
2,147,483,647✔
475
    // Write final position for this particle
476
    if (write_track()) {
231,813,884✔
477
      write_particle_track(*this);
6,244✔
478
    }
479

480
    // If no secondary particles, break out of event loop
481
    if (secondary_bank().empty())
231,813,884✔
482
      return;
483

484
    from_source(&secondary_bank().back());
63,126,313✔
485
    secondary_bank().pop_back();
63,126,313✔
486
    n_event() = 0;
63,126,313✔
487
    bank_second_E() = 0.0;
63,126,313✔
488

489
    // Subtract secondary particle energy from interim pulse-height results
490
    if (!model::active_pulse_height_tallies.empty() &&
63,126,313✔
491
        this->type().is_photon()) {
15,499✔
492
      // Since the birth cell of the particle has not been set we
493
      // have to determine it before the energy of the secondary particle can be
494
      // removed from the pulse-height of this cell.
495
      if (lowest_coord().cell() == C_NONE) {
605!
496
        bool verbose = settings::verbosity >= 10 || trace();
605!
497
        if (!exhaustive_find_cell(*this, verbose)) {
605!
498
          mark_as_lost("Could not find the cell containing particle " +
×
499
                       std::to_string(id()));
×
500
          return;
×
501
        }
502
        // Set birth cell attribute
503
        if (cell_born() == C_NONE)
605!
504
          cell_born() = lowest_coord().cell();
605✔
505

506
        // Initialize last cells from current cell
507
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
508
          cell_last(j) = coord(j).cell();
605✔
509
        }
510
        n_coord_last() = n_coord();
605✔
511
      }
512
      pht_secondary_particles();
605✔
513
    }
514

515
    // Enter new particle in particle track file
516
    if (write_track())
63,126,313✔
517
      add_particle_track(*this);
5,234✔
518
  }
519
}
520

521
void Particle::event_death()
168,688,571✔
522
{
523
#ifdef OPENMC_DAGMC_ENABLED
524
  history().reset();
15,411,985✔
525
#endif
526

527
  // Finish particle track output.
528
  if (write_track()) {
168,688,571✔
529
    finalize_particle_track(*this);
1,010✔
530
  }
531

532
// Contribute tally reduction variables to global accumulator
533
#pragma omp atomic
92,898,280✔
534
  global_tally_absorption += keff_tally_absorption();
168,688,571✔
535
#pragma omp atomic
93,109,313✔
536
  global_tally_collision += keff_tally_collision();
168,688,571✔
537
#pragma omp atomic
92,906,395✔
538
  global_tally_tracklength += keff_tally_tracklength();
168,688,571✔
539
#pragma omp atomic
92,275,863✔
540
  global_tally_leakage += keff_tally_leakage();
168,688,571✔
541

542
  // Reset particle tallies once accumulated
543
  keff_tally_absorption() = 0.0;
168,688,571✔
544
  keff_tally_collision() = 0.0;
168,688,571✔
545
  keff_tally_tracklength() = 0.0;
168,688,571✔
546
  keff_tally_leakage() = 0.0;
168,688,571✔
547

548
  if (!model::active_pulse_height_tallies.empty()) {
168,688,571✔
549
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
550
  }
551

552
  // Record the number of progeny created by this particle.
553
  // This data will be used to efficiently sort the fission bank.
554
  if (settings::run_mode == RunMode::EIGENVALUE) {
168,688,571✔
555
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
141,424,700✔
556
    simulation::progeny_per_particle[offset] = n_progeny();
141,424,700✔
557
  }
558
}
168,688,571✔
559

560
void Particle::pht_collision_energy()
2,024✔
561
{
562
  // Adds the energy particles lose in a collision to the pulse-height
563

564
  // determine index of cell in pulse_height_cells
565
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
566
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024!
567

568
  if (it != model::pulse_height_cells.end()) {
2,024!
569
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
570
    pht_storage()[index] += E_last() - E();
2,024✔
571

572
    // If the energy of the particle is below the cutoff, it will not be sampled
573
    // so its energy is added to the pulse-height in the cell
574
    int photon = ParticleType::photon().transport_index();
2,024✔
575
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
576
      pht_storage()[index] += E();
825✔
577
    }
578
  }
579
}
2,024✔
580

581
void Particle::pht_secondary_particles()
605✔
582
{
583
  // Removes the energy of secondary produced particles from the pulse-height
584

585
  // determine index of cell in pulse_height_cells
586
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
587
    model::pulse_height_cells.end(), cell_born());
605!
588

589
  if (it != model::pulse_height_cells.end()) {
605!
590
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
591
    pht_storage()[index] -= E();
605✔
592
  }
593
}
605✔
594

595
void Particle::cross_surface(const Surface& surf)
1,673,353,614✔
596
{
597

598
  if (settings::verbosity >= 10 || trace()) {
1,673,353,614✔
599
    write_message(1, "    Crossing surface {}", surf.id_);
66✔
600
  }
601

602
// if we're crossing a CSG surface, make sure the DAG history is reset
603
#ifdef OPENMC_DAGMC_ENABLED
604
  if (surf.geom_type() == GeometryType::CSG)
152,794,206✔
605
    history().reset();
152,737,047✔
606
#endif
607

608
  // Handle any applicable boundary conditions.
609
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,673,353,614!
610
      settings::run_mode != RunMode::VOLUME) {
611
    surf.bc_->handle_particle(*this, surf);
720,576,998✔
612
    return;
720,576,998✔
613
  }
614

615
  // ==========================================================================
616
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
617

618
#ifdef OPENMC_DAGMC_ENABLED
619
  // in DAGMC, we know what the next cell should be
620
  if (surf.geom_type() == GeometryType::DAG) {
86,847,514✔
621
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,350✔
622
                       lowest_coord().universe()) -
46,350✔
623
                     1;
46,350✔
624
    // save material, temperature, and density multiplier
625
    material_last() = material();
46,350✔
626
    sqrtkT_last() = sqrtkT();
46,350✔
627
    density_mult_last() = density_mult();
46,350✔
628
    // set new cell value
629
    lowest_coord().cell() = i_cell;
46,350✔
630
    auto& cell = model::cells[i_cell];
46,350✔
631

632
    cell_instance() = 0;
46,350✔
633
    if (cell->distribcell_index_ >= 0)
46,350✔
634
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,326✔
635

636
    material() = cell->material(cell_instance());
46,350!
637
    sqrtkT() = cell->sqrtkT(cell_instance());
46,350!
638
    density_mult() = cell->density_mult(cell_instance());
46,350✔
639
    return;
46,350✔
640
  }
641
#endif
642

643
  bool verbose = settings::verbosity >= 10 || trace();
952,730,266!
644
  if (neighbor_list_find_cell(*this, verbose)) {
952,730,266✔
645
    return;
646
  }
647

648
  // ==========================================================================
649
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
650

651
  // Remove lower coordinate levels
652
  n_coord() = 1;
29,911✔
653
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
654

655
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
29,911!
656
    // If a cell is still not found, there are two possible causes: 1) there is
657
    // a void in the model, and 2) the particle hit a surface at a tangent. If
658
    // the particle is really traveling tangent to a surface, if we move it
659
    // forward a tiny bit it should fix the problem.
660

661
    surface() = SURFACE_NONE;
5,799✔
662
    n_coord() = 1;
5,799✔
663
    r() += TINY_BIT * u();
5,799✔
664

665
    // Couldn't find next cell anywhere! This probably means there is an actual
666
    // undefined region in the geometry.
667

668
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
669
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
670
                   " crossed surface " + std::to_string(surf.id_) +
17,388✔
671
                   " it could not be located in any cell and it did not leak.");
672
      return;
5,790✔
673
    }
674
  }
675
}
676

677
void Particle::cross_vacuum_bc(const Surface& surf)
35,017,319✔
678
{
679
  // Score any surface current tallies -- note that the particle is moved
680
  // forward slightly so that if the mesh boundary is on the surface, it is
681
  // still processed
682

683
  if (!model::active_meshsurf_tallies.empty()) {
35,017,319✔
684
    // TODO: Find a better solution to score surface currents than
685
    // physically moving the particle forward slightly
686

687
    r() += TINY_BIT * u();
937,222✔
688
    score_surface_tally(*this, model::active_meshsurf_tallies);
937,222✔
689
  }
690

691
  // Score to global leakage tally
692
  keff_tally_leakage() += wgt();
35,017,319✔
693

694
  // Kill the particle
695
  wgt() = 0.0;
35,017,319✔
696

697
  // Display message
698
  if (settings::verbosity >= 10 || trace()) {
35,017,319!
699
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
700
  }
701
}
35,017,319✔
702

703
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
684,318,903✔
704
{
705
  // Do not handle reflective boundary conditions on lower universes
706
  if (n_coord() != 1) {
684,318,903!
707
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
708
                 " off surface in a lower universe.");
709
    return;
×
710
  }
711

712
  // Score surface currents since reflection causes the direction of the
713
  // particle to change. For surface filters, we need to score the tallies
714
  // twice, once before the particle's surface attribute has changed and
715
  // once after. For mesh surface filters, we need to artificially move
716
  // the particle slightly back in case the surface crossing is coincident
717
  // with a mesh boundary
718

719
  if (!model::active_surface_tallies.empty()) {
684,318,903✔
720
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
721
  }
722

723
  if (!model::active_meshsurf_tallies.empty()) {
684,318,903✔
724
    Position r {this->r()};
46,885,487✔
725
    this->r() -= TINY_BIT * u();
46,885,487✔
726
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
727
    this->r() = r;
46,885,487✔
728
  }
729

730
  // Set the new particle direction
731
  u() = new_u;
684,318,903✔
732

733
  // Reassign particle's cell and surface
734
  coord(0).cell() = cell_last(0);
684,318,903✔
735
  surface() = -surface();
684,318,903✔
736

737
  // If a reflective surface is coincident with a lattice or universe
738
  // boundary, it is necessary to redetermine the particle's coordinates in
739
  // the lower universes.
740
  // (unless we're using a dagmc model, which has exactly one universe)
741
  n_coord() = 1;
684,318,903✔
742
  if (surf.geom_type() != GeometryType::DAG &&
1,368,635,048!
743
      !neighbor_list_find_cell(*this)) {
684,316,145✔
744
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
745
                 std::to_string(surf.id_) + ".");
×
746
    return;
×
747
  }
748

749
  // Set previous coordinate going slightly past surface crossing
750
  r_last_current() = r() + TINY_BIT * u();
684,318,903✔
751

752
  // Diagnostic message
753
  if (settings::verbosity >= 10 || trace()) {
684,318,903!
754
    write_message(1, "    Reflected from surface {}", surf.id_);
×
755
  }
756
}
757

758
void Particle::cross_periodic_bc(
2,246,242✔
759
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
760
{
761
  // Do not handle periodic boundary conditions on lower universes
762
  if (n_coord() != 1) {
2,246,242!
763
    mark_as_lost(
×
764
      "Cannot transfer particle " + std::to_string(id()) +
×
765
      " across surface in a lower universe. Boundary conditions must be "
766
      "applied to root universe.");
767
    return;
×
768
  }
769

770
  // Score surface currents since reflection causes the direction of the
771
  // particle to change -- artificially move the particle slightly back in
772
  // case the surface crossing is coincident with a mesh boundary
773
  if (!model::active_meshsurf_tallies.empty()) {
2,246,242!
774
    Position r {this->r()};
×
775
    this->r() -= TINY_BIT * u();
×
776
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
777
    this->r() = r;
×
778
  }
779

780
  // Adjust the particle's location and direction.
781
  r() = new_r;
2,246,242✔
782
  u() = new_u;
2,246,242✔
783

784
  // Reassign particle's surface
785
  surface() = new_surface;
2,246,242✔
786

787
  // Figure out what cell particle is in now
788
  n_coord() = 1;
2,246,242✔
789

790
  if (!neighbor_list_find_cell(*this)) {
2,246,242!
791
    mark_as_lost("Couldn't find particle after hitting periodic "
×
792
                 "boundary on surface " +
×
793
                 std::to_string(surf.id_) + ".");
×
794
    return;
×
795
  }
796

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

800
  // Diagnostic message
801
  if (settings::verbosity >= 10 || trace()) {
2,246,242!
802
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
803
  }
804
}
805

806
void Particle::mark_as_lost(const char* message)
5,799✔
807
{
808
  // Print warning and write lost particle file
809
  warning(message);
5,799✔
810
  if (settings::max_write_lost_particles < 0 ||
5,799✔
811
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
812
    write_restart();
374✔
813
  }
814
  // Increment number of lost particles
815
  wgt() = 0.0;
5,799✔
816
#pragma omp atomic
3,154✔
817
  simulation::n_lost_particles += 1;
2,645✔
818

819
  // Count the total number of simulated particles (on this processor)
820
  auto n = simulation::current_batch * settings::gen_per_batch *
5,799✔
821
           simulation::work_per_rank;
822

823
  // Abort the simulation if the maximum number of lost particles has been
824
  // reached
825
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
826
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
827
    fatal_error("Maximum number of lost particles has been reached.");
9✔
828
  }
829
}
5,790✔
830

831
void Particle::write_restart() const
374✔
832
{
833
  // Dont write another restart file if in particle restart mode
834
  if (settings::run_mode == RunMode::PARTICLE)
374✔
835
    return;
22✔
836

837
  // Set up file name
838
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
352✔
839
    simulation::current_batch, id());
352✔
840

841
#pragma omp critical(WriteParticleRestart)
187✔
842
  {
352✔
843
    // Create file
844
    hid_t file_id = file_open(filename, 'w');
352✔
845

846
    // Write filetype and version info
847
    write_attribute(file_id, "filetype", "particle restart");
352✔
848
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
352✔
849
    write_attribute(file_id, "openmc_version", VERSION);
352✔
850
#ifdef GIT_SHA1
851
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
852
#endif
853

854
    // Write data to file
855
    write_dataset(file_id, "current_batch", simulation::current_batch);
352✔
856
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
352✔
857
    write_dataset(file_id, "current_generation", simulation::current_gen);
352✔
858
    write_dataset(file_id, "n_particles", settings::n_particles);
352✔
859
    switch (settings::run_mode) {
352!
860
    case RunMode::FIXED_SOURCE:
220✔
861
      write_dataset(file_id, "run_mode", "fixed source");
220✔
862
      break;
115✔
863
    case RunMode::EIGENVALUE:
132✔
864
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
865
      break;
72✔
866
    case RunMode::PARTICLE:
×
867
      write_dataset(file_id, "run_mode", "particle restart");
×
868
      break;
869
    default:
870
      break;
871
    }
872
    write_dataset(file_id, "id", id());
352✔
873
    write_dataset(file_id, "type", type().pdg_number());
352✔
874

875
    int64_t i = current_work();
352✔
876
    if (settings::run_mode == RunMode::EIGENVALUE) {
352✔
877
      // take source data from primary bank for eigenvalue simulation
878
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
879
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
880
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
881
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
882
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
883
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
220!
884
      // re-sample using rng random number seed used to generate source particle
885
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
220✔
886
                     settings::n_particles +
220✔
887
                   simulation::work_index[mpi::rank] + i;
220✔
888
      uint64_t seed = init_seed(id, STREAM_SOURCE);
220✔
889
      // re-sample source site
890
      auto site = sample_external_source(&seed);
220✔
891
      write_dataset(file_id, "weight", site.wgt);
220✔
892
      write_dataset(file_id, "energy", site.E);
220✔
893
      write_dataset(file_id, "xyz", site.r);
220✔
894
      write_dataset(file_id, "uvw", site.u);
220✔
895
      write_dataset(file_id, "time", site.time);
220✔
896
    }
897

898
    // Close file
899
    file_close(file_id);
352✔
900
  } // #pragma omp critical
901
}
352✔
902

903
void Particle::update_neutron_xs(
2,147,483,647✔
904
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
905
{
906
  // Get microscopic cross section cache
907
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
908

909
  // If the cache doesn't match, recalculate micro xs
910
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
911
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
912
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
913
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
914

915
    // If NCrystal is being used, update micro cross section cache
916
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
917
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
918
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
919
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
920
    }
921
  }
922
}
2,147,483,647✔
923

924
//==============================================================================
925
// Non-method functions
926
//==============================================================================
927
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,670,225,480✔
928
{
929
  if (simulation::current_batch <= settings::n_inactive ||
1,670,225,480✔
930
      simulation::surf_source_bank.full()) {
1,284,790,565✔
931
    return;
1,670,095,827✔
932
  }
933

934
  // If a cell/cellfrom/cellto parameter is defined
935
  if (settings::ssw_cell_id != C_NONE) {
337,077✔
936

937
    // Retrieve cell index and storage type
938
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,432✔
939

940
    if (surf.bc_) {
254,432✔
941
      // Leave if cellto with vacuum boundary condition
942
      if (surf.bc_->type() == "vacuum" &&
298,914✔
943
          settings::ssw_cell_type == SSWCellType::To) {
33,097✔
944
        return;
945
      }
946

947
      // Leave if other boundary condition than vacuum
948
      if (surf.bc_->type() != "vacuum") {
274,644✔
949
        return;
950
      }
951
    }
952

953
    // Check if the cell of interest has been exited
954
    bool exited = false;
955
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,663✔
956
      if (p.cell_last(i) == cell_idx) {
207,726✔
957
        exited = true;
73,764✔
958
      }
959
    }
960

961
    // Check if the cell of interest has been entered
962
    bool entered = false;
963
    for (int i = 0; i < p.n_coord(); ++i) {
297,965✔
964
      if (p.coord(i).cell() == cell_idx) {
172,028✔
965
        entered = true;
57,515✔
966
      }
967
    }
968

969
    // Vacuum boundary conditions: return if cell is not exited
970
    if (surf.bc_) {
125,937✔
971
      if (surf.bc_->type() == "vacuum" && !exited) {
41,924!
972
        return;
973
      }
974
    } else {
975

976
      // If we both enter and exit the cell of interest
977
      if (entered && exited) {
104,975✔
978
        return;
979
      }
980

981
      // If we did not enter nor exit the cell of interest
982
      if (!entered && !exited) {
77,772✔
983
        return;
984
      }
985

986
      // If cellfrom and the cell before crossing is not the cell of
987
      // interest
988
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,273✔
989
        return;
990
      }
991

992
      // If cellto and the cell after crossing is not the cell of interest
993
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,732✔
994
        return;
995
      }
996
    }
997
  }
998

999
  SourceSite site;
129,653✔
1000
  site.r = p.r();
129,653✔
1001
  site.u = p.u();
129,653✔
1002
  site.E = p.E();
129,653✔
1003
  site.time = p.time();
129,653✔
1004
  site.wgt = p.wgt();
129,653✔
1005
  site.delayed_group = p.delayed_group();
129,653✔
1006
  site.surf_id = surf.id_;
129,653✔
1007
  site.particle = p.type();
129,653✔
1008
  site.parent_id = p.id();
129,653✔
1009
  site.progeny_id = p.n_progeny();
129,653✔
1010
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1011
}
1012

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