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

openmc-dev / openmc / 21533365354

30 Jan 2026 10:48PM UTC coverage: 81.979% (-3.2%) from 85.162%
21533365354

Pull #3453

github

web-flow
Merge de22ee16c into 7b4617aff
Pull Request #3453: Secondary energy filter

17272 of 24046 branches covered (71.83%)

Branch coverage included in aggregate %.

50 of 52 new or added lines in 8 files covered. (96.15%)

4544 existing lines in 133 files now uncovered.

55847 of 65146 relevant lines covered (85.73%)

44003337.54 hits per line

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

85.44
/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()) {
2,115,024,870!
52
    case ParticleType::neutron:
2,039,757,523✔
53
      mass = MASS_NEUTRON_EV;
2,039,757,523✔
54
      break;
2,039,757,523✔
55
    case ParticleType::photon:
21,804,060✔
56
      mass = 0.0;
21,804,060✔
57
      break;
21,804,060✔
58
    case ParticleType::electron:
53,463,287✔
59
    case ParticleType::positron:
60
      mass = MASS_ELECTRON_EV;
53,463,287✔
61
      break;
53,463,287✔
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)) /
2,115,024,870✔
65
           (this->E() + mass);
2,115,024,870✔
66
  } else {
67
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
68
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
69
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
70
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
71
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
72
  }
73
}
74

75
bool Particle::create_secondary(
111,526,245✔
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)]) {
111,526,245✔
81
    return false;
53,310,153✔
82
  }
83

84
  // This is used to count backward in the secondary source bank for tallying
85
  // outgoing photon energies from a neutron in the SecondaryPhotonEnergy
86
  // filter.
87
  secondaries_this_collision()++;
58,216,092✔
88

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

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

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

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

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

158
  // Convert signed surface ID to signed index
159
  if (src->surf_id != SURFACE_NONE) {
238,066,786✔
160
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,336✔
161
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,336!
162
  }
163
}
238,066,786✔
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)) {
229,582,877!
UNCOV
187
      mark_as_lost(
×
UNCOV
188
        "Could not find the cell containing particle " + std::to_string(id()));
×
UNCOV
189
      return;
×
190
    }
191

192
    // Set birth cell attribute
193
    if (cell_born() == C_NONE)
229,582,877!
194
      cell_born() = lowest_coord().cell();
229,582,877✔
195

196
    // Initialize last cells from current cell
197
    for (int j = 0; j < n_coord(); ++j) {
476,190,434✔
198
      cell_last(j) = coord(j).cell();
246,607,557✔
199
    }
200
    n_coord_last() = n_coord();
229,582,877✔
201
  }
202

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

207
  if (settings::check_overlaps)
2,147,483,647!
UNCOV
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()) {
365,036,757✔
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,610,725,934✔
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,825,110✔
231
    macro_xs().absorption = 0.0;
111,825,110✔
232
    macro_xs().fission = 0.0;
111,825,110✔
233
    macro_xs().nu_fission = 0.0;
111,825,110✔
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 || type() == ParticleType::positron) {
2,147,483,647✔
244
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
53,463,287!
245
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
246
    collision_distance() = INFINITY;
111,825,110✔
247
  } else {
248
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
249
  }
250

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

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

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

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

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

276
  // Score track-length estimate of k-eff
277
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
278
      type() == ParticleType::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,732,975,888✔
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
  // Set surface that particle is on and adjust coordinate levels
302
  surface() = boundary().surface();
2,147,483,647✔
303
  n_coord() = boundary().coord_level();
2,147,483,647✔
304

305
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
306
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
307
      boundary().lattice_translation()[2] != 0) {
1,695,543,265✔
308
    // Particle crosses lattice boundary
309

310
    bool verbose = settings::verbosity >= 10 || trace();
732,435,579!
311
    cross_lattice(*this, boundary(), verbose);
732,435,579✔
312
    event() = TallyEvent::LATTICE;
732,435,579✔
313
  } else {
314
    // Particle crosses surface
315
    const auto& surf {model::surfaces[surface_index()].get()};
1,507,001,366✔
316
    // If BC, add particle to surface source before crossing surface
317
    if (surf->surf_source_ && surf->bc_) {
1,507,001,366✔
318
      add_surf_source_to_bank(*this, *surf);
688,542,619✔
319
    }
320
    this->cross_surface(*surf);
1,507,001,366✔
321
    // If no BC, add particle to surface source after crossing surface
322
    if (surf->surf_source_ && !surf->bc_) {
1,507,001,357✔
323
      add_surf_source_to_bank(*this, *surf);
817,220,911✔
324
    }
325
    if (settings::weight_window_checkpoint_surface) {
1,507,001,357✔
326
      apply_weight_windows(*this);
10,738!
327
    }
328
    event() = TallyEvent::SURFACE;
1,507,001,357✔
329
  }
330
  // Score cell to cell partial currents
331
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
332
    score_surface_tally(*this, model::active_surface_tallies);
34,922,767✔
333
  }
334
}
2,147,483,647✔
335

336
void Particle::event_collide()
2,147,483,647✔
337
{
338

339
  // Score collision estimate of keff
340
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
341
      type() == ParticleType::neutron) {
2,147,483,647✔
342
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,125,051,544✔
343
  }
344

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

349
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
350
    score_surface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
351

352
  // Clear surface component
353
  surface() = SURFACE_NONE;
2,147,483,647✔
354

355
  if (settings::run_CE) {
2,147,483,647✔
356
    collision(*this);
944,789,087✔
357
  } else {
358
    collision_mg(*this);
1,783,060,477✔
359
  }
360

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

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

379
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
380
      type() == ParticleType::photon) {
16,918✔
381
    pht_collision_energy();
2,024✔
382
  }
383

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

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

393
  zero_delayed_bank();
2,147,483,647✔
394

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

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

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

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

419
  // Score flux derivative accumulators for differential tallies.
420
  if (!model::active_tallies.empty())
2,147,483,647✔
421
    score_collision_derivative(*this);
817,153,275✔
422

423
#ifdef OPENMC_DAGMC_ENABLED
424
  history().reset();
250,212,502✔
425
#endif
426
}
2,147,483,647✔
427

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

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

445
    // If no secondary particles, break out of event loop
446
    if (secondary_bank().empty())
229,582,473✔
447
      return;
167,076,081✔
448

449
    from_source(&secondary_bank().back());
62,506,392✔
450
    secondary_bank().pop_back();
62,506,392✔
451
    n_event() = 0;
62,506,392✔
452
    bank_second_E() = 0.0;
62,506,392✔
453

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

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

480
    // Enter new particle in particle track file
481
    if (write_track())
62,506,392✔
482
      add_particle_track(*this);
5,604✔
483
  }
484
}
485

486
void Particle::event_death()
167,077,081✔
487
{
488
#ifdef OPENMC_DAGMC_ENABLED
489
  history().reset();
15,264,135✔
490
#endif
491

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

497
// Contribute tally reduction variables to global accumulator
498
#pragma omp atomic
92,020,064✔
499
  global_tally_absorption += keff_tally_absorption();
167,077,081✔
500
#pragma omp atomic
92,096,142✔
501
  global_tally_collision += keff_tally_collision();
167,077,081✔
502
#pragma omp atomic
91,601,937✔
503
  global_tally_tracklength += keff_tally_tracklength();
167,077,081✔
504
#pragma omp atomic
91,455,789✔
505
  global_tally_leakage += keff_tally_leakage();
167,077,081✔
506

507
  // Reset particle tallies once accumulated
508
  keff_tally_absorption() = 0.0;
167,077,081✔
509
  keff_tally_collision() = 0.0;
167,077,081✔
510
  keff_tally_tracklength() = 0.0;
167,077,081✔
511
  keff_tally_leakage() = 0.0;
167,077,081✔
512

513
  if (!model::active_pulse_height_tallies.empty()) {
167,077,081✔
514
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
515
  }
516

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

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

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

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

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

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

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

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

560
void Particle::cross_surface(const Surface& surf)
1,508,937,816✔
561
{
562

563
  if (settings::verbosity >= 10 || trace()) {
1,508,937,816✔
564
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
565
  }
566

567
// if we're crossing a CSG surface, make sure the DAG history is reset
568
#ifdef OPENMC_DAGMC_ENABLED
569
  if (surf.geom_type() == GeometryType::CSG)
137,924,635✔
570
    history().reset();
137,869,516✔
571
#endif
572

573
  // Handle any applicable boundary conditions.
574
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
575
      settings::run_mode != RunMode::VOLUME) {
689,014,671✔
576
    surf.bc_->handle_particle(*this, surf);
688,894,727✔
577
    return;
688,894,727✔
578
  }
579

580
  // ==========================================================================
581
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
582

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

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

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

608
  bool verbose = settings::verbosity >= 10 || trace();
819,998,779!
609
  if (neighbor_list_find_cell(*this, verbose)) {
819,998,779✔
610
    return;
819,968,868✔
611
  }
612

613
  // ==========================================================================
614
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
615

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

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

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

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

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

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

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

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

656
  // Score to global leakage tally
657
  keff_tally_leakage() += wgt();
35,012,131✔
658

659
  // Kill the particle
660
  wgt() = 0.0;
35,012,131✔
661

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

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

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

684
  if (!model::active_surface_tallies.empty()) {
652,640,003✔
685
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
686
  }
687

688
  if (!model::active_meshsurf_tallies.empty()) {
652,640,003✔
689
    Position r {this->r()};
46,885,487✔
690
    this->r() -= TINY_BIT * u();
46,885,487✔
691
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
692
    this->r() = r;
46,885,487✔
693
  }
694

695
  // Set the new particle direction
696
  u() = new_u;
652,640,003✔
697

698
  // Reassign particle's cell and surface
699
  coord(0).cell() = cell_last(0);
652,640,003✔
700
  surface() = -surface();
652,640,003✔
701

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

714
  // Set previous coordinate going slightly past surface crossing
715
  r_last_current() = r() + TINY_BIT * u();
652,640,003✔
716

717
  // Diagnostic message
718
  if (settings::verbosity >= 10 || trace()) {
652,640,003!
UNCOV
719
    write_message(1, "    Reflected from surface {}", surf.id_);
×
720
  }
721
}
722

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

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

745
  // Adjust the particle's location and direction.
746
  r() = new_r;
2,248,059✔
747
  u() = new_u;
2,248,059✔
748

749
  // Reassign particle's surface
750
  surface() = new_surface;
2,248,059✔
751

752
  // Figure out what cell particle is in now
753
  n_coord() = 1;
2,248,059✔
754

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

762
  // Set previous coordinate going slightly past surface crossing
763
  r_last_current() = r() + TINY_BIT * u();
2,248,059✔
764

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

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

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

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

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

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

806
#pragma omp critical(WriteParticleRestart)
374✔
807
  {
808
    // Create file
809
    hid_t file_id = file_open(filename, 'w');
357✔
810

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

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

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

863
    // Close file
864
    file_close(file_id);
357✔
865
  } // #pragma omp critical
866
}
357✔
867

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

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

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

889
//==============================================================================
890
// Non-method functions
891
//==============================================================================
892

893
std::string particle_type_to_str(ParticleType type)
3,130,263✔
894
{
895
  switch (type) {
3,130,263!
896
  case ParticleType::neutron:
2,399,984✔
897
    return "neutron";
2,399,984✔
898
  case ParticleType::photon:
730,015✔
899
    return "photon";
730,015✔
900
  case ParticleType::electron:
132✔
901
    return "electron";
132✔
902
  case ParticleType::positron:
132✔
903
    return "positron";
132✔
904
  }
UNCOV
905
  UNREACHABLE();
×
906
}
907

908
ParticleType str_to_particle_type(std::string str)
3,316,643✔
909
{
910
  if (str == "neutron") {
3,316,643✔
911
    return ParticleType::neutron;
774,629✔
912
  } else if (str == "photon") {
2,542,014✔
913
    return ParticleType::photon;
2,541,928✔
914
  } else if (str == "electron") {
86✔
915
    return ParticleType::electron;
43✔
916
  } else if (str == "positron") {
43!
917
    return ParticleType::positron;
43✔
918
  } else {
UNCOV
919
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
920
  }
921
}
922

923
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,505,763,530✔
924
{
925
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
926
      simulation::surf_source_bank.full()) {
1,178,688,813✔
927
    return;
1,505,633,877✔
928
  }
929

930
  // If a cell/cellfrom/cellto parameter is defined
931
  if (settings::ssw_cell_id != C_NONE) {
337,086✔
932

933
    // Retrieve cell index and storage type
934
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,441✔
935

936
    if (surf.bc_) {
254,441✔
937
      // Leave if cellto with vacuum boundary condition
938
      if (surf.bc_->type() == "vacuum" &&
182,560!
939
          settings::ssw_cell_type == SSWCellType::To) {
33,100✔
940
        return;
12,136✔
941
      }
942

943
      // Leave if other boundary condition than vacuum
944
      if (surf.bc_->type() != "vacuum") {
137,324✔
945
        return;
116,360✔
946
      }
947
    }
948

949
    // Check if the cell of interest has been exited
950
    bool exited = false;
125,945✔
951
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,679✔
952
      if (p.cell_last(i) == cell_idx) {
207,734✔
953
        exited = true;
73,765✔
954
      }
955
    }
956

957
    // Check if the cell of interest has been entered
958
    bool entered = false;
125,945✔
959
    for (int i = 0; i < p.n_coord(); ++i) {
297,981✔
960
      if (p.coord(i).cell() == cell_idx) {
172,036✔
961
        entered = true;
57,517✔
962
      }
963
    }
964

965
    // Vacuum boundary conditions: return if cell is not exited
966
    if (surf.bc_) {
125,945✔
967
      if (surf.bc_->type() == "vacuum" && !exited) {
20,964!
968
        return;
14,664✔
969
      }
970
    } else {
971

972
      // If we both enter and exit the cell of interest
973
      if (entered && exited) {
104,981✔
974
        return;
27,203✔
975
      }
976

977
      // If we did not enter nor exit the cell of interest
978
      if (!entered && !exited) {
77,778✔
979
        return;
13,502✔
980
      }
981

982
      // If cellfrom and the cell before crossing is not the cell of
983
      // interest
984
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,276✔
985
        return;
11,543✔
986
      }
987

988
      // If cellto and the cell after crossing is not the cell of interest
989
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,733✔
990
        return;
12,025✔
991
      }
992
    }
993
  }
994

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

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