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

openmc-dev / openmc / 21673990708

04 Feb 2026 01:49PM UTC coverage: 81.605% (-0.2%) from 81.763%
21673990708

Pull #3769

github

web-flow
Merge c80589e69 into b41e22f68
Pull Request #3769: Fixing compiler warning about VLA (Clang extension)

16763 of 23253 branches covered (72.09%)

Branch coverage included in aggregate %.

4 of 4 new or added lines in 1 file covered. (100.0%)

308 existing lines in 25 files now uncovered.

55026 of 64718 relevant lines covered (85.02%)

42513899.51 hits per line

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

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

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

6
#include <fmt/core.h>
7

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

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

40
namespace openmc {
41

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

46
double Particle::speed() const
2,147,483,647✔
47
{
48
  if (settings::run_CE) {
2,147,483,647✔
49
    // Determine mass in eV/c^2
50
    double mass;
51
    switch (this->type().pdg_number()) {
1,908,709,168!
52
    case PDG_NEUTRON:
1,840,292,827✔
53
      mass = MASS_NEUTRON_EV;
1,840,292,827✔
54
      break;
1,840,292,827✔
55
    case PDG_PHOTON:
19,821,537✔
56
      mass = 0.0;
19,821,537✔
57
      break;
19,821,537✔
58
    case PDG_ELECTRON:
48,594,804✔
59
    case PDG_POSITRON:
60
      mass = MASS_ELECTRON_EV;
48,594,804✔
61
      break;
48,594,804✔
62
    default:
×
63
      fatal_error("Unsupported particle for speed calculation.");
×
64
    }
65
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
66
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,908,709,168✔
67
           (this->E() + mass);
1,908,709,168✔
68
  } else {
69
    auto& macro_xs = data::mg.macro_xs_[this->material()];
1,876,306,740✔
70
    int macro_t = this->mg_xs_cache().t;
1,876,306,740✔
71
    int macro_a = macro_xs.get_angle_index(this->u());
1,876,306,740✔
72
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
1,876,306,740✔
73
                   nullptr, nullptr, macro_t, macro_a);
1,876,306,740✔
74
  }
75
}
76

77
bool Particle::create_secondary(
101,363,997✔
78
  double wgt, Direction u, double E, ParticleType type)
79
{
80
  // If energy is below cutoff for this particle, don't create secondary
81
  // particle
82
  int idx = type.transport_index();
101,363,997✔
83
  if (idx == C_NONE) {
101,363,997!
84
    return false;
×
85
  }
86
  if (E < settings::energy_cutoff[idx]) {
101,363,997✔
87
    return false;
48,455,512✔
88
  }
89

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

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

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

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

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

159
  // Convert signed surface ID to signed index
160
  if (src->surf_id != SURFACE_NONE) {
216,255,676✔
161
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
100,000✔
162
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
100,000!
163
  }
164
}
216,255,676✔
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)) {
208,543,686!
188
      mark_as_lost(
×
189
        "Could not find the cell containing particle " + std::to_string(id()));
×
190
      return;
×
191
    }
192

193
    // Set birth cell attribute
194
    if (cell_born() == C_NONE)
208,543,686!
195
      cell_born() = lowest_coord().cell();
208,543,686✔
196

197
    // Initialize last cells from current cell
198
    for (int j = 0; j < n_coord(); ++j) {
432,561,520✔
199
      cell_last(j) = coord(j).cell();
224,017,834✔
200
    }
201
    n_coord_last() = n_coord();
208,543,686✔
202
  }
203

204
  // Write particle track.
205
  if (write_track())
2,147,483,647✔
206
    write_particle_track(*this);
9,541✔
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,102,410,396✔
215
          density_mult() != density_mult_last()) {
320,301,039✔
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);
1,461,817,038✔
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);
1,876,306,740✔
226

227
      // Update the particle's group while we know we are multi-group
228
      g_last() = g();
1,876,306,740✔
229
    }
230
  } else {
231
    macro_xs().total = 0.0;
101,648,301✔
232
    macro_xs().absorption = 0.0;
101,648,301✔
233
    macro_xs().fission = 0.0;
101,648,301✔
234
    macro_xs().nu_fission = 0.0;
101,648,301✔
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
  // Sample a distance to collision
244
  if (type() == ParticleType::electron() ||
2,147,483,647✔
245
      type() == ParticleType::positron()) {
2,147,483,647✔
246
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
48,594,804!
247
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
248
    collision_distance() = INFINITY;
101,648,301✔
249
  } else {
250
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
251
  }
252

253
  double speed = this->speed();
2,147,483,647✔
254
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,147,483,647✔
255
  double distance_cutoff =
256
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
257

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

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

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

273
  // Score track-length tallies
274
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
275
    score_tracklength_tally(*this, distance);
1,408,693,582✔
276
  }
277

278
  // Score track-length estimate of k-eff
279
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
280
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
281
  }
282

283
  // Score flux derivative accumulators for differential tallies.
284
  if (!model::active_tallies.empty()) {
2,147,483,647✔
285
    score_track_derivative(*this, distance);
1,561,668,976✔
286
  }
287

288
  // Set particle weight to zero if it hit the time boundary
289
  if (distance == distance_cutoff) {
2,147,483,647✔
290
    wgt() = 0.0;
204,480✔
291
  }
292
}
2,147,483,647✔
293

294
void Particle::event_cross_surface()
2,024,131,014✔
295
{
296
  // Saving previous cell data
297
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
298
    cell_last(j) = coord(j).cell();
2,147,483,647✔
299
  }
300
  n_coord_last() = n_coord();
2,024,131,014✔
301

302
  // Set surface that particle is on and adjust coordinate levels
303
  surface() = boundary().surface();
2,024,131,014✔
304
  n_coord() = boundary().coord_level();
2,024,131,014✔
305

306
  if (boundary().lattice_translation()[0] != 0 ||
2,024,131,014✔
307
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
308
      boundary().lattice_translation()[2] != 0) {
1,540,664,809✔
309
    // Particle crosses lattice boundary
310

311
    bool verbose = settings::verbosity >= 10 || trace();
654,867,345!
312
    cross_lattice(*this, boundary(), verbose);
654,867,345✔
313
    event() = TallyEvent::LATTICE;
654,867,345✔
314
  } else {
315
    // Particle crosses surface
316
    const auto& surf {model::surfaces[surface_index()].get()};
1,369,263,669✔
317
    // If BC, add particle to surface source before crossing surface
318
    if (surf->surf_source_ && surf->bc_) {
1,369,263,669✔
319
      add_surf_source_to_bank(*this, *surf);
625,505,772✔
320
    }
321
    this->cross_surface(*surf);
1,369,263,669✔
322
    // If no BC, add particle to surface source after crossing surface
323
    if (surf->surf_source_ && !surf->bc_) {
1,369,263,661✔
324
      add_surf_source_to_bank(*this, *surf);
742,642,266✔
325
    }
326
    if (settings::weight_window_checkpoint_surface) {
1,369,263,661!
UNCOV
327
      apply_weight_windows(*this);
×
328
    }
329
    event() = TallyEvent::SURFACE;
1,369,263,661✔
330
  }
331
  // Score cell to cell partial currents
332
  if (!model::active_surface_tallies.empty()) {
2,024,131,006✔
333
    score_surface_tally(*this, model::active_surface_tallies);
31,747,970✔
334
  }
335
}
2,024,131,006✔
336

337
void Particle::event_collide()
2,147,483,647✔
338
{
339
  // Score collision estimate of keff
340
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,147,483,647✔
341
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
1,931,837,318✔
342
  }
343

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

348
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
349
    score_surface_tally(*this, model::active_meshsurf_tallies);
57,362,660✔
350

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

354
  if (settings::run_CE) {
2,147,483,647✔
355
    collision(*this);
856,556,794✔
356
  } else {
357
    collision_mg(*this);
1,620,964,070✔
358
  }
359

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

365
  // Score collision estimator tallies -- this is done after a collision
366
  // has occurred rather than before because we need information on the
367
  // outgoing energy for any tallies with an outgoing energy filter
368
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
369
    score_collision_tally(*this);
96,550,719✔
370
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
371
    if (settings::run_CE) {
265,078,820✔
372
      score_analog_tally_ce(*this);
263,980,400✔
373
    } else {
374
      score_analog_tally_mg(*this);
1,098,420✔
375
    }
376
  }
377

378
  if (!model::active_pulse_height_tallies.empty() && type().is_photon()) {
2,147,483,647✔
379
    pht_collision_energy();
1,840✔
380
  }
381

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

388
  // Reset fission logical
389
  fission() = false;
2,147,483,647✔
390

391
  // Save coordinates for tallying purposes
392
  r_last_current() = r();
2,147,483,647✔
393

394
  // Set last material to none since cross sections will need to be
395
  // re-evaluated
396
  material_last() = C_NONE;
2,147,483,647✔
397

398
  // Set all directions to base level -- right now, after a collision, only
399
  // the base level directions are changed
400
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
401
    if (coord(j + 1).rotated()) {
129,970,285✔
402
      // If next level is rotated, apply rotation matrix
403
      const auto& m {model::cells[coord(j).cell()]->rotation_};
9,478,740✔
404
      const auto& u {coord(j).u()};
9,478,740✔
405
      coord(j + 1).u() = u.rotate(m);
9,478,740✔
406
    } else {
407
      // Otherwise, copy this level's direction
408
      coord(j + 1).u() = coord(j).u();
120,491,545✔
409
    }
410
  }
411

412
  // Score flux derivative accumulators for differential tallies.
413
  if (!model::active_tallies.empty())
2,147,483,647✔
414
    score_collision_derivative(*this);
740,759,878✔
415

416
#ifdef OPENMC_DAGMC_ENABLED
417
  history().reset();
418
#endif
419
}
2,147,483,647✔
420

421
void Particle::event_revive_from_secondary()
2,147,483,647✔
422
{
423
  // If particle has too many events, display warning and kill it
424
  ++n_event();
2,147,483,647✔
425
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
426
    warning("Particle " + std::to_string(id()) +
×
427
            " underwent maximum number of events.");
428
    wgt() = 0.0;
×
429
  }
430

431
  // Check for secondary particles if this particle is dead
432
  if (!alive()) {
2,147,483,647✔
433
    // Write final position for this particle
434
    if (write_track()) {
208,543,228✔
435
      write_particle_track(*this);
5,828✔
436
    }
437

438
    // If no secondary particles, break out of event loop
439
    if (secondary_bank().empty())
208,543,228✔
440
      return;
151,811,946✔
441

442
    from_source(&secondary_bank().back());
56,731,282✔
443
    secondary_bank().pop_back();
56,731,282✔
444
    n_event() = 0;
56,731,282✔
445
    bank_second_E() = 0.0;
56,731,282✔
446

447
    // Subtract secondary particle energy from interim pulse-height results
448
    if (!model::active_pulse_height_tallies.empty() &&
56,745,372✔
449
        this->type().is_photon()) {
14,090✔
450
      // Since the birth cell of the particle has not been set we
451
      // have to determine it before the energy of the secondary particle can be
452
      // removed from the pulse-height of this cell.
453
      if (lowest_coord().cell() == C_NONE) {
550!
454
        bool verbose = settings::verbosity >= 10 || trace();
550!
455
        if (!exhaustive_find_cell(*this, verbose)) {
550!
456
          mark_as_lost("Could not find the cell containing particle " +
×
457
                       std::to_string(id()));
×
458
          return;
×
459
        }
460
        // Set birth cell attribute
461
        if (cell_born() == C_NONE)
550!
462
          cell_born() = lowest_coord().cell();
550✔
463

464
        // Initialize last cells from current cell
465
        for (int j = 0; j < n_coord(); ++j) {
1,100✔
466
          cell_last(j) = coord(j).cell();
550✔
467
        }
468
        n_coord_last() = n_coord();
550✔
469
      }
470
      pht_secondary_particles();
550✔
471
    }
472

473
    // Enter new particle in particle track file
474
    if (write_track())
56,731,282✔
475
      add_particle_track(*this);
4,888✔
476
  }
477
}
478

479
void Particle::event_death()
151,812,946✔
480
{
481
#ifdef OPENMC_DAGMC_ENABLED
482
  history().reset();
483
#endif
484

485
  // Finish particle track output.
486
  if (write_track()) {
151,812,946✔
487
    finalize_particle_track(*this);
940✔
488
  }
489

490
// Contribute tally reduction variables to global accumulator
491
#pragma omp atomic
76,695,272✔
492
  global_tally_absorption += keff_tally_absorption();
151,812,946✔
493
#pragma omp atomic
76,279,646✔
494
  global_tally_collision += keff_tally_collision();
151,812,946✔
495
#pragma omp atomic
76,268,531✔
496
  global_tally_tracklength += keff_tally_tracklength();
151,812,946✔
497
#pragma omp atomic
76,058,460✔
498
  global_tally_leakage += keff_tally_leakage();
151,812,946✔
499

500
  // Reset particle tallies once accumulated
501
  keff_tally_absorption() = 0.0;
151,812,946✔
502
  keff_tally_collision() = 0.0;
151,812,946✔
503
  keff_tally_tracklength() = 0.0;
151,812,946✔
504
  keff_tally_leakage() = 0.0;
151,812,946✔
505

506
  if (!model::active_pulse_height_tallies.empty()) {
151,812,946✔
507
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,000✔
508
  }
509

510
  // Record the number of progeny created by this particle.
511
  // This data will be used to efficiently sort the fission bank.
512
  if (settings::run_mode == RunMode::EIGENVALUE) {
151,812,946✔
513
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
128,106,000✔
514
    simulation::progeny_per_particle[offset] = n_progeny();
128,106,000✔
515
  }
516
}
151,812,946✔
517

518
void Particle::pht_collision_energy()
1,840✔
519
{
520
  // Adds the energy particles lose in a collision to the pulse-height
521

522
  // determine index of cell in pulse_height_cells
523
  auto it = std::find(model::pulse_height_cells.begin(),
1,840✔
524
    model::pulse_height_cells.end(), lowest_coord().cell());
1,840✔
525

526
  if (it != model::pulse_height_cells.end()) {
1,840!
527
    int index = std::distance(model::pulse_height_cells.begin(), it);
1,840✔
528
    pht_storage()[index] += E_last() - E();
1,840✔
529

530
    // If the energy of the particle is below the cutoff, it will not be sampled
531
    // so its energy is added to the pulse-height in the cell
532
    int photon = ParticleType::photon().transport_index();
1,840✔
533
    if (E() < settings::energy_cutoff[photon]) {
1,840✔
534
      pht_storage()[index] += E();
750✔
535
    }
536
  }
537
}
1,840✔
538

539
void Particle::pht_secondary_particles()
550✔
540
{
541
  // Removes the energy of secondary produced particles from the pulse-height
542

543
  // determine index of cell in pulse_height_cells
544
  auto it = std::find(model::pulse_height_cells.begin(),
550✔
545
    model::pulse_height_cells.end(), cell_born());
550✔
546

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

553
void Particle::cross_surface(const Surface& surf)
1,370,923,865✔
554
{
555

556
  if (settings::verbosity >= 10 || trace()) {
1,370,923,865✔
557
    write_message(1, "    Crossing surface {}", surf.id_);
30✔
558
  }
559

560
// if we're crossing a CSG surface, make sure the DAG history is reset
561
#ifdef OPENMC_DAGMC_ENABLED
562
  if (surf.geom_type() == GeometryType::CSG)
563
    history().reset();
564
#endif
565

566
  // Handle any applicable boundary conditions.
567
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,996,856,623!
568
      settings::run_mode != RunMode::VOLUME) {
625,932,758✔
569
    surf.bc_->handle_particle(*this, surf);
625,823,718✔
570
    return;
625,823,718✔
571
  }
572

573
  // ==========================================================================
574
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
575

576
#ifdef OPENMC_DAGMC_ENABLED
577
  // in DAGMC, we know what the next cell should be
578
  if (surf.geom_type() == GeometryType::DAG) {
579
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
580
                       lowest_coord().universe()) -
581
                     1;
582
    // save material, temperature, and density multiplier
583
    material_last() = material();
584
    sqrtkT_last() = sqrtkT();
585
    density_mult_last() = density_mult();
586
    // set new cell value
587
    lowest_coord().cell() = i_cell;
588
    auto& cell = model::cells[i_cell];
589

590
    cell_instance() = 0;
591
    if (cell->distribcell_index_ >= 0)
592
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
593

594
    material() = cell->material(cell_instance());
595
    sqrtkT() = cell->sqrtkT(cell_instance());
596
    density_mult() = cell->density_mult(cell_instance());
597
    return;
598
  }
599
#endif
600

601
  bool verbose = settings::verbosity >= 10 || trace();
745,100,147!
602
  if (neighbor_list_find_cell(*this, verbose)) {
745,100,147✔
603
    return;
745,072,957✔
604
  }
605

606
  // ==========================================================================
607
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
608

609
  // Remove lower coordinate levels
610
  n_coord() = 1;
27,190✔
611
  bool found = exhaustive_find_cell(*this, verbose);
27,190✔
612

613
  if (settings::run_mode != RunMode::PLOTTING && (!found)) {
27,190!
614
    // If a cell is still not found, there are two possible causes: 1) there is
615
    // a void in the model, and 2) the particle hit a surface at a tangent. If
616
    // the particle is really traveling tangent to a surface, if we move it
617
    // forward a tiny bit it should fix the problem.
618

619
    surface() = SURFACE_NONE;
5,270✔
620
    n_coord() = 1;
5,270✔
621
    r() += TINY_BIT * u();
5,270✔
622

623
    // Couldn't find next cell anywhere! This probably means there is an actual
624
    // undefined region in the geometry.
625

626
    if (!exhaustive_find_cell(*this, verbose)) {
5,270!
627
      mark_as_lost("After particle " + std::to_string(id()) +
15,802✔
628
                   " crossed surface " + std::to_string(surf.id_) +
21,064✔
629
                   " it could not be located in any cell and it did not leak.");
630
      return;
5,262✔
631
    }
632
  }
633
}
634

635
void Particle::cross_vacuum_bc(const Surface& surf)
31,714,874✔
636
{
637
  // Score any surface current tallies -- note that the particle is moved
638
  // forward slightly so that if the mesh boundary is on the surface, it is
639
  // still processed
640

641
  if (!model::active_meshsurf_tallies.empty()) {
31,714,874✔
642
    // TODO: Find a better solution to score surface currents than
643
    // physically moving the particle forward slightly
644

645
    r() += TINY_BIT * u();
852,020✔
646
    score_surface_tally(*this, model::active_meshsurf_tallies);
852,020✔
647
  }
648

649
  // Score to global leakage tally
650
  keff_tally_leakage() += wgt();
31,714,874✔
651

652
  // Kill the particle
653
  wgt() = 0.0;
31,714,874✔
654

655
  // Display message
656
  if (settings::verbosity >= 10 || trace()) {
31,714,874!
657
    write_message(1, "    Leaked out of surface {}", surf.id_);
10✔
658
  }
659
}
31,714,874✔
660

661
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
592,980,222✔
662
{
663
  // Do not handle reflective boundary conditions on lower universes
664
  if (n_coord() != 1) {
592,980,222!
665
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
666
                 " off surface in a lower universe.");
667
    return;
×
668
  }
669

670
  // Score surface currents since reflection causes the direction of the
671
  // particle to change. For surface filters, we need to score the tallies
672
  // twice, once before the particle's surface attribute has changed and
673
  // once after. For mesh surface filters, we need to artificially move
674
  // the particle slightly back in case the surface crossing is coincident
675
  // with a mesh boundary
676

677
  if (!model::active_surface_tallies.empty()) {
592,980,222✔
678
    score_surface_tally(*this, model::active_surface_tallies);
259,110✔
679
  }
680

681
  if (!model::active_meshsurf_tallies.empty()) {
592,980,222✔
682
    Position r {this->r()};
42,623,170✔
683
    this->r() -= TINY_BIT * u();
42,623,170✔
684
    score_surface_tally(*this, model::active_meshsurf_tallies);
42,623,170✔
685
    this->r() = r;
42,623,170✔
686
  }
687

688
  // Set the new particle direction
689
  u() = new_u;
592,980,222✔
690

691
  // Reassign particle's cell and surface
692
  coord(0).cell() = cell_last(0);
592,980,222✔
693
  surface() = -surface();
592,980,222✔
694

695
  // If a reflective surface is coincident with a lattice or universe
696
  // boundary, it is necessary to redetermine the particle's coordinates in
697
  // the lower universes.
698
  // (unless we're using a dagmc model, which has exactly one universe)
699
  n_coord() = 1;
592,980,222✔
700
  if (surf.geom_type() != GeometryType::DAG &&
1,185,960,444!
701
      !neighbor_list_find_cell(*this)) {
592,980,222!
702
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
703
                 std::to_string(surf.id_) + ".");
×
704
    return;
×
705
  }
706

707
  // Set previous coordinate going slightly past surface crossing
708
  r_last_current() = r() + TINY_BIT * u();
592,980,222✔
709

710
  // Diagnostic message
711
  if (settings::verbosity >= 10 || trace()) {
592,980,222!
712
    write_message(1, "    Reflected from surface {}", surf.id_);
×
713
  }
714
}
715

716
void Particle::cross_periodic_bc(
2,042,682✔
717
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
718
{
719
  // Do not handle periodic boundary conditions on lower universes
720
  if (n_coord() != 1) {
2,042,682!
721
    mark_as_lost(
×
722
      "Cannot transfer particle " + std::to_string(id()) +
×
723
      " across surface in a lower universe. Boundary conditions must be "
724
      "applied to root universe.");
725
    return;
×
726
  }
727

728
  // Score surface currents since reflection causes the direction of the
729
  // particle to change -- artificially move the particle slightly back in
730
  // case the surface crossing is coincident with a mesh boundary
731
  if (!model::active_meshsurf_tallies.empty()) {
2,042,682!
732
    Position r {this->r()};
×
733
    this->r() -= TINY_BIT * u();
×
734
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
735
    this->r() = r;
×
736
  }
737

738
  // Adjust the particle's location and direction.
739
  r() = new_r;
2,042,682✔
740
  u() = new_u;
2,042,682✔
741

742
  // Reassign particle's surface
743
  surface() = new_surface;
2,042,682✔
744

745
  // Figure out what cell particle is in now
746
  n_coord() = 1;
2,042,682✔
747

748
  if (!neighbor_list_find_cell(*this)) {
2,042,682!
749
    mark_as_lost("Couldn't find particle after hitting periodic "
×
750
                 "boundary on surface " +
×
751
                 std::to_string(surf.id_) + ".");
×
752
    return;
×
753
  }
754

755
  // Set previous coordinate going slightly past surface crossing
756
  r_last_current() = r() + TINY_BIT * u();
2,042,682✔
757

758
  // Diagnostic message
759
  if (settings::verbosity >= 10 || trace()) {
2,042,682!
760
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
761
  }
762
}
763

764
void Particle::mark_as_lost(const char* message)
5,270✔
765
{
766
  // Print warning and write lost particle file
767
  warning(message);
5,270✔
768
  if (settings::max_write_lost_particles < 0 ||
5,270✔
769
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,000✔
770
    write_restart();
340✔
771
  }
772
  // Increment number of lost particles
773
  wgt() = 0.0;
5,270✔
774
#pragma omp atomic
2,625✔
775
  simulation::n_lost_particles += 1;
2,645✔
776

777
  // Count the total number of simulated particles (on this processor)
778
  auto n = simulation::current_batch * settings::gen_per_batch *
5,270✔
779
           simulation::work_per_rank;
780

781
  // Abort the simulation if the maximum number of lost particles has been
782
  // reached
783
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,270✔
784
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
8!
785
    fatal_error("Maximum number of lost particles has been reached.");
8✔
786
  }
787
}
5,262✔
788

789
void Particle::write_restart() const
340✔
790
{
791
  // Dont write another restart file if in particle restart mode
792
  if (settings::run_mode == RunMode::PARTICLE)
340✔
793
    return;
20✔
794

795
  // Set up file name
796
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
797
    simulation::current_batch, id());
591✔
798

799
#pragma omp critical(WriteParticleRestart)
300✔
800
  {
801
    // Create file
802
    hid_t file_id = file_open(filename, 'w');
320✔
803

804
    // Write filetype and version info
805
    write_attribute(file_id, "filetype", "particle restart");
320✔
806
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
320✔
807
    write_attribute(file_id, "openmc_version", VERSION);
320✔
808
#ifdef GIT_SHA1
809
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
810
#endif
811

812
    // Write data to file
813
    write_dataset(file_id, "current_batch", simulation::current_batch);
320✔
814
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
320✔
815
    write_dataset(file_id, "current_generation", simulation::current_gen);
320✔
816
    write_dataset(file_id, "n_particles", settings::n_particles);
320✔
817
    switch (settings::run_mode) {
320!
818
    case RunMode::FIXED_SOURCE:
200✔
819
      write_dataset(file_id, "run_mode", "fixed source");
200✔
820
      break;
200✔
821
    case RunMode::EIGENVALUE:
120✔
822
      write_dataset(file_id, "run_mode", "eigenvalue");
120✔
823
      break;
120✔
824
    case RunMode::PARTICLE:
×
825
      write_dataset(file_id, "run_mode", "particle restart");
×
826
      break;
×
827
    default:
×
828
      break;
×
829
    }
830
    write_dataset(file_id, "id", id());
320✔
831
    write_dataset(file_id, "type", type().pdg_number());
320✔
832

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

856
    // Close file
857
    file_close(file_id);
320✔
858
  } // #pragma omp critical
859
}
320✔
860

861
void Particle::update_neutron_xs(
2,147,483,647✔
862
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
863
{
864
  // Get microscopic cross section cache
865
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
866

867
  // If the cache doesn't match, recalculate micro xs
868
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
869
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
870
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
871
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
872

873
    // If NCrystal is being used, update micro cross section cache
874
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
875
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
876
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
10,017,230✔
877
      ncrystal_update_micro(ncrystal_xs, micro);
10,017,230✔
878
    }
879
  }
880
}
2,147,483,647✔
881

882
//==============================================================================
883
// Non-method functions
884
//==============================================================================
885
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,368,148,038✔
886
{
887
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
888
      simulation::surf_source_bank.full()) {
1,070,825,881✔
889
    return;
1,368,034,384✔
890
  }
891

892
  // If a cell/cellfrom/cellto parameter is defined
893
  if (settings::ssw_cell_id != C_NONE) {
295,201✔
894

895
    // Retrieve cell index and storage type
896
    int cell_idx = model::cell_map[settings::ssw_cell_id];
221,431✔
897

898
    if (surf.bc_) {
221,431✔
899
      // Leave if cellto with vacuum boundary condition
900
      if (surf.bc_->type() == "vacuum" &&
161,374!
901
          settings::ssw_cell_type == SSWCellType::To) {
28,325✔
902
        return;
10,134✔
903
      }
904

905
      // Leave if other boundary condition than vacuum
906
      if (surf.bc_->type() != "vacuum") {
122,915✔
907
        return;
104,724✔
908
      }
909
    }
910

911
    // Check if the cell of interest has been exited
912
    bool exited = false;
106,573✔
913
    for (int i = 0; i < p.n_coord_last(); ++i) {
286,391✔
914
      if (p.cell_last(i) == cell_idx) {
179,818✔
915
        exited = true;
64,166✔
916
      }
917
    }
918

919
    // Check if the cell of interest has been entered
920
    bool entered = false;
106,573✔
921
    for (int i = 0; i < p.n_coord(); ++i) {
254,519✔
922
      if (p.coord(i).cell() == cell_idx) {
147,946✔
923
        entered = true;
50,542✔
924
      }
925
    }
926

927
    // Vacuum boundary conditions: return if cell is not exited
928
    if (surf.bc_) {
106,573✔
929
      if (surf.bc_->type() == "vacuum" && !exited) {
18,191!
930
        return;
12,491✔
931
      }
932
    } else {
933

934
      // If we both enter and exit the cell of interest
935
      if (entered && exited) {
88,382✔
936
        return;
24,547✔
937
      }
938

939
      // If we did not enter nor exit the cell of interest
940
      if (!entered && !exited) {
63,835✔
941
        return;
9,621✔
942
      }
943

944
      // If cellfrom and the cell before crossing is not the cell of
945
      // interest
946
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
54,214✔
947
        return;
10,085✔
948
      }
949

950
      // If cellto and the cell after crossing is not the cell of interest
951
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
44,129✔
952
        return;
9,945✔
953
      }
954
    }
955
  }
956

957
  SourceSite site;
113,654✔
958
  site.r = p.r();
113,654✔
959
  site.u = p.u();
113,654✔
960
  site.E = p.E();
113,654✔
961
  site.time = p.time();
113,654✔
962
  site.wgt = p.wgt();
113,654✔
963
  site.delayed_group = p.delayed_group();
113,654✔
964
  site.surf_id = surf.id_;
113,654✔
965
  site.particle = p.type();
113,654✔
966
  site.parent_id = p.id();
113,654✔
967
  site.progeny_id = p.n_progeny();
113,654✔
968
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
113,654✔
969
}
970

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