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

openmc-dev / openmc / 22670832759

04 Mar 2026 01:11PM UTC coverage: 81.478% (-0.08%) from 81.556%
22670832759

Pull #3847

github

web-flow
Merge 9853f1f4b into 0ab46dfa3
Pull Request #3847: Implementation of forced collision variance reduction scheme

17565 of 25304 branches covered (69.42%)

Branch coverage included in aggregate %.

78 of 87 new or added lines in 5 files covered. (89.66%)

66 existing lines in 10 files now uncovered.

57934 of 67358 relevant lines covered (86.01%)

61109854.28 hits per line

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

87.53
/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_dist.h"
26
#include "openmc/random_lcg.h"
27
#include "openmc/settings.h"
28
#include "openmc/simulation.h"
29
#include "openmc/source.h"
30
#include "openmc/surface.h"
31
#include "openmc/tallies/derivative.h"
32
#include "openmc/tallies/tally.h"
33
#include "openmc/tallies/tally_scoring.h"
34
#include "openmc/track_output.h"
35
#include "openmc/weight_windows.h"
36

37
#ifdef OPENMC_DAGMC_ENABLED
38
#include "DagMC.hpp"
39
#endif
40

41
namespace openmc {
42

43
//==============================================================================
44
// Particle implementation
45
//==============================================================================
46

47
double Particle::speed() const
2,147,483,647✔
48
{
49
  if (settings::run_CE) {
2,147,483,647✔
50
    // Determine mass in eV/c^2
51
    double mass;
2,147,483,647✔
52
    switch (type().pdg_number()) {
2,147,483,647✔
53
    case PDG_NEUTRON:
54
      mass = MASS_NEUTRON_EV;
55
    case PDG_ELECTRON:
56
    case PDG_POSITRON:
57
      mass = MASS_ELECTRON_EV;
2,147,483,647✔
58
    default:
2,147,483,647✔
59
      mass = this->type().mass() * AMU_EV;
2,147,483,647✔
60
    }
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)) /
2,147,483,647✔
64
           (this->E() + mass);
2,147,483,647✔
65
  } else {
66
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
67
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
68
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
69
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
70
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
71
  }
72
}
73

74
bool Particle::create_secondary(
2,147,483,647✔
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
  int idx = type.transport_index();
2,147,483,647✔
80
  if (idx == C_NONE) {
2,147,483,647!
81
    return false;
82
  }
83
  if (E < settings::energy_cutoff[idx]) {
2,147,483,647✔
84
    return false;
85
  }
86

87
  // Increment number of secondaries created (for ParticleProductionFilter)
88
  n_secondaries()++;
2,147,483,647✔
89

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

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

111
  // Convert signed index to a signed surface ID
112
  if (surface() == SURFACE_NONE) {
2,147,483,647✔
113
    bank.surf_id = SURFACE_NONE;
2,147,483,647✔
114
  } else {
115
    int surf_id = model::surfaces[surface_index()]->id_;
2,147,483,647✔
116
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
2,147,483,647✔
117
  }
118
}
2,147,483,647✔
119

120
void Particle::from_source(const SourceSite* src)
2,147,483,647✔
121
{
122
  // Reset some attributes
123
  clear();
2,147,483,647✔
124
  surface() = SURFACE_NONE;
2,147,483,647✔
125
  cell_born() = C_NONE;
2,147,483,647✔
126
  material() = C_NONE;
2,147,483,647✔
127
  n_collision() = 0;
2,147,483,647✔
128
  fission() = false;
2,147,483,647✔
129
  zero_flux_derivs();
2,147,483,647✔
130
  lifetime() = 0.0;
2,147,483,647✔
131
#ifdef OPENMC_DAGMC_ENABLED
132
  history().reset();
1,961,348,172✔
133
#endif
134

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

159
  // Convert signed surface ID to signed index
160
  if (src->surf_id != SURFACE_NONE) {
2,147,483,647✔
161
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
2,147,483,647✔
162
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
2,147,483,647✔
163
  }
164
}
2,147,483,647✔
165

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

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

178
  // Reset event variables
179
  event() = TallyEvent::KILL;
2,147,483,647✔
180
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
181
  event_mt() = REACTION_NONE;
2,147,483,647✔
182

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

193
    // Set birth cell attribute
194
    if (cell_born() == C_NONE)
2,147,483,647!
195
      cell_born() = lowest_coord().cell();
2,147,483,647✔
196

197
    // Initialize last cells from current cell
198
    for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
199
      cell_last(j) = coord(j).cell();
2,147,483,647✔
200
    }
201
    n_coord_last() = n_coord();
2,147,483,647✔
202
  }
203

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

208
  if (settings::check_overlaps)
2,147,483,647!
209
    check_cell_overlap(*this);
×
210

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

227
      // Update the particle's group while we know we are multi-group
228
      g_last() = g();
2,063,937,414✔
229
    }
230
  } else {
231
    macro_xs().total = 0.0;
2,147,483,647✔
232
    macro_xs().absorption = 0.0;
2,147,483,647✔
233
    macro_xs().fission = 0.0;
2,147,483,647✔
234
    macro_xs().nu_fission = 0.0;
2,147,483,647✔
235
  }
236
}
237

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

243
  bool forced_collision = false;
2,147,483,647✔
244

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

250
  // Sample a distance to collision
251
  if (type() == ParticleType::electron() ||
2,147,483,647✔
252
      type() == ParticleType::positron()) {
2,147,483,647✔
253
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
2,147,483,647!
254
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
255
    collision_distance() = INFINITY;
2,147,483,647✔
256
  } else {
257
    if (simulation::forced_collision &&
2,147,483,647!
258
        boundary().distance() <= distance_cutoff &&
2,147,483,647!
259
        boundary().distance() > TINY_BIT) {
2,147,483,647✔
260
      auto c_id = coord(n_coord() - 1).cell();
2,147,483,647✔
261
      auto& c = model::cells[c_id];
2,147,483,647✔
262
      if (c->forced_collision(cell_instance())) {
2,147,483,647!
263
        if (cell_last(n_coord_last() - 1) != c_id)
2,147,483,647✔
264
          forced_collision = true;
2,147,483,647✔
265
      }
266
    }
267
    double U;
2,147,483,647✔
268
    if (forced_collision) {
2,147,483,647✔
269
      U = uniform_distribution(
2,147,483,647✔
270
        std::exp(-boundary().distance() * macro_xs().total), 1, current_seed());
2,147,483,647✔
271
    } else {
272
      U = prn(current_seed());
2,147,483,647✔
273
    }
274
    collision_distance() = -std::log(U) / macro_xs().total;
2,147,483,647✔
275
  }
276

277
  double distance;
2,147,483,647✔
278
  double dt;
2,147,483,647✔
279

280
  if (forced_collision) {
2,147,483,647✔
281
    distance = boundary().distance() - TINY_BIT;
2,147,483,647✔
282
    double uncollided_wgt = wgt() * std::exp(-distance * macro_xs().total);
2,147,483,647✔
283
    double collided_wgt = wgt() * -expm1(-distance * macro_xs().total);
2,147,483,647✔
284
    wgt() = uncollided_wgt;
2,147,483,647✔
285
    dt = distance / speed;
2,147,483,647✔
286
    this->move_distance(distance);
2,147,483,647✔
287
    this->time() += dt;
2,147,483,647✔
288
    this->lifetime() += dt;
2,147,483,647✔
289

290
    // Score timed track-length tallies
291
    if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647!
NEW
292
      score_timed_tracklength_tally(*this, distance);
×
293
    }
294

295
    // Score track-length tallies
296
    if (!model::active_tracklength_tallies.empty()) {
2,147,483,647!
NEW
297
      score_tracklength_tally(*this, distance);
×
298
    }
299

300
    // Score track-length estimate of k-eff
301
    if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647!
NEW
302
      keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
×
303
    }
304

305
    // Score flux derivative accumulators for differential tallies.
306
    if (!model::active_tallies.empty()) {
2,147,483,647!
307
      score_track_derivative(*this, distance);
2,147,483,647✔
308
    }
309

310
    split(uncollided_wgt);
2,147,483,647✔
311

312
    this->move_distance(-distance);
2,147,483,647✔
313
    this->time() -= dt;
2,147,483,647✔
314
    this->lifetime() -= dt;
2,147,483,647✔
315
    wgt() = collided_wgt;
2,147,483,647✔
316
  }
317

318
  // Select smaller of the three distances
319
  distance =
2,147,483,647✔
320
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
321

322
  // Advance particle in space and time
323
  this->move_distance(distance);
2,147,483,647✔
324
  dt = distance / speed;
2,147,483,647✔
325
  this->time() += dt;
2,147,483,647✔
326
  this->lifetime() += dt;
2,147,483,647✔
327

328
  // Score timed track-length tallies
329
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
330
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
331
  }
332

333
  // Score track-length tallies
334
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
335
    score_tracklength_tally(*this, distance);
1,721,787,277✔
336
  }
337

338
  // Score track-length estimate of k-eff
339
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
340
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
341
  }
342

343
  // Score flux derivative accumulators for differential tallies.
344
  if (!model::active_tallies.empty()) {
2,147,483,647✔
345
    score_track_derivative(*this, distance);
2,147,483,647✔
346
  }
347

348
  // Set particle weight to zero if it hit the time boundary
349
  if (distance == distance_cutoff) {
2,147,483,647✔
350
    wgt() = 0.0;
224,928✔
351
  }
352
}
2,147,483,647✔
353

354
void Particle::event_cross_surface()
2,147,483,647✔
355
{
356
  // Saving previous cell data
357
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
358
    cell_last(j) = coord(j).cell();
2,147,483,647✔
359
  }
360
  n_coord_last() = n_coord();
2,147,483,647✔
361

362
  // Set surface that particle is on and adjust coordinate levels
363
  surface() = boundary().surface();
2,147,483,647✔
364
  n_coord() = boundary().coord_level();
2,147,483,647✔
365

366
  const auto& surf {*model::surfaces[surface_index()].get()};
2,147,483,647✔
367

368
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
369
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
370
      boundary().lattice_translation()[2] != 0) {
2,147,483,647✔
371
    // Particle crosses lattice boundary
372

373
    bool verbose = settings::verbosity >= 10 || trace();
750,250,876!
374
    cross_lattice(*this, boundary(), verbose);
750,250,876✔
375
    event() = TallyEvent::LATTICE;
750,250,876✔
376
  } else {
377
    // Particle crosses surface
378
    // If BC, add particle to surface source before crossing surface
379
    if (surf.surf_source_ && surf.bc_) {
2,147,483,647✔
380
      add_surf_source_to_bank(*this, surf);
2,147,483,647✔
381
    }
382
    this->cross_surface(surf);
2,147,483,647✔
383
    // If no BC, add particle to surface source after crossing surface
384
    if (surf.surf_source_ && !surf.bc_) {
2,147,483,647✔
385
      add_surf_source_to_bank(*this, surf);
2,147,483,647✔
386
    }
387
    if (settings::weight_window_checkpoint_surface) {
2,147,483,647✔
388
      apply_weight_windows(*this);
74,912✔
389
    }
390
    event() = TallyEvent::SURFACE;
2,147,483,647✔
391
  }
392
  // Score cell to cell partial currents
393
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
394
    score_surface_tally(*this, model::active_surface_tallies, surf);
34,931,567✔
395
  }
396
}
2,147,483,647✔
397

398
void Particle::event_collide()
2,147,483,647✔
399
{
400

401
  // Score collision estimate of keff
402
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
403
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,139,390,696✔
404
  }
405

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

410
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
411
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
412

413
  // Clear surface component
414
  surface() = SURFACE_NONE;
2,147,483,647✔
415

416
  if (settings::run_CE) {
2,147,483,647✔
417
    collision(*this);
2,147,483,647✔
418
  } else {
419
    collision_mg(*this);
1,783,060,477✔
420
  }
421

422
  // Collision track feature to recording particle interaction
423
  if (settings::collision_track) {
2,147,483,647✔
424
    collision_track_record(*this);
150,087✔
425
  }
426

427
  // Score collision estimator tallies -- this is done after a collision
428
  // has occurred rather than before because we need information on the
429
  // outgoing energy for any tallies with an outgoing energy filter
430
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
431
    score_collision_tally(*this);
2,147,483,647✔
432
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
433
    if (settings::run_CE) {
406,034,945✔
434
      score_analog_tally_ce(*this);
404,826,683✔
435
    } else {
436
      score_analog_tally_mg(*this);
1,208,262✔
437
    }
438
  }
439

440
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
441
    pht_collision_energy();
2,024✔
442
  }
443

444
  // Reset banked weight during collision
445
  n_bank() = 0;
2,147,483,647✔
446
  bank_second_E() = 0.0;
2,147,483,647✔
447
  wgt_bank() = 0.0;
2,147,483,647✔
448

449
  // Clear number of secondaries in this collision. This is
450
  // distinct from the number of created neutrons n_bank() above!
451
  n_secondaries() = 0;
2,147,483,647✔
452

453
  zero_delayed_bank();
2,147,483,647✔
454

455
  // Reset fission logical
456
  fission() = false;
2,147,483,647✔
457

458
  // Save coordinates for tallying purposes
459
  r_last_current() = r();
2,147,483,647✔
460

461
  // Set last material to none since cross sections will need to be
462
  // re-evaluated
463
  material_last() = C_NONE;
2,147,483,647✔
464

465
  // Set all directions to base level -- right now, after a collision, only
466
  // the base level directions are changed
467
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
468
    if (coord(j + 1).rotated()) {
161,247,365✔
469
      // If next level is rotated, apply rotation matrix
470
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
471
      const auto& u {coord(j).u()};
10,426,614✔
472
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
473
    } else {
474
      // Otherwise, copy this level's direction
475
      coord(j + 1).u() = coord(j).u();
150,820,751✔
476
    }
477
  }
478

479
  // Score flux derivative accumulators for differential tallies.
480
  if (!model::active_tallies.empty())
2,147,483,647✔
481
    score_collision_derivative(*this);
2,147,483,647✔
482

483
#ifdef OPENMC_DAGMC_ENABLED
484
  history().reset();
2,147,483,647✔
485
#endif
486
}
2,147,483,647✔
487

488
void Particle::event_revive_from_secondary()
2,147,483,647✔
489
{
490
  // If particle has too many events, display warning and kill it
491
  ++n_event();
2,147,483,647✔
492
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
493
    warning("Particle " + std::to_string(id()) +
×
494
            " underwent maximum number of events.");
495
    wgt() = 0.0;
×
496
  }
497

498
  // Check for secondary particles if this particle is dead
499
  if (!alive()) {
2,147,483,647✔
500
    // Write final position for this particle
501
    if (write_track()) {
2,147,483,647✔
502
      write_particle_track(*this);
6,244✔
503
    }
504

505
    // If no secondary particles, break out of event loop
506
    if (secondary_bank().empty())
2,147,483,647✔
507
      return;
508

509
    from_source(&secondary_bank().back());
2,147,483,647✔
510
    secondary_bank().pop_back();
2,147,483,647✔
511
    n_event() = 0;
2,147,483,647✔
512
    bank_second_E() = 0.0;
2,147,483,647✔
513

514
    // Subtract secondary particle energy from interim pulse-height results
515
    if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
516
        this->type().is_photon()) {
15,499✔
517
      // Since the birth cell of the particle has not been set we
518
      // have to determine it before the energy of the secondary particle can be
519
      // removed from the pulse-height of this cell.
520
      if (lowest_coord().cell() == C_NONE) {
605!
521
        bool verbose = settings::verbosity >= 10 || trace();
605!
522
        if (!exhaustive_find_cell(*this, verbose)) {
605!
523
          mark_as_lost("Could not find the cell containing particle " +
×
524
                       std::to_string(id()));
×
525
          return;
×
526
        }
527
        // Set birth cell attribute
528
        if (cell_born() == C_NONE)
605!
529
          cell_born() = lowest_coord().cell();
605✔
530

531
        // Initialize last cells from current cell
532
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
533
          cell_last(j) = coord(j).cell();
605✔
534
        }
535
        n_coord_last() = n_coord();
605✔
536
      }
537
      pht_secondary_particles();
605✔
538
    }
539

540
    // Enter new particle in particle track file
541
    if (write_track())
2,147,483,647✔
542
      add_particle_track(*this);
5,234✔
543
  }
544
}
545

546
void Particle::event_death()
168,803,081✔
547
{
548
#ifdef OPENMC_DAGMC_ENABLED
549
  history().reset();
15,422,395✔
550
#endif
551

552
  // Finish particle track output.
553
  if (write_track()) {
168,803,081✔
554
    finalize_particle_track(*this);
1,010✔
555
  }
556

557
// Contribute tally reduction variables to global accumulator
558
#pragma omp atomic
93,128,395✔
559
  global_tally_absorption += keff_tally_absorption();
168,803,081✔
560
#pragma omp atomic
93,101,479✔
561
  global_tally_collision += keff_tally_collision();
168,803,081✔
562
#pragma omp atomic
93,048,162✔
563
  global_tally_tracklength += keff_tally_tracklength();
168,803,081✔
564
#pragma omp atomic
92,339,683✔
565
  global_tally_leakage += keff_tally_leakage();
168,803,081✔
566

567
  // Reset particle tallies once accumulated
568
  keff_tally_absorption() = 0.0;
168,803,081✔
569
  keff_tally_collision() = 0.0;
168,803,081✔
570
  keff_tally_tracklength() = 0.0;
168,803,081✔
571
  keff_tally_leakage() = 0.0;
168,803,081✔
572

573
  if (!model::active_pulse_height_tallies.empty()) {
168,803,081✔
574
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
575
  }
576

577
  // Record the number of progeny created by this particle.
578
  // This data will be used to efficiently sort the fission bank.
579
  if (settings::run_mode == RunMode::EIGENVALUE) {
168,803,081✔
580
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
141,534,700✔
581
    simulation::progeny_per_particle[offset] = n_progeny();
141,534,700✔
582
  }
583
}
168,803,081✔
584

585
void Particle::pht_collision_energy()
2,024✔
586
{
587
  // Adds the energy particles lose in a collision to the pulse-height
588

589
  // determine index of cell in pulse_height_cells
590
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
591
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024!
592

593
  if (it != model::pulse_height_cells.end()) {
2,024!
594
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
595
    pht_storage()[index] += E_last() - E();
2,024✔
596

597
    // If the energy of the particle is below the cutoff, it will not be sampled
598
    // so its energy is added to the pulse-height in the cell
599
    int photon = ParticleType::photon().transport_index();
2,024✔
600
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
601
      pht_storage()[index] += E();
825✔
602
    }
603
  }
604
}
2,024✔
605

606
void Particle::pht_secondary_particles()
605✔
607
{
608
  // Removes the energy of secondary produced particles from the pulse-height
609

610
  // determine index of cell in pulse_height_cells
611
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
612
    model::pulse_height_cells.end(), cell_born());
605!
613

614
  if (it != model::pulse_height_cells.end()) {
605!
615
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
616
    pht_storage()[index] -= E();
605✔
617
  }
618
}
605✔
619

620
void Particle::cross_surface(const Surface& surf)
2,147,483,647✔
621
{
622

623
  if (settings::verbosity >= 10 || trace()) {
2,147,483,647✔
624
    write_message(1, "    Crossing surface {}", surf.id_);
66✔
625
  }
626

627
// if we're crossing a CSG surface, make sure the DAG history is reset
628
#ifdef OPENMC_DAGMC_ENABLED
629
  if (surf.geom_type() == GeometryType::CSG)
1,610,011,705✔
630
    history().reset();
1,609,954,546✔
631
#endif
632

633
  // Handle any applicable boundary conditions.
634
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
635
      settings::run_mode != RunMode::VOLUME) {
636
    surf.bc_->handle_particle(*this, surf);
2,147,483,647✔
637
    return;
2,147,483,647✔
638
  }
639

640
  // ==========================================================================
641
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
642

643
#ifdef OPENMC_DAGMC_ENABLED
644
  // in DAGMC, we know what the next cell should be
645
  if (surf.geom_type() == GeometryType::DAG) {
792,846,693✔
646
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,350✔
647
                       lowest_coord().universe()) -
46,350✔
648
                     1;
46,350✔
649
    // save material, temperature, and density multiplier
650
    material_last() = material();
46,350✔
651
    sqrtkT_last() = sqrtkT();
46,350✔
652
    density_mult_last() = density_mult();
46,350✔
653
    // set new cell value
654
    lowest_coord().cell() = i_cell;
46,350✔
655
    auto& cell = model::cells[i_cell];
46,350✔
656

657
    cell_instance() = 0;
46,350✔
658
    if (cell->distribcell_index_ >= 0)
46,350✔
659
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,326✔
660

661
    material() = cell->material(cell_instance());
46,350!
662
    sqrtkT() = cell->sqrtkT(cell_instance());
46,350!
663
    density_mult() = cell->density_mult(cell_instance());
46,350✔
664
    return;
46,350✔
665
  }
666
#endif
667

668
  bool verbose = settings::verbosity >= 10 || trace();
2,147,483,647!
669
  if (neighbor_list_find_cell(*this, verbose)) {
2,147,483,647✔
670
    return;
671
  }
672

673
  // ==========================================================================
674
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
675

676
  // Remove lower coordinate levels
677
  n_coord() = 1;
29,911✔
678
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
679

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

686
    surface() = SURFACE_NONE;
5,799✔
687
    n_coord() = 1;
5,799✔
688
    r() += TINY_BIT * u();
5,799✔
689

690
    // Couldn't find next cell anywhere! This probably means there is an actual
691
    // undefined region in the geometry.
692

693
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
694
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
695
                   " crossed surface " + std::to_string(surf.id_) +
17,388✔
696
                   " it could not be located in any cell and it did not leak.");
697
      return;
5,790✔
698
    }
699
  }
700
}
701

702
void Particle::cross_vacuum_bc(const Surface& surf)
2,147,483,647✔
703
{
704
  // Score any surface current tallies -- note that the particle is moved
705
  // forward slightly so that if the mesh boundary is on the surface, it is
706
  // still processed
707

708
  if (!model::active_meshsurf_tallies.empty()) {
2,147,483,647✔
709
    // TODO: Find a better solution to score surface currents than
710
    // physically moving the particle forward slightly
711

712
    r() += TINY_BIT * u();
937,222✔
713
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
714
  }
715

716
  // Score to global leakage tally
717
  keff_tally_leakage() += wgt();
2,147,483,647✔
718

719
  // Kill the particle
720
  wgt() = 0.0;
2,147,483,647✔
721

722
  // Display message
723
  if (settings::verbosity >= 10 || trace()) {
2,147,483,647!
724
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
725
  }
726
}
2,147,483,647✔
727

728
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
684,318,903✔
729
{
730
  // Do not handle reflective boundary conditions on lower universes
731
  if (n_coord() != 1) {
684,318,903!
732
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
733
                 " off surface in a lower universe.");
734
    return;
×
735
  }
736

737
  // Score surface currents since reflection causes the direction of the
738
  // particle to change. For surface filters, we need to score the tallies
739
  // twice, once before the particle's surface attribute has changed and
740
  // once after. For mesh surface filters, we need to artificially move
741
  // the particle slightly back in case the surface crossing is coincident
742
  // with a mesh boundary
743

744
  if (!model::active_surface_tallies.empty()) {
684,318,903✔
745
    score_surface_tally(*this, model::active_surface_tallies, surf);
285,021✔
746
  }
747

748
  if (!model::active_meshsurf_tallies.empty()) {
684,318,903✔
749
    Position r {this->r()};
46,885,487✔
750
    this->r() -= TINY_BIT * u();
46,885,487✔
751
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
752
    this->r() = r;
46,885,487✔
753
  }
754

755
  // Set the new particle direction
756
  u() = new_u;
684,318,903✔
757

758
  // Reassign particle's cell and surface
759
  coord(0).cell() = cell_last(0);
684,318,903✔
760
  surface() = -surface();
684,318,903✔
761

762
  // If a reflective surface is coincident with a lattice or universe
763
  // boundary, it is necessary to redetermine the particle's coordinates in
764
  // the lower universes.
765
  // (unless we're using a dagmc model, which has exactly one universe)
766
  n_coord() = 1;
684,318,903✔
767
  if (surf.geom_type() != GeometryType::DAG &&
1,368,635,048!
768
      !neighbor_list_find_cell(*this)) {
684,316,145✔
769
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
770
                 std::to_string(surf.id_) + ".");
×
771
    return;
×
772
  }
773

774
  // Set previous coordinate going slightly past surface crossing
775
  r_last_current() = r() + TINY_BIT * u();
684,318,903✔
776

777
  // Diagnostic message
778
  if (settings::verbosity >= 10 || trace()) {
684,318,903!
779
    write_message(1, "    Reflected from surface {}", surf.id_);
×
780
  }
781
}
782

783
void Particle::cross_periodic_bc(
2,246,030✔
784
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
785
{
786
  // Do not handle periodic boundary conditions on lower universes
787
  if (n_coord() != 1) {
2,246,030!
788
    mark_as_lost(
×
789
      "Cannot transfer particle " + std::to_string(id()) +
×
790
      " across surface in a lower universe. Boundary conditions must be "
791
      "applied to root universe.");
792
    return;
×
793
  }
794

795
  // Score surface currents since reflection causes the direction of the
796
  // particle to change -- artificially move the particle slightly back in
797
  // case the surface crossing is coincident with a mesh boundary
798
  if (!model::active_meshsurf_tallies.empty()) {
2,246,030!
799
    Position r {this->r()};
×
800
    this->r() -= TINY_BIT * u();
×
801
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
802
    this->r() = r;
×
803
  }
804

805
  // Adjust the particle's location and direction.
806
  r() = new_r;
2,246,030✔
807
  u() = new_u;
2,246,030✔
808

809
  // Reassign particle's surface
810
  surface() = new_surface;
2,246,030✔
811

812
  // Figure out what cell particle is in now
813
  n_coord() = 1;
2,246,030✔
814

815
  if (!neighbor_list_find_cell(*this)) {
2,246,030!
816
    mark_as_lost("Couldn't find particle after hitting periodic "
×
817
                 "boundary on surface " +
×
818
                 std::to_string(surf.id_) + ".");
×
819
    return;
×
820
  }
821

822
  // Set previous coordinate going slightly past surface crossing
823
  r_last_current() = r() + TINY_BIT * u();
2,246,030✔
824

825
  // Diagnostic message
826
  if (settings::verbosity >= 10 || trace()) {
2,246,030!
827
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
828
  }
829
}
830

831
void Particle::mark_as_lost(const char* message)
5,832✔
832
{
833
  // Print warning and write lost particle file
834
  warning(message);
5,832✔
835
  if (settings::max_write_lost_particles < 0 ||
5,832✔
836
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
837
    write_restart();
407✔
838
  }
839
  // Increment number of lost particles
840
  wgt() = 0.0;
5,832✔
841
#pragma omp atomic
3,172✔
842
  simulation::n_lost_particles += 1;
2,660✔
843

844
  // Count the total number of simulated particles (on this processor)
845
  auto n = simulation::current_batch * settings::gen_per_batch *
5,832✔
846
           simulation::work_per_rank;
847

848
  // Abort the simulation if the maximum number of lost particles has been
849
  // reached
850
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,832✔
851
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
852
    fatal_error("Maximum number of lost particles has been reached.");
9✔
853
  }
854
}
5,823✔
855

856
void Particle::write_restart() const
407✔
857
{
858
  // Dont write another restart file if in particle restart mode
859
  if (settings::run_mode == RunMode::PARTICLE)
407✔
860
    return;
22✔
861

862
  // Set up file name
863
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
385✔
864
    simulation::current_batch, id());
385✔
865

866
#pragma omp critical(WriteParticleRestart)
205✔
867
  {
385✔
868
    // Create file
869
    hid_t file_id = file_open(filename, 'w');
385✔
870

871
    // Write filetype and version info
872
    write_attribute(file_id, "filetype", "particle restart");
385✔
873
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
385✔
874
    write_attribute(file_id, "openmc_version", VERSION);
385✔
875
#ifdef GIT_SHA1
876
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
877
#endif
878

879
    // Write data to file
880
    write_dataset(file_id, "current_batch", simulation::current_batch);
385✔
881
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
385✔
882
    write_dataset(file_id, "current_generation", simulation::current_gen);
385✔
883
    write_dataset(file_id, "n_particles", settings::n_particles);
385✔
884
    switch (settings::run_mode) {
385!
885
    case RunMode::FIXED_SOURCE:
253✔
886
      write_dataset(file_id, "run_mode", "fixed source");
253✔
887
      break;
133✔
888
    case RunMode::EIGENVALUE:
132✔
889
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
890
      break;
72✔
891
    case RunMode::PARTICLE:
×
892
      write_dataset(file_id, "run_mode", "particle restart");
×
893
      break;
894
    default:
895
      break;
896
    }
897
    write_dataset(file_id, "id", id());
385✔
898
    write_dataset(file_id, "type", type().pdg_number());
385✔
899

900
    int64_t i = current_work();
385✔
901
    if (settings::run_mode == RunMode::EIGENVALUE) {
385✔
902
      // take source data from primary bank for eigenvalue simulation
903
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
904
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
905
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
906
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
907
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
908
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
253!
909
      // re-sample using rng random number seed used to generate source particle
910
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
253✔
911
                     settings::n_particles +
253✔
912
                   simulation::work_index[mpi::rank] + i;
253✔
913
      uint64_t seed = init_seed(id, STREAM_SOURCE);
253✔
914
      // re-sample source site
915
      auto site = sample_external_source(&seed);
253✔
916
      write_dataset(file_id, "weight", site.wgt);
253✔
917
      write_dataset(file_id, "energy", site.E);
253✔
918
      write_dataset(file_id, "xyz", site.r);
253✔
919
      write_dataset(file_id, "uvw", site.u);
253✔
920
      write_dataset(file_id, "time", site.time);
253✔
921
    }
922

923
    // Close file
924
    file_close(file_id);
385✔
925
  } // #pragma omp critical
926
}
385✔
927

928
void Particle::update_neutron_xs(
2,147,483,647✔
929
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
930
{
931
  // Get microscopic cross section cache
932
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
933

934
  // If the cache doesn't match, recalculate micro xs
935
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
936
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
937
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
938
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
939

940
    // If NCrystal is being used, update micro cross section cache
941
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
942
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
943
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
944
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
945
    }
946
  }
947
}
2,147,483,647✔
948

949
//==============================================================================
950
// Non-method functions
951
//==============================================================================
952
void add_surf_source_to_bank(Particle& p, const Surface& surf)
2,147,483,647✔
953
{
954
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
955
      simulation::surf_source_bank.full()) {
2,147,483,647✔
956
    return;
2,147,483,647✔
957
  }
958

959
  // If a cell/cellfrom/cellto parameter is defined
960
  if (settings::ssw_cell_id != C_NONE) {
337,077✔
961

962
    // Retrieve cell index and storage type
963
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,432✔
964

965
    if (surf.bc_) {
254,432✔
966
      // Leave if cellto with vacuum boundary condition
967
      if (surf.bc_->type() == "vacuum" &&
298,914✔
968
          settings::ssw_cell_type == SSWCellType::To) {
33,097✔
969
        return;
970
      }
971

972
      // Leave if other boundary condition than vacuum
973
      if (surf.bc_->type() != "vacuum") {
274,644✔
974
        return;
975
      }
976
    }
977

978
    // Check if the cell of interest has been exited
979
    bool exited = false;
980
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,663✔
981
      if (p.cell_last(i) == cell_idx) {
207,726✔
982
        exited = true;
73,764✔
983
      }
984
    }
985

986
    // Check if the cell of interest has been entered
987
    bool entered = false;
988
    for (int i = 0; i < p.n_coord(); ++i) {
297,965✔
989
      if (p.coord(i).cell() == cell_idx) {
172,028✔
990
        entered = true;
57,516✔
991
      }
992
    }
993

994
    // Vacuum boundary conditions: return if cell is not exited
995
    if (surf.bc_) {
125,937✔
996
      if (surf.bc_->type() == "vacuum" && !exited) {
41,924!
997
        return;
998
      }
999
    } else {
1000

1001
      // If we both enter and exit the cell of interest
1002
      if (entered && exited) {
104,975✔
1003
        return;
1004
      }
1005

1006
      // If we did not enter nor exit the cell of interest
1007
      if (!entered && !exited) {
77,772✔
1008
        return;
1009
      }
1010

1011
      // If cellfrom and the cell before crossing is not the cell of
1012
      // interest
1013
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,274✔
1014
        return;
1015
      }
1016

1017
      // If cellto and the cell after crossing is not the cell of interest
1018
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,732✔
1019
        return;
1020
      }
1021
    }
1022
  }
1023

1024
  SourceSite site;
129,653✔
1025
  site.r = p.r();
129,653✔
1026
  site.u = p.u();
129,653✔
1027
  site.E = p.E();
129,653✔
1028
  site.time = p.time();
129,653✔
1029
  site.wgt = p.wgt();
129,653✔
1030
  site.delayed_group = p.delayed_group();
129,653✔
1031
  site.surf_id = surf.id_;
129,653✔
1032
  site.particle = p.type();
129,653✔
1033
  site.parent_id = p.id();
129,653✔
1034
  site.progeny_id = p.n_progeny();
129,653✔
1035
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1036
}
1037

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