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

openmc-dev / openmc / 21597104861

02 Feb 2026 03:53PM UTC coverage: 81.674% (-0.3%) from 81.968%
21597104861

Pull #3751

github

web-flow
Merge 4a6501226 into 6041ee6ae
Pull Request #3751: Resolve conflict with weight windows and global russian roulette

16697 of 23049 branches covered (72.44%)

Branch coverage included in aggregate %.

76 of 84 new or added lines in 5 files covered. (90.48%)

471 existing lines in 31 files now uncovered.

54833 of 64531 relevant lines covered (84.97%)

37154420.72 hits per line

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

84.14
/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()) {
1,525,391,398!
52
    case ParticleType::neutron:
1,470,646,453✔
53
      mass = MASS_NEUTRON_EV;
1,470,646,453✔
54
      break;
1,470,646,453✔
55
    case ParticleType::photon:
15,859,631✔
56
      mass = 0.0;
15,859,631✔
57
      break;
15,859,631✔
58
    case ParticleType::electron:
38,885,314✔
59
    case ParticleType::positron:
60
      mass = MASS_ELECTRON_EV;
38,885,314✔
61
      break;
38,885,314✔
62
    }
63
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
64
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,525,391,398✔
65
           (this->E() + mass);
1,525,391,398✔
66
  } else {
67
    auto& macro_xs = data::mg.macro_xs_[this->material()];
1,501,045,392✔
68
    int macro_t = this->mg_xs_cache().t;
1,501,045,392✔
69
    int macro_a = macro_xs.get_angle_index(this->u());
1,501,045,392✔
70
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
1,501,045,392✔
71
                   nullptr, nullptr, macro_t, macro_a);
1,501,045,392✔
72
  }
73
}
74

75
bool Particle::create_secondary(
81,108,197✔
76
  double wgt, Direction u, double E, ParticleType type)
77
{
78
  // If energy is below cutoff for this particle, don't create secondary
79
  // particle
80
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
81,108,197✔
81
    return false;
38,773,929✔
82
  }
83

84
  auto& bank = secondary_bank().emplace_back();
42,334,268✔
85
  bank.particle = type;
42,334,268✔
86
  bank.wgt = wgt;
42,334,268✔
87
  bank.r = r();
42,334,268✔
88
  bank.u = u;
42,334,268✔
89
  bank.E = settings::run_CE ? E : g();
42,334,268!
90
  bank.time = time();
42,334,268✔
91
  bank_second_E() += bank.E;
42,334,268✔
92
  return true;
42,334,268✔
93
}
94

95
void Particle::split(double wgt)
2,969,551✔
96
{
97
  auto& bank = secondary_bank().emplace_back();
2,969,551✔
98
  bank.particle = type();
2,969,551✔
99
  bank.wgt = wgt;
2,969,551✔
100
  bank.r = r();
2,969,551✔
101
  bank.u = u();
2,969,551✔
102
  bank.E = settings::run_CE ? E() : g();
2,969,551✔
103
  bank.time = time();
2,969,551✔
104

105
  // Convert signed index to a signed surface ID
106
  if (surface() == SURFACE_NONE) {
2,969,551!
107
    bank.surf_id = SURFACE_NONE;
2,969,551✔
108
  } else {
UNCOV
109
    int surf_id = model::surfaces[surface_index()]->id_;
×
UNCOV
110
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
×
111
  }
112
}
2,969,551✔
113

114
void Particle::from_source(const SourceSite* src)
172,953,033✔
115
{
116
  // Reset some attributes
117
  clear();
172,953,033✔
118
  surface() = SURFACE_NONE;
172,953,033✔
119
  cell_born() = C_NONE;
172,953,033✔
120
  material() = C_NONE;
172,953,033✔
121
  n_collision() = 0;
172,953,033✔
122
  fission() = false;
172,953,033✔
123
  zero_flux_derivs();
172,953,033✔
124
  lifetime() = 0.0;
172,953,033✔
125
#ifdef OPENMC_DAGMC_ENABLED
126
  history().reset();
127
#endif
128

129
  // Copy attributes from source bank site
130
  type() = src->particle;
172,953,033✔
131
  wgt() = src->wgt;
172,953,033✔
132
  wgt_last() = src->wgt;
172,953,033✔
133
  r() = src->r;
172,953,033✔
134
  u() = src->u;
172,953,033✔
135
  r_born() = src->r;
172,953,033✔
136
  r_last_current() = src->r;
172,953,033✔
137
  r_last() = src->r;
172,953,033✔
138
  u_last() = src->u;
172,953,033✔
139
  if (settings::run_CE) {
172,953,033✔
140
    E() = src->E;
88,780,017✔
141
    g() = 0;
88,780,017✔
142
  } else {
143
    g() = static_cast<int>(src->E);
84,173,016✔
144
    g_last() = static_cast<int>(src->E);
84,173,016✔
145
    E() = data::mg.energy_bin_avg_[g()];
84,173,016✔
146
  }
147
  E_last() = E();
172,953,033✔
148
  time() = src->time;
172,953,033✔
149
  time_last() = src->time;
172,953,033✔
150
  parent_nuclide() = src->parent_nuclide;
172,953,033✔
151
  delayed_group() = src->delayed_group;
172,953,033✔
152

153
  // Convert signed surface ID to signed index
154
  if (src->surf_id != SURFACE_NONE) {
172,953,033✔
155
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
80,000✔
156
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
80,000!
157
  }
158
}
172,953,033✔
159

160
void Particle::event_calculate_xs()
2,147,483,647✔
161
{
162
  // Set the random number stream
163
  stream() = STREAM_TRACKING;
2,147,483,647✔
164

165
  // Store pre-collision particle properties
166
  wgt_last() = wgt();
2,147,483,647✔
167
  E_last() = E();
2,147,483,647✔
168
  u_last() = u();
2,147,483,647✔
169
  r_last() = r();
2,147,483,647✔
170
  time_last() = time();
2,147,483,647✔
171

172
  // Reset event variables
173
  event() = TallyEvent::KILL;
2,147,483,647✔
174
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
175
  event_mt() = REACTION_NONE;
2,147,483,647✔
176

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

187
    // Set birth cell attribute
188
    if (cell_born() == C_NONE)
166,783,441!
189
      cell_born() = lowest_coord().cell();
166,783,441✔
190

191
    // Initialize last cells from current cell
192
    for (int j = 0; j < n_coord(); ++j) {
345,950,754✔
193
      cell_last(j) = coord(j).cell();
179,167,313✔
194
    }
195
    n_coord_last() = n_coord();
166,783,441✔
196
  }
197

198
  // Write particle track.
199
  if (write_track())
2,147,483,647✔
200
    write_particle_track(*this);
8,101✔
201

202
  if (settings::check_overlaps)
2,147,483,647!
203
    check_cell_overlap(*this);
×
204

205
  // Calculate microscopic and macroscopic cross sections
206
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
207
    if (settings::run_CE) {
2,147,483,647✔
208
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
1,680,182,052✔
209
          density_mult() != density_mult_last()) {
256,067,194✔
210
        // If the material is the same as the last material and the
211
        // temperature hasn't changed, we don't need to lookup cross
212
        // sections again.
213
        model::materials[material()]->calculate_xs(*this);
1,168,054,640✔
214
      }
215
    } else {
216
      // Get the MG data; unlike the CE case above, we have to re-calculate
217
      // cross sections for every collision since the cross sections may
218
      // be angle-dependent
219
      data::mg.macro_xs_[material()].calculate_xs(*this);
1,501,045,392✔
220

221
      // Update the particle's group while we know we are multi-group
222
      g_last() = g();
1,501,045,392✔
223
    }
224
  } else {
225
    macro_xs().total = 0.0;
81,315,332✔
226
    macro_xs().absorption = 0.0;
81,315,332✔
227
    macro_xs().fission = 0.0;
81,315,332✔
228
    macro_xs().nu_fission = 0.0;
81,315,332✔
229
  }
230
}
231

232
void Particle::event_advance()
2,147,483,647✔
233
{
234
  // Find the distance to the nearest boundary
235
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
236

237
  // Sample a distance to collision
238
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
239
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
38,885,314!
240
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
241
    collision_distance() = INFINITY;
81,315,332✔
242
  } else {
243
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
244
  }
245

246
  double speed = this->speed();
2,147,483,647✔
247
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
248
  double distance_cutoff =
249
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
250

251
  // Select smaller of the three distances
252
  double distance =
253
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
254

255
  // Advance particle in space and time
256
  this->move_distance(distance);
2,147,483,647✔
257
  double dt = distance / speed;
2,147,483,647✔
258
  this->time() += dt;
2,147,483,647✔
259
  this->lifetime() += dt;
2,147,483,647✔
260

261
  // Score timed track-length tallies
262
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
263
    score_timed_tracklength_tally(*this, distance);
2,638,776✔
264
  }
265

266
  // Score track-length tallies
267
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
268
    score_tracklength_tally(*this, distance);
1,126,213,703✔
269
  }
270

271
  // Score track-length estimate of k-eff
272
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
273
      type() == ParticleType::neutron) {
2,147,483,647✔
274
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
275
  }
276

277
  // Score flux derivative accumulators for differential tallies.
278
  if (!model::active_tallies.empty()) {
2,147,483,647✔
279
    score_track_derivative(*this, distance);
1,247,583,809✔
280
  }
281

282
  // Set particle weight to zero if it hit the time boundary
283
  if (distance == distance_cutoff) {
2,147,483,647✔
284
    wgt() = 0.0;
163,584✔
285
  }
286
}
2,147,483,647✔
287

288
void Particle::event_cross_surface()
1,618,437,692✔
289
{
290
  // Saving previous cell data
291
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
292
    cell_last(j) = coord(j).cell();
2,147,483,647✔
293
  }
294
  n_coord_last() = n_coord();
1,618,437,692✔
295

296
  // Set surface that particle is on and adjust coordinate levels
297
  surface() = boundary().surface();
1,618,437,692✔
298
  n_coord() = boundary().coord_level();
1,618,437,692✔
299

300
  if (boundary().lattice_translation()[0] != 0 ||
1,618,437,692✔
301
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
302
      boundary().lattice_translation()[2] != 0) {
1,231,738,838✔
303
    // Particle crosses lattice boundary
304

305
    bool verbose = settings::verbosity >= 10 || trace();
523,819,300!
306
    cross_lattice(*this, boundary(), verbose);
523,819,300✔
307
    event() = TallyEvent::LATTICE;
523,819,300✔
308
  } else {
309
    // Particle crosses surface
310
    const auto& surf {model::surfaces[surface_index()].get()};
1,094,618,392✔
311
    // If BC, add particle to surface source before crossing surface
312
    if (surf->surf_source_ && surf->bc_) {
1,094,618,392✔
313
      add_surf_source_to_bank(*this, *surf);
500,331,810✔
314
    }
315
    this->cross_surface(*surf);
1,094,618,392✔
316
    // If no BC, add particle to surface source after crossing surface
317
    if (surf->surf_source_ && !surf->bc_) {
1,094,618,385✔
318
      add_surf_source_to_bank(*this, *surf);
593,352,095✔
319
    }
320
    if (settings::weight_window_checkpoint_surface) {
1,094,618,385!
UNCOV
321
      apply_weight_windows(*this);
×
322
    }
323
    event() = TallyEvent::SURFACE;
1,094,618,385✔
324
  }
325
  // Score cell to cell partial currents
326
  if (!model::active_surface_tallies.empty()) {
1,618,437,685✔
327
    score_surface_tally(*this, model::active_surface_tallies);
25,398,376✔
328
  }
329
}
1,618,437,685✔
330

331
void Particle::event_collide()
1,981,307,874✔
332
{
333
  // Score collision estimate of keff
334
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
335
      type() == ParticleType::neutron) {
1,574,515,808✔
336
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
1,545,501,584✔
337
  }
338

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

343
  if (!model::active_meshsurf_tallies.empty())
1,981,307,874✔
344
    score_surface_tally(*this, model::active_meshsurf_tallies);
45,890,128✔
345

346
  // Clear surface component
347
  surface() = SURFACE_NONE;
1,981,307,874✔
348

349
  if (settings::run_CE) {
1,981,307,874✔
350
    collision(*this);
684,536,618✔
351
  } else {
352
    collision_mg(*this);
1,296,771,256✔
353
  }
354

355
  // Collision track feature to recording particle interaction
356
  if (settings::collision_track) {
1,981,307,874✔
357
    collision_track_record(*this);
110,392✔
358
  }
359

360
  // Score collision estimator tallies -- this is done after a collision
361
  // has occurred rather than before because we need information on the
362
  // outgoing energy for any tallies with an outgoing energy filter
363
  if (!model::active_collision_tallies.empty())
1,981,307,874✔
364
    score_collision_tally(*this);
76,555,824✔
365
  if (!model::active_analog_tallies.empty()) {
1,981,307,874✔
366
    if (settings::run_CE) {
212,063,056✔
367
      score_analog_tally_ce(*this);
211,184,320✔
368
    } else {
369
      score_analog_tally_mg(*this);
878,736✔
370
    }
371
  }
372

373
  if (!model::active_pulse_height_tallies.empty() &&
1,981,320,178✔
374
      type() == ParticleType::photon) {
12,304✔
375
    pht_collision_energy();
1,472✔
376
  }
377

378
  // Reset banked weight during collision
379
  n_bank() = 0;
1,981,307,874✔
380
  bank_second_E() = 0.0;
1,981,307,874✔
381
  wgt_bank() = 0.0;
1,981,307,874✔
382
  zero_delayed_bank();
1,981,307,874✔
383

384
  // Reset fission logical
385
  fission() = false;
1,981,307,874✔
386

387
  // Save coordinates for tallying purposes
388
  r_last_current() = r();
1,981,307,874✔
389

390
  // Set last material to none since cross sections will need to be
391
  // re-evaluated
392
  material_last() = C_NONE;
1,981,307,874✔
393

394
  // Set all directions to base level -- right now, after a collision, only
395
  // the base level directions are changed
396
  for (int j = 0; j < n_coord() - 1; ++j) {
2,085,310,022✔
397
    if (coord(j + 1).rotated()) {
104,002,148✔
398
      // If next level is rotated, apply rotation matrix
399
      const auto& m {model::cells[coord(j).cell()]->rotation_};
7,582,992✔
400
      const auto& u {coord(j).u()};
7,582,992✔
401
      coord(j + 1).u() = u.rotate(m);
7,582,992✔
402
    } else {
403
      // Otherwise, copy this level's direction
404
      coord(j + 1).u() = coord(j).u();
96,419,156✔
405
    }
406
  }
407

408
  // Score flux derivative accumulators for differential tallies.
409
  if (!model::active_tallies.empty())
1,981,307,874✔
410
    score_collision_derivative(*this);
591,790,965✔
411

412
#ifdef OPENMC_DAGMC_ENABLED
413
  history().reset();
414
#endif
415
}
1,981,307,874✔
416

417
void Particle::event_revive_from_secondary()
2,147,483,647✔
418
{
419
  // If particle has too many events, display warning and kill it
420
  ++n_event();
2,147,483,647✔
421
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
422
    warning("Particle " + std::to_string(id()) +
×
423
            " underwent maximum number of events.");
424
    wgt() = 0.0;
×
425
  }
426

427
  // Check for secondary particles if this particle is dead
428
  if (!alive()) {
2,147,483,647✔
429
    // Write final position for this particle
430
    if (write_track()) {
166,783,874✔
431
      write_particle_track(*this);
5,024✔
432
    }
433

434
    // If no secondary particles, break out of event loop
435
    if (secondary_bank().empty())
166,783,874✔
436
      return;
121,424,088✔
437

438
    from_source(&secondary_bank().back());
45,359,786✔
439
    secondary_bank().pop_back();
45,359,786✔
440
    n_event() = 0;
45,359,786✔
441
    bank_second_E() = 0.0;
45,359,786✔
442

443
    // Subtract secondary particle energy from interim pulse-height results
444
    if (!model::active_pulse_height_tallies.empty() &&
45,371,058✔
445
        this->type() == ParticleType::photon) {
11,272✔
446
      // Since the birth cell of the particle has not been set we
447
      // have to determine it before the energy of the secondary particle can be
448
      // removed from the pulse-height of this cell.
449
      if (lowest_coord().cell() == C_NONE) {
440!
450
        bool verbose = settings::verbosity >= 10 || trace();
440!
451
        if (!exhaustive_find_cell(*this, verbose)) {
440!
452
          mark_as_lost("Could not find the cell containing particle " +
×
453
                       std::to_string(id()));
×
454
          return;
×
455
        }
456
        // Set birth cell attribute
457
        if (cell_born() == C_NONE)
440!
458
          cell_born() = lowest_coord().cell();
440✔
459

460
        // Initialize last cells from current cell
461
        for (int j = 0; j < n_coord(); ++j) {
880✔
462
          cell_last(j) = coord(j).cell();
440✔
463
        }
464
        n_coord_last() = n_coord();
440✔
465
      }
466
      pht_secondary_particles();
440✔
467
    }
468

469
    // Enter new particle in particle track file
470
    if (write_track())
45,359,786✔
471
      add_particle_track(*this);
4,224✔
472
  }
473
}
474

475
void Particle::event_death()
121,424,088✔
476
{
477
#ifdef OPENMC_DAGMC_ENABLED
478
  history().reset();
479
#endif
480

481
  // Finish particle track output.
482
  if (write_track()) {
121,424,088✔
483
    finalize_particle_track(*this);
800✔
484
  }
485

486
// Contribute tally reduction variables to global accumulator
487
#pragma omp atomic
45,566,976✔
488
  global_tally_absorption += keff_tally_absorption();
121,424,088✔
489
#pragma omp atomic
45,567,325✔
490
  global_tally_collision += keff_tally_collision();
121,424,088✔
491
#pragma omp atomic
45,566,443✔
492
  global_tally_tracklength += keff_tally_tracklength();
121,424,088✔
493
#pragma omp atomic
45,646,138✔
494
  global_tally_leakage += keff_tally_leakage();
121,424,088✔
495

496
  // Reset particle tallies once accumulated
497
  keff_tally_absorption() = 0.0;
121,424,088✔
498
  keff_tally_collision() = 0.0;
121,424,088✔
499
  keff_tally_tracklength() = 0.0;
121,424,088✔
500
  keff_tally_leakage() = 0.0;
121,424,088✔
501

502
  if (!model::active_pulse_height_tallies.empty()) {
121,424,088✔
503
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
4,000✔
504
  }
505

506
  // Record the number of progeny created by this particle.
507
  // This data will be used to efficiently sort the fission bank.
508
  if (settings::run_mode == RunMode::EIGENVALUE) {
121,424,088✔
509
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
102,489,600✔
510
    simulation::progeny_per_particle[offset] = n_progeny();
102,489,600✔
511
  }
512
}
121,424,088✔
513

514
void Particle::pht_collision_energy()
1,472✔
515
{
516
  // Adds the energy particles lose in a collision to the pulse-height
517

518
  // determine index of cell in pulse_height_cells
519
  auto it = std::find(model::pulse_height_cells.begin(),
1,472✔
520
    model::pulse_height_cells.end(), lowest_coord().cell());
1,472✔
521

522
  if (it != model::pulse_height_cells.end()) {
1,472!
523
    int index = std::distance(model::pulse_height_cells.begin(), it);
1,472✔
524
    pht_storage()[index] += E_last() - E();
1,472✔
525

526
    // If the energy of the particle is below the cutoff, it will not be sampled
527
    // so its energy is added to the pulse-height in the cell
528
    int photon = static_cast<int>(ParticleType::photon);
1,472✔
529
    if (E() < settings::energy_cutoff[photon]) {
1,472✔
530
      pht_storage()[index] += E();
600✔
531
    }
532
  }
533
}
1,472✔
534

535
void Particle::pht_secondary_particles()
440✔
536
{
537
  // Removes the energy of secondary produced particles from the pulse-height
538

539
  // determine index of cell in pulse_height_cells
540
  auto it = std::find(model::pulse_height_cells.begin(),
440✔
541
    model::pulse_height_cells.end(), cell_born());
440✔
542

543
  if (it != model::pulse_height_cells.end()) {
440!
544
    int index = std::distance(model::pulse_height_cells.begin(), it);
440✔
545
    pht_storage()[index] -= E();
440✔
546
  }
547
}
440✔
548

549
void Particle::cross_surface(const Surface& surf)
1,096,038,176✔
550
{
551

552
  if (settings::verbosity >= 10 || trace()) {
1,096,038,176✔
553
    write_message(1, "    Crossing surface {}", surf.id_);
24✔
554
  }
555

556
// if we're crossing a CSG surface, make sure the DAG history is reset
557
#ifdef OPENMC_DAGMC_ENABLED
558
  if (surf.geom_type() == GeometryType::CSG)
559
    history().reset();
560
#endif
561

562
  // Handle any applicable boundary conditions.
563
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,596,719,618!
564
      settings::run_mode != RunMode::VOLUME) {
500,681,442✔
565
    surf.bc_->handle_particle(*this, surf);
500,594,210✔
566
    return;
500,594,210✔
567
  }
568

569
  // ==========================================================================
570
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
571

572
#ifdef OPENMC_DAGMC_ENABLED
573
  // in DAGMC, we know what the next cell should be
574
  if (surf.geom_type() == GeometryType::DAG) {
575
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
576
                       lowest_coord().universe()) -
577
                     1;
578
    // save material, temperature, and density multiplier
579
    material_last() = material();
580
    sqrtkT_last() = sqrtkT();
581
    density_mult_last() = density_mult();
582
    // set new cell value
583
    lowest_coord().cell() = i_cell;
584
    auto& cell = model::cells[i_cell];
585

586
    cell_instance() = 0;
587
    if (cell->distribcell_index_ >= 0)
588
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
589

590
    material() = cell->material(cell_instance());
591
    sqrtkT() = cell->sqrtkT(cell_instance());
592
    density_mult() = cell->density_mult(cell_instance());
593
    return;
594
  }
595
#endif
596

597
  bool verbose = settings::verbosity >= 10 || trace();
595,443,966!
598
  if (neighbor_list_find_cell(*this, verbose)) {
595,443,966✔
599
    return;
595,422,208✔
600
  }
601

602
  // ==========================================================================
603
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
604

605
  // Remove lower coordinate levels
606
  n_coord() = 1;
21,758✔
607
  bool found = exhaustive_find_cell(*this, verbose);
21,758✔
608

609
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
21,758!
610
    // If a cell is still not found, there are two possible causes: 1) there is
611
    // a void in the model, and 2) the particle hit a surface at a tangent. If
612
    // the particle is really traveling tangent to a surface, if we move it
613
    // forward a tiny bit it should fix the problem.
614

615
    surface() = SURFACE_NONE;
4,222✔
616
    n_coord() = 1;
4,222✔
617
    r() += TINY_BIT * u();
4,222✔
618

619
    // Couldn't find next cell anywhere! This probably means there is an actual
620
    // undefined region in the geometry.
621

622
    if (!exhaustive_find_cell(*this, verbose)) {
4,222!
623
      mark_as_lost("After particle " + std::to_string(id()) +
12,659✔
624
                   " crossed surface " + std::to_string(surf.id_) +
16,874✔
625
                   " it could not be located in any cell and it did not leak.");
626
      return;
4,215✔
627
    }
628
  }
629
}
630

631
void Particle::cross_vacuum_bc(const Surface& surf)
25,325,996✔
632
{
633
  // Score any surface current tallies -- note that the particle is moved
634
  // forward slightly so that if the mesh boundary is on the surface, it is
635
  // still processed
636

637
  if (!model::active_meshsurf_tallies.empty()) {
25,325,996✔
638
    // TODO: Find a better solution to score surface currents than
639
    // physically moving the particle forward slightly
640

641
    r() += TINY_BIT * u();
681,616✔
642
    score_surface_tally(*this, model::active_meshsurf_tallies);
681,616✔
643
  }
644

645
  // Score to global leakage tally
646
  keff_tally_leakage() += wgt();
25,325,996✔
647

648
  // Kill the particle
649
  wgt() = 0.0;
25,325,996✔
650

651
  // Display message
652
  if (settings::verbosity >= 10 || trace()) {
25,325,996!
653
    write_message(1, "    Leaked out of surface {}", surf.id_);
8✔
654
  }
655
}
25,325,996✔
656

657
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
474,364,216✔
658
{
659
  // Do not handle reflective boundary conditions on lower universes
660
  if (n_coord() != 1) {
474,364,216!
661
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
662
                 " off surface in a lower universe.");
663
    return;
×
664
  }
665

666
  // Score surface currents since reflection causes the direction of the
667
  // particle to change. For surface filters, we need to score the tallies
668
  // twice, once before the particle's surface attribute has changed and
669
  // once after. For mesh surface filters, we need to artificially move
670
  // the particle slightly back in case the surface crossing is coincident
671
  // with a mesh boundary
672

673
  if (!model::active_surface_tallies.empty()) {
474,364,216✔
674
    score_surface_tally(*this, model::active_surface_tallies);
207,288✔
675
  }
676

677
  if (!model::active_meshsurf_tallies.empty()) {
474,364,216✔
678
    Position r {this->r()};
34,098,536✔
679
    this->r() -= TINY_BIT * u();
34,098,536✔
680
    score_surface_tally(*this, model::active_meshsurf_tallies);
34,098,536✔
681
    this->r() = r;
34,098,536✔
682
  }
683

684
  // Set the new particle direction
685
  u() = new_u;
474,364,216✔
686

687
  // Reassign particle's cell and surface
688
  coord(0).cell() = cell_last(0);
474,364,216✔
689
  surface() = -surface();
474,364,216✔
690

691
  // If a reflective surface is coincident with a lattice or universe
692
  // boundary, it is necessary to redetermine the particle's coordinates in
693
  // the lower universes.
694
  // (unless we're using a dagmc model, which has exactly one universe)
695
  n_coord() = 1;
474,364,216✔
696
  if (surf.geom_type() != GeometryType::DAG &&
948,728,432!
697
      !neighbor_list_find_cell(*this)) {
474,364,216!
698
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
699
                 std::to_string(surf.id_) + ".");
×
700
    return;
×
701
  }
702

703
  // Set previous coordinate going slightly past surface crossing
704
  r_last_current() = r() + TINY_BIT * u();
474,364,216✔
705

706
  // Diagnostic message
707
  if (settings::verbosity >= 10 || trace()) {
474,364,216!
708
    write_message(1, "    Reflected from surface {}", surf.id_);
×
709
  }
710
}
711

712
void Particle::cross_periodic_bc(
1,635,246✔
713
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
714
{
715
  // Do not handle periodic boundary conditions on lower universes
716
  if (n_coord() != 1) {
1,635,246!
717
    mark_as_lost(
×
718
      "Cannot transfer particle " + std::to_string(id()) +
×
719
      " across surface in a lower universe. Boundary conditions must be "
720
      "applied to root universe.");
721
    return;
×
722
  }
723

724
  // Score surface currents since reflection causes the direction of the
725
  // particle to change -- artificially move the particle slightly back in
726
  // case the surface crossing is coincident with a mesh boundary
727
  if (!model::active_meshsurf_tallies.empty()) {
1,635,246!
728
    Position r {this->r()};
×
729
    this->r() -= TINY_BIT * u();
×
730
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
731
    this->r() = r;
×
732
  }
733

734
  // Adjust the particle's location and direction.
735
  r() = new_r;
1,635,246✔
736
  u() = new_u;
1,635,246✔
737

738
  // Reassign particle's surface
739
  surface() = new_surface;
1,635,246✔
740

741
  // Figure out what cell particle is in now
742
  n_coord() = 1;
1,635,246✔
743

744
  if (!neighbor_list_find_cell(*this)) {
1,635,246!
745
    mark_as_lost("Couldn't find particle after hitting periodic "
×
746
                 "boundary on surface " +
×
747
                 std::to_string(surf.id_) + ".");
×
748
    return;
×
749
  }
750

751
  // Set previous coordinate going slightly past surface crossing
752
  r_last_current() = r() + TINY_BIT * u();
1,635,246✔
753

754
  // Diagnostic message
755
  if (settings::verbosity >= 10 || trace()) {
1,635,246!
756
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
757
  }
758
}
759

760
void Particle::mark_as_lost(const char* message)
4,222✔
761
{
762
  // Print warning and write lost particle file
763
  warning(message);
4,222✔
764
  if (settings::max_write_lost_particles < 0 ||
4,222✔
765
      simulation::n_lost_particles < settings::max_write_lost_particles) {
4,000✔
766
    write_restart();
282✔
767
  }
768
  // Increment number of lost particles
769
  wgt() = 0.0;
4,222✔
770
#pragma omp atomic
1,577✔
771
  simulation::n_lost_particles += 1;
2,645✔
772

773
  // Count the total number of simulated particles (on this processor)
774
  auto n = simulation::current_batch * settings::gen_per_batch *
4,222✔
775
           simulation::work_per_rank;
776

777
  // Abort the simulation if the maximum number of lost particles has been
778
  // reached
779
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
4,222✔
780
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
7!
781
    fatal_error("Maximum number of lost particles has been reached.");
7✔
782
  }
783
}
4,215✔
784

785
void Particle::write_restart() const
282✔
786
{
787
  // Dont write another restart file if in particle restart mode
788
  if (settings::run_mode == RunMode::PARTICLE)
282✔
789
    return;
16✔
790

791
  // Set up file name
792
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
793
    simulation::current_batch, id());
505✔
794

795
#pragma omp critical(WriteParticleRestart)
192✔
796
  {
797
    // Create file
798
    hid_t file_id = file_open(filename, 'w');
266✔
799

800
    // Write filetype and version info
801
    write_attribute(file_id, "filetype", "particle restart");
266✔
802
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
266✔
803
    write_attribute(file_id, "openmc_version", VERSION);
266✔
804
#ifdef GIT_SHA1
805
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
806
#endif
807

808
    // Write data to file
809
    write_dataset(file_id, "current_batch", simulation::current_batch);
266✔
810
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
266✔
811
    write_dataset(file_id, "current_generation", simulation::current_gen);
266✔
812
    write_dataset(file_id, "n_particles", settings::n_particles);
266✔
813
    switch (settings::run_mode) {
266!
814
    case RunMode::FIXED_SOURCE:
170✔
815
      write_dataset(file_id, "run_mode", "fixed source");
170✔
816
      break;
170✔
817
    case RunMode::EIGENVALUE:
96✔
818
      write_dataset(file_id, "run_mode", "eigenvalue");
96✔
819
      break;
96✔
820
    case RunMode::PARTICLE:
×
821
      write_dataset(file_id, "run_mode", "particle restart");
×
822
      break;
×
823
    default:
×
824
      break;
×
825
    }
826
    write_dataset(file_id, "id", id());
266✔
827
    write_dataset(file_id, "type", static_cast<int>(type()));
266✔
828

829
    int64_t i = current_work();
266✔
830
    if (settings::run_mode == RunMode::EIGENVALUE) {
266✔
831
      // take source data from primary bank for eigenvalue simulation
832
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
96✔
833
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
96✔
834
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
96✔
835
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
96✔
836
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
96✔
837
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
170!
838
      // re-sample using rng random number seed used to generate source particle
839
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
170✔
840
                     settings::n_particles +
170✔
841
                   simulation::work_index[mpi::rank] + i;
170✔
842
      uint64_t seed = init_seed(id, STREAM_SOURCE);
170✔
843
      // re-sample source site
844
      auto site = sample_external_source(&seed);
170✔
845
      write_dataset(file_id, "weight", site.wgt);
170✔
846
      write_dataset(file_id, "energy", site.E);
170✔
847
      write_dataset(file_id, "xyz", site.r);
170✔
848
      write_dataset(file_id, "uvw", site.u);
170✔
849
      write_dataset(file_id, "time", site.time);
170✔
850
    }
851

852
    // Close file
853
    file_close(file_id);
266✔
854
  } // #pragma omp critical
855
}
266✔
856

857
void Particle::update_neutron_xs(
2,147,483,647✔
858
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
859
{
860
  // Get microscopic cross section cache
861
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
862

863
  // If the cache doesn't match, recalculate micro xs
864
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
865
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
866
      ncrystal_xs != micro.ncrystal_xs) {
1,865,091,616!
867
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
868

869
    // If NCrystal is being used, update micro cross section cache
870
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
871
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
872
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
8,013,784✔
873
      ncrystal_update_micro(ncrystal_xs, micro);
8,013,784✔
874
    }
875
  }
876
}
2,147,483,647✔
877

878
//==============================================================================
879
// Non-method functions
880
//==============================================================================
881

882
std::string particle_type_to_str(ParticleType type)
2,276,504✔
883
{
884
  switch (type) {
2,276,504!
885
  case ParticleType::neutron:
1,745,408✔
886
    return "neutron";
1,745,408✔
887
  case ParticleType::photon:
530,904✔
888
    return "photon";
530,904✔
889
  case ParticleType::electron:
96✔
890
    return "electron";
96✔
891
  case ParticleType::positron:
96✔
892
    return "positron";
96✔
893
  }
894
  UNREACHABLE();
×
895
}
896

897
ParticleType str_to_particle_type(std::string str)
2,419,496✔
898
{
899
  if (str == "neutron") {
2,419,496✔
900
    return ParticleType::neutron;
569,002✔
901
  } else if (str == "photon") {
1,850,494✔
902
    return ParticleType::photon;
1,850,430✔
903
  } else if (str == "electron") {
64✔
904
    return ParticleType::electron;
32✔
905
  } else if (str == "positron") {
32!
906
    return ParticleType::positron;
32✔
907
  } else {
908
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
909
  }
910
}
911

912
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,093,683,905✔
913
{
914
  if (simulation::current_batch <= settings::n_inactive ||
1,949,505,628✔
915
      simulation::surf_source_bank.full()) {
855,821,723✔
916
    return;
1,093,588,745✔
917
  }
918

919
  // If a cell/cellfrom/cellto parameter is defined
920
  if (settings::ssw_cell_id != C_NONE) {
255,021✔
921

922
    // Retrieve cell index and storage type
923
    int cell_idx = model::cell_map[settings::ssw_cell_id];
193,885✔
924

925
    if (surf.bc_) {
193,885✔
926
      // Leave if cellto with vacuum boundary condition
927
      if (surf.bc_->type() == "vacuum" &&
142,288!
928
          settings::ssw_cell_type == SSWCellType::To) {
24,600✔
929
        return;
9,008✔
930
      }
931

932
      // Leave if other boundary condition than vacuum
933
      if (surf.bc_->type() != "vacuum") {
108,680✔
934
        return;
93,088✔
935
      }
936
    }
937

938
    // Check if the cell of interest has been exited
939
    bool exited = false;
91,789✔
940
    for (int i = 0; i < p.n_coord_last(); ++i) {
247,146✔
941
      if (p.cell_last(i) == cell_idx) {
155,357✔
942
        exited = true;
55,104✔
943
      }
944
    }
945

946
    // Check if the cell of interest has been entered
947
    bool entered = false;
91,789✔
948
    for (int i = 0; i < p.n_coord(); ++i) {
219,738✔
949
      if (p.coord(i).cell() == cell_idx) {
127,949✔
950
        entered = true;
43,613✔
951
      }
952
    }
953

954
    // Vacuum boundary conditions: return if cell is not exited
955
    if (surf.bc_) {
91,789✔
956
      if (surf.bc_->type() == "vacuum" && !exited) {
15,592!
957
        return;
10,792✔
958
      }
959
    } else {
960

961
      // If we both enter and exit the cell of interest
962
      if (entered && exited) {
76,197✔
963
        return;
21,248✔
964
      }
965

966
      // If we did not enter nor exit the cell of interest
967
      if (!entered && !exited) {
54,949✔
968
        return;
8,328✔
969
      }
970

971
      // If cellfrom and the cell before crossing is not the cell of
972
      // interest
973
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
46,621✔
974
        return;
8,773✔
975
      }
976

977
      // If cellto and the cell after crossing is not the cell of interest
978
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
37,848✔
979
        return;
8,624✔
980
      }
981
    }
982
  }
983

984
  SourceSite site;
95,160✔
985
  site.r = p.r();
95,160✔
986
  site.u = p.u();
95,160✔
987
  site.E = p.E();
95,160✔
988
  site.time = p.time();
95,160✔
989
  site.wgt = p.wgt();
95,160✔
990
  site.delayed_group = p.delayed_group();
95,160✔
991
  site.surf_id = surf.id_;
95,160✔
992
  site.particle = p.type();
95,160✔
993
  site.parent_id = p.id();
95,160✔
994
  site.progeny_id = p.n_progeny();
95,160✔
995
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
95,160✔
996
}
997

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