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

openmc-dev / openmc / 22753099428

06 Mar 2026 07:09AM UTC coverage: 81.561% (+0.003%) from 81.558%
22753099428

Pull #3849

github

web-flow
Merge 527b17649 into 908e63115
Pull Request #3849: Fixed a bug in cell last update

17546 of 25255 branches covered (69.48%)

Branch coverage included in aggregate %.

25 of 27 new or added lines in 4 files covered. (92.59%)

202 existing lines in 10 files now uncovered.

57944 of 67302 relevant lines covered (86.1%)

45477463.75 hits per line

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

87.28
/src/particle.cpp
1
#include "openmc/particle.h"
2

3
#include <algorithm> // copy, min
4
#include <cmath>     // log, abs
5

6
#include <fmt/core.h>
7

8
#include "openmc/bank.h"
9
#include "openmc/capi.h"
10
#include "openmc/cell.h"
11
#include "openmc/collision_track.h"
12
#include "openmc/constants.h"
13
#include "openmc/dagmc.h"
14
#include "openmc/error.h"
15
#include "openmc/geometry.h"
16
#include "openmc/hdf5_interface.h"
17
#include "openmc/material.h"
18
#include "openmc/message_passing.h"
19
#include "openmc/mgxs_interface.h"
20
#include "openmc/nuclide.h"
21
#include "openmc/particle_data.h"
22
#include "openmc/photon.h"
23
#include "openmc/physics.h"
24
#include "openmc/physics_mg.h"
25
#include "openmc/random_lcg.h"
26
#include "openmc/settings.h"
27
#include "openmc/simulation.h"
28
#include "openmc/source.h"
29
#include "openmc/surface.h"
30
#include "openmc/tallies/derivative.h"
31
#include "openmc/tallies/tally.h"
32
#include "openmc/tallies/tally_scoring.h"
33
#include "openmc/track_output.h"
34
#include "openmc/weight_windows.h"
35

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

40
namespace openmc {
41

42
//==============================================================================
43
// Particle implementation
44
//==============================================================================
45

46
double Particle::speed() const
2,147,483,647✔
47
{
48
  if (settings::run_CE) {
2,147,483,647✔
49
    // Determine mass in eV/c^2
50
    double mass;
2,147,483,647✔
51
    switch (type().pdg_number()) {
2,147,483,647✔
52
    case PDG_NEUTRON:
53
      mass = MASS_NEUTRON_EV;
54
    case PDG_ELECTRON:
55
    case PDG_POSITRON:
56
      mass = MASS_ELECTRON_EV;
2,147,483,647✔
57
    default:
2,147,483,647✔
58
      mass = this->type().mass() * AMU_EV;
2,147,483,647✔
59
    }
60

61
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
62
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,147,483,647✔
63
           (this->E() + mass);
2,147,483,647✔
64
  } else {
65
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
66
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
67
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
68
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
69
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
70
  }
71
}
72

73
bool Particle::create_secondary(
112,531,222✔
74
  double wgt, Direction u, double E, ParticleType type)
75
{
76
  // If energy is below cutoff for this particle, don't create secondary
77
  // particle
78
  int idx = type.transport_index();
112,531,222✔
79
  if (idx == C_NONE) {
112,531,222!
80
    return false;
81
  }
82
  if (E < settings::energy_cutoff[idx]) {
112,531,222✔
83
    return false;
84
  }
85

86
  // Increment number of secondaries created (for ParticleProductionFilter)
87
  n_secondaries()++;
58,718,862✔
88

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

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

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

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

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

158
  // Convert signed surface ID to signed index
159
  if (src->surf_id != SURFACE_NONE) {
240,658,188✔
160
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,545✔
161
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,545✔
162
  }
163
}
240,658,188✔
164

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

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

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

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

193
    // Set birth cell attribute
194
    if (cell_born() == C_NONE)
231,987,279!
195
      cell_born() = lowest_coord().cell();
231,987,279✔
196

197
    // Initialize last cells from current cell
198
    for (int j = 0; j < n_coord(); ++j) {
481,446,470✔
199
      cell_last(j) = coord(j).cell();
249,459,191✔
200
    }
201
    n_coord_last() = n_coord();
231,987,279✔
202

203
    update_mat = true;
231,987,279✔
204
  }
205

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

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

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

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

239
  // Initialize last material from current material
240
  if (update_mat)
2,147,483,647✔
241
    material_last() = material();
231,987,279✔
242
}
243

244
void Particle::event_advance()
2,147,483,647✔
245
{
246
  // Find the distance to the nearest boundary
247
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
248

249
  // Sample a distance to collision
250
  if (type() == ParticleType::electron() ||
2,147,483,647✔
251
      type() == ParticleType::positron()) {
2,147,483,647✔
252
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
107,929,430!
253
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
254
    collision_distance() = INFINITY;
111,849,560✔
255
  } else {
256
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
257
  }
258

259
  double speed = this->speed();
2,147,483,647✔
260
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
261
  double distance_cutoff =
2,147,483,647✔
262
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
263

264
  // Select smaller of the three distances
265
  double distance =
2,147,483,647✔
266
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
267

268
  // Advance particle in space and time
269
  this->move_distance(distance);
2,147,483,647✔
270
  double dt = distance / speed;
2,147,483,647✔
271
  this->time() += dt;
2,147,483,647✔
272
  this->lifetime() += dt;
2,147,483,647✔
273

274
  // Score timed track-length tallies
275
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
276
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
277
  }
278

279
  // Score track-length tallies
280
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
281
    score_tracklength_tally(*this, distance);
1,828,367,675✔
282
  }
283

284
  // Score track-length estimate of k-eff
285
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
286
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
287
  }
288

289
  // Score flux derivative accumulators for differential tallies.
290
  if (!model::active_tallies.empty()) {
2,147,483,647✔
291
    score_track_derivative(*this, distance);
1,998,241,333✔
292
  }
293

294
  // Set particle weight to zero if it hit the time boundary
295
  if (distance == distance_cutoff) {
2,147,483,647✔
296
    wgt() = 0.0;
224,928✔
297
  }
298
}
2,147,483,647✔
299

300
void Particle::event_cross_surface()
2,147,483,647✔
301
{
302
  // Saving previous cell data
303
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
304
    cell_last(j) = coord(j).cell();
2,147,483,647✔
305
  }
306
  n_coord_last() = n_coord();
2,147,483,647✔
307

308
  // Saving previous material data
309
  material_last() = material();
2,147,483,647✔
310

311
  // Set surface that particle is on and adjust coordinate levels
312
  surface() = boundary().surface();
2,147,483,647✔
313
  n_coord() = boundary().coord_level();
2,147,483,647✔
314

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

317
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
318
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
319
      boundary().lattice_translation()[2] != 0) {
1,860,125,609✔
320
    // Particle crosses lattice boundary
321

322
    bool verbose = settings::verbosity >= 10 || trace();
750,250,844!
323
    cross_lattice(*this, boundary(), verbose);
750,250,844✔
324
    event() = TallyEvent::LATTICE;
750,250,844✔
325
  } else {
326
    // Particle crosses surface
327
    // If BC, add particle to surface source before crossing surface
328
    if (surf.surf_source_ && surf.bc_) {
1,671,583,745✔
329
      add_surf_source_to_bank(*this, surf);
720,323,903✔
330
    }
331
    this->cross_surface(surf);
1,671,583,745✔
332
    // If no BC, add particle to surface source after crossing surface
333
    if (surf.surf_source_ && !surf.bc_) {
1,671,583,736✔
334
      add_surf_source_to_bank(*this, surf);
950,022,006✔
335
    }
336
    if (settings::weight_window_checkpoint_surface) {
1,671,583,736✔
337
      apply_weight_windows(*this);
74,912✔
338
    }
339
    event() = TallyEvent::SURFACE;
1,671,583,736✔
340
  }
341
  // Score cell to cell partial currents
342
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
343
    score_surface_tally(*this, model::active_surface_tallies, surf);
34,954,711✔
344
  }
345
}
2,147,483,647✔
346

347
void Particle::event_collide()
2,147,483,647✔
348
{
349

350
  // Score collision estimate of keff
351
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
352
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,139,390,273✔
353
  }
354

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

359
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
360
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
361

362
  // Clear surface component
363
  surface() = SURFACE_NONE;
2,147,483,647✔
364

365
  if (settings::run_CE) {
2,147,483,647✔
366
    collision(*this);
1,177,339,821✔
367
  } else {
368
    collision_mg(*this);
1,783,060,477✔
369
  }
370

371
  // Collision track feature to recording particle interaction
372
  if (settings::collision_track) {
2,147,483,647✔
373
    collision_track_record(*this);
150,087✔
374
  }
375

376
  // Score collision estimator tallies -- this is done after a collision
377
  // has occurred rather than before because we need information on the
378
  // outgoing energy for any tallies with an outgoing energy filter
379
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
380
    score_collision_tally(*this);
107,405,389✔
381
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
382
    if (settings::run_CE) {
406,034,945✔
383
      score_analog_tally_ce(*this);
404,826,683✔
384
    } else {
385
      score_analog_tally_mg(*this);
1,208,262✔
386
    }
387
  }
388

389
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
390
    pht_collision_energy();
2,024✔
391
  }
392

393
  // Reset banked weight during collision
394
  n_bank() = 0;
2,147,483,647✔
395
  bank_second_E() = 0.0;
2,147,483,647✔
396
  wgt_bank() = 0.0;
2,147,483,647✔
397

398
  // Clear number of secondaries in this collision. This is
399
  // distinct from the number of created neutrons n_bank() above!
400
  n_secondaries() = 0;
2,147,483,647✔
401

402
  zero_delayed_bank();
2,147,483,647✔
403

404
  // Reset fission logical
405
  fission() = false;
2,147,483,647✔
406

407
  // Save coordinates for tallying purposes
408
  r_last_current() = r();
2,147,483,647✔
409

410
  // Set last material to none since cross sections will need to be
411
  // re-evaluated
412
  material_last() = C_NONE;
2,147,483,647✔
413

414
  // Set all directions to base level -- right now, after a collision, only
415
  // the base level directions are changed
416
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
417
    if (coord(j + 1).rotated()) {
161,247,365✔
418
      // If next level is rotated, apply rotation matrix
419
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
420
      const auto& u {coord(j).u()};
10,426,614✔
421
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
422
    } else {
423
      // Otherwise, copy this level's direction
424
      coord(j + 1).u() = coord(j).u();
150,820,751✔
425
    }
426
  }
427

428
  // Score flux derivative accumulators for differential tallies.
429
  if (!model::active_tallies.empty())
2,147,483,647✔
430
    score_collision_derivative(*this);
1,042,727,183✔
431

432
  // Saving previous cell data
433
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
434
    cell_last(j) = coord(j).cell();
2,147,483,647✔
435
  }
436
  n_coord_last() = n_coord();
2,147,483,647✔
437

438
#ifdef OPENMC_DAGMC_ENABLED
439
  history().reset();
271,173,309✔
440
#endif
441
}
2,147,483,647✔
442

443
void Particle::event_revive_from_secondary()
2,147,483,647✔
444
{
445
  // If particle has too many events, display warning and kill it
446
  ++n_event();
2,147,483,647✔
447
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
448
    warning("Particle " + std::to_string(id()) +
×
449
            " underwent maximum number of events.");
450
    wgt() = 0.0;
×
451
  }
452

453
  // Check for secondary particles if this particle is dead
454
  if (!alive()) {
2,147,483,647✔
455
    // Write final position for this particle
456
    if (write_track()) {
231,986,875✔
457
      write_particle_track(*this);
6,244✔
458
    }
459

460
    // If no secondary particles, break out of event loop
461
    if (secondary_bank().empty())
231,986,875✔
462
      return;
463

464
    from_source(&secondary_bank().back());
63,171,704✔
465
    secondary_bank().pop_back();
63,171,704✔
466
    n_event() = 0;
63,171,704✔
467
    bank_second_E() = 0.0;
63,171,704✔
468

469
    // Subtract secondary particle energy from interim pulse-height results
470
    if (!model::active_pulse_height_tallies.empty() &&
63,171,704✔
471
        this->type().is_photon()) {
15,499✔
472
      // Since the birth cell of the particle has not been set we
473
      // have to determine it before the energy of the secondary particle can be
474
      // removed from the pulse-height of this cell.
475
      if (lowest_coord().cell() == C_NONE) {
605!
476
        bool verbose = settings::verbosity >= 10 || trace();
605!
477
        if (!exhaustive_find_cell(*this, verbose)) {
605!
478
          mark_as_lost("Could not find the cell containing particle " +
×
479
                       std::to_string(id()));
×
480
          return;
×
481
        }
482
        // Set birth cell attribute
483
        if (cell_born() == C_NONE)
605!
484
          cell_born() = lowest_coord().cell();
605✔
485

486
        // Initialize last cells from current cell
487
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
488
          cell_last(j) = coord(j).cell();
605✔
489
        }
490
        n_coord_last() = n_coord();
605✔
491
      }
492
      pht_secondary_particles();
605✔
493
    }
494

495
    // Enter new particle in particle track file
496
    if (write_track())
63,171,704✔
497
      add_particle_track(*this);
5,234✔
498
  }
499
}
500

501
void Particle::event_death()
168,816,171✔
502
{
503
#ifdef OPENMC_DAGMC_ENABLED
504
  history().reset();
15,423,585✔
505
#endif
506

507
  // Finish particle track output.
508
  if (write_track()) {
168,816,171✔
509
    finalize_particle_track(*this);
1,010✔
510
  }
511

512
// Contribute tally reduction variables to global accumulator
513
#pragma omp atomic
93,087,609✔
514
  global_tally_absorption += keff_tally_absorption();
168,816,171✔
515
#pragma omp atomic
93,005,136✔
516
  global_tally_collision += keff_tally_collision();
168,816,171✔
517
#pragma omp atomic
93,604,093✔
518
  global_tally_tracklength += keff_tally_tracklength();
168,816,171✔
519
#pragma omp atomic
92,366,005✔
520
  global_tally_leakage += keff_tally_leakage();
168,816,171✔
521

522
  // Reset particle tallies once accumulated
523
  keff_tally_absorption() = 0.0;
168,816,171✔
524
  keff_tally_collision() = 0.0;
168,816,171✔
525
  keff_tally_tracklength() = 0.0;
168,816,171✔
526
  keff_tally_leakage() = 0.0;
168,816,171✔
527

528
  if (!model::active_pulse_height_tallies.empty()) {
168,816,171✔
529
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
530
  }
531

532
  // Record the number of progeny created by this particle.
533
  // This data will be used to efficiently sort the fission bank.
534
  if (settings::run_mode == RunMode::EIGENVALUE) {
168,816,171✔
535
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
141,534,700✔
536
    simulation::progeny_per_particle[offset] = n_progeny();
141,534,700✔
537
  }
538
}
168,816,171✔
539

540
void Particle::pht_collision_energy()
2,024✔
541
{
542
  // Adds the energy particles lose in a collision to the pulse-height
543

544
  // determine index of cell in pulse_height_cells
545
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
546
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024!
547

548
  if (it != model::pulse_height_cells.end()) {
2,024!
549
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
550
    pht_storage()[index] += E_last() - E();
2,024✔
551

552
    // If the energy of the particle is below the cutoff, it will not be sampled
553
    // so its energy is added to the pulse-height in the cell
554
    int photon = ParticleType::photon().transport_index();
2,024✔
555
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
556
      pht_storage()[index] += E();
825✔
557
    }
558
  }
559
}
2,024✔
560

561
void Particle::pht_secondary_particles()
605✔
562
{
563
  // Removes the energy of secondary produced particles from the pulse-height
564

565
  // determine index of cell in pulse_height_cells
566
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
567
    model::pulse_height_cells.end(), cell_born());
605!
568

569
  if (it != model::pulse_height_cells.end()) {
605!
570
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
571
    pht_storage()[index] -= E();
605✔
572
  }
573
}
605✔
574

575
void Particle::cross_surface(const Surface& surf)
1,673,459,283✔
576
{
577

578
  if (settings::verbosity >= 10 || trace()) {
1,673,459,283✔
579
    write_message(1, "    Crossing surface {}", surf.id_);
66✔
580
  }
581

582
// if we're crossing a CSG surface, make sure the DAG history is reset
583
#ifdef OPENMC_DAGMC_ENABLED
584
  if (surf.geom_type() == GeometryType::CSG)
152,823,400✔
585
    history().reset();
152,766,241✔
586
#endif
587

588
  // Handle any applicable boundary conditions.
589
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,673,459,283!
590
      settings::run_mode != RunMode::VOLUME) {
591
    surf.bc_->handle_particle(*this, surf);
720,676,011✔
592
    return;
720,676,011✔
593
  }
594

595
  // ==========================================================================
596
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
597

598
#ifdef OPENMC_DAGMC_ENABLED
599
  // in DAGMC, we know what the next cell should be
600
  if (surf.geom_type() == GeometryType::DAG) {
86,864,040✔
601
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,350✔
602
                       lowest_coord().universe()) -
46,350✔
603
                     1;
46,350✔
604
    // save material, temperature, and density multiplier
605
    material_last() = material();
46,350✔
606
    sqrtkT_last() = sqrtkT();
46,350✔
607
    density_mult_last() = density_mult();
46,350✔
608
    // set new cell value
609
    lowest_coord().cell() = i_cell;
46,350✔
610
    auto& cell = model::cells[i_cell];
46,350✔
611

612
    cell_instance() = 0;
46,350✔
613
    if (cell->distribcell_index_ >= 0)
46,350✔
614
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,326✔
615

616
    material() = cell->material(cell_instance());
46,350!
617
    sqrtkT() = cell->sqrtkT(cell_instance());
46,350!
618
    density_mult() = cell->density_mult(cell_instance());
46,350✔
619
    return;
46,350✔
620
  }
621
#endif
622

623
  bool verbose = settings::verbosity >= 10 || trace();
952,736,922!
624
  if (neighbor_list_find_cell(*this, verbose)) {
952,736,922✔
625
    return;
626
  }
627

628
  // ==========================================================================
629
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
630

631
  // Remove lower coordinate levels
632
  n_coord() = 1;
29,911✔
633
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
634

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

641
    surface() = SURFACE_NONE;
5,799✔
642
    n_coord() = 1;
5,799✔
643
    r() += TINY_BIT * u();
5,799✔
644

645
    // Couldn't find next cell anywhere! This probably means there is an actual
646
    // undefined region in the geometry.
647

648
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
649
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
650
                   " crossed surface " + std::to_string(surf.id_) +
17,388✔
651
                   " it could not be located in any cell and it did not leak.");
652
      return;
5,790✔
653
    }
654
  }
655
}
656

657
void Particle::cross_vacuum_bc(const Surface& surf)
35,100,443✔
658
{
659
  // Score any surface current tallies -- note that the particle is moved
660
  // forward slightly so that if the mesh boundary is on the surface, it is
661
  // still processed
662

663
  if (!model::active_meshsurf_tallies.empty()) {
35,100,443✔
664
    // TODO: Find a better solution to score surface currents than
665
    // physically moving the particle forward slightly
666

667
    r() += TINY_BIT * u();
937,222✔
668
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
669
  }
670

671
  // Score to global leakage tally
672
  keff_tally_leakage() += wgt();
35,100,443✔
673

674
  // Kill the particle
675
  wgt() = 0.0;
35,100,443✔
676

677
  // Display message
678
  if (settings::verbosity >= 10 || trace()) {
35,100,443!
679
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
680
  }
681
}
35,100,443✔
682

683
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
684,336,305✔
684
{
685
  // Do not handle reflective boundary conditions on lower universes
686
  if (n_coord() != 1) {
684,336,305!
687
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
688
                 " off surface in a lower universe.");
689
    return;
×
690
  }
691

692
  // Score surface currents since reflection causes the direction of the
693
  // particle to change. For surface filters, we need to score the tallies
694
  // twice, once before the particle's surface attribute has changed and
695
  // once after. For mesh surface filters, we need to artificially move
696
  // the particle slightly back in case the surface crossing is coincident
697
  // with a mesh boundary
698

699
  if (!model::active_surface_tallies.empty()) {
684,336,305✔
700
    score_surface_tally(*this, model::active_surface_tallies, surf);
302,423✔
701
  }
702

703
  if (!model::active_meshsurf_tallies.empty()) {
684,336,305✔
704
    Position r {this->r()};
46,885,487✔
705
    this->r() -= TINY_BIT * u();
46,885,487✔
706
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
707
    this->r() = r;
46,885,487✔
708
  }
709

710
  // Set the new particle direction
711
  u() = new_u;
684,336,305✔
712

713
  // Reassign particle's cell and surface
714
  coord(0).cell() = cell_last(0);
684,336,305✔
715
  surface() = -surface();
684,336,305✔
716

717
  // If a reflective surface is coincident with a lattice or universe
718
  // boundary, it is necessary to redetermine the particle's coordinates in
719
  // the lower universes.
720
  // (unless we're using a dagmc model, which has exactly one universe)
721
  n_coord() = 1;
684,336,305✔
722
  if (surf.geom_type() != GeometryType::DAG &&
1,368,669,852!
723
      !neighbor_list_find_cell(*this)) {
684,333,547✔
724
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
725
                 std::to_string(surf.id_) + ".");
×
726
    return;
×
727
  }
728

729
  // Set previous coordinate going slightly past surface crossing
730
  r_last_current() = r() + TINY_BIT * u();
684,336,305✔
731

732
  // Diagnostic message
733
  if (settings::verbosity >= 10 || trace()) {
684,336,305!
734
    write_message(1, "    Reflected from surface {}", surf.id_);
×
735
  }
736
}
737

738
void Particle::cross_periodic_bc(
2,244,729✔
739
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
740
{
741
  // Do not handle periodic boundary conditions on lower universes
742
  if (n_coord() != 1) {
2,244,729!
743
    mark_as_lost(
×
744
      "Cannot transfer particle " + std::to_string(id()) +
×
745
      " across surface in a lower universe. Boundary conditions must be "
746
      "applied to root universe.");
747
    return;
×
748
  }
749

750
  // Score surface currents since reflection causes the direction of the
751
  // particle to change -- artificially move the particle slightly back in
752
  // case the surface crossing is coincident with a mesh boundary
753
  if (!model::active_meshsurf_tallies.empty()) {
2,244,729!
754
    Position r {this->r()};
×
755
    this->r() -= TINY_BIT * u();
×
756
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
757
    this->r() = r;
×
758
  }
759

760
  // Adjust the particle's location and direction.
761
  r() = new_r;
2,244,729✔
762
  u() = new_u;
2,244,729✔
763

764
  // Reassign particle's surface
765
  surface() = new_surface;
2,244,729✔
766

767
  // Figure out what cell particle is in now
768
  n_coord() = 1;
2,244,729✔
769

770
  if (!neighbor_list_find_cell(*this)) {
2,244,729!
771
    mark_as_lost("Couldn't find particle after hitting periodic "
×
772
                 "boundary on surface " +
×
773
                 std::to_string(surf.id_) + ".");
×
774
    return;
×
775
  }
776

777
  // Set previous coordinate going slightly past surface crossing
778
  r_last_current() = r() + TINY_BIT * u();
2,244,729✔
779

780
  // Diagnostic message
781
  if (settings::verbosity >= 10 || trace()) {
2,244,729!
782
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
783
  }
784
}
785

786
void Particle::mark_as_lost(const char* message)
5,799✔
787
{
788
  // Print warning and write lost particle file
789
  warning(message);
5,799✔
790
  if (settings::max_write_lost_particles < 0 ||
5,799✔
791
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
792
    write_restart();
374✔
793
  }
794
  // Increment number of lost particles
795
  wgt() = 0.0;
5,799✔
796
#pragma omp atomic
3,154✔
797
  simulation::n_lost_particles += 1;
2,645✔
798

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

803
  // Abort the simulation if the maximum number of lost particles has been
804
  // reached
805
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
806
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
807
    fatal_error("Maximum number of lost particles has been reached.");
9✔
808
  }
809
}
5,790✔
810

811
void Particle::write_restart() const
374✔
812
{
813
  // Dont write another restart file if in particle restart mode
814
  if (settings::run_mode == RunMode::PARTICLE)
374✔
815
    return;
22✔
816

817
  // Set up file name
818
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
352✔
819
    simulation::current_batch, id());
352✔
820

821
#pragma omp critical(WriteParticleRestart)
187✔
822
  {
352✔
823
    // Create file
824
    hid_t file_id = file_open(filename, 'w');
352✔
825

826
    // Write filetype and version info
827
    write_attribute(file_id, "filetype", "particle restart");
352✔
828
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
352✔
829
    write_attribute(file_id, "openmc_version", VERSION);
352✔
830
#ifdef GIT_SHA1
831
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
832
#endif
833

834
    // Write data to file
835
    write_dataset(file_id, "current_batch", simulation::current_batch);
352✔
836
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
352✔
837
    write_dataset(file_id, "current_generation", simulation::current_gen);
352✔
838
    write_dataset(file_id, "n_particles", settings::n_particles);
352✔
839
    switch (settings::run_mode) {
352!
840
    case RunMode::FIXED_SOURCE:
220✔
841
      write_dataset(file_id, "run_mode", "fixed source");
220✔
842
      break;
115✔
843
    case RunMode::EIGENVALUE:
132✔
844
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
845
      break;
72✔
846
    case RunMode::PARTICLE:
×
847
      write_dataset(file_id, "run_mode", "particle restart");
×
848
      break;
849
    default:
850
      break;
851
    }
852
    write_dataset(file_id, "id", id());
352✔
853
    write_dataset(file_id, "type", type().pdg_number());
352✔
854

855
    int64_t i = current_work();
352✔
856
    if (settings::run_mode == RunMode::EIGENVALUE) {
352✔
857
      // take source data from primary bank for eigenvalue simulation
858
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
859
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
860
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
861
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
862
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
863
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
220!
864
      // re-sample using rng random number seed used to generate source particle
865
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
220✔
866
                     settings::n_particles +
220✔
867
                   simulation::work_index[mpi::rank] + i;
220✔
868
      uint64_t seed = init_seed(id, STREAM_SOURCE);
220✔
869
      // re-sample source site
870
      auto site = sample_external_source(&seed);
220✔
871
      write_dataset(file_id, "weight", site.wgt);
220✔
872
      write_dataset(file_id, "energy", site.E);
220✔
873
      write_dataset(file_id, "xyz", site.r);
220✔
874
      write_dataset(file_id, "uvw", site.u);
220✔
875
      write_dataset(file_id, "time", site.time);
220✔
876
    }
877

878
    // Close file
879
    file_close(file_id);
352✔
880
  } // #pragma omp critical
881
}
352✔
882

883
void Particle::update_neutron_xs(
2,147,483,647✔
884
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
885
{
886
  // Get microscopic cross section cache
887
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
888

889
  // If the cache doesn't match, recalculate micro xs
890
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
891
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
892
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
893
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
894

895
    // If NCrystal is being used, update micro cross section cache
896
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
897
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
898
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
899
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
900
    }
901
  }
902
}
2,147,483,647✔
903

904
//==============================================================================
905
// Non-method functions
906
//==============================================================================
907
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,670,345,909✔
908
{
909
  if (simulation::current_batch <= settings::n_inactive ||
1,670,345,909✔
910
      simulation::surf_source_bank.full()) {
1,284,876,990✔
911
    return;
1,670,216,256✔
912
  }
913

914
  // If a cell/cellfrom/cellto parameter is defined
915
  if (settings::ssw_cell_id != C_NONE) {
337,082✔
916

917
    // Retrieve cell index and storage type
918
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,437✔
919

920
    if (surf.bc_) {
254,437✔
921
      // Leave if cellto with vacuum boundary condition
922
      if (surf.bc_->type() == "vacuum" &&
298,918✔
923
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
924
        return;
925
      }
926

927
      // Leave if other boundary condition than vacuum
928
      if (surf.bc_->type() != "vacuum") {
274,648✔
929
        return;
930
      }
931
    }
932

933
    // Check if the cell of interest has been exited
934
    bool exited = false;
935
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,673✔
936
      if (p.cell_last(i) == cell_idx) {
207,731✔
937
        exited = true;
73,763✔
938
      }
939
    }
940

941
    // Check if the cell of interest has been entered
942
    bool entered = false;
943
    for (int i = 0; i < p.n_coord(); ++i) {
297,975✔
944
      if (p.coord(i).cell() == cell_idx) {
172,033✔
945
        entered = true;
57,519✔
946
      }
947
    }
948

949
    // Vacuum boundary conditions: return if cell is not exited
950
    if (surf.bc_) {
125,942✔
951
      if (surf.bc_->type() == "vacuum" && !exited) {
41,928!
952
        return;
953
      }
954
    } else {
955

956
      // If we both enter and exit the cell of interest
957
      if (entered && exited) {
104,978✔
958
        return;
959
      }
960

961
      // If we did not enter nor exit the cell of interest
962
      if (!entered && !exited) {
77,775✔
963
        return;
964
      }
965

966
      // If cellfrom and the cell before crossing is not the cell of
967
      // interest
968
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,276✔
969
        return;
970
      }
971

972
      // If cellto and the cell after crossing is not the cell of interest
973
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,731✔
974
        return;
975
      }
976
    }
977
  }
978

979
  SourceSite site;
129,653✔
980
  site.r = p.r();
129,653✔
981
  site.u = p.u();
129,653✔
982
  site.E = p.E();
129,653✔
983
  site.time = p.time();
129,653✔
984
  site.wgt = p.wgt();
129,653✔
985
  site.delayed_group = p.delayed_group();
129,653✔
986
  site.surf_id = surf.id_;
129,653✔
987
  site.particle = p.type();
129,653✔
988
  site.parent_id = p.id();
129,653✔
989
  site.progeny_id = p.n_progeny();
129,653✔
990
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
991
}
992

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