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

openmc-dev / openmc / 17770988861

16 Sep 2025 03:31PM UTC coverage: 85.176% (-0.03%) from 85.21%
17770988861

Pull #3425

github

web-flow
Merge a392c5ed3 into afd9d0607
Pull Request #3425: Multi-group capability for kinetics parameter calculations with Iterated Fission Probability

33 of 69 new or added lines in 3 files covered. (47.83%)

180 existing lines in 5 files now uncovered.

53045 of 62277 relevant lines covered (85.18%)

38148081.69 hits per line

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

93.05
/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,801,807,854✔
51
    case ParticleType::neutron:
1,732,949,383✔
52
      mass = MASS_NEUTRON_EV;
1,732,949,383✔
53
      break;
1,732,949,383✔
54
    case ParticleType::photon:
17,445,324✔
55
      mass = 0.0;
17,445,324✔
56
      break;
17,445,324✔
57
    case ParticleType::electron:
51,413,147✔
58
    case ParticleType::positron:
59
      mass = MASS_ELECTRON_EV;
51,413,147✔
60
      break;
51,413,147✔
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,801,807,854✔
64
           (this->E() + mass);
1,801,807,854✔
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,384,400✔
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,384,400✔
80
    return false;
51,363,226✔
81
  }
82

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

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

104
  // Convert signed index to a signed surface ID
105
  if (surface() == SURFACE_NONE) {
4,163,327✔
106
    bank.surf_id = SURFACE_NONE;
4,163,307✔
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,163,327✔
112

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

125
  // Copy attributes from source bank site
126
  type() = src->particle;
223,674,310✔
127
  wgt() = src->wgt;
223,674,310✔
128
  wgt_last() = src->wgt;
223,674,310✔
129
  r() = src->r;
223,674,310✔
130
  u() = src->u;
223,674,310✔
131
  r_born() = src->r;
223,674,310✔
132
  r_last_current() = src->r;
223,674,310✔
133
  r_last() = src->r;
223,674,310✔
134
  u_last() = src->u;
223,674,310✔
135
  if (settings::run_CE) {
223,674,310✔
136
    E() = src->E;
108,043,493✔
137
    g() = 0;
108,043,493✔
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();
223,674,310✔
144
  time() = src->time;
223,674,310✔
145
  time_last() = src->time;
223,674,310✔
146
  parent_nuclide() = src->parent_nuclide;
223,674,310✔
147

148
  // Convert signed surface ID to signed index
149
  if (src->surf_id != SURFACE_NONE) {
223,674,310✔
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
}
223,674,310✔
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)) {
220,586,758✔
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)
220,586,758✔
184
      cell_born() = lowest_coord().cell();
220,586,758✔
185

186
    // Initialize last cells from current cell
187
    for (int j = 0; j < n_coord(); ++j) {
457,424,463✔
188
      cell_last(j) = coord(j).cell();
236,837,705✔
189
    }
190
    n_coord_last() = n_coord();
220,586,758✔
191
  }
192

193
  // Write particle track.
194
  if (write_track())
2,147,483,647✔
195
    write_particle_track(*this);
10,840✔
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,707,438,517✔
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,366,561,319✔
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,286,380✔
220
    macro_xs().absorption = 0.0;
67,286,380✔
221
    macro_xs().fission = 0.0;
67,286,380✔
222
    macro_xs().nu_fission = 0.0;
67,286,380✔
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,413,147✔
234
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
235
    collision_distance() = INFINITY;
67,286,380✔
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 timed track-length tallies
256
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
257
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
258
  }
259

260
  // Score track-length tallies
261
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
262
    score_tracklength_tally(*this, distance);
1,300,260,259✔
263
  }
264

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

271
  // Score flux derivative accumulators for differential tallies.
272
  if (!model::active_tallies.empty()) {
2,147,483,647✔
273
    score_track_derivative(*this, distance);
1,468,093,984✔
274
  }
275

276
  // Set particle weight to zero if it hit the time boundary
277
  if (distance == distance_cutoff) {
2,147,483,647✔
278
    wgt() = 0.0;
224,928✔
279
  }
280
}
2,147,483,647✔
281

282
void Particle::event_cross_surface()
2,069,894,885✔
283
{
284
  // Saving previous cell data
285
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
286
    cell_last(j) = coord(j).cell();
2,147,483,647✔
287
  }
288
  n_coord_last() = n_coord();
2,069,894,885✔
289

290
  // Set surface that particle is on and adjust coordinate levels
291
  surface() = boundary().surface();
2,069,894,885✔
292
  n_coord() = boundary().coord_level();
2,069,894,885✔
293

294
  if (boundary().lattice_translation()[0] != 0 ||
2,069,894,885✔
295
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
296
      boundary().lattice_translation()[2] != 0) {
1,576,401,414✔
297
    // Particle crosses lattice boundary
298

299
    bool verbose = settings::verbosity >= 10 || trace();
679,876,415✔
300
    cross_lattice(*this, boundary(), verbose);
679,876,415✔
301
    event() = TallyEvent::LATTICE;
679,876,415✔
302
  } else {
303
    // Particle crosses surface
304
    const auto& surf {model::surfaces[surface_index()].get()};
1,390,018,470✔
305
    // If BC, add particle to surface source before crossing surface
306
    if (surf->surf_source_ && surf->bc_) {
1,390,018,470✔
307
      add_surf_source_to_bank(*this, *surf);
646,783,797✔
308
    }
309
    this->cross_surface(*surf);
1,390,018,470✔
310
    // If no BC, add particle to surface source after crossing surface
311
    if (surf->surf_source_ && !surf->bc_) {
1,390,018,461✔
312
      add_surf_source_to_bank(*this, *surf);
742,001,255✔
313
    }
314
    if (settings::weight_window_checkpoint_surface) {
1,390,018,461✔
315
      apply_weight_windows(*this);
396✔
316
    }
317
    event() = TallyEvent::SURFACE;
1,390,018,461✔
318
  }
319
  // Score cell to cell partial currents
320
  if (!model::active_surface_tallies.empty()) {
2,069,894,876✔
321
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
322
  }
323
}
2,069,894,876✔
324

325
void Particle::event_collide()
2,147,483,647✔
326
{
327
  // Score collision estimate of keff
328
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
329
      type() == ParticleType::neutron) {
2,146,528,853✔
330
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,107,206,669✔
331
  }
332

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

337
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
338
    score_surface_tally(*this, model::active_meshsurf_tallies);
68,565,871✔
339

340
  // Clear surface component
341
  surface() = SURFACE_NONE;
2,147,483,647✔
342

343
  if (settings::run_CE) {
2,147,483,647✔
344
    collision(*this);
750,472,529✔
345
  } else {
346
    collision_mg(*this);
1,781,763,302✔
347
  }
348

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

362
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
363
      type() == ParticleType::photon) {
16,918✔
364
    pht_collision_energy();
2,024✔
365
  }
366

367
  // Reset banked weight during collision
368
  n_bank() = 0;
2,147,483,647✔
369
  bank_second_E() = 0.0;
2,147,483,647✔
370
  wgt_bank() = 0.0;
2,147,483,647✔
371
  zero_delayed_bank();
2,147,483,647✔
372

373
  // Reset fission logical
374
  fission() = false;
2,147,483,647✔
375

376
  // Save coordinates for tallying purposes
377
  r_last_current() = r();
2,147,483,647✔
378

379
  // Set last material to none since cross sections will need to be
380
  // re-evaluated
381
  material_last() = C_NONE;
2,147,483,647✔
382

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

397
  // Score flux derivative accumulators for differential tallies.
398
  if (!model::active_tallies.empty())
2,147,483,647✔
399
    score_collision_derivative(*this);
646,921,558✔
400

401
#ifdef OPENMC_DAGMC_ENABLED
402
  history().reset();
230,349,108✔
403
#endif
404
}
2,147,483,647✔
405

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

416
  // Check for secondary particles if this particle is dead
417
  if (!alive()) {
2,147,483,647✔
418
    // Write final position for this particle
419
    if (write_track()) {
220,586,354✔
420
      write_particle_track(*this);
6,676✔
421
    }
422

423
    // If no secondary particles, break out of event loop
424
    if (secondary_bank().empty())
220,586,354✔
425
      return;
160,063,098✔
426

427
    from_source(&secondary_bank().back());
60,523,256✔
428
    secondary_bank().pop_back();
60,523,256✔
429
    n_event() = 0;
60,523,256✔
430
    bank_second_E() = 0.0;
60,523,256✔
431

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

449
        // Initialize last cells from current cell
450
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
451
          cell_last(j) = coord(j).cell();
605✔
452
        }
453
        n_coord_last() = n_coord();
605✔
454
      }
455
      pht_secondary_particles();
605✔
456
    }
457

458
    // Enter new particle in particle track file
459
    if (write_track())
60,523,256✔
460
      add_particle_track(*this);
5,606✔
461
  }
462
}
463

464
void Particle::event_death()
160,064,098✔
465
{
466
#ifdef OPENMC_DAGMC_ENABLED
467
  history().reset();
14,488,682✔
468
#endif
469

470
  // Finish particle track output.
471
  if (write_track()) {
160,064,098✔
472
    finalize_particle_track(*this);
1,070✔
473
  }
474

475
// Contribute tally reduction variables to global accumulator
476
#pragma omp atomic
88,301,334✔
477
  global_tally_absorption += keff_tally_absorption();
160,064,098✔
478
#pragma omp atomic
87,931,558✔
479
  global_tally_collision += keff_tally_collision();
160,064,098✔
480
#pragma omp atomic
88,042,621✔
481
  global_tally_tracklength += keff_tally_tracklength();
160,064,098✔
482
#pragma omp atomic
87,780,502✔
483
  global_tally_leakage += keff_tally_leakage();
160,064,098✔
484

485
  // Reset particle tallies once accumulated
486
  keff_tally_absorption() = 0.0;
160,064,098✔
487
  keff_tally_collision() = 0.0;
160,064,098✔
488
  keff_tally_tracklength() = 0.0;
160,064,098✔
489
  keff_tally_leakage() = 0.0;
160,064,098✔
490

491
  if (!model::active_pulse_height_tallies.empty()) {
160,064,098✔
492
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
493
  }
494

495
  // Record the number of progeny created by this particle.
496
  // This data will be used to efficiently sort the fission bank.
497
  if (settings::run_mode == RunMode::EIGENVALUE) {
160,064,098✔
498
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
134,686,700✔
499
    simulation::progeny_per_particle[offset] = n_progeny();
134,686,700✔
500
  }
501
}
160,064,098✔
502

503
void Particle::pht_collision_energy()
2,024✔
504
{
505
  // Adds the energy particles lose in a collision to the pulse-height
506

507
  // determine index of cell in pulse_height_cells
508
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
509
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
510

511
  if (it != model::pulse_height_cells.end()) {
2,024✔
512
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
513
    pht_storage()[index] += E_last() - E();
2,024✔
514

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

524
void Particle::pht_secondary_particles()
605✔
525
{
526
  // Removes the energy of secondary produced particles from the pulse-height
527

528
  // determine index of cell in pulse_height_cells
529
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
530
    model::pulse_height_cells.end(), cell_born());
605✔
531

532
  if (it != model::pulse_height_cells.end()) {
605✔
533
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
534
    pht_storage()[index] -= E();
605✔
535
  }
536
}
605✔
537

538
void Particle::cross_surface(const Surface& surf)
1,391,254,686✔
539
{
540

541
  if (settings::verbosity >= 10 || trace()) {
1,391,254,686✔
542
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
543
  }
544

545
// if we're crossing a CSG surface, make sure the DAG history is reset
546
#ifdef OPENMC_DAGMC_ENABLED
547
  if (surf.geom_type() == GeometryType::CSG)
123,271,684✔
548
    history().reset();
123,227,636✔
549
#endif
550

551
  // Handle any applicable boundary conditions.
552
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,038,516,948✔
553
      settings::run_mode != RunMode::VOLUME) {
647,262,262✔
554
    surf.bc_->handle_particle(*this, surf);
647,131,414✔
555
    return;
647,131,414✔
556
  }
557

558
  // ==========================================================================
559
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
560

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

574
    cell_instance() = 0;
36,997✔
575
    if (cell->distribcell_index_ >= 0)
36,997✔
576
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
35,996✔
577

578
    material() = cell->material(cell_instance());
36,997✔
579
    sqrtkT() = cell->sqrtkT(cell_instance());
36,997✔
580
    return;
36,997✔
581
  }
582
#endif
583

584
  bool verbose = settings::verbosity >= 10 || trace();
744,086,275✔
585
  if (neighbor_list_find_cell(*this, verbose)) {
744,086,275✔
586
    return;
744,058,256✔
587
  }
588

589
  // ==========================================================================
590
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
591

592
  // Remove lower coordinate levels
593
  n_coord() = 1;
28,019✔
594
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
595

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

602
    surface() = SURFACE_NONE;
5,744✔
603
    n_coord() = 1;
5,744✔
604
    r() += TINY_BIT * u();
5,744✔
605

606
    // Couldn't find next cell anywhere! This probably means there is an actual
607
    // undefined region in the geometry.
608

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

618
void Particle::cross_vacuum_bc(const Surface& surf)
33,187,195✔
619
{
620
  // Score any surface current tallies -- note that the particle is moved
621
  // forward slightly so that if the mesh boundary is on the surface, it is
622
  // still processed
623

624
  if (!model::active_meshsurf_tallies.empty()) {
33,187,195✔
625
    // TODO: Find a better solution to score surface currents than
626
    // physically moving the particle forward slightly
627

628
    r() += TINY_BIT * u();
1,021,265✔
629
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,021,265✔
630
  }
631

632
  // Score to global leakage tally
633
  keff_tally_leakage() += wgt();
33,187,195✔
634

635
  // Kill the particle
636
  wgt() = 0.0;
33,187,195✔
637

638
  // Display message
639
  if (settings::verbosity >= 10 || trace()) {
33,187,195✔
640
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
641
  }
642
}
33,187,195✔
643

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

653
  // Score surface currents since reflection causes the direction of the
654
  // particle to change. For surface filters, we need to score the tallies
655
  // twice, once before the particle's surface attribute has changed and
656
  // once after. For mesh surface filters, we need to artificially move
657
  // the particle slightly back in case the surface crossing is coincident
658
  // with a mesh boundary
659

660
  if (!model::active_surface_tallies.empty()) {
614,305,257✔
661
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
662
  }
663

664
  if (!model::active_meshsurf_tallies.empty()) {
614,305,257✔
665
    Position r {this->r()};
50,811,809✔
666
    this->r() -= TINY_BIT * u();
50,811,809✔
667
    score_surface_tally(*this, model::active_meshsurf_tallies);
50,811,809✔
668
    this->r() = r;
50,811,809✔
669
  }
670

671
  // Set the new particle direction
672
  u() = new_u;
614,305,257✔
673

674
  // Reassign particle's cell and surface
675
  coord(0).cell() = cell_last(0);
614,305,257✔
676
  surface() = -surface();
614,305,257✔
677

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

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

693
  // Diagnostic message
694
  if (settings::verbosity >= 10 || trace()) {
614,305,257✔
UNCOV
695
    write_message(1, "    Reflected from surface {}", surf.id_);
×
696
  }
697
}
698

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

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

721
  // Adjust the particle's location and direction.
722
  r() = new_r;
666,318✔
723
  u() = new_u;
666,318✔
724

725
  // Reassign particle's surface
726
  surface() = new_surface;
666,318✔
727

728
  // Figure out what cell particle is in now
729
  n_coord() = 1;
666,318✔
730

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

740
  // Set previous coordinate going slightly past surface crossing
741
  r_last_current() = r() + TINY_BIT * u();
666,318✔
742

743
  // Diagnostic message
744
  if (settings::verbosity >= 10 || trace()) {
666,318✔
UNCOV
745
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
746
  }
747
}
748

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

762
  // Count the total number of simulated particles (on this processor)
763
  auto n = simulation::current_batch * settings::gen_per_batch *
5,744✔
764
           simulation::work_per_rank;
765

766
  // Abort the simulation if the maximum number of lost particles has been
767
  // reached
768
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,744✔
769
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
770
    fatal_error("Maximum number of lost particles has been reached.");
9✔
771
  }
772
}
5,735✔
773

774
void Particle::write_restart() const
324✔
775
{
776
  // Dont write another restart file if in particle restart mode
777
  if (settings::run_mode == RunMode::PARTICLE)
324✔
778
    return;
22✔
779

780
  // Set up file name
781
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
782
    simulation::current_batch, id());
565✔
783

784
#pragma omp critical(WriteParticleRestart)
314✔
785
  {
786
    // Create file
787
    hid_t file_id = file_open(filename, 'w');
302✔
788

789
    // Write filetype and version info
790
    write_attribute(file_id, "filetype", "particle restart");
302✔
791
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
302✔
792
    write_attribute(file_id, "openmc_version", VERSION);
302✔
793
#ifdef GIT_SHA1
794
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
795
#endif
796

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

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

841
    // Close file
842
    file_close(file_id);
302✔
843
  } // #pragma omp critical
844
}
302✔
845

846
void Particle::update_neutron_xs(
2,147,483,647✔
847
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
848
{
849
  // Get microscopic cross section cache
850
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
851

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

857
    // If NCrystal is being used, update micro cross section cache
858
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
859
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
860
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
861
    }
862
  }
863
}
2,147,483,647✔
864

865
//==============================================================================
866
// Non-method functions
867
//==============================================================================
868

869
std::string particle_type_to_str(ParticleType type)
3,258,770✔
870
{
871
  switch (type) {
3,258,770✔
872
  case ParticleType::neutron:
2,464,228✔
873
    return "neutron";
2,464,228✔
874
  case ParticleType::photon:
794,278✔
875
    return "photon";
794,278✔
876
  case ParticleType::electron:
132✔
877
    return "electron";
132✔
878
  case ParticleType::positron:
132✔
879
    return "positron";
132✔
880
  }
UNCOV
881
  UNREACHABLE();
×
882
}
883

884
ParticleType str_to_particle_type(std::string str)
3,228,463✔
885
{
886
  if (str == "neutron") {
3,228,463✔
887
    return ParticleType::neutron;
745,038✔
888
  } else if (str == "photon") {
2,483,425✔
889
    return ParticleType::photon;
2,483,339✔
890
  } else if (str == "electron") {
86✔
891
    return ParticleType::electron;
43✔
892
  } else if (str == "positron") {
43✔
893
    return ParticleType::positron;
43✔
894
  } else {
UNCOV
895
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
896
  }
897
}
898

899
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,388,785,052✔
900
{
901
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
902
      simulation::surf_source_bank.full()) {
1,095,146,743✔
903
    return;
1,388,656,287✔
904
  }
905

906
  // If a cell/cellfrom/cellto parameter is defined
907
  if (settings::ssw_cell_id != C_NONE) {
341,267✔
908

909
    // Retrieve cell index and storage type
910
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,706✔
911

912
    if (surf.bc_) {
258,706✔
913
      // Leave if cellto with vacuum boundary condition
914
      if (surf.bc_->type() == "vacuum" &&
184,448✔
915
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
916
        return;
11,953✔
917
      }
918

919
      // Leave if other boundary condition than vacuum
920
      if (surf.bc_->type() != "vacuum") {
140,281✔
921
        return;
120,020✔
922
      }
923
    }
924

925
    // Check if the cell of interest has been exited
926
    bool exited = false;
126,733✔
927
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,343✔
928
      if (p.cell_last(i) == cell_idx) {
208,610✔
929
        exited = true;
74,235✔
930
      }
931
    }
932

933
    // Check if the cell of interest has been entered
934
    bool entered = false;
126,733✔
935
    for (int i = 0; i < p.n_coord(); ++i) {
301,039✔
936
      if (p.coord(i).cell() == cell_idx) {
174,306✔
937
        entered = true;
59,099✔
938
      }
939
    }
940

941
    // Vacuum boundary conditions: return if cell is not exited
942
    if (surf.bc_) {
126,733✔
943
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
944
        return;
13,961✔
945
      }
946
    } else {
947

948
      // If we both enter and exit the cell of interest
949
      if (entered && exited) {
106,472✔
950
        return;
28,613✔
951
      }
952

953
      // If we did not enter nor exit the cell of interest
954
      if (!entered && !exited) {
77,859✔
955
        return;
14,351✔
956
      }
957

958
      // If cellfrom and the cell before crossing is not the cell of
959
      // interest
960
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,508✔
961
        return;
11,566✔
962
      }
963

964
      // If cellto and the cell after crossing is not the cell of interest
965
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
51,942✔
966
        return;
12,038✔
967
      }
968
    }
969
  }
970

971
  SourceSite site;
128,765✔
972
  site.r = p.r();
128,765✔
973
  site.u = p.u();
128,765✔
974
  site.E = p.E();
128,765✔
975
  site.time = p.time();
128,765✔
976
  site.wgt = p.wgt();
128,765✔
977
  site.delayed_group = p.delayed_group();
128,765✔
978
  site.surf_id = surf.id_;
128,765✔
979
  site.particle = p.type();
128,765✔
980
  site.parent_id = p.id();
128,765✔
981
  site.progeny_id = p.n_progeny();
128,765✔
982
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
128,765✔
983
}
984

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