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

openmc-dev / openmc / 22930337917

11 Mar 2026 12:16AM UTC coverage: 81.578% (+0.02%) from 81.556%
22930337917

Pull #3766

github

web-flow
Merge 222611310 into 1dc4aa988
Pull Request #3766: Approximate multigroup velocity

17571 of 25278 branches covered (69.51%)

Branch coverage included in aggregate %.

25 of 26 new or added lines in 4 files covered. (96.15%)

419 existing lines in 11 files now uncovered.

57992 of 67349 relevant lines covered (86.11%)

44824146.01 hits per line

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

87.04
/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 = this->mass();
2,147,483,647✔
51

52
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
53
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
2,147,483,647✔
54
           (this->E() + mass);
2,147,483,647✔
55
  } else {
56
    auto mat = this->material();
2,063,937,744✔
57
    if (mat == MATERIAL_VOID)
2,063,937,744!
NEW
58
      return 1.0 / data::mg.default_inverse_velocity_[this->g()];
×
59
    auto& macro_xs = data::mg.macro_xs_[mat];
2,063,937,744✔
60
    int macro_t = this->mg_xs_cache().t;
2,063,937,744✔
61
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,744✔
62
    return 1.0 / macro_xs.get_xs(
2,147,483,647✔
63
                   MgxsType::INVERSE_VELOCITY, this->g(), macro_t, macro_a);
2,063,937,744✔
64
  }
65
}
66

67
double Particle::mass() const
2,147,483,647✔
68
{
69
  switch (type().pdg_number()) {
2,147,483,647✔
70
  case PDG_NEUTRON:
71
    return MASS_NEUTRON_EV;
72
  case PDG_ELECTRON:
54,148,211✔
73
  case PDG_POSITRON:
54,148,211✔
74
    return MASS_ELECTRON_EV;
54,148,211✔
75
  default:
22,301,654✔
76
    return this->type().mass() * AMU_EV;
22,301,654✔
77
  }
78
}
79

80
bool Particle::create_secondary(
112,656,384✔
81
  double wgt, Direction u, double E, ParticleType type)
82
{
83
  // If energy is below cutoff for this particle, don't create secondary
84
  // particle
85
  int idx = type.transport_index();
112,656,384✔
86
  if (idx == C_NONE) {
112,656,384!
87
    return false;
88
  }
89
  if (E < settings::energy_cutoff[idx]) {
112,656,384✔
90
    return false;
91
  }
92

93
  // Increment number of secondaries created (for ParticleProductionFilter)
94
  n_secondaries()++;
58,901,429✔
95

96
  auto& bank = secondary_bank().emplace_back();
58,901,429✔
97
  bank.particle = type;
58,901,429✔
98
  bank.wgt = wgt;
58,901,429✔
99
  bank.r = r();
58,901,429!
100
  bank.u = u;
58,901,429✔
101
  bank.E = settings::run_CE ? E : g();
58,901,429!
102
  bank.time = time();
58,901,429✔
103
  bank_second_E() += bank.E;
58,901,429✔
104
  return true;
58,901,429✔
105
}
106

107
void Particle::split(double wgt)
4,250,157✔
108
{
109
  auto& bank = secondary_bank().emplace_back();
4,250,157✔
110
  bank.particle = type();
4,250,157✔
111
  bank.wgt = wgt;
4,250,157✔
112
  bank.r = r();
4,250,157✔
113
  bank.u = u();
4,250,157✔
114
  bank.E = settings::run_CE ? E() : g();
4,250,157✔
115
  bank.time = time();
4,250,157✔
116

117
  // Convert signed index to a signed surface ID
118
  if (surface() == SURFACE_NONE) {
4,250,157✔
119
    bank.surf_id = SURFACE_NONE;
4,249,612✔
120
  } else {
121
    int surf_id = model::surfaces[surface_index()]->id_;
545✔
122
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
545✔
123
  }
124
}
4,250,157✔
125

126
void Particle::from_source(const SourceSite* src)
240,938,719✔
127
{
128
  // Reset some attributes
129
  clear();
240,938,719✔
130
  surface() = SURFACE_NONE;
240,938,719✔
131
  cell_born() = C_NONE;
240,938,719✔
132
  material() = C_NONE;
240,938,719✔
133
  n_collision() = 0;
240,938,719✔
134
  fission() = false;
240,938,719✔
135
  zero_flux_derivs();
240,938,719✔
136
  lifetime() = 0.0;
240,938,719✔
137
#ifdef OPENMC_DAGMC_ENABLED
138
  history().reset();
22,057,643✔
139
#endif
140

141
  // Copy attributes from source bank site
142
  type() = src->particle;
240,938,719✔
143
  wgt() = src->wgt;
240,938,719✔
144
  wgt_last() = src->wgt;
240,938,719✔
145
  r() = src->r;
240,938,719✔
146
  u() = src->u;
240,938,719✔
147
  r_born() = src->r;
240,938,719✔
148
  r_last_current() = src->r;
240,938,719✔
149
  r_last() = src->r;
240,938,719✔
150
  u_last() = src->u;
240,938,719✔
151
  if (settings::run_CE) {
240,938,719✔
152
    E() = src->E;
125,012,772✔
153
    g() = 0;
125,012,772✔
154
  } else {
155
    g() = static_cast<int>(src->E);
115,925,947✔
156
    g_last() = static_cast<int>(src->E);
115,925,947✔
157
    E() = data::mg.energy_bin_avg_[g()];
115,925,947✔
158
  }
159
  E_last() = E();
240,938,719✔
160
  time() = src->time;
240,938,719✔
161
  time_last() = src->time;
240,938,719✔
162
  parent_nuclide() = src->parent_nuclide;
240,938,719✔
163
  delayed_group() = src->delayed_group;
240,938,719✔
164

165
  // Convert signed surface ID to signed index
166
  if (src->surf_id != SURFACE_NONE) {
240,938,719✔
167
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,545✔
168
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,545✔
169
  }
170
}
240,938,719✔
171

172
void Particle::event_calculate_xs()
2,147,483,647✔
173
{
174
  // Set the random number stream
175
  stream() = STREAM_TRACKING;
2,147,483,647✔
176

177
  // Store pre-collision particle properties
178
  wgt_last() = wgt();
2,147,483,647✔
179
  E_last() = E();
2,147,483,647✔
180
  u_last() = u();
2,147,483,647✔
181
  r_last() = r();
2,147,483,647✔
182
  time_last() = time();
2,147,483,647✔
183

184
  // Reset event variables
185
  event() = TallyEvent::KILL;
2,147,483,647✔
186
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
187
  event_mt() = REACTION_NONE;
2,147,483,647✔
188

189
  // If the cell hasn't been determined based on the particle's location,
190
  // initiate a search for the current cell. This generally happens at the
191
  // beginning of the history and again for any secondary particles
192
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
193
    if (!exhaustive_find_cell(*this)) {
232,267,810!
194
      mark_as_lost(
×
195
        "Could not find the cell containing particle " + std::to_string(id()));
×
196
      return;
×
197
    }
198

199
    // Set birth cell attribute
200
    if (cell_born() == C_NONE)
232,267,810!
201
      cell_born() = lowest_coord().cell();
232,267,810✔
202

203
    // Initialize last cells from current cell
204
    for (int j = 0; j < n_coord(); ++j) {
482,007,532✔
205
      cell_last(j) = coord(j).cell();
249,739,722✔
206
    }
207
    n_coord_last() = n_coord();
232,267,810✔
208
  }
209

210
  // Write particle track.
211
  if (write_track())
2,147,483,647✔
212
    write_particle_track(*this);
10,310✔
213

214
  if (settings::check_overlaps)
2,147,483,647!
215
    check_cell_overlap(*this);
×
216

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

233
      // Update the particle's group while we know we are multi-group
234
      g_last() = g();
2,063,937,744✔
235
    }
236
  } else {
237
    macro_xs().total = 0.0;
111,838,603✔
238
    macro_xs().absorption = 0.0;
111,838,603✔
239
    macro_xs().fission = 0.0;
111,838,603✔
240
    macro_xs().nu_fission = 0.0;
111,838,603✔
241
  }
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;
108,296,422!
253
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
254
    collision_distance() = INFINITY;
111,838,603✔
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,722,564,165✔
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,892,830,006✔
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
  // Set surface that particle is on and adjust coordinate levels
309
  surface() = boundary().surface();
2,147,483,647✔
310
  n_coord() = boundary().coord_level();
2,147,483,647✔
311

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

314
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
315
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
316
      boundary().lattice_translation()[2] != 0) {
1,860,093,539✔
317
    // Particle crosses lattice boundary
318

319
    bool verbose = settings::verbosity >= 10 || trace();
750,250,909!
320
    cross_lattice(*this, boundary(), verbose);
750,250,909✔
321
    event() = TallyEvent::LATTICE;
750,250,909✔
322
  } else {
323
    // Particle crosses surface
324
    // If BC, add particle to surface source before crossing surface
325
    if (surf.surf_source_ && surf.bc_) {
1,671,551,644✔
326
      add_surf_source_to_bank(*this, surf);
720,309,054✔
327
    }
328
    this->cross_surface(surf);
1,671,551,644✔
329
    // If no BC, add particle to surface source after crossing surface
330
    if (surf.surf_source_ && !surf.bc_) {
1,671,551,635✔
331
      add_surf_source_to_bank(*this, surf);
950,004,754✔
332
    }
333
    if (settings::weight_window_checkpoint_surface) {
1,671,551,635✔
334
      apply_weight_windows(*this);
74,912✔
335
    }
336
    event() = TallyEvent::SURFACE;
1,671,551,635✔
337
  }
338
  // Score cell to cell partial currents
339
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
340
    score_surface_tally(*this, model::active_surface_tallies, surf);
34,931,567✔
341
  }
342
}
2,147,483,647✔
343

344
void Particle::event_collide()
2,147,483,647✔
345
{
346

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

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

356
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
357
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
358

359
  // Clear surface component
360
  surface() = SURFACE_NONE;
2,147,483,647✔
361

362
  if (settings::run_CE) {
2,147,483,647✔
363
    collision(*this);
1,071,965,087✔
364
  } else {
365
    collision_mg(*this);
1,783,060,477✔
366
  }
367

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

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

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

390
  // Reset banked weight during collision
391
  n_bank() = 0;
2,147,483,647✔
392
  bank_second_E() = 0.0;
2,147,483,647✔
393
  wgt_bank() = 0.0;
2,147,483,647✔
394

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

399
  zero_delayed_bank();
2,147,483,647✔
400

401
  // Reset fission logical
402
  fission() = false;
2,147,483,647✔
403

404
  // Save coordinates for tallying purposes
405
  r_last_current() = r();
2,147,483,647✔
406

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

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

425
  // Score flux derivative accumulators for differential tallies.
426
  if (!model::active_tallies.empty())
2,147,483,647✔
427
    score_collision_derivative(*this);
937,352,022✔
428

429
#ifdef OPENMC_DAGMC_ENABLED
430
  history().reset();
261,474,786✔
431
#endif
432
}
2,147,483,647✔
433

434
void Particle::event_revive_from_secondary()
2,147,483,647✔
435
{
436
  // If particle has too many events, display warning and kill it
437
  ++n_event();
2,147,483,647✔
438
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
439
    warning("Particle " + std::to_string(id()) +
×
440
            " underwent maximum number of events.");
441
    wgt() = 0.0;
×
442
  }
443

444
  // Check for secondary particles if this particle is dead
445
  if (!alive()) {
2,147,483,647✔
446
    // Write final position for this particle
447
    if (write_track()) {
232,267,406✔
448
      write_particle_track(*this);
6,244✔
449
    }
450

451
    // If no secondary particles, break out of event loop
452
    if (secondary_bank().empty())
232,267,406✔
453
      return;
454

455
    from_source(&secondary_bank().back());
63,355,105✔
456
    secondary_bank().pop_back();
63,355,105✔
457
    n_event() = 0;
63,355,105✔
458
    bank_second_E() = 0.0;
63,355,105✔
459

460
    // Subtract secondary particle energy from interim pulse-height results
461
    if (!model::active_pulse_height_tallies.empty() &&
63,355,105✔
462
        this->type().is_photon()) {
15,499✔
463
      // Since the birth cell of the particle has not been set we
464
      // have to determine it before the energy of the secondary particle can be
465
      // removed from the pulse-height of this cell.
466
      if (lowest_coord().cell() == C_NONE) {
605!
467
        bool verbose = settings::verbosity >= 10 || trace();
605!
468
        if (!exhaustive_find_cell(*this, verbose)) {
605!
469
          mark_as_lost("Could not find the cell containing particle " +
×
470
                       std::to_string(id()));
×
471
          return;
×
472
        }
473
        // Set birth cell attribute
474
        if (cell_born() == C_NONE)
605!
475
          cell_born() = lowest_coord().cell();
605✔
476

477
        // Initialize last cells from current cell
478
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
479
          cell_last(j) = coord(j).cell();
605✔
480
        }
481
        n_coord_last() = n_coord();
605✔
482
      }
483
      pht_secondary_particles();
605✔
484
    }
485

486
    // Enter new particle in particle track file
487
    if (write_track())
63,355,105✔
488
      add_particle_track(*this);
5,234✔
489
  }
490
}
491

492
void Particle::event_death()
168,913,301✔
493
{
494
#ifdef OPENMC_DAGMC_ENABLED
495
  history().reset();
15,432,415✔
496
#endif
497

498
  // Finish particle track output.
499
  if (write_track()) {
168,913,301✔
500
    finalize_particle_track(*this);
1,010✔
501
  }
502

503
// Contribute tally reduction variables to global accumulator
504
#pragma omp atomic
93,253,441✔
505
  global_tally_absorption += keff_tally_absorption();
168,913,301✔
506
#pragma omp atomic
92,880,065✔
507
  global_tally_collision += keff_tally_collision();
168,913,301✔
508
#pragma omp atomic
93,615,744✔
509
  global_tally_tracklength += keff_tally_tracklength();
168,913,301✔
510
#pragma omp atomic
92,602,225✔
511
  global_tally_leakage += keff_tally_leakage();
168,913,301✔
512

513
  // Reset particle tallies once accumulated
514
  keff_tally_absorption() = 0.0;
168,913,301✔
515
  keff_tally_collision() = 0.0;
168,913,301✔
516
  keff_tally_tracklength() = 0.0;
168,913,301✔
517
  keff_tally_leakage() = 0.0;
168,913,301✔
518

519
  if (!model::active_pulse_height_tallies.empty()) {
168,913,301✔
520
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
521
  }
522

523
  // Record the number of progeny created by this particle.
524
  // This data will be used to efficiently sort the fission bank.
525
  if (settings::run_mode == RunMode::EIGENVALUE) {
168,913,301✔
526
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
141,534,700✔
527
    simulation::progeny_per_particle[offset] = n_progeny();
141,534,700✔
528
  }
529
}
168,913,301✔
530

531
void Particle::pht_collision_energy()
2,024✔
532
{
533
  // Adds the energy particles lose in a collision to the pulse-height
534

535
  // determine index of cell in pulse_height_cells
536
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
537
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024!
538

539
  if (it != model::pulse_height_cells.end()) {
2,024!
540
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
541
    pht_storage()[index] += E_last() - E();
2,024✔
542

543
    // If the energy of the particle is below the cutoff, it will not be sampled
544
    // so its energy is added to the pulse-height in the cell
545
    int photon = ParticleType::photon().transport_index();
2,024✔
546
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
547
      pht_storage()[index] += E();
825✔
548
    }
549
  }
550
}
2,024✔
551

552
void Particle::pht_secondary_particles()
605✔
553
{
554
  // Removes the energy of secondary produced particles from the pulse-height
555

556
  // determine index of cell in pulse_height_cells
557
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
558
    model::pulse_height_cells.end(), cell_born());
605!
559

560
  if (it != model::pulse_height_cells.end()) {
605!
561
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
562
    pht_storage()[index] -= E();
605✔
563
  }
564
}
605✔
565

566
void Particle::cross_surface(const Surface& surf)
1,673,428,478✔
567
{
568

569
  if (settings::verbosity >= 10 || trace()) {
1,673,428,478✔
570
    write_message(1, "    Crossing surface {}", surf.id_);
66✔
571
  }
572

573
// if we're crossing a CSG surface, make sure the DAG history is reset
574
#ifdef OPENMC_DAGMC_ENABLED
575
  if (surf.geom_type() == GeometryType::CSG)
152,793,439✔
576
    history().reset();
152,736,280✔
577
#endif
578

579
  // Handle any applicable boundary conditions.
580
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
1,673,428,478!
581
      settings::run_mode != RunMode::VOLUME) {
582
    surf.bc_->handle_particle(*this, surf);
720,661,162✔
583
    return;
720,661,162✔
584
  }
585

586
  // ==========================================================================
587
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
588

589
#ifdef OPENMC_DAGMC_ENABLED
590
  // in DAGMC, we know what the next cell should be
591
  if (surf.geom_type() == GeometryType::DAG) {
86,834,455✔
592
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
46,350✔
593
                       lowest_coord().universe()) -
46,350✔
594
                     1;
46,350✔
595
    // save material, temperature, and density multiplier
596
    material_last() = material();
46,350✔
597
    sqrtkT_last() = sqrtkT();
46,350✔
598
    density_mult_last() = density_mult();
46,350✔
599
    // set new cell value
600
    lowest_coord().cell() = i_cell;
46,350✔
601
    auto& cell = model::cells[i_cell];
46,350✔
602

603
    cell_instance() = 0;
46,350✔
604
    if (cell->distribcell_index_ >= 0)
46,350✔
605
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
45,326✔
606

607
    material() = cell->material(cell_instance());
46,350!
608
    sqrtkT() = cell->sqrtkT(cell_instance());
46,350!
609
    density_mult() = cell->density_mult(cell_instance());
46,350✔
610
    return;
46,350✔
611
  }
612
#endif
613

614
  bool verbose = settings::verbosity >= 10 || trace();
952,720,966!
615
  if (neighbor_list_find_cell(*this, verbose)) {
952,720,966✔
616
    return;
617
  }
618

619
  // ==========================================================================
620
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
621

622
  // Remove lower coordinate levels
623
  n_coord() = 1;
29,911✔
624
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
625

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

632
    surface() = SURFACE_NONE;
5,799✔
633
    n_coord() = 1;
5,799✔
634
    r() += TINY_BIT * u();
5,799✔
635

636
    // Couldn't find next cell anywhere! This probably means there is an actual
637
    // undefined region in the geometry.
638

639
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
640
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
641
                   " crossed surface " + std::to_string(surf.id_) +
17,388✔
642
                   " it could not be located in any cell and it did not leak.");
643
      return;
5,790✔
644
    }
645
  }
646
}
647

648
void Particle::cross_vacuum_bc(const Surface& surf)
35,098,935✔
649
{
650
  // Score any surface current tallies -- note that the particle is moved
651
  // forward slightly so that if the mesh boundary is on the surface, it is
652
  // still processed
653

654
  if (!model::active_meshsurf_tallies.empty()) {
35,098,935✔
655
    // TODO: Find a better solution to score surface currents than
656
    // physically moving the particle forward slightly
657

658
    r() += TINY_BIT * u();
937,222✔
659
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
937,222✔
660
  }
661

662
  // Score to global leakage tally
663
  keff_tally_leakage() += wgt();
35,098,935✔
664

665
  // Kill the particle
666
  wgt() = 0.0;
35,098,935✔
667

668
  // Display message
669
  if (settings::verbosity >= 10 || trace()) {
35,098,935!
670
    write_message(1, "    Leaked out of surface {}", surf.id_);
22✔
671
  }
672
}
35,098,935✔
673

674
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
684,318,903✔
675
{
676
  // Do not handle reflective boundary conditions on lower universes
677
  if (n_coord() != 1) {
684,318,903!
678
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
679
                 " off surface in a lower universe.");
680
    return;
×
681
  }
682

683
  // Score surface currents since reflection causes the direction of the
684
  // particle to change. For surface filters, we need to score the tallies
685
  // twice, once before the particle's surface attribute has changed and
686
  // once after. For mesh surface filters, we need to artificially move
687
  // the particle slightly back in case the surface crossing is coincident
688
  // with a mesh boundary
689

690
  if (!model::active_surface_tallies.empty()) {
684,318,903✔
691
    score_surface_tally(*this, model::active_surface_tallies, surf);
285,021✔
692
  }
693

694
  if (!model::active_meshsurf_tallies.empty()) {
684,318,903✔
695
    Position r {this->r()};
46,885,487✔
696
    this->r() -= TINY_BIT * u();
46,885,487✔
697
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
698
    this->r() = r;
46,885,487✔
699
  }
700

701
  // Set the new particle direction
702
  u() = new_u;
684,318,903✔
703

704
  // Reassign particle's cell and surface
705
  coord(0).cell() = cell_last(0);
684,318,903✔
706
  surface() = -surface();
684,318,903✔
707

708
  // If a reflective surface is coincident with a lattice or universe
709
  // boundary, it is necessary to redetermine the particle's coordinates in
710
  // the lower universes.
711
  // (unless we're using a dagmc model, which has exactly one universe)
712
  n_coord() = 1;
684,318,903✔
713
  if (surf.geom_type() != GeometryType::DAG &&
1,368,635,048!
714
      !neighbor_list_find_cell(*this)) {
684,316,145✔
715
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
716
                 std::to_string(surf.id_) + ".");
×
717
    return;
×
718
  }
719

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

723
  // Diagnostic message
724
  if (settings::verbosity >= 10 || trace()) {
684,318,903!
725
    write_message(1, "    Reflected from surface {}", surf.id_);
×
726
  }
727
}
728

729
void Particle::cross_periodic_bc(
2,248,790✔
730
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
731
{
732
  // Do not handle periodic boundary conditions on lower universes
733
  if (n_coord() != 1) {
2,248,790!
734
    mark_as_lost(
×
735
      "Cannot transfer particle " + std::to_string(id()) +
×
736
      " across surface in a lower universe. Boundary conditions must be "
737
      "applied to root universe.");
738
    return;
×
739
  }
740

741
  // Score surface currents since reflection causes the direction of the
742
  // particle to change -- artificially move the particle slightly back in
743
  // case the surface crossing is coincident with a mesh boundary
744
  if (!model::active_meshsurf_tallies.empty()) {
2,248,790!
745
    Position r {this->r()};
×
746
    this->r() -= TINY_BIT * u();
×
747
    score_meshsurface_tally(*this, model::active_meshsurf_tallies);
×
748
    this->r() = r;
×
749
  }
750

751
  // Adjust the particle's location and direction.
752
  r() = new_r;
2,248,790✔
753
  u() = new_u;
2,248,790✔
754

755
  // Reassign particle's surface
756
  surface() = new_surface;
2,248,790✔
757

758
  // Figure out what cell particle is in now
759
  n_coord() = 1;
2,248,790✔
760

761
  if (!neighbor_list_find_cell(*this)) {
2,248,790!
762
    mark_as_lost("Couldn't find particle after hitting periodic "
×
763
                 "boundary on surface " +
×
764
                 std::to_string(surf.id_) + ".");
×
765
    return;
×
766
  }
767

768
  // Set previous coordinate going slightly past surface crossing
769
  r_last_current() = r() + TINY_BIT * u();
2,248,790✔
770

771
  // Diagnostic message
772
  if (settings::verbosity >= 10 || trace()) {
2,248,790!
773
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
774
  }
775
}
776

777
void Particle::mark_as_lost(const char* message)
5,799✔
778
{
779
  // Print warning and write lost particle file
780
  warning(message);
5,799✔
781
  if (settings::max_write_lost_particles < 0 ||
5,799✔
782
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
783
    write_restart();
374✔
784
  }
785
  // Increment number of lost particles
786
  wgt() = 0.0;
5,799✔
787
#pragma omp atomic
3,154✔
788
  simulation::n_lost_particles += 1;
2,645✔
789

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

794
  // Abort the simulation if the maximum number of lost particles has been
795
  // reached
796
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
797
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
798
    fatal_error("Maximum number of lost particles has been reached.");
9✔
799
  }
800
}
5,790✔
801

802
void Particle::write_restart() const
374✔
803
{
804
  // Dont write another restart file if in particle restart mode
805
  if (settings::run_mode == RunMode::PARTICLE)
374✔
806
    return;
22✔
807

808
  // Set up file name
809
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
352✔
810
    simulation::current_batch, id());
352✔
811

812
#pragma omp critical(WriteParticleRestart)
187✔
813
  {
352✔
814
    // Create file
815
    hid_t file_id = file_open(filename, 'w');
352✔
816

817
    // Write filetype and version info
818
    write_attribute(file_id, "filetype", "particle restart");
352✔
819
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
352✔
820
    write_attribute(file_id, "openmc_version", VERSION);
352✔
821
#ifdef GIT_SHA1
822
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
823
#endif
824

825
    // Write data to file
826
    write_dataset(file_id, "current_batch", simulation::current_batch);
352✔
827
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
352✔
828
    write_dataset(file_id, "current_generation", simulation::current_gen);
352✔
829
    write_dataset(file_id, "n_particles", settings::n_particles);
352✔
830
    switch (settings::run_mode) {
352!
831
    case RunMode::FIXED_SOURCE:
220✔
832
      write_dataset(file_id, "run_mode", "fixed source");
220✔
833
      break;
115✔
834
    case RunMode::EIGENVALUE:
132✔
835
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
836
      break;
72✔
837
    case RunMode::PARTICLE:
×
838
      write_dataset(file_id, "run_mode", "particle restart");
×
839
      break;
840
    default:
841
      break;
842
    }
843
    write_dataset(file_id, "id", id());
352✔
844
    write_dataset(file_id, "type", type().pdg_number());
352✔
845

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

869
    // Close file
870
    file_close(file_id);
352✔
871
  } // #pragma omp critical
872
}
352✔
873

874
void Particle::update_neutron_xs(
2,147,483,647✔
875
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
876
{
877
  // Get microscopic cross section cache
878
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
879

880
  // If the cache doesn't match, recalculate micro xs
881
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
882
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
883
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
884
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
885

886
    // If NCrystal is being used, update micro cross section cache
887
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
888
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
889
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
890
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
891
    }
892
  }
893
}
2,147,483,647✔
894

895
//==============================================================================
896
// Non-method functions
897
//==============================================================================
898
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,670,313,808✔
899
{
900
  if (simulation::current_batch <= settings::n_inactive ||
1,670,313,808✔
901
      simulation::surf_source_bank.full()) {
1,284,841,187✔
902
    return;
1,670,184,155✔
903
  }
904

905
  // If a cell/cellfrom/cellto parameter is defined
906
  if (settings::ssw_cell_id != C_NONE) {
337,078✔
907

908
    // Retrieve cell index and storage type
909
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,433✔
910

911
    if (surf.bc_) {
254,433✔
912
      // Leave if cellto with vacuum boundary condition
913
      if (surf.bc_->type() == "vacuum" &&
298,918✔
914
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
915
        return;
916
      }
917

918
      // Leave if other boundary condition than vacuum
919
      if (surf.bc_->type() != "vacuum") {
274,648✔
920
        return;
921
      }
922
    }
923

924
    // Check if the cell of interest has been exited
925
    bool exited = false;
926
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,665✔
927
      if (p.cell_last(i) == cell_idx) {
207,727✔
928
        exited = true;
73,763✔
929
      }
930
    }
931

932
    // Check if the cell of interest has been entered
933
    bool entered = false;
934
    for (int i = 0; i < p.n_coord(); ++i) {
297,967✔
935
      if (p.coord(i).cell() == cell_idx) {
172,029✔
936
        entered = true;
57,515✔
937
      }
938
    }
939

940
    // Vacuum boundary conditions: return if cell is not exited
941
    if (surf.bc_) {
125,938✔
942
      if (surf.bc_->type() == "vacuum" && !exited) {
41,928!
943
        return;
944
      }
945
    } else {
946

947
      // If we both enter and exit the cell of interest
948
      if (entered && exited) {
104,974✔
949
        return;
950
      }
951

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

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

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

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

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