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

openmc-dev / openmc / 21832433950

09 Feb 2026 04:03PM UTC coverage: 81.85% (+0.09%) from 81.763%
21832433950

Pull #3761

github

web-flow
Merge 53a0f365f into d0346e94a
Pull Request #3761: Add truncated normal distribution support

17371 of 24316 branches covered (71.44%)

Branch coverage included in aggregate %.

85 of 88 new or added lines in 3 files covered. (96.59%)

892 existing lines in 18 files now uncovered.

56139 of 65495 relevant lines covered (85.71%)

45125887.34 hits per line

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

85.29
/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;
51
    switch (this->type().pdg_number()) {
2,114,288,897!
52
    case PDG_NEUTRON:
2,039,019,756✔
53
      mass = MASS_NEUTRON_EV;
2,039,019,756✔
54
      break;
2,039,019,756✔
55
    case PDG_PHOTON:
21,805,073✔
56
      mass = 0.0;
21,805,073✔
57
      break;
21,805,073✔
58
    case PDG_ELECTRON:
53,464,068✔
59
    case PDG_POSITRON:
60
      mass = MASS_ELECTRON_EV;
53,464,068✔
61
      break;
53,464,068✔
62
    default:
×
63
      fatal_error("Unsupported particle for speed calculation.");
×
64
    }
65
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
66
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,114,288,897✔
67
           (this->E() + mass);
2,114,288,897✔
68
  } else {
69
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
70
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
71
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
72
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
73
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
74
  }
75
}
76

77
bool Particle::create_secondary(
111,527,798✔
78
  double wgt, Direction u, double E, ParticleType type)
79
{
80
  // If energy is below cutoff for this particle, don't create secondary
81
  // particle
82
  int idx = type.transport_index();
111,527,798✔
83
  if (idx == C_NONE) {
111,527,798!
84
    return false;
×
85
  }
86
  if (E < settings::energy_cutoff[idx]) {
111,527,798✔
87
    return false;
53,310,944✔
88
  }
89

90
  // Increment number of secondaries created (for ParticleProductionFilter)
91
  n_secondaries()++;
58,216,854✔
92

93
  auto& bank = secondary_bank().emplace_back();
58,216,854✔
94
  bank.particle = type;
58,216,854✔
95
  bank.wgt = wgt;
58,216,854✔
96
  bank.r = r();
58,216,854✔
97
  bank.u = u;
58,216,854✔
98
  bank.E = settings::run_CE ? E : g();
58,216,854!
99
  bank.time = time();
58,216,854✔
100
  bank_second_E() += bank.E;
58,216,854✔
101
  return true;
58,216,854✔
102
}
103

104
void Particle::split(double wgt)
4,087,101✔
105
{
106
  auto& bank = secondary_bank().emplace_back();
4,087,101✔
107
  bank.particle = type();
4,087,101✔
108
  bank.wgt = wgt;
4,087,101✔
109
  bank.r = r();
4,087,101✔
110
  bank.u = u();
4,087,101✔
111
  bank.E = settings::run_CE ? E() : g();
4,087,101✔
112
  bank.time = time();
4,087,101✔
113

114
  // Convert signed index to a signed surface ID
115
  if (surface() == SURFACE_NONE) {
4,087,101✔
116
    bank.surf_id = SURFACE_NONE;
4,086,765✔
117
  } else {
118
    int surf_id = model::surfaces[surface_index()]->id_;
336✔
119
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
336!
120
  }
121
}
4,087,101✔
122

123
void Particle::from_source(const SourceSite* src)
238,177,966✔
124
{
125
  // Reset some attributes
126
  clear();
238,177,966✔
127
  surface() = SURFACE_NONE;
238,177,966✔
128
  cell_born() = C_NONE;
238,177,966✔
129
  material() = C_NONE;
238,177,966✔
130
  n_collision() = 0;
238,177,966✔
131
  fission() = false;
238,177,966✔
132
  zero_flux_derivs();
238,177,966✔
133
  lifetime() = 0.0;
238,177,966✔
134
#ifdef OPENMC_DAGMC_ENABLED
135
  history().reset();
21,812,665✔
136
#endif
137

138
  // Copy attributes from source bank site
139
  type() = src->particle;
238,177,966✔
140
  wgt() = src->wgt;
238,177,966✔
141
  wgt_last() = src->wgt;
238,177,966✔
142
  r() = src->r;
238,177,966✔
143
  u() = src->u;
238,177,966✔
144
  r_born() = src->r;
238,177,966✔
145
  r_last_current() = src->r;
238,177,966✔
146
  r_last() = src->r;
238,177,966✔
147
  u_last() = src->u;
238,177,966✔
148
  if (settings::run_CE) {
238,177,966✔
149
    E() = src->E;
122,329,349✔
150
    g() = 0;
122,329,349✔
151
  } else {
152
    g() = static_cast<int>(src->E);
115,848,617✔
153
    g_last() = static_cast<int>(src->E);
115,848,617✔
154
    E() = data::mg.energy_bin_avg_[g()];
115,848,617✔
155
  }
156
  E_last() = E();
238,177,966✔
157
  time() = src->time;
238,177,966✔
158
  time_last() = src->time;
238,177,966✔
159
  parent_nuclide() = src->parent_nuclide;
238,177,966✔
160
  delayed_group() = src->delayed_group;
238,177,966✔
161

162
  // Convert signed surface ID to signed index
163
  if (src->surf_id != SURFACE_NONE) {
238,177,966✔
164
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,336✔
165
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,336!
166
  }
167
}
238,177,966✔
168

169
void Particle::event_calculate_xs()
2,147,483,647✔
170
{
171
  // Set the random number stream
172
  stream() = STREAM_TRACKING;
2,147,483,647✔
173

174
  // Store pre-collision particle properties
175
  wgt_last() = wgt();
2,147,483,647✔
176
  E_last() = E();
2,147,483,647✔
177
  u_last() = u();
2,147,483,647✔
178
  r_last() = r();
2,147,483,647✔
179
  time_last() = time();
2,147,483,647✔
180

181
  // Reset event variables
182
  event() = TallyEvent::KILL;
2,147,483,647✔
183
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
184
  event_mt() = REACTION_NONE;
2,147,483,647✔
185

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

196
    // Set birth cell attribute
197
    if (cell_born() == C_NONE)
229,584,057!
198
      cell_born() = lowest_coord().cell();
229,584,057✔
199

200
    // Initialize last cells from current cell
201
    for (int j = 0; j < n_coord(); ++j) {
476,192,892✔
202
      cell_last(j) = coord(j).cell();
246,608,835✔
203
    }
204
    n_coord_last() = n_coord();
229,584,057✔
205
  }
206

207
  // Write particle track.
208
  if (write_track())
2,147,483,647✔
209
    write_particle_track(*this);
10,814✔
210

211
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
212
    check_cell_overlap(*this);
×
213

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

230
      // Update the particle's group while we know we are multi-group
231
      g_last() = g();
2,063,937,414✔
232
    }
233
  } else {
234
    macro_xs().total = 0.0;
111,825,092✔
235
    macro_xs().absorption = 0.0;
111,825,092✔
236
    macro_xs().fission = 0.0;
111,825,092✔
237
    macro_xs().nu_fission = 0.0;
111,825,092✔
238
  }
239
}
240

241
void Particle::event_advance()
2,147,483,647✔
242
{
243
  // Find the distance to the nearest boundary
244
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
245

246
  // Sample a distance to collision
247
  if (type() == ParticleType::electron() ||
2,147,483,647✔
248
      type() == ParticleType::positron()) {
2,147,483,647✔
249
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
53,464,068!
250
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
251
    collision_distance() = INFINITY;
111,825,092✔
252
  } else {
253
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
254
  }
255

256
  double speed = this->speed();
2,147,483,647✔
257
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
258
  double distance_cutoff =
259
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
260

261
  // Select smaller of the three distances
262
  double distance =
263
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
264

265
  // Advance particle in space and time
266
  this->move_distance(distance);
2,147,483,647✔
267
  double dt = distance / speed;
2,147,483,647✔
268
  this->time() += dt;
2,147,483,647✔
269
  this->lifetime() += dt;
2,147,483,647✔
270

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

276
  // Score track-length tallies
277
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
278
    score_tracklength_tally(*this, distance);
1,562,790,200✔
279
  }
280

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

286
  // Score flux derivative accumulators for differential tallies.
287
  if (!model::active_tallies.empty()) {
2,147,483,647✔
288
    score_track_derivative(*this, distance);
1,732,232,823✔
289
  }
290

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

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

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

309
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
310
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
311
      boundary().lattice_translation()[2] != 0) {
1,789,437,239✔
312
    // Particle crosses lattice boundary
313

314
    bool verbose = settings::verbosity >= 10 || trace();
732,435,837!
315
    cross_lattice(*this, boundary(), verbose);
732,435,837✔
316
    event() = TallyEvent::LATTICE;
732,435,837✔
317
  } else {
318
    // Particle crosses surface
319
    const auto& surf {model::surfaces[surface_index()].get()};
1,600,895,351✔
320
    // If BC, add particle to surface source before crossing surface
321
    if (surf->surf_source_ && surf->bc_) {
1,600,895,351✔
322
      add_surf_source_to_bank(*this, *surf);
698,984,666✔
323
    }
324
    this->cross_surface(*surf);
1,600,895,351✔
325
    // If no BC, add particle to surface source after crossing surface
326
    if (surf->surf_source_ && !surf->bc_) {
1,600,895,342✔
327
      add_surf_source_to_bank(*this, *surf);
900,672,849✔
328
    }
329
    if (settings::weight_window_checkpoint_surface) {
1,600,895,342✔
330
      apply_weight_windows(*this);
10,738!
331
    }
332
    event() = TallyEvent::SURFACE;
1,600,895,342✔
333
  }
334
  // Score cell to cell partial currents
335
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
336
    score_surface_tally(*this, model::active_surface_tallies);
34,922,767✔
337
  }
338
}
2,147,483,647✔
339

340
void Particle::event_collide()
2,147,483,647✔
341
{
342

343
  // Score collision estimate of keff
344
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
345
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,125,060,818✔
346
  }
347

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

352
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
353
    score_surface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
354

355
  // Clear surface component
356
  surface() = SURFACE_NONE;
2,147,483,647✔
357

358
  if (settings::run_CE) {
2,147,483,647✔
359
    collision(*this);
944,048,482✔
360
  } else {
361
    collision_mg(*this);
1,783,060,477✔
362
  }
363

364
  // Collision track feature to recording particle interaction
365
  if (settings::collision_track) {
2,147,483,647✔
366
    collision_track_record(*this);
150,087✔
367
  }
368

369
  // Score collision estimator tallies -- this is done after a collision
370
  // has occurred rather than before because we need information on the
371
  // outgoing energy for any tallies with an outgoing energy filter
372
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
373
    score_collision_tally(*this);
107,054,865✔
374
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
375
    if (settings::run_CE) {
291,821,708✔
376
      score_analog_tally_ce(*this);
290,613,446✔
377
    } else {
378
      score_analog_tally_mg(*this);
1,208,262✔
379
    }
380
  }
381

382
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
383
    pht_collision_energy();
2,024✔
384
  }
385

386
  // Reset banked weight during collision
387
  n_bank() = 0;
2,147,483,647✔
388
  bank_second_E() = 0.0;
2,147,483,647✔
389
  wgt_bank() = 0.0;
2,147,483,647✔
390

391
  // Clear number of secondaries in this collision. This is
392
  // distinct from the number of created neutrons n_bank() above!
393
  n_secondaries() = 0;
2,147,483,647✔
394

395
  zero_delayed_bank();
2,147,483,647✔
396

397
  // Reset fission logical
398
  fission() = false;
2,147,483,647✔
399

400
  // Save coordinates for tallying purposes
401
  r_last_current() = r();
2,147,483,647✔
402

403
  // Set last material to none since cross sections will need to be
404
  // re-evaluated
405
  material_last() = C_NONE;
2,147,483,647✔
406

407
  // Set all directions to base level -- right now, after a collision, only
408
  // the base level directions are changed
409
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
410
    if (coord(j + 1).rotated()) {
143,198,676✔
411
      // If next level is rotated, apply rotation matrix
412
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
413
      const auto& u {coord(j).u()};
10,426,614✔
414
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
415
    } else {
416
      // Otherwise, copy this level's direction
417
      coord(j + 1).u() = coord(j).u();
132,772,062✔
418
    }
419
  }
420

421
  // Score flux derivative accumulators for differential tallies.
422
  if (!model::active_tallies.empty())
2,147,483,647✔
423
    score_collision_derivative(*this);
816,403,396✔
424

425
#ifdef OPENMC_DAGMC_ENABLED
426
  history().reset();
250,204,366✔
427
#endif
428
}
2,147,483,647✔
429

430
void Particle::event_revive_from_secondary()
2,147,483,647✔
431
{
432
  // If particle has too many events, display warning and kill it
433
  ++n_event();
2,147,483,647✔
434
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
UNCOV
435
    warning("Particle " + std::to_string(id()) +
×
436
            " underwent maximum number of events.");
UNCOV
437
    wgt() = 0.0;
×
438
  }
439

440
  // Check for secondary particles if this particle is dead
441
  if (!alive()) {
2,147,483,647✔
442
    // Write final position for this particle
443
    if (write_track()) {
229,583,652✔
444
      write_particle_track(*this);
6,674✔
445
    }
446

447
    // If no secondary particles, break out of event loop
448
    if (secondary_bank().empty())
229,583,652✔
449
      return;
167,076,178✔
450

451
    from_source(&secondary_bank().back());
62,507,474✔
452
    secondary_bank().pop_back();
62,507,474✔
453
    n_event() = 0;
62,507,474✔
454
    bank_second_E() = 0.0;
62,507,474✔
455

456
    // Subtract secondary particle energy from interim pulse-height results
457
    if (!model::active_pulse_height_tallies.empty() &&
62,522,973✔
458
        this->type().is_photon()) {
15,499✔
459
      // Since the birth cell of the particle has not been set we
460
      // have to determine it before the energy of the secondary particle can be
461
      // removed from the pulse-height of this cell.
462
      if (lowest_coord().cell() == C_NONE) {
605!
463
        bool verbose = settings::verbosity >= 10 || trace();
605!
464
        if (!exhaustive_find_cell(*this, verbose)) {
605!
UNCOV
465
          mark_as_lost("Could not find the cell containing particle " +
×
UNCOV
466
                       std::to_string(id()));
×
UNCOV
467
          return;
×
468
        }
469
        // Set birth cell attribute
470
        if (cell_born() == C_NONE)
605!
471
          cell_born() = lowest_coord().cell();
605✔
472

473
        // Initialize last cells from current cell
474
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
475
          cell_last(j) = coord(j).cell();
605✔
476
        }
477
        n_coord_last() = n_coord();
605✔
478
      }
479
      pht_secondary_particles();
605✔
480
    }
481

482
    // Enter new particle in particle track file
483
    if (write_track())
62,507,474✔
484
      add_particle_track(*this);
5,604✔
485
  }
486
}
487

488
void Particle::event_death()
167,077,178✔
489
{
490
#ifdef OPENMC_DAGMC_ENABLED
491
  history().reset();
15,264,232✔
492
#endif
493

494
  // Finish particle track output.
495
  if (write_track()) {
167,077,178✔
496
    finalize_particle_track(*this);
1,070✔
497
  }
498

499
// Contribute tally reduction variables to global accumulator
500
#pragma omp atomic
92,100,086✔
501
  global_tally_absorption += keff_tally_absorption();
167,077,178✔
502
#pragma omp atomic
91,649,094✔
503
  global_tally_collision += keff_tally_collision();
167,077,178✔
504
#pragma omp atomic
91,603,700✔
505
  global_tally_tracklength += keff_tally_tracklength();
167,077,178✔
506
#pragma omp atomic
91,376,364✔
507
  global_tally_leakage += keff_tally_leakage();
167,077,178✔
508

509
  // Reset particle tallies once accumulated
510
  keff_tally_absorption() = 0.0;
167,077,178✔
511
  keff_tally_collision() = 0.0;
167,077,178✔
512
  keff_tally_tracklength() = 0.0;
167,077,178✔
513
  keff_tally_leakage() = 0.0;
167,077,178✔
514

515
  if (!model::active_pulse_height_tallies.empty()) {
167,077,178✔
516
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
517
  }
518

519
  // Record the number of progeny created by this particle.
520
  // This data will be used to efficiently sort the fission bank.
521
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,077,178✔
522
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
140,925,797✔
523
    simulation::progeny_per_particle[offset] = n_progeny();
140,925,797✔
524
  }
525
}
167,077,178✔
526

527
void Particle::pht_collision_energy()
2,024✔
528
{
529
  // Adds the energy particles lose in a collision to the pulse-height
530

531
  // determine index of cell in pulse_height_cells
532
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
533
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
534

535
  if (it != model::pulse_height_cells.end()) {
2,024!
536
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
537
    pht_storage()[index] += E_last() - E();
2,024✔
538

539
    // If the energy of the particle is below the cutoff, it will not be sampled
540
    // so its energy is added to the pulse-height in the cell
541
    int photon = ParticleType::photon().transport_index();
2,024✔
542
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
543
      pht_storage()[index] += E();
825✔
544
    }
545
  }
546
}
2,024✔
547

548
void Particle::pht_secondary_particles()
605✔
549
{
550
  // Removes the energy of secondary produced particles from the pulse-height
551

552
  // determine index of cell in pulse_height_cells
553
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
554
    model::pulse_height_cells.end(), cell_born());
605✔
555

556
  if (it != model::pulse_height_cells.end()) {
605!
557
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
558
    pht_storage()[index] -= E();
605✔
559
  }
560
}
605✔
561

562
void Particle::cross_surface(const Surface& surf)
1,602,838,881✔
563
{
564

565
  if (settings::verbosity >= 10 || trace()) {
1,602,838,881✔
566
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
567
  }
568

569
// if we're crossing a CSG surface, make sure the DAG history is reset
570
#ifdef OPENMC_DAGMC_ENABLED
571
  if (surf.geom_type() == GeometryType::CSG)
146,454,114✔
572
    history().reset();
146,398,995✔
573
#endif
574

575
  // Handle any applicable boundary conditions.
576
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
577
      settings::run_mode != RunMode::VOLUME) {
699,456,718✔
578
    surf.bc_->handle_particle(*this, surf);
699,336,774✔
579
    return;
699,336,774✔
580
  }
581

582
  // ==========================================================================
583
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
584

585
#ifdef OPENMC_DAGMC_ENABLED
586
  // in DAGMC, we know what the next cell should be
587
  if (surf.geom_type() == GeometryType::DAG) {
82,433,961✔
588
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
44,310✔
589
                       lowest_coord().universe()) -
44,310✔
590
                     1;
44,310✔
591
    // save material, temperature, and density multiplier
592
    material_last() = material();
44,310✔
593
    sqrtkT_last() = sqrtkT();
44,310✔
594
    density_mult_last() = density_mult();
44,310✔
595
    // set new cell value
596
    lowest_coord().cell() = i_cell;
44,310✔
597
    auto& cell = model::cells[i_cell];
44,310✔
598

599
    cell_instance() = 0;
44,310✔
600
    if (cell->distribcell_index_ >= 0)
44,310✔
601
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
43,286✔
602

603
    material() = cell->material(cell_instance());
44,310✔
604
    sqrtkT() = cell->sqrtkT(cell_instance());
44,310✔
605
    density_mult() = cell->density_mult(cell_instance());
44,310✔
606
    return;
44,310✔
607
  }
608
#endif
609

610
  bool verbose = settings::verbosity >= 10 || trace();
903,457,797!
611
  if (neighbor_list_find_cell(*this, verbose)) {
903,457,797✔
612
    return;
903,427,886✔
613
  }
614

615
  // ==========================================================================
616
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
617

618
  // Remove lower coordinate levels
619
  n_coord() = 1;
29,911✔
620
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
621

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

628
    surface() = SURFACE_NONE;
5,799✔
629
    n_coord() = 1;
5,799✔
630
    r() += TINY_BIT * u();
5,799✔
631

632
    // Couldn't find next cell anywhere! This probably means there is an actual
633
    // undefined region in the geometry.
634

635
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
636
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
637
                   " crossed surface " + std::to_string(surf.id_) +
23,178✔
638
                   " it could not be located in any cell and it did not leak.");
639
      return;
5,790✔
640
    }
641
  }
642
}
643

644
void Particle::cross_vacuum_bc(const Surface& surf)
35,018,732✔
645
{
646
  // Score any surface current tallies -- note that the particle is moved
647
  // forward slightly so that if the mesh boundary is on the surface, it is
648
  // still processed
649

650
  if (!model::active_meshsurf_tallies.empty()) {
35,018,732✔
651
    // TODO: Find a better solution to score surface currents than
652
    // physically moving the particle forward slightly
653

654
    r() += TINY_BIT * u();
937,222✔
655
    score_surface_tally(*this, model::active_meshsurf_tallies);
937,222✔
656
  }
657

658
  // Score to global leakage tally
659
  keff_tally_leakage() += wgt();
35,018,732✔
660

661
  // Kill the particle
662
  wgt() = 0.0;
35,018,732✔
663

664
  // Display message
665
  if (settings::verbosity >= 10 || trace()) {
35,018,732!
666
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
667
  }
668
}
35,018,732✔
669

670
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
663,077,987✔
671
{
672
  // Do not handle reflective boundary conditions on lower universes
673
  if (n_coord() != 1) {
663,077,987!
UNCOV
674
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
675
                 " off surface in a lower universe.");
UNCOV
676
    return;
×
677
  }
678

679
  // Score surface currents since reflection causes the direction of the
680
  // particle to change. For surface filters, we need to score the tallies
681
  // twice, once before the particle's surface attribute has changed and
682
  // once after. For mesh surface filters, we need to artificially move
683
  // the particle slightly back in case the surface crossing is coincident
684
  // with a mesh boundary
685

686
  if (!model::active_surface_tallies.empty()) {
663,077,987✔
687
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
688
  }
689

690
  if (!model::active_meshsurf_tallies.empty()) {
663,077,987✔
691
    Position r {this->r()};
46,885,487✔
692
    this->r() -= TINY_BIT * u();
46,885,487✔
693
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
694
    this->r() = r;
46,885,487✔
695
  }
696

697
  // Set the new particle direction
698
  u() = new_u;
663,077,987✔
699

700
  // Reassign particle's cell and surface
701
  coord(0).cell() = cell_last(0);
663,077,987✔
702
  surface() = -surface();
663,077,987✔
703

704
  // If a reflective surface is coincident with a lattice or universe
705
  // boundary, it is necessary to redetermine the particle's coordinates in
706
  // the lower universes.
707
  // (unless we're using a dagmc model, which has exactly one universe)
708
  n_coord() = 1;
663,077,987✔
709
  if (surf.geom_type() != GeometryType::DAG &&
1,326,153,216!
710
      !neighbor_list_find_cell(*this)) {
663,075,229!
UNCOV
711
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
712
                 std::to_string(surf.id_) + ".");
×
UNCOV
713
    return;
×
714
  }
715

716
  // Set previous coordinate going slightly past surface crossing
717
  r_last_current() = r() + TINY_BIT * u();
663,077,987✔
718

719
  // Diagnostic message
720
  if (settings::verbosity >= 10 || trace()) {
663,077,987!
721
    write_message(1, "    Reflected from surface {}", surf.id_);
×
722
  }
723
}
724

725
void Particle::cross_periodic_bc(
2,245,521✔
726
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
727
{
728
  // Do not handle periodic boundary conditions on lower universes
729
  if (n_coord() != 1) {
2,245,521!
UNCOV
730
    mark_as_lost(
×
UNCOV
731
      "Cannot transfer particle " + std::to_string(id()) +
×
732
      " across surface in a lower universe. Boundary conditions must be "
733
      "applied to root universe.");
734
    return;
×
735
  }
736

737
  // Score surface currents since reflection causes the direction of the
738
  // particle to change -- artificially move the particle slightly back in
739
  // case the surface crossing is coincident with a mesh boundary
740
  if (!model::active_meshsurf_tallies.empty()) {
2,245,521!
UNCOV
741
    Position r {this->r()};
×
UNCOV
742
    this->r() -= TINY_BIT * u();
×
UNCOV
743
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
UNCOV
744
    this->r() = r;
×
745
  }
746

747
  // Adjust the particle's location and direction.
748
  r() = new_r;
2,245,521✔
749
  u() = new_u;
2,245,521✔
750

751
  // Reassign particle's surface
752
  surface() = new_surface;
2,245,521✔
753

754
  // Figure out what cell particle is in now
755
  n_coord() = 1;
2,245,521✔
756

757
  if (!neighbor_list_find_cell(*this)) {
2,245,521!
UNCOV
758
    mark_as_lost("Couldn't find particle after hitting periodic "
×
UNCOV
759
                 "boundary on surface " +
×
760
                 std::to_string(surf.id_) + ".");
×
UNCOV
761
    return;
×
762
  }
763

764
  // Set previous coordinate going slightly past surface crossing
765
  r_last_current() = r() + TINY_BIT * u();
2,245,521✔
766

767
  // Diagnostic message
768
  if (settings::verbosity >= 10 || trace()) {
2,245,521!
UNCOV
769
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
770
  }
771
}
772

773
void Particle::mark_as_lost(const char* message)
5,809✔
774
{
775
  // Print warning and write lost particle file
776
  warning(message);
5,809✔
777
  if (settings::max_write_lost_particles < 0 ||
5,809✔
778
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
779
    write_restart();
389✔
780
  }
781
  // Increment number of lost particles
782
  wgt() = 0.0;
5,809✔
783
#pragma omp atomic
3,164✔
784
  simulation::n_lost_particles += 1;
2,645✔
785

786
  // Count the total number of simulated particles (on this processor)
787
  auto n = simulation::current_batch * settings::gen_per_batch *
5,809✔
788
           simulation::work_per_rank;
789

790
  // Abort the simulation if the maximum number of lost particles has been
791
  // reached
792
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,809✔
793
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
10!
794
    fatal_error("Maximum number of lost particles has been reached.");
10✔
795
  }
796
}
5,799✔
797

798
void Particle::write_restart() const
389✔
799
{
800
  // Dont write another restart file if in particle restart mode
801
  if (settings::run_mode == RunMode::PARTICLE)
389✔
802
    return;
22✔
803

804
  // Set up file name
805
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
806
    simulation::current_batch, id());
685✔
807

808
#pragma omp critical(WriteParticleRestart)
394✔
809
  {
810
    // Create file
811
    hid_t file_id = file_open(filename, 'w');
367✔
812

813
    // Write filetype and version info
814
    write_attribute(file_id, "filetype", "particle restart");
367✔
815
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
367✔
816
    write_attribute(file_id, "openmc_version", VERSION);
367✔
817
#ifdef GIT_SHA1
818
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
819
#endif
820

821
    // Write data to file
822
    write_dataset(file_id, "current_batch", simulation::current_batch);
367✔
823
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
367✔
824
    write_dataset(file_id, "current_generation", simulation::current_gen);
367✔
825
    write_dataset(file_id, "n_particles", settings::n_particles);
367✔
826
    switch (settings::run_mode) {
367!
827
    case RunMode::FIXED_SOURCE:
225✔
828
      write_dataset(file_id, "run_mode", "fixed source");
225✔
829
      break;
225✔
830
    case RunMode::EIGENVALUE:
142✔
831
      write_dataset(file_id, "run_mode", "eigenvalue");
142✔
832
      break;
142✔
UNCOV
833
    case RunMode::PARTICLE:
×
UNCOV
834
      write_dataset(file_id, "run_mode", "particle restart");
×
UNCOV
835
      break;
×
UNCOV
836
    default:
×
UNCOV
837
      break;
×
838
    }
839
    write_dataset(file_id, "id", id());
367✔
840
    write_dataset(file_id, "type", type().pdg_number());
367✔
841

842
    int64_t i = current_work();
367✔
843
    if (settings::run_mode == RunMode::EIGENVALUE) {
367✔
844
      // take source data from primary bank for eigenvalue simulation
845
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
142✔
846
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
142✔
847
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
142✔
848
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
142✔
849
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
142✔
850
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
225!
851
      // re-sample using rng random number seed used to generate source particle
852
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
225✔
853
                     settings::n_particles +
225✔
854
                   simulation::work_index[mpi::rank] + i;
225✔
855
      uint64_t seed = init_seed(id, STREAM_SOURCE);
225✔
856
      // re-sample source site
857
      auto site = sample_external_source(&seed);
225✔
858
      write_dataset(file_id, "weight", site.wgt);
225✔
859
      write_dataset(file_id, "energy", site.E);
225✔
860
      write_dataset(file_id, "xyz", site.r);
225✔
861
      write_dataset(file_id, "uvw", site.u);
225✔
862
      write_dataset(file_id, "time", site.time);
225✔
863
    }
864

865
    // Close file
866
    file_close(file_id);
367✔
867
  } // #pragma omp critical
868
}
367✔
869

870
void Particle::update_neutron_xs(
2,147,483,647✔
871
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
872
{
873
  // Get microscopic cross section cache
874
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
875

876
  // If the cache doesn't match, recalculate micro xs
877
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
878
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
879
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
880
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
881

882
    // If NCrystal is being used, update micro cross section cache
883
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
884
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
885
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
886
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
887
    }
888
  }
889
}
2,147,483,647✔
890

891
//==============================================================================
892
// Non-method functions
893
//==============================================================================
894
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,599,657,515✔
895
{
896
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
897
      simulation::surf_source_bank.full()) {
1,249,065,909✔
898
    return;
1,599,527,861✔
899
  }
900

901
  // If a cell/cellfrom/cellto parameter is defined
902
  if (settings::ssw_cell_id != C_NONE) {
337,085✔
903

904
    // Retrieve cell index and storage type
905
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,439✔
906

907
    if (surf.bc_) {
254,439✔
908
      // Leave if cellto with vacuum boundary condition
909
      if (surf.bc_->type() == "vacuum" &&
182,558!
910
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
911
        return;
12,136✔
912
      }
913

914
      // Leave if other boundary condition than vacuum
915
      if (surf.bc_->type() != "vacuum") {
137,323✔
916
        return;
116,360✔
917
      }
918
    }
919

920
    // Check if the cell of interest has been exited
921
    bool exited = false;
125,943✔
922
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,675✔
923
      if (p.cell_last(i) == cell_idx) {
207,732✔
924
        exited = true;
73,765✔
925
      }
926
    }
927

928
    // Check if the cell of interest has been entered
929
    bool entered = false;
125,943✔
930
    for (int i = 0; i < p.n_coord(); ++i) {
297,977✔
931
      if (p.coord(i).cell() == cell_idx) {
172,034✔
932
        entered = true;
57,517✔
933
      }
934
    }
935

936
    // Vacuum boundary conditions: return if cell is not exited
937
    if (surf.bc_) {
125,943✔
938
      if (surf.bc_->type() == "vacuum" && !exited) {
20,963!
939
        return;
14,663✔
940
      }
941
    } else {
942

943
      // If we both enter and exit the cell of interest
944
      if (entered && exited) {
104,980✔
945
        return;
27,203✔
946
      }
947

948
      // If we did not enter nor exit the cell of interest
949
      if (!entered && !exited) {
77,777✔
950
        return;
13,501✔
951
      }
952

953
      // If cellfrom and the cell before crossing is not the cell of
954
      // interest
955
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,276✔
956
        return;
11,543✔
957
      }
958

959
      // If cellto and the cell after crossing is not the cell of interest
960
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,733✔
961
        return;
12,025✔
962
      }
963
    }
964
  }
965

966
  SourceSite site;
129,654✔
967
  site.r = p.r();
129,654✔
968
  site.u = p.u();
129,654✔
969
  site.E = p.E();
129,654✔
970
  site.time = p.time();
129,654✔
971
  site.wgt = p.wgt();
129,654✔
972
  site.delayed_group = p.delayed_group();
129,654✔
973
  site.surf_id = surf.id_;
129,654✔
974
  site.particle = p.type();
129,654✔
975
  site.parent_id = p.id();
129,654✔
976
  site.progeny_id = p.n_progeny();
129,654✔
977
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,654✔
978
}
979

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