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

openmc-dev / openmc / 17480518891

05 Sep 2025 12:54AM UTC coverage: 85.087% (-0.1%) from 85.209%
17480518891

Pull #3454

github

web-flow
Merge dabe58363 into 591856472
Pull Request #3454: Adding variance of variance and normality tests for tally statistics

212 of 339 new or added lines in 8 files covered. (62.54%)

16 existing lines in 2 files now uncovered.

53134 of 62447 relevant lines covered (85.09%)

37878934.13 hits per line

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

93.0
/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/constants.h"
12
#include "openmc/dagmc.h"
13
#include "openmc/error.h"
14
#include "openmc/geometry.h"
15
#include "openmc/hdf5_interface.h"
16
#include "openmc/material.h"
17
#include "openmc/message_passing.h"
18
#include "openmc/mgxs_interface.h"
19
#include "openmc/nuclide.h"
20
#include "openmc/particle_data.h"
21
#include "openmc/photon.h"
22
#include "openmc/physics.h"
23
#include "openmc/physics_mg.h"
24
#include "openmc/random_lcg.h"
25
#include "openmc/settings.h"
26
#include "openmc/simulation.h"
27
#include "openmc/source.h"
28
#include "openmc/surface.h"
29
#include "openmc/tallies/derivative.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/tallies/tally_scoring.h"
32
#include "openmc/track_output.h"
33
#include "openmc/weight_windows.h"
34

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

39
namespace openmc {
40

41
//==============================================================================
42
// Particle implementation
43
//==============================================================================
44

45
double Particle::speed() const
2,147,483,647✔
46
{
47
  if (settings::run_CE) {
2,147,483,647✔
48
    // Determine mass in eV/c^2
49
    double mass;
50
    switch (this->type()) {
1,787,710,831✔
51
    case ParticleType::neutron:
1,718,847,298✔
52
      mass = MASS_NEUTRON_EV;
1,718,847,298✔
53
      break;
1,718,847,298✔
54
    case ParticleType::photon:
17,444,504✔
55
      mass = 0.0;
17,444,504✔
56
      break;
17,444,504✔
57
    case ParticleType::electron:
51,419,029✔
58
    case ParticleType::positron:
59
      mass = MASS_ELECTRON_EV;
51,419,029✔
60
      break;
51,419,029✔
61
    }
62
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
63
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,787,710,831✔
64
           (this->E() + mass);
1,787,710,831✔
65
  } else {
66
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,062,680,774✔
67
    int macro_t = this->mg_xs_cache().t;
2,062,680,774✔
68
    int macro_a = macro_xs.get_angle_index(this->u());
2,062,680,774✔
69
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,062,680,774✔
70
                   nullptr, nullptr, macro_t, macro_a);
2,062,680,774✔
71
  }
72
}
73

74
bool Particle::create_secondary(
107,395,801✔
75
  double wgt, Direction u, double E, ParticleType type)
76
{
77
  // If energy is below cutoff for this particle, don't create secondary
78
  // particle
79
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
107,395,801✔
80
    return false;
51,369,102✔
81
  }
82

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

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

104
  // Convert signed index to a signed surface ID
105
  if (surface() == SURFACE_NONE) {
4,162,740✔
106
    bank.surf_id = SURFACE_NONE;
4,162,720✔
107
  } else {
108
    int surf_id = model::surfaces[surface_index()]->id_;
20✔
109
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
20✔
110
  }
111
}
4,162,740✔
112

113
void Particle::from_source(const SourceSite* src)
222,850,046✔
114
{
115
  // Reset some attributes
116
  clear();
222,850,046✔
117
  surface() = SURFACE_NONE;
222,850,046✔
118
  cell_born() = C_NONE;
222,850,046✔
119
  material() = C_NONE;
222,850,046✔
120
  n_collision() = 0;
222,850,046✔
121
  fission() = false;
222,850,046✔
122
  zero_flux_derivs();
222,850,046✔
123
  lifetime() = 0.0;
222,850,046✔
124

125
  // Copy attributes from source bank site
126
  type() = src->particle;
222,850,046✔
127
  wgt() = src->wgt;
222,850,046✔
128
  wgt_last() = src->wgt;
222,850,046✔
129
  r() = src->r;
222,850,046✔
130
  u() = src->u;
222,850,046✔
131
  r_born() = src->r;
222,850,046✔
132
  r_last_current() = src->r;
222,850,046✔
133
  r_last() = src->r;
222,850,046✔
134
  u_last() = src->u;
222,850,046✔
135
  if (settings::run_CE) {
222,850,046✔
136
    E() = src->E;
107,219,229✔
137
    g() = 0;
107,219,229✔
138
  } else {
139
    g() = static_cast<int>(src->E);
115,630,817✔
140
    g_last() = static_cast<int>(src->E);
115,630,817✔
141
    E() = data::mg.energy_bin_avg_[g()];
115,630,817✔
142
  }
143
  E_last() = E();
222,850,046✔
144
  time() = src->time;
222,850,046✔
145
  time_last() = src->time;
222,850,046✔
146
  parent_nuclide() = src->parent_nuclide;
222,850,046✔
147

148
  // Convert signed surface ID to signed index
149
  if (src->surf_id != SURFACE_NONE) {
222,850,046✔
150
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,020✔
151
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,020✔
152
  }
153
}
222,850,046✔
154

155
void Particle::event_calculate_xs()
2,147,483,647✔
156
{
157
  // Set the random number stream
158
  stream() = STREAM_TRACKING;
2,147,483,647✔
159

160
  // Store pre-collision particle properties
161
  wgt_last() = wgt();
2,147,483,647✔
162
  E_last() = E();
2,147,483,647✔
163
  u_last() = u();
2,147,483,647✔
164
  r_last() = r();
2,147,483,647✔
165
  time_last() = time();
2,147,483,647✔
166

167
  // Reset event variables
168
  event() = TallyEvent::KILL;
2,147,483,647✔
169
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
170
  event_mt() = REACTION_NONE;
2,147,483,647✔
171

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

182
    // Set birth cell attribute
183
    if (cell_born() == C_NONE)
219,882,494✔
184
      cell_born() = lowest_coord().cell();
219,882,494✔
185

186
    // Initialize last cells from current cell
187
    for (int j = 0; j < n_coord(); ++j) {
456,015,535✔
188
      cell_last(j) = coord(j).cell();
236,133,041✔
189
    }
190
    n_coord_last() = n_coord();
219,882,494✔
191
  }
192

193
  // Write particle track.
194
  if (write_track())
2,147,483,647✔
195
    write_particle_track(*this);
10,835✔
196

197
  if (settings::check_overlaps)
2,147,483,647✔
198
    check_cell_overlap(*this);
×
199

200
  // Calculate microscopic and macroscopic cross sections
201
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
202
    if (settings::run_CE) {
2,147,483,647✔
203
      if (material() != material_last() || sqrtkT() != sqrtkT_last()) {
1,696,972,744✔
204
        // If the material is the same as the last material and the
205
        // temperature hasn't changed, we don't need to lookup cross
206
        // sections again.
207
        model::materials[material()]->calculate_xs(*this);
1,356,095,546✔
208
      }
209
    } else {
210
      // Get the MG data; unlike the CE case above, we have to re-calculate
211
      // cross sections for every collision since the cross sections may
212
      // be angle-dependent
213
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,062,680,774✔
214

215
      // Update the particle's group while we know we are multi-group
216
      g_last() = g();
2,062,680,774✔
217
    }
218
  } else {
219
    macro_xs().total = 0.0;
67,283,447✔
220
    macro_xs().absorption = 0.0;
67,283,447✔
221
    macro_xs().fission = 0.0;
67,283,447✔
222
    macro_xs().nu_fission = 0.0;
67,283,447✔
223
  }
224
}
225

226
void Particle::event_advance()
2,147,483,647✔
227
{
228
  // Find the distance to the nearest boundary
229
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
230

231
  // Sample a distance to collision
232
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
233
    collision_distance() = 0.0;
51,419,029✔
234
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
235
    collision_distance() = INFINITY;
67,283,447✔
236
  } else {
237
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
238
  }
239

240
  double speed = this->speed();
2,147,483,647✔
241
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
242
  double distance_cutoff =
243
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
244

245
  // Select smaller of the three distances
246
  double distance =
247
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
248

249
  // Advance particle in space and time
250
  this->move_distance(distance);
2,147,483,647✔
251
  double dt = distance / speed;
2,147,483,647✔
252
  this->time() += dt;
2,147,483,647✔
253
  this->lifetime() += dt;
2,147,483,647✔
254

255
  // Score track-length tallies
256
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
257
    score_tracklength_tally(*this, distance);
1,294,786,671✔
258
  }
259

260
  // Score track-length estimate of k-eff
261
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
262
      type() == ParticleType::neutron) {
2,147,483,647✔
263
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
264
  }
265

266
  // Score flux derivative accumulators for differential tallies.
267
  if (!model::active_tallies.empty()) {
2,147,483,647✔
268
    score_track_derivative(*this, distance);
1,457,958,739✔
269
  }
270

271
  // Set particle weight to zero if it hit the time boundary
272
  if (distance == distance_cutoff) {
2,147,483,647✔
273
    wgt() = 0.0;
11,000✔
274
  }
275
}
2,147,483,647✔
276

277
void Particle::event_cross_surface()
2,069,634,515✔
278
{
279
  // Saving previous cell data
280
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
281
    cell_last(j) = coord(j).cell();
2,147,483,647✔
282
  }
283
  n_coord_last() = n_coord();
2,069,634,515✔
284

285
  // Set surface that particle is on and adjust coordinate levels
286
  surface() = boundary().surface();
2,069,634,515✔
287
  n_coord() = boundary().coord_level();
2,069,634,515✔
288

289
  if (boundary().lattice_translation()[0] != 0 ||
2,069,634,515✔
290
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
291
      boundary().lattice_translation()[2] != 0) {
1,576,142,732✔
292
    // Particle crosses lattice boundary
293

294
    bool verbose = settings::verbosity >= 10 || trace();
679,873,882✔
295
    cross_lattice(*this, boundary(), verbose);
679,873,882✔
296
    event() = TallyEvent::LATTICE;
679,873,882✔
297
  } else {
298
    // Particle crosses surface
299
    const auto& surf {model::surfaces[surface_index()].get()};
1,389,760,633✔
300
    // If BC, add particle to surface source before crossing surface
301
    if (surf->surf_source_ && surf->bc_) {
1,389,760,633✔
302
      add_surf_source_to_bank(*this, *surf);
646,526,089✔
303
    }
304
    this->cross_surface(*surf);
1,389,760,633✔
305
    // If no BC, add particle to surface source after crossing surface
306
    if (surf->surf_source_ && !surf->bc_) {
1,389,760,624✔
307
      add_surf_source_to_bank(*this, *surf);
742,001,126✔
308
    }
309
    if (settings::weight_window_checkpoint_surface) {
1,389,760,624✔
310
      apply_weight_windows(*this);
396✔
311
    }
312
    event() = TallyEvent::SURFACE;
1,389,760,624✔
313
  }
314
  // Score cell to cell partial currents
315
  if (!model::active_surface_tallies.empty()) {
2,069,634,506✔
316
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
317
  }
318
}
2,069,634,506✔
319

320
void Particle::event_collide()
2,147,483,647✔
321
{
322
  // Score collision estimate of keff
323
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
324
      type() == ParticleType::neutron) {
2,145,419,503✔
325
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,106,097,319✔
326
  }
327

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

332
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
333
    score_surface_tally(*this, model::active_meshsurf_tallies);
68,565,871✔
334

335
  // Clear surface component
336
  surface() = SURFACE_NONE;
2,147,483,647✔
337

338
  if (settings::run_CE) {
2,147,483,647✔
339
    collision(*this);
740,478,121✔
340
  } else {
341
    collision_mg(*this);
1,781,763,302✔
342
  }
343

344
  // Score collision estimator tallies -- this is done after a collision
345
  // has occurred rather than before because we need information on the
346
  // outgoing energy for any tallies with an outgoing energy filter
347
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
348
    score_collision_tally(*this);
98,078,919✔
349
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
350
    if (settings::run_CE) {
113,518,064✔
351
      score_analog_tally_ce(*this);
112,316,853✔
352
    } else {
353
      score_analog_tally_mg(*this);
1,201,211✔
354
    }
355
  }
356

357
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
358
      type() == ParticleType::photon) {
16,918✔
359
    pht_collision_energy();
2,024✔
360
  }
361

362
  // Reset banked weight during collision
363
  n_bank() = 0;
2,147,483,647✔
364
  bank_second_E() = 0.0;
2,147,483,647✔
365
  wgt_bank() = 0.0;
2,147,483,647✔
366
  zero_delayed_bank();
2,147,483,647✔
367

368
  // Reset fission logical
369
  fission() = false;
2,147,483,647✔
370

371
  // Save coordinates for tallying purposes
372
  r_last_current() = r();
2,147,483,647✔
373

374
  // Set last material to none since cross sections will need to be
375
  // re-evaluated
376
  material_last() = C_NONE;
2,147,483,647✔
377

378
  // Set all directions to base level -- right now, after a collision, only
379
  // the base level directions are changed
380
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
381
    if (coord(j + 1).rotated()) {
114,485,213✔
382
      // If next level is rotated, apply rotation matrix
383
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,394,285✔
384
      const auto& u {coord(j).u()};
10,394,285✔
385
      coord(j + 1).u() = u.rotate(m);
10,394,285✔
386
    } else {
387
      // Otherwise, copy this level's direction
388
      coord(j + 1).u() = coord(j).u();
104,090,928✔
389
    }
390
  }
391

392
  // Score flux derivative accumulators for differential tallies.
393
  if (!model::active_tallies.empty())
2,147,483,647✔
394
    score_collision_derivative(*this);
637,193,812✔
395

396
#ifdef OPENMC_DAGMC_ENABLED
397
  history().reset();
230,147,783✔
398
#endif
399
}
2,147,483,647✔
400

401
void Particle::event_revive_from_secondary()
2,147,483,647✔
402
{
403
  // If particle has too many events, display warning and kill it
404
  ++n_event();
2,147,483,647✔
405
  if (n_event() == settings::max_particle_events) {
2,147,483,647✔
406
    warning("Particle " + std::to_string(id()) +
×
407
            " underwent maximum number of events.");
408
    wgt() = 0.0;
×
409
  }
410

411
  // Check for secondary particles if this particle is dead
412
  if (!alive()) {
2,147,483,647✔
413
    // Write final position for this particle
414
    if (write_track()) {
219,882,090✔
415
      write_particle_track(*this);
6,674✔
416
    }
417

418
    // If no secondary particles, break out of event loop
419
    if (secondary_bank().empty())
219,882,090✔
420
      return;
159,353,808✔
421

422
    from_source(&secondary_bank().back());
60,528,282✔
423
    secondary_bank().pop_back();
60,528,282✔
424
    n_event() = 0;
60,528,282✔
425
    bank_second_E() = 0.0;
60,528,282✔
426

427
    // Subtract secondary particle energy from interim pulse-height results
428
    if (!model::active_pulse_height_tallies.empty() &&
60,543,781✔
429
        this->type() == ParticleType::photon) {
15,499✔
430
      // Since the birth cell of the particle has not been set we
431
      // have to determine it before the energy of the secondary particle can be
432
      // removed from the pulse-height of this cell.
433
      if (lowest_coord().cell() == C_NONE) {
605✔
434
        bool verbose = settings::verbosity >= 10 || trace();
605✔
435
        if (!exhaustive_find_cell(*this, verbose)) {
605✔
436
          mark_as_lost("Could not find the cell containing particle " +
×
437
                       std::to_string(id()));
×
438
          return;
×
439
        }
440
        // Set birth cell attribute
441
        if (cell_born() == C_NONE)
605✔
442
          cell_born() = lowest_coord().cell();
605✔
443

444
        // Initialize last cells from current cell
445
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
446
          cell_last(j) = coord(j).cell();
605✔
447
        }
448
        n_coord_last() = n_coord();
605✔
449
      }
450
      pht_secondary_particles();
605✔
451
    }
452

453
    // Enter new particle in particle track file
454
    if (write_track())
60,528,282✔
455
      add_particle_track(*this);
5,604✔
456
  }
457
}
458

459
void Particle::event_death()
159,354,808✔
460
{
461
#ifdef OPENMC_DAGMC_ENABLED
462
  history().reset();
14,685,692✔
463
#endif
464

465
  // Finish particle track output.
466
  if (write_track()) {
159,354,808✔
467
    finalize_particle_track(*this);
1,070✔
468
  }
469

470
// Contribute tally reduction variables to global accumulator
471
#pragma omp atomic
87,233,008✔
472
  global_tally_absorption += keff_tally_absorption();
159,354,808✔
473
#pragma omp atomic
86,868,973✔
474
  global_tally_collision += keff_tally_collision();
159,354,808✔
475
#pragma omp atomic
86,894,727✔
476
  global_tally_tracklength += keff_tally_tracklength();
159,354,808✔
477
#pragma omp atomic
86,582,606✔
478
  global_tally_leakage += keff_tally_leakage();
159,354,808✔
479

480
  // Reset particle tallies once accumulated
481
  keff_tally_absorption() = 0.0;
159,354,808✔
482
  keff_tally_collision() = 0.0;
159,354,808✔
483
  keff_tally_tracklength() = 0.0;
159,354,808✔
484
  keff_tally_leakage() = 0.0;
159,354,808✔
485

486
  if (!model::active_pulse_height_tallies.empty()) {
159,354,808✔
487
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
488
  }
489

490
  // Record the number of progeny created by this particle.
491
  // This data will be used to efficiently sort the fission bank.
492
  if (settings::run_mode == RunMode::EIGENVALUE) {
159,354,808✔
493
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
134,246,700✔
494
    simulation::progeny_per_particle[offset] = n_progeny();
134,246,700✔
495
  }
496
}
159,354,808✔
497

498
void Particle::pht_collision_energy()
2,024✔
499
{
500
  // Adds the energy particles lose in a collision to the pulse-height
501

502
  // determine index of cell in pulse_height_cells
503
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
504
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
505

506
  if (it != model::pulse_height_cells.end()) {
2,024✔
507
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
508
    pht_storage()[index] += E_last() - E();
2,024✔
509

510
    // If the energy of the particle is below the cutoff, it will not be sampled
511
    // so its energy is added to the pulse-height in the cell
512
    int photon = static_cast<int>(ParticleType::photon);
2,024✔
513
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
514
      pht_storage()[index] += E();
825✔
515
    }
516
  }
517
}
2,024✔
518

519
void Particle::pht_secondary_particles()
605✔
520
{
521
  // Removes the energy of secondary produced particles from the pulse-height
522

523
  // determine index of cell in pulse_height_cells
524
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
525
    model::pulse_height_cells.end(), cell_born());
605✔
526

527
  if (it != model::pulse_height_cells.end()) {
605✔
528
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
529
    pht_storage()[index] -= E();
605✔
530
  }
531
}
605✔
532

533
void Particle::cross_surface(const Surface& surf)
1,390,833,289✔
534
{
535

536
  if (settings::verbosity >= 10 || trace()) {
1,390,833,289✔
537
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
538
  }
539

540
// if we're crossing a CSG surface, make sure the DAG history is reset
541
#ifdef OPENMC_DAGMC_ENABLED
542
  if (surf.geom_type() == GeometryType::CSG)
123,605,176✔
543
    history().reset();
123,561,128✔
544
#endif
545

546
  // Handle any applicable boundary conditions.
547
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,390,833,289✔
548
    surf.bc_->handle_particle(*this, surf);
646,873,706✔
549
    return;
646,873,706✔
550
  }
551

552
  // ==========================================================================
553
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
554

555
#ifdef OPENMC_DAGMC_ENABLED
556
  // in DAGMC, we know what the next cell should be
557
  if (surf.geom_type() == GeometryType::DAG) {
65,705,761✔
558
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
36,997✔
559
                       lowest_coord().universe()) -
36,997✔
560
                     1;
36,997✔
561
    // save material and temp
562
    material_last() = material();
36,997✔
563
    sqrtkT_last() = sqrtkT();
36,997✔
564
    // set new cell value
565
    lowest_coord().cell() = i_cell;
36,997✔
566
    auto& cell = model::cells[i_cell];
36,997✔
567

568
    cell_instance() = 0;
36,997✔
569
    if (cell->distribcell_index_ >= 0)
36,997✔
570
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
35,996✔
571

572
    material() = cell->material(cell_instance());
36,997✔
573
    sqrtkT() = cell->sqrtkT(cell_instance());
36,997✔
574
    return;
36,997✔
575
  }
576
#endif
577

578
  bool verbose = settings::verbosity >= 10 || trace();
743,922,586✔
579
  if (neighbor_list_find_cell(*this, verbose)) {
743,922,586✔
580
    return;
743,894,567✔
581
  }
582

583
  // ==========================================================================
584
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
585

586
  // Remove lower coordinate levels
587
  n_coord() = 1;
28,019✔
588
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
589

590
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
28,019✔
591
    // If a cell is still not found, there are two possible causes: 1) there is
592
    // a void in the model, and 2) the particle hit a surface at a tangent. If
593
    // the particle is really traveling tangent to a surface, if we move it
594
    // forward a tiny bit it should fix the problem.
595

596
    surface() = SURFACE_NONE;
5,744✔
597
    n_coord() = 1;
5,744✔
598
    r() += TINY_BIT * u();
5,744✔
599

600
    // Couldn't find next cell anywhere! This probably means there is an actual
601
    // undefined region in the geometry.
602

603
    if (!exhaustive_find_cell(*this, verbose)) {
5,744✔
604
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
605
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
606
                   " it could not be located in any cell and it did not leak.");
607
      return;
5,735✔
608
    }
609
  }
610
}
611

612
void Particle::cross_vacuum_bc(const Surface& surf)
32,929,487✔
613
{
614
  // Score any surface current tallies -- note that the particle is moved
615
  // forward slightly so that if the mesh boundary is on the surface, it is
616
  // still processed
617

618
  if (!model::active_meshsurf_tallies.empty()) {
32,929,487✔
619
    // TODO: Find a better solution to score surface currents than
620
    // physically moving the particle forward slightly
621

622
    r() += TINY_BIT * u();
1,021,265✔
623
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,021,265✔
624
  }
625

626
  // Score to global leakage tally
627
  keff_tally_leakage() += wgt();
32,929,487✔
628

629
  // Kill the particle
630
  wgt() = 0.0;
32,929,487✔
631

632
  // Display message
633
  if (settings::verbosity >= 10 || trace()) {
32,929,487✔
634
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
635
  }
636
}
32,929,487✔
637

638
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
614,305,257✔
639
{
640
  // Do not handle reflective boundary conditions on lower universes
641
  if (n_coord() != 1) {
614,305,257✔
UNCOV
642
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
643
                 " off surface in a lower universe.");
UNCOV
644
    return;
×
645
  }
646

647
  // Score surface currents since reflection causes the direction of the
648
  // particle to change. For surface filters, we need to score the tallies
649
  // twice, once before the particle's surface attribute has changed and
650
  // once after. For mesh surface filters, we need to artificially move
651
  // the particle slightly back in case the surface crossing is coincident
652
  // with a mesh boundary
653

654
  if (!model::active_surface_tallies.empty()) {
614,305,257✔
655
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
656
  }
657

658
  if (!model::active_meshsurf_tallies.empty()) {
614,305,257✔
659
    Position r {this->r()};
50,811,809✔
660
    this->r() -= TINY_BIT * u();
50,811,809✔
661
    score_surface_tally(*this, model::active_meshsurf_tallies);
50,811,809✔
662
    this->r() = r;
50,811,809✔
663
  }
664

665
  // Set the new particle direction
666
  u() = new_u;
614,305,257✔
667

668
  // Reassign particle's cell and surface
669
  coord(0).cell() = cell_last(0);
614,305,257✔
670
  surface() = -surface();
614,305,257✔
671

672
  // If a reflective surface is coincident with a lattice or universe
673
  // boundary, it is necessary to redetermine the particle's coordinates in
674
  // the lower universes.
675
  // (unless we're using a dagmc model, which has exactly one universe)
676
  n_coord() = 1;
614,305,257✔
677
  if (surf.geom_type() != GeometryType::DAG &&
1,228,607,975✔
678
      !neighbor_list_find_cell(*this)) {
614,302,718✔
UNCOV
679
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
680
                 std::to_string(surf.id_) + ".");
×
681
    return;
×
682
  }
683

684
  // Set previous coordinate going slightly past surface crossing
685
  r_last_current() = r() + TINY_BIT * u();
614,305,257✔
686

687
  // Diagnostic message
688
  if (settings::verbosity >= 10 || trace()) {
614,305,257✔
UNCOV
689
    write_message(1, "    Reflected from surface {}", surf.id_);
×
690
  }
691
}
692

693
void Particle::cross_periodic_bc(
666,318✔
694
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
695
{
696
  // Do not handle periodic boundary conditions on lower universes
697
  if (n_coord() != 1) {
666,318✔
UNCOV
698
    mark_as_lost(
×
699
      "Cannot transfer particle " + std::to_string(id()) +
×
700
      " across surface in a lower universe. Boundary conditions must be "
701
      "applied to root universe.");
UNCOV
702
    return;
×
703
  }
704

705
  // Score surface currents since reflection causes the direction of the
706
  // particle to change -- artificially move the particle slightly back in
707
  // case the surface crossing is coincident with a mesh boundary
708
  if (!model::active_meshsurf_tallies.empty()) {
666,318✔
UNCOV
709
    Position r {this->r()};
×
710
    this->r() -= TINY_BIT * u();
×
711
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
712
    this->r() = r;
×
713
  }
714

715
  // Adjust the particle's location and direction.
716
  r() = new_r;
666,318✔
717
  u() = new_u;
666,318✔
718

719
  // Reassign particle's surface
720
  surface() = new_surface;
666,318✔
721

722
  // Figure out what cell particle is in now
723
  n_coord() = 1;
666,318✔
724

725
  if (!neighbor_list_find_cell(*this)) {
666,318✔
UNCOV
726
    mark_as_lost("Couldn't find particle after hitting periodic "
×
727
                 "boundary on surface " +
×
728
                 std::to_string(surf.id_) +
×
729
                 ". The normal vector "
730
                 "of one periodic surface may need to be reversed.");
UNCOV
731
    return;
×
732
  }
733

734
  // Set previous coordinate going slightly past surface crossing
735
  r_last_current() = r() + TINY_BIT * u();
666,318✔
736

737
  // Diagnostic message
738
  if (settings::verbosity >= 10 || trace()) {
666,318✔
UNCOV
739
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
740
  }
741
}
742

743
void Particle::mark_as_lost(const char* message)
5,744✔
744
{
745
  // Print warning and write lost particle file
746
  warning(message);
5,744✔
747
  if (settings::max_write_lost_particles < 0 ||
5,744✔
748
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
749
    write_restart();
324✔
750
  }
751
  // Increment number of lost particles
752
  wgt() = 0.0;
5,744✔
753
#pragma omp atomic
3,124✔
754
  simulation::n_lost_particles += 1;
2,620✔
755

756
  // Count the total number of simulated particles (on this processor)
757
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
758
           simulation::work_per_rank;
759

760
  // Abort the simulation if the maximum number of lost particles has been
761
  // reached
762
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,744✔
763
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
764
    fatal_error("Maximum number of lost particles has been reached.");
9✔
765
  }
766
}
5,735✔
767

768
void Particle::write_restart() const
324✔
769
{
770
  // Dont write another restart file if in particle restart mode
771
  if (settings::run_mode == RunMode::PARTICLE)
324✔
772
    return;
22✔
773

774
  // Set up file name
775
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
776
    simulation::current_batch, id());
565✔
777

778
#pragma omp critical(WriteParticleRestart)
314✔
779
  {
780
    // Create file
781
    hid_t file_id = file_open(filename, 'w');
302✔
782

783
    // Write filetype and version info
784
    write_attribute(file_id, "filetype", "particle restart");
302✔
785
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
302✔
786
    write_attribute(file_id, "openmc_version", VERSION);
302✔
787
#ifdef GIT_SHA1
788
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
789
#endif
790

791
    // Write data to file
792
    write_dataset(file_id, "current_batch", simulation::current_batch);
302✔
793
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
302✔
794
    write_dataset(file_id, "current_generation", simulation::current_gen);
302✔
795
    write_dataset(file_id, "n_particles", settings::n_particles);
302✔
796
    switch (settings::run_mode) {
302✔
797
    case RunMode::FIXED_SOURCE:
225✔
798
      write_dataset(file_id, "run_mode", "fixed source");
225✔
799
      break;
225✔
800
    case RunMode::EIGENVALUE:
77✔
801
      write_dataset(file_id, "run_mode", "eigenvalue");
77✔
802
      break;
77✔
UNCOV
803
    case RunMode::PARTICLE:
×
804
      write_dataset(file_id, "run_mode", "particle restart");
×
805
      break;
×
806
    default:
×
807
      break;
×
808
    }
809
    write_dataset(file_id, "id", id());
302✔
810
    write_dataset(file_id, "type", static_cast<int>(type()));
302✔
811

812
    int64_t i = current_work();
302✔
813
    if (settings::run_mode == RunMode::EIGENVALUE) {
302✔
814
      // take source data from primary bank for eigenvalue simulation
815
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
77✔
816
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
77✔
817
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
77✔
818
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
77✔
819
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
77✔
820
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
225✔
821
      // re-sample using rng random number seed used to generate source particle
822
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
225✔
823
                     settings::n_particles +
225✔
824
                   simulation::work_index[mpi::rank] + i;
225✔
825
      uint64_t seed = init_seed(id, STREAM_SOURCE);
225✔
826
      // re-sample source site
827
      auto site = sample_external_source(&seed);
225✔
828
      write_dataset(file_id, "weight", site.wgt);
225✔
829
      write_dataset(file_id, "energy", site.E);
225✔
830
      write_dataset(file_id, "xyz", site.r);
225✔
831
      write_dataset(file_id, "uvw", site.u);
225✔
832
      write_dataset(file_id, "time", site.time);
225✔
833
    }
834

835
    // Close file
836
    file_close(file_id);
302✔
837
  } // #pragma omp critical
838
}
302✔
839

840
void Particle::update_neutron_xs(
2,147,483,647✔
841
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
842
{
843
  // Get microscopic cross section cache
844
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
845

846
  // If the cache doesn't match, recalculate micro xs
847
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
848
      i_sab != micro.index_sab || sab_frac != micro.sab_frac) {
2,147,483,647✔
849
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
850

851
    // If NCrystal is being used, update micro cross section cache
852
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
853
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
854
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
855
    }
856
  }
857
}
2,147,483,647✔
858

859
//==============================================================================
860
// Non-method functions
861
//==============================================================================
862

863
std::string particle_type_to_str(ParticleType type)
3,258,770✔
864
{
865
  switch (type) {
3,258,770✔
866
  case ParticleType::neutron:
2,464,228✔
867
    return "neutron";
2,464,228✔
868
  case ParticleType::photon:
794,278✔
869
    return "photon";
794,278✔
870
  case ParticleType::electron:
132✔
871
    return "electron";
132✔
872
  case ParticleType::positron:
132✔
873
    return "positron";
132✔
874
  }
UNCOV
875
  UNREACHABLE();
×
876
}
877

878
ParticleType str_to_particle_type(std::string str)
3,223,629✔
879
{
880
  if (str == "neutron") {
3,223,629✔
881
    return ParticleType::neutron;
745,765✔
882
  } else if (str == "photon") {
2,477,864✔
883
    return ParticleType::photon;
2,477,778✔
884
  } else if (str == "electron") {
86✔
885
    return ParticleType::electron;
43✔
886
  } else if (str == "positron") {
43✔
887
    return ParticleType::positron;
43✔
888
  } else {
UNCOV
889
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
890
  }
891
}
892

893
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,388,527,215✔
894
{
895
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
896
      simulation::surf_source_bank.full()) {
1,094,952,772✔
897
    return;
1,388,398,450✔
898
  }
899

900
  // If a cell/cellfrom/cellto parameter is defined
901
  if (settings::ssw_cell_id != C_NONE) {
341,266✔
902

903
    // Retrieve cell index and storage type
904
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,705✔
905

906
    if (surf.bc_) {
258,705✔
907
      // Leave if cellto with vacuum boundary condition
908
      if (surf.bc_->type() == "vacuum" &&
184,448✔
909
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
910
        return;
11,953✔
911
      }
912

913
      // Leave if other boundary condition than vacuum
914
      if (surf.bc_->type() != "vacuum") {
140,281✔
915
        return;
120,020✔
916
      }
917
    }
918

919
    // Check if the cell of interest has been exited
920
    bool exited = false;
126,732✔
921
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,341✔
922
      if (p.cell_last(i) == cell_idx) {
208,609✔
923
        exited = true;
74,236✔
924
      }
925
    }
926

927
    // Check if the cell of interest has been entered
928
    bool entered = false;
126,732✔
929
    for (int i = 0; i < p.n_coord(); ++i) {
301,037✔
930
      if (p.coord(i).cell() == cell_idx) {
174,305✔
931
        entered = true;
59,097✔
932
      }
933
    }
934

935
    // Vacuum boundary conditions: return if cell is not exited
936
    if (surf.bc_) {
126,732✔
937
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
938
        return;
13,961✔
939
      }
940
    } else {
941

942
      // If we both enter and exit the cell of interest
943
      if (entered && exited) {
106,471✔
944
        return;
28,613✔
945
      }
946

947
      // If we did not enter nor exit the cell of interest
948
      if (!entered && !exited) {
77,858✔
949
        return;
14,351✔
950
      }
951

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

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

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

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