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

openmc-dev / openmc / 22070080915

16 Feb 2026 04:15PM UTC coverage: 81.702% (-0.02%) from 81.72%
22070080915

Pull #3806

github

web-flow
Merge 4824efac8 into c6ef84d1d
Pull Request #3806: Introduce new C API function for slice plots

17579 of 24709 branches covered (71.14%)

Branch coverage included in aggregate %.

197 of 245 new or added lines in 4 files covered. (80.41%)

336 existing lines in 26 files now uncovered.

57190 of 66805 relevant lines covered (85.61%)

50553675.8 hits per line

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

85.61
/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,557,737,819✔
47
{
48
  if (settings::run_CE) {
2,557,737,819✔
49
    // Determine mass in eV/c^2
50
    double mass;
51
    switch (type().pdg_number()) {
2,091,827,903✔
52
    case PDG_NEUTRON:
2,022,775,528✔
53
      mass = MASS_NEUTRON_EV;
2,022,775,528✔
54
    case PDG_ELECTRON:
2,071,786,440✔
55
    case PDG_POSITRON:
56
      mass = MASS_ELECTRON_EV;
2,071,786,440✔
57
    default:
2,091,827,903✔
58
      mass = this->type().mass() * AMU_EV;
2,091,827,903✔
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,091,827,903✔
63
           (this->E() + mass);
2,091,827,903✔
64
  } else {
65
    auto& macro_xs = data::mg.macro_xs_[this->material()];
1,876,306,740✔
66
    int macro_t = this->mg_xs_cache().t;
1,876,306,740✔
67
    int macro_a = macro_xs.get_angle_index(this->u());
1,876,306,740✔
68
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
1,876,306,740✔
69
                   nullptr, nullptr, macro_t, macro_a);
1,876,306,740✔
70
  }
71
}
72

73
bool Particle::create_secondary(
102,202,698✔
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();
102,202,698✔
79
  if (idx == C_NONE) {
102,202,698!
80
    return false;
×
81
  }
82
  if (E < settings::energy_cutoff[idx]) {
102,202,698✔
83
    return false;
48,872,413✔
84
  }
85

86
  // Increment number of secondaries created (for ParticleProductionFilter)
87
  n_secondaries()++;
53,330,285✔
88

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

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

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

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

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

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

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

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

177
  // Reset event variables
178
  event() = TallyEvent::KILL;
2,555,242,668✔
179
  event_nuclide() = NUCLIDE_NONE;
2,555,242,668✔
180
  event_mt() = REACTION_NONE;
2,555,242,668✔
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
  if (lowest_coord().cell() == C_NONE) {
2,555,242,668✔
186
    if (!exhaustive_find_cell(*this)) {
210,617,897!
187
      mark_as_lost(
×
188
        "Could not find the cell containing particle " + std::to_string(id()));
×
189
      return;
×
190
    }
191

192
    // Set birth cell attribute
193
    if (cell_born() == C_NONE)
210,617,897!
194
      cell_born() = lowest_coord().cell();
210,617,897✔
195

196
    // Initialize last cells from current cell
197
    for (int j = 0; j < n_coord(); ++j) {
437,115,584✔
198
      cell_last(j) = coord(j).cell();
226,497,687✔
199
    }
200
    n_coord_last() = n_coord();
210,617,897✔
201
  }
202

203
  // Write particle track.
204
  if (write_track())
2,555,242,668✔
205
    write_particle_track(*this);
9,532✔
206

207
  if (settings::check_overlaps)
2,555,242,668!
208
    check_cell_overlap(*this);
×
209

210
  // Calculate microscopic and macroscopic cross sections
211
  if (material() != MATERIAL_VOID) {
2,555,242,668✔
212
    if (settings::run_CE) {
2,545,065,873✔
213
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,316,612,123✔
214
          density_mult() != density_mult_last()) {
351,398,025✔
215
        // If the material is the same as the last material and the
216
        // temperature hasn't changed, we don't need to lookup cross
217
        // sections again.
218
        model::materials[material()]->calculate_xs(*this);
1,613,824,793✔
219
      }
220
    } else {
221
      // Get the MG data; unlike the CE case above, we have to re-calculate
222
      // cross sections for every collision since the cross sections may
223
      // be angle-dependent
224
      data::mg.macro_xs_[material()].calculate_xs(*this);
1,876,306,740✔
225

226
      // Update the particle's group while we know we are multi-group
227
      g_last() = g();
1,876,306,740✔
228
    }
229
  } else {
230
    macro_xs().total = 0.0;
101,662,295✔
231
    macro_xs().absorption = 0.0;
101,662,295✔
232
    macro_xs().fission = 0.0;
101,662,295✔
233
    macro_xs().nu_fission = 0.0;
101,662,295✔
234
  }
235
}
236

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

242
  // Sample a distance to collision
243
  if (type() == ParticleType::electron() ||
2,958,108,359✔
244
      type() == ParticleType::positron()) {
2,550,349,338✔
245
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
49,010,912!
246
  } else if (macro_xs().total == 0.0) {
2,550,341,370✔
247
    collision_distance() = INFINITY;
101,662,295✔
248
  } else {
249
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,540,164,575✔
250
  }
251

252
  double speed = this->speed();
2,555,242,668✔
253
  double time_cutoff = settings::time_cutoff[type().transport_index()];
2,555,242,668✔
254
  double distance_cutoff =
255
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,555,242,668✔
256

257
  // Select smaller of the three distances
258
  double distance =
259
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,555,242,668✔
260

261
  // Advance particle in space and time
262
  this->move_distance(distance);
2,555,242,668✔
263
  double dt = distance / speed;
2,555,242,668✔
264
  this->time() += dt;
2,555,242,668✔
265
  this->lifetime() += dt;
2,555,242,668✔
266

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

272
  // Score track-length tallies
273
  if (!model::active_tracklength_tallies.empty()) {
2,555,242,668✔
274
    score_tracklength_tally(*this, distance);
1,562,043,081✔
275
  }
276

277
  // Score track-length estimate of k-eff
278
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,555,242,668✔
279
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,463,395,265✔
280
  }
281

282
  // Score flux derivative accumulators for differential tallies.
283
  if (!model::active_tallies.empty()) {
2,555,242,668✔
284
    score_track_derivative(*this, distance);
1,716,524,901✔
285
  }
286

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

293
void Particle::event_cross_surface()
2,202,151,307✔
294
{
295
  // Saving previous cell data
296
  for (int j = 0; j < n_coord(); ++j) {
2,827,232,866✔
297
    cell_last(j) = coord(j).cell();
2,595,467,661✔
298
  }
299
  n_coord_last() = n_coord();
2,202,151,307✔
300

301
  // Set surface that particle is on and adjust coordinate levels
302
  surface() = boundary().surface();
2,202,151,307✔
303
  n_coord() = boundary().coord_level();
2,202,151,307✔
304

305
  if (boundary().lattice_translation()[0] != 0 ||
2,202,151,307✔
306
      boundary().lattice_translation()[1] != 0 ||
2,548,975,332✔
307
      boundary().lattice_translation()[2] != 0) {
1,690,436,465✔
308
    // Particle crosses lattice boundary
309

310
    bool verbose = settings::verbosity >= 10 || trace();
683,116,767!
311
    cross_lattice(*this, boundary(), verbose);
683,116,767✔
312
    event() = TallyEvent::LATTICE;
683,116,767✔
313
  } else {
314
    // Particle crosses surface
315
    const auto& surf {model::surfaces[surface_index()].get()};
1,519,034,540✔
316
    // If BC, add particle to surface source before crossing surface
317
    if (surf->surf_source_ && surf->bc_) {
1,519,034,540✔
318
      add_surf_source_to_bank(*this, *surf);
654,359,953✔
319
    }
320
    this->cross_surface(*surf);
1,519,034,540✔
321
    // If no BC, add particle to surface source after crossing surface
322
    if (surf->surf_source_ && !surf->bc_) {
1,519,034,532✔
323
      add_surf_source_to_bank(*this, *surf);
863,553,562✔
324
    }
325
    if (settings::weight_window_checkpoint_surface) {
1,519,034,532✔
326
      apply_weight_windows(*this);
10,798✔
327
    }
328
    event() = TallyEvent::SURFACE;
1,519,034,532✔
329
  }
330
  // Score cell to cell partial currents
331
  if (!model::active_surface_tallies.empty()) {
2,202,151,299✔
332
    score_surface_tally(*this, model::active_surface_tallies);
31,747,970✔
333
  }
334
}
2,202,151,299✔
335

336
void Particle::event_collide()
2,408,411,296✔
337
{
338

339
  // Score collision estimate of keff
340
  if (settings::run_mode == RunMode::EIGENVALUE && type().is_neutron()) {
2,408,411,296✔
341
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
1,944,221,754✔
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,408,411,296✔
349
    score_surface_tally(*this, model::active_meshsurf_tallies);
57,362,660✔
350

351
  // Clear surface component
352
  surface() = SURFACE_NONE;
2,408,411,296✔
353

354
  if (settings::run_CE) {
2,408,411,296✔
355
    collision(*this);
969,184,164✔
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,408,411,296✔
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,408,411,296✔
369
    score_collision_tally(*this);
97,624,009✔
370
  if (!model::active_analog_tallies.empty()) {
2,408,411,296✔
371
    if (settings::run_CE) {
369,143,536✔
372
      score_analog_tally_ce(*this);
368,045,116✔
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,408,411,296✔
379
    pht_collision_energy();
1,840✔
380
  }
381

382
  // Reset banked weight during collision
383
  n_bank() = 0;
2,408,411,296✔
384
  bank_second_E() = 0.0;
2,408,411,296✔
385
  wgt_bank() = 0.0;
2,408,411,296✔
386

387
  // Clear number of secondaries in this collision. This is
388
  // distinct from the number of created neutrons n_bank() above!
389
  n_secondaries() = 0;
2,408,411,296✔
390

391
  zero_delayed_bank();
2,408,411,296✔
392

393
  // Reset fission logical
394
  fission() = false;
2,408,411,296✔
395

396
  // Save coordinates for tallying purposes
397
  r_last_current() = r();
2,408,411,296✔
398

399
  // Set last material to none since cross sections will need to be
400
  // re-evaluated
401
  material_last() = C_NONE;
2,408,411,296✔
402

403
  // Set all directions to base level -- right now, after a collision, only
404
  // the base level directions are changed
405
  for (int j = 0; j < n_coord() - 1; ++j) {
2,423,262,467✔
406
    if (coord(j + 1).rotated()) {
146,562,876✔
407
      // If next level is rotated, apply rotation matrix
408
      const auto& m {model::cells[coord(j).cell()]->rotation_};
9,478,740✔
409
      const auto& u {coord(j).u()};
9,478,740✔
410
      coord(j + 1).u() = u.rotate(m);
9,478,740✔
411
    } else {
412
      // Otherwise, copy this level's direction
413
      coord(j + 1).u() = coord(j).u();
137,084,136✔
414
    }
415
  }
416

417
  // Score flux derivative accumulators for differential tallies.
418
  if (!model::active_tallies.empty())
2,408,411,296✔
419
    score_collision_derivative(*this);
846,982,777✔
420

421
#ifdef OPENMC_DAGMC_ENABLED
422
  history().reset();
260,927,649✔
423
#endif
424
}
2,408,411,296✔
425

426
void Particle::event_revive_from_secondary()
2,555,242,667✔
427
{
428
  // If particle has too many events, display warning and kill it
429
  ++n_event();
2,555,242,667✔
430
  if (n_event() == settings::max_particle_events) {
2,555,242,667!
431
    warning("Particle " + std::to_string(id()) +
×
432
            " underwent maximum number of events.");
433
    wgt() = 0.0;
×
434
  }
435

436
  // Check for secondary particles if this particle is dead
437
  if (!alive()) {
2,555,242,667✔
438
    // Write final position for this particle
439
    if (write_track()) {
210,617,439✔
440
      write_particle_track(*this);
5,824✔
441
    }
442

443
    // If no secondary particles, break out of event loop
444
    if (secondary_bank().empty())
210,617,439✔
445
      return;
153,312,946✔
446

447
    from_source(&secondary_bank().back());
57,304,493✔
448
    secondary_bank().pop_back();
57,304,493✔
449
    n_event() = 0;
57,304,493✔
450
    bank_second_E() = 0.0;
57,304,493✔
451

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

469
        // Initialize last cells from current cell
470
        for (int j = 0; j < n_coord(); ++j) {
1,100✔
471
          cell_last(j) = coord(j).cell();
550✔
472
        }
473
        n_coord_last() = n_coord();
550✔
474
      }
475
      pht_secondary_particles();
550✔
476
    }
477

478
    // Enter new particle in particle track file
479
    if (write_track())
57,304,493✔
480
      add_particle_track(*this);
4,884✔
481
  }
482
}
483

484
void Particle::event_death()
153,313,946✔
485
{
486
#ifdef OPENMC_DAGMC_ENABLED
487
  history().reset();
15,404,735✔
488
#endif
489

490
  // Finish particle track output.
491
  if (write_track()) {
153,313,946✔
492
    finalize_particle_track(*this);
940✔
493
  }
494

495
// Contribute tally reduction variables to global accumulator
496
#pragma omp atomic
92,760,220✔
497
  global_tally_absorption += keff_tally_absorption();
153,313,946✔
498
#pragma omp atomic
92,391,864✔
499
  global_tally_collision += keff_tally_collision();
153,313,946✔
500
#pragma omp atomic
92,380,135✔
501
  global_tally_tracklength += keff_tally_tracklength();
153,313,946✔
502
#pragma omp atomic
92,172,576✔
503
  global_tally_leakage += keff_tally_leakage();
153,313,946✔
504

505
  // Reset particle tallies once accumulated
506
  keff_tally_absorption() = 0.0;
153,313,946✔
507
  keff_tally_collision() = 0.0;
153,313,946✔
508
  keff_tally_tracklength() = 0.0;
153,313,946✔
509
  keff_tally_leakage() = 0.0;
153,313,946✔
510

511
  if (!model::active_pulse_height_tallies.empty()) {
153,313,946✔
512
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,000✔
513
  }
514

515
  // Record the number of progeny created by this particle.
516
  // This data will be used to efficiently sort the fission bank.
517
  if (settings::run_mode == RunMode::EIGENVALUE) {
153,313,946✔
518
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
128,516,500✔
519
    simulation::progeny_per_particle[offset] = n_progeny();
128,516,500✔
520
  }
521
}
153,313,946✔
522

523
void Particle::pht_collision_energy()
1,840✔
524
{
525
  // Adds the energy particles lose in a collision to the pulse-height
526

527
  // determine index of cell in pulse_height_cells
528
  auto it = std::find(model::pulse_height_cells.begin(),
1,840✔
529
    model::pulse_height_cells.end(), lowest_coord().cell());
1,840✔
530

531
  if (it != model::pulse_height_cells.end()) {
1,840!
532
    int index = std::distance(model::pulse_height_cells.begin(), it);
1,840✔
533
    pht_storage()[index] += E_last() - E();
1,840✔
534

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

544
void Particle::pht_secondary_particles()
550✔
545
{
546
  // Removes the energy of secondary produced particles from the pulse-height
547

548
  // determine index of cell in pulse_height_cells
549
  auto it = std::find(model::pulse_height_cells.begin(),
550✔
550
    model::pulse_height_cells.end(), cell_born());
550✔
551

552
  if (it != model::pulse_height_cells.end()) {
550!
553
    int index = std::distance(model::pulse_height_cells.begin(), it);
550✔
554
    pht_storage()[index] -= E();
550✔
555
  }
556
}
550✔
557

558
void Particle::cross_surface(const Surface& surf)
1,520,696,512✔
559
{
560

561
  if (settings::verbosity >= 10 || trace()) {
1,520,696,512✔
562
    write_message(1, "    Crossing surface {}", surf.id_);
30✔
563
  }
564

565
// if we're crossing a CSG surface, make sure the DAG history is reset
566
#ifdef OPENMC_DAGMC_ENABLED
567
  if (surf.geom_type() == GeometryType::CSG)
152,770,035✔
568
    history().reset();
152,714,916✔
569
#endif
570

571
  // Handle any applicable boundary conditions.
572
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,175,484,813!
573
      settings::run_mode != RunMode::VOLUME) {
654,788,301✔
574
    surf.bc_->handle_particle(*this, surf);
654,679,261✔
575
    return;
654,679,261✔
576
  }
577

578
  // ==========================================================================
579
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
580

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

595
    cell_instance() = 0;
44,310✔
596
    if (cell->distribcell_index_ >= 0)
44,310✔
597
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
43,286✔
598

599
    material() = cell->material(cell_instance());
44,310✔
600
    sqrtkT() = cell->sqrtkT(cell_instance());
44,310✔
601
    density_mult() = cell->density_mult(cell_instance());
44,310✔
602
    return;
44,310✔
603
  }
604
#endif
605

606
  bool verbose = settings::verbosity >= 10 || trace();
865,972,941!
607
  if (neighbor_list_find_cell(*this, verbose)) {
865,972,941✔
608
    return;
865,945,751✔
609
  }
610

611
  // ==========================================================================
612
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
613

614
  // Remove lower coordinate levels
615
  n_coord() = 1;
27,190✔
616
  bool found = exhaustive_find_cell(*this, verbose);
27,190✔
617

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

624
    surface() = SURFACE_NONE;
5,270✔
625
    n_coord() = 1;
5,270✔
626
    r() += TINY_BIT * u();
5,270✔
627

628
    // Couldn't find next cell anywhere! This probably means there is an actual
629
    // undefined region in the geometry.
630

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

640
void Particle::cross_vacuum_bc(const Surface& surf)
31,861,609✔
641
{
642
  // Score any surface current tallies -- note that the particle is moved
643
  // forward slightly so that if the mesh boundary is on the surface, it is
644
  // still processed
645

646
  if (!model::active_meshsurf_tallies.empty()) {
31,861,609✔
647
    // TODO: Find a better solution to score surface currents than
648
    // physically moving the particle forward slightly
649

650
    r() += TINY_BIT * u();
852,020✔
651
    score_surface_tally(*this, model::active_meshsurf_tallies);
852,020✔
652
  }
653

654
  // Score to global leakage tally
655
  keff_tally_leakage() += wgt();
31,861,609✔
656

657
  // Kill the particle
658
  wgt() = 0.0;
31,861,609✔
659

660
  // Display message
661
  if (settings::verbosity >= 10 || trace()) {
31,861,609!
662
    write_message(1, "    Leaked out of surface {}", surf.id_);
10✔
663
  }
664
}
31,861,609✔
665

666
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
621,689,851✔
667
{
668
  // Do not handle reflective boundary conditions on lower universes
669
  if (n_coord() != 1) {
621,689,851!
670
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
671
                 " off surface in a lower universe.");
672
    return;
×
673
  }
674

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

682
  if (!model::active_surface_tallies.empty()) {
621,689,851✔
683
    score_surface_tally(*this, model::active_surface_tallies);
259,110✔
684
  }
685

686
  if (!model::active_meshsurf_tallies.empty()) {
621,689,851✔
687
    Position r {this->r()};
42,623,170✔
688
    this->r() -= TINY_BIT * u();
42,623,170✔
689
    score_surface_tally(*this, model::active_meshsurf_tallies);
42,623,170✔
690
    this->r() = r;
42,623,170✔
691
  }
692

693
  // Set the new particle direction
694
  u() = new_u;
621,689,851✔
695

696
  // Reassign particle's cell and surface
697
  coord(0).cell() = cell_last(0);
621,689,851✔
698
  surface() = -surface();
621,689,851✔
699

700
  // If a reflective surface is coincident with a lattice or universe
701
  // boundary, it is necessary to redetermine the particle's coordinates in
702
  // the lower universes.
703
  // (unless we're using a dagmc model, which has exactly one universe)
704
  n_coord() = 1;
621,689,851✔
705
  if (surf.geom_type() != GeometryType::DAG &&
1,243,376,944!
706
      !neighbor_list_find_cell(*this)) {
621,687,093!
707
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
708
                 std::to_string(surf.id_) + ".");
×
709
    return;
×
710
  }
711

712
  // Set previous coordinate going slightly past surface crossing
713
  r_last_current() = r() + TINY_BIT * u();
621,689,851✔
714

715
  // Diagnostic message
716
  if (settings::verbosity >= 10 || trace()) {
621,689,851!
717
    write_message(1, "    Reflected from surface {}", surf.id_);
×
718
  }
719
}
720

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

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

743
  // Adjust the particle's location and direction.
744
  r() = new_r;
2,041,861✔
745
  u() = new_u;
2,041,861✔
746

747
  // Reassign particle's surface
748
  surface() = new_surface;
2,041,861✔
749

750
  // Figure out what cell particle is in now
751
  n_coord() = 1;
2,041,861✔
752

753
  if (!neighbor_list_find_cell(*this)) {
2,041,861!
754
    mark_as_lost("Couldn't find particle after hitting periodic "
×
755
                 "boundary on surface " +
×
756
                 std::to_string(surf.id_) + ".");
×
757
    return;
×
758
  }
759

760
  // Set previous coordinate going slightly past surface crossing
761
  r_last_current() = r() + TINY_BIT * u();
2,041,861✔
762

763
  // Diagnostic message
764
  if (settings::verbosity >= 10 || trace()) {
2,041,861!
765
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
766
  }
767
}
768

769
void Particle::mark_as_lost(const char* message)
5,270✔
770
{
771
  // Print warning and write lost particle file
772
  warning(message);
5,270✔
773
  if (settings::max_write_lost_particles < 0 ||
5,270✔
774
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,000✔
775
    write_restart();
340✔
776
  }
777
  // Increment number of lost particles
778
  wgt() = 0.0;
5,270✔
779
#pragma omp atomic
3,154✔
780
  simulation::n_lost_particles += 1;
2,116✔
781

782
  // Count the total number of simulated particles (on this processor)
783
  auto n = simulation::current_batch * settings::gen_per_batch *
5,270✔
784
           simulation::work_per_rank;
785

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

794
void Particle::write_restart() const
340✔
795
{
796
  // Dont write another restart file if in particle restart mode
797
  if (settings::run_mode == RunMode::PARTICLE)
340✔
798
    return;
20✔
799

800
  // Set up file name
801
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
802
    simulation::current_batch, id());
591✔
803

804
#pragma omp critical(WriteParticleRestart)
374✔
805
  {
806
    // Create file
807
    hid_t file_id = file_open(filename, 'w');
320✔
808

809
    // Write filetype and version info
810
    write_attribute(file_id, "filetype", "particle restart");
320✔
811
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
320✔
812
    write_attribute(file_id, "openmc_version", VERSION);
320✔
813
#ifdef GIT_SHA1
814
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
815
#endif
816

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

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

861
    // Close file
862
    file_close(file_id);
320✔
863
  } // #pragma omp critical
864
}
320✔
865

866
void Particle::update_neutron_xs(
2,877,174,277✔
867
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
868
{
869
  // Get microscopic cross section cache
870
  auto& micro = this->neutron_xs(i_nuclide);
2,877,174,277✔
871

872
  // If the cache doesn't match, recalculate micro xs
873
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
3,126,860,369✔
874
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
3,366,355,466✔
875
      ncrystal_xs != micro.ncrystal_xs) {
2,386,978,744!
876
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,637,679,180✔
877

878
    // If NCrystal is being used, update micro cross section cache
879
    micro.ncrystal_xs = ncrystal_xs;
2,637,679,180✔
880
    if (ncrystal_xs >= 0.0) {
2,637,679,180✔
881
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
10,017,230✔
882
      ncrystal_update_micro(ncrystal_xs, micro);
10,017,230✔
883
    }
884
  }
885
}
2,877,174,277✔
886

887
//==============================================================================
888
// Non-method functions
889
//==============================================================================
890
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,517,913,515✔
891
{
892
  if (simulation::current_batch <= settings::n_inactive ||
2,417,364,915✔
893
      simulation::surf_source_bank.full()) {
1,167,642,041✔
894
    return;
1,517,795,756✔
895
  }
896

897
  // If a cell/cellfrom/cellto parameter is defined
898
  if (settings::ssw_cell_id != C_NONE) {
305,204✔
899

900
    // Retrieve cell index and storage type
901
    int cell_idx = model::cell_map[settings::ssw_cell_id];
230,200✔
902

903
    if (surf.bc_) {
230,200✔
904
      // Leave if cellto with vacuum boundary condition
905
      if (surf.bc_->type() == "vacuum" &&
164,772!
906
          settings::ssw_cell_type == SSWCellType::To) {
30,024✔
907
        return;
11,010✔
908
      }
909

910
      // Leave if other boundary condition than vacuum
911
      if (surf.bc_->type() != "vacuum") {
123,738✔
912
        return;
104,724✔
913
      }
914
    }
915

916
    // Check if the cell of interest has been exited
917
    bool exited = false;
114,466✔
918
    for (int i = 0; i < p.n_coord_last(); ++i) {
302,775✔
919
      if (p.cell_last(i) == cell_idx) {
188,309✔
920
        exited = true;
66,877✔
921
      }
922
    }
923

924
    // Check if the cell of interest has been entered
925
    bool entered = false;
114,466✔
926
    for (int i = 0; i < p.n_coord(); ++i) {
270,503✔
927
      if (p.coord(i).cell() == cell_idx) {
156,037✔
928
        entered = true;
52,063✔
929
      }
930
    }
931

932
    // Vacuum boundary conditions: return if cell is not exited
933
    if (surf.bc_) {
114,466✔
934
      if (surf.bc_->type() == "vacuum" && !exited) {
19,014!
935
        return;
13,314✔
936
      }
937
    } else {
938

939
      // If we both enter and exit the cell of interest
940
      if (entered && exited) {
95,452✔
941
        return;
24,547✔
942
      }
943

944
      // If we did not enter nor exit the cell of interest
945
      if (!entered && !exited) {
70,905✔
946
        return;
12,459✔
947
      }
948

949
      // If cellfrom and the cell before crossing is not the cell of
950
      // interest
951
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
58,446✔
952
        return;
10,444✔
953
      }
954

955
      // If cellto and the cell after crossing is not the cell of interest
956
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
48,002✔
957
        return;
10,947✔
958
      }
959
    }
960
  }
961

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

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