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

openmc-dev / openmc / 21489137916

29 Jan 2026 05:58PM UTC coverage: 81.248% (-0.7%) from 81.953%
21489137916

Pull #3757

github

web-flow
Merge 9d16542dd into f7a734189
Pull Request #3757: Testing point detectors

17267 of 24417 branches covered (70.72%)

Branch coverage included in aggregate %.

94 of 512 new or added lines in 26 files covered. (18.36%)

3 existing lines in 2 files now uncovered.

55822 of 65541 relevant lines covered (85.17%)

43735001.71 hits per line

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

78.6
/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::mass() const
2,114,093,850✔
47
{
48
  // Determine mass in eV/c^2
49
  switch (this->type()) {
2,114,093,850!
50
  case ParticleType::neutron:
2,038,819,939✔
51
    return MASS_NEUTRON_EV;
2,038,819,939✔
52
  case ParticleType::photon:
21,806,970✔
53
    return 0.0;
21,806,970✔
54
  case ParticleType::electron:
53,466,941✔
55
  case ParticleType::positron:
56
    return MASS_ELECTRON_EV;
53,466,941✔
57
  }
NEW
58
  UNREACHABLE();
×
59
}
60

61
double Particle::speed() const
2,147,483,647✔
62
{
63
  if (settings::run_CE) {
2,147,483,647✔
64
    double mass = this->mass();
2,114,093,850✔
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)) /
2,114,093,850✔
67
           (this->E() + mass);
2,114,093,850✔
68
  } else {
69
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
70
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
71
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
72
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
73
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
74
  }
75
}
76

77
bool Particle::create_secondary(
111,533,613✔
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
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
111,533,613✔
83
    return false;
53,313,832✔
84
  }
85

86
  auto& bank = secondary_bank().emplace_back();
58,219,781✔
87
  bank.particle = type;
58,219,781✔
88
  bank.wgt = wgt;
58,219,781✔
89
  bank.r = r();
58,219,781✔
90
  bank.u = u;
58,219,781✔
91
  bank.E = settings::run_CE ? E : g();
58,219,781!
92
  bank.time = time();
58,219,781✔
93
  bank_second_E() += bank.E;
58,219,781✔
94
  return true;
58,219,781✔
95
}
96

97
void Particle::split(double wgt)
4,088,033✔
98
{
99
  auto& bank = secondary_bank().emplace_back();
4,088,033✔
100
  bank.particle = type();
4,088,033✔
101
  bank.wgt = wgt;
4,088,033✔
102
  bank.r = r();
4,088,033✔
103
  bank.u = u();
4,088,033✔
104
  bank.E = settings::run_CE ? E() : g();
4,088,033✔
105
  bank.time = time();
4,088,033✔
106

107
  // Convert signed index to a signed surface ID
108
  if (surface() == SURFACE_NONE) {
4,088,033✔
109
    bank.surf_id = SURFACE_NONE;
4,087,697✔
110
  } else {
111
    int surf_id = model::surfaces[surface_index()]->id_;
336✔
112
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
336!
113
  }
114
}
4,088,033✔
115

116
void Particle::from_source(const SourceSite* src)
238,071,727✔
117
{
118
  // Reset some attributes
119
  clear();
238,071,727✔
120
  surface() = SURFACE_NONE;
238,071,727✔
121
  cell_born() = C_NONE;
238,071,727✔
122
  material() = C_NONE;
238,071,727✔
123
  n_collision() = 0;
238,071,727✔
124
  fission() = false;
238,071,727✔
125
  zero_flux_derivs();
238,071,727✔
126
  lifetime() = 0.0;
238,071,727✔
127
#ifdef OPENMC_DAGMC_ENABLED
128
  history().reset();
21,802,419✔
129
#endif
130

131
  // Copy attributes from source bank site
132
  type() = src->particle;
238,071,727✔
133
  wgt() = src->wgt;
238,071,727✔
134
  wgt_last() = src->wgt;
238,071,727✔
135
  r() = src->r;
238,071,727✔
136
  u() = src->u;
238,071,727✔
137
  r_born() = src->r;
238,071,727✔
138
  r_last_current() = src->r;
238,071,727✔
139
  r_last() = src->r;
238,071,727✔
140
  u_last() = src->u;
238,071,727✔
141
  if (settings::run_CE) {
238,071,727✔
142
    E() = src->E;
122,333,110✔
143
    g() = 0;
122,333,110✔
144
  } else {
145
    g() = static_cast<int>(src->E);
115,738,617✔
146
    g_last() = static_cast<int>(src->E);
115,738,617✔
147
    E() = data::mg.energy_bin_avg_[g()];
115,738,617✔
148
  }
149
  E_last() = E();
238,071,727✔
150
  time() = src->time;
238,071,727✔
151
  time_last() = src->time;
238,071,727✔
152
  parent_nuclide() = src->parent_nuclide;
238,071,727✔
153
  delayed_group() = src->delayed_group;
238,071,727✔
154

155
  // Convert signed surface ID to signed index
156
  if (src->surf_id != SURFACE_NONE) {
238,071,727✔
157
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,336✔
158
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,336!
159
  }
160
}
238,071,727✔
161

NEW
162
void Particle::initialize_pseudoparticle(
×
163
  Particle& p, Direction u_new, double E_new)
164
{
165
  // Reset some attributes
NEW
166
  clear();
×
NEW
167
  surface() = SURFACE_NONE;
×
NEW
168
  cell_born() = C_NONE;
×
NEW
169
  material() = C_NONE;
×
NEW
170
  n_collision() = 0;
×
NEW
171
  fission() = false;
×
NEW
172
  zero_flux_derivs();
×
NEW
173
  lifetime() = 0.0;
×
174

175
  // Copy attributes from particle
NEW
176
  type() = p.type();
×
NEW
177
  wgt() = p.wgt();
×
NEW
178
  wgt_last() = p.wgt();
×
NEW
179
  r() = p.r();
×
NEW
180
  u() = u_new;
×
NEW
181
  r_born() = p.r();
×
NEW
182
  r_last_current() = p.r();
×
NEW
183
  r_last() = p.r();
×
NEW
184
  u_last() = p.u();
×
NEW
185
  if (settings::run_CE) {
×
NEW
186
    E() = E_new;
×
NEW
187
    g() = 0;
×
188
  } else {
NEW
189
    g() = static_cast<int>(E_new);
×
NEW
190
    g_last() = static_cast<int>(E_new);
×
NEW
191
    E() = data::mg.energy_bin_avg_[g()];
×
192
  }
NEW
193
  E_last() = E();
×
NEW
194
  time() = p.time();
×
NEW
195
  time_last() = p.time();
×
NEW
196
}
×
197

198
void Particle::event_calculate_xs()
2,147,483,647✔
199
{
200
  // Set the random number stream
201
  stream() = STREAM_TRACKING;
2,147,483,647✔
202

203
  // Store pre-collision particle properties
204
  wgt_last() = wgt();
2,147,483,647✔
205
  E_last() = E();
2,147,483,647✔
206
  u_last() = u();
2,147,483,647✔
207
  r_last() = r();
2,147,483,647✔
208
  time_last() = time();
2,147,483,647✔
209

210
  // Reset event variables
211
  event() = TallyEvent::KILL;
2,147,483,647✔
212
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
213
  event_mt() = REACTION_NONE;
2,147,483,647✔
214

215
  // If the cell hasn't been determined based on the particle's location,
216
  // initiate a search for the current cell. This generally happens at the
217
  // beginning of the history and again for any secondary particles
218
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
219
    if (!exhaustive_find_cell(*this)) {
229,587,818!
220
      mark_as_lost(
×
221
        "Could not find the cell containing particle " + std::to_string(id()));
×
222
      return;
×
223
    }
224

225
    // Set birth cell attribute
226
    if (cell_born() == C_NONE)
229,587,818!
227
      cell_born() = lowest_coord().cell();
229,587,818✔
228

229
    // Initialize last cells from current cell
230
    for (int j = 0; j < n_coord(); ++j) {
476,200,316✔
231
      cell_last(j) = coord(j).cell();
246,612,498✔
232
    }
233
    n_coord_last() = n_coord();
229,587,818✔
234
  }
235

236
  // Write particle track.
237
  if (write_track())
2,147,483,647✔
238
    write_particle_track(*this);
10,811✔
239

240
  if (settings::check_overlaps)
2,147,483,647!
241
    check_cell_overlap(*this);
×
242

243
  // Calculate microscopic and macroscopic cross sections
244
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
245
    if (settings::run_CE) {
2,147,483,647✔
246
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
247
          density_mult() != density_mult_last()) {
365,038,835✔
248
        // If the material is the same as the last material and the
249
        // temperature hasn't changed, we don't need to lookup cross
250
        // sections again.
251
        model::materials[material()]->calculate_xs(*this);
1,609,792,759✔
252
      }
253
    } else {
254
      // Get the MG data; unlike the CE case above, we have to re-calculate
255
      // cross sections for every collision since the cross sections may
256
      // be angle-dependent
257
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,063,937,414✔
258

259
      // Update the particle's group while we know we are multi-group
260
      g_last() = g();
2,063,937,414✔
261
    }
262
  } else {
263
    macro_xs().total = 0.0;
111,825,187✔
264
    macro_xs().absorption = 0.0;
111,825,187✔
265
    macro_xs().fission = 0.0;
111,825,187✔
266
    macro_xs().nu_fission = 0.0;
111,825,187✔
267
  }
268
}
269

270
void Particle::event_advance()
2,147,483,647✔
271
{
272
  // Find the distance to the nearest boundary
273
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
274

275
  // Sample a distance to collision
276
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
277
    collision_distance() = material() == MATERIAL_VOID ? INFINITY : 0.0;
53,466,941!
278
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
279
    collision_distance() = INFINITY;
111,825,187✔
280
  } else {
281
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
282
  }
283

284
  double speed = this->speed();
2,147,483,647✔
285
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
286
  double distance_cutoff =
287
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
288

289
  // Select smaller of the three distances
290
  double distance =
291
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
292

293
  // Advance particle in space and time
294
  this->move_distance(distance);
2,147,483,647✔
295
  double dt = distance / speed;
2,147,483,647✔
296
  this->time() += dt;
2,147,483,647✔
297
  this->lifetime() += dt;
2,147,483,647✔
298

299
  // Score timed track-length tallies
300
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
301
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
302
  }
303

304
  // Score track-length tallies
305
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
306
    score_tracklength_tally(*this, distance);
1,562,600,011✔
307
  }
308

309
  // Score track-length estimate of k-eff
310
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
311
      type() == ParticleType::neutron) {
2,147,483,647✔
312
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
313
  }
314

315
  // Score flux derivative accumulators for differential tallies.
316
  if (!model::active_tallies.empty()) {
2,147,483,647✔
317
    score_track_derivative(*this, distance);
1,732,042,634✔
318
  }
319

320
  // Set particle weight to zero if it hit the time boundary
321
  if (distance == distance_cutoff) {
2,147,483,647✔
322
    wgt() = 0.0;
224,928✔
323
  }
324
}
2,147,483,647✔
325

326
void Particle::event_cross_surface()
2,147,483,647✔
327
{
328
  // Saving previous cell data
329
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
330
    cell_last(j) = coord(j).cell();
2,147,483,647✔
331
  }
332
  n_coord_last() = n_coord();
2,147,483,647✔
333

334
  // Set surface that particle is on and adjust coordinate levels
335
  surface() = boundary().surface();
2,147,483,647✔
336
  n_coord() = boundary().coord_level();
2,147,483,647✔
337

338
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
339
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
340
      boundary().lattice_translation()[2] != 0) {
1,695,553,341✔
341
    // Particle crosses lattice boundary
342

343
    bool verbose = settings::verbosity >= 10 || trace();
732,435,656!
344
    cross_lattice(*this, boundary(), verbose);
732,435,656✔
345
    event() = TallyEvent::LATTICE;
732,435,656✔
346
  } else {
347
    // Particle crosses surface
348
    const auto& surf {model::surfaces[surface_index()].get()};
1,507,011,411✔
349
    // If BC, add particle to surface source before crossing surface
350
    if (surf->surf_source_ && surf->bc_) {
1,507,011,411✔
351
      add_surf_source_to_bank(*this, *surf);
688,552,835✔
352
    }
353
    this->cross_surface(*surf);
1,507,011,411✔
354
    // If no BC, add particle to surface source after crossing surface
355
    if (surf->surf_source_ && !surf->bc_) {
1,507,011,402✔
356
      add_surf_source_to_bank(*this, *surf);
817,220,740✔
357
    }
358
    if (settings::weight_window_checkpoint_surface) {
1,507,011,402✔
359
      apply_weight_windows(*this);
10,738!
360
    }
361
    event() = TallyEvent::SURFACE;
1,507,011,402✔
362
  }
363
  // Score cell to cell partial currents
364
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
365
    score_surface_tally(*this, model::active_surface_tallies);
34,922,767✔
366
  }
367
}
2,147,483,647✔
368

369
void Particle::event_collide()
2,147,483,647✔
370
{
371
  // Score collision estimate of keff
372
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
373
      type() == ParticleType::neutron) {
2,147,483,647✔
374
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,125,051,519✔
375
  }
376

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

381
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
382
    score_surface_tally(*this, model::active_meshsurf_tallies);
63,098,926✔
383

384
  // Clear surface component
385
  surface() = SURFACE_NONE;
2,147,483,647✔
386

387
  if (settings::run_CE) {
2,147,483,647✔
388
    collision(*this);
943,847,945✔
389
  } else {
390
    collision_mg(*this);
1,783,060,477✔
391
  }
392

393
  // Collision track feature to recording particle interaction
394
  if (settings::collision_track) {
2,147,483,647✔
395
    collision_track_record(*this);
150,087✔
396
  }
397

398
  // Score collision estimator tallies -- this is done after a collision
399
  // has occurred rather than before because we need information on the
400
  // outgoing energy for any tallies with an outgoing energy filter
401
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
402
    score_collision_tally(*this);
107,059,635✔
403
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
404
    if (settings::run_CE) {
291,821,708✔
405
      score_analog_tally_ce(*this);
290,613,446✔
406
    } else {
407
      score_analog_tally_mg(*this);
1,208,262✔
408
    }
409
  }
410

411
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
412
      type() == ParticleType::photon) {
16,918✔
413
    pht_collision_energy();
2,024✔
414
  }
415

416
  // Reset banked weight during collision
417
  n_bank() = 0;
2,147,483,647✔
418
  bank_second_E() = 0.0;
2,147,483,647✔
419
  wgt_bank() = 0.0;
2,147,483,647✔
420
  zero_delayed_bank();
2,147,483,647✔
421

422
  // Reset fission logical
423
  fission() = false;
2,147,483,647✔
424

425
  // Save coordinates for tallying purposes
426
  r_last_current() = r();
2,147,483,647✔
427

428
  // Set last material to none since cross sections will need to be
429
  // re-evaluated
430
  material_last() = C_NONE;
2,147,483,647✔
431

432
  // Set all directions to base level -- right now, after a collision, only
433
  // the base level directions are changed
434
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
435
    if (coord(j + 1).rotated()) {
143,189,203✔
436
      // If next level is rotated, apply rotation matrix
437
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,426,614✔
438
      const auto& u {coord(j).u()};
10,426,614✔
439
      coord(j + 1).u() = u.rotate(m);
10,426,614✔
440
    } else {
441
      // Otherwise, copy this level's direction
442
      coord(j + 1).u() = coord(j).u();
132,762,589✔
443
    }
444
  }
445

446
  // Score flux derivative accumulators for differential tallies.
447
  if (!model::active_tallies.empty())
2,147,483,647✔
448
    score_collision_derivative(*this);
816,212,158✔
449

450
#ifdef OPENMC_DAGMC_ENABLED
451
  history().reset();
249,993,189✔
452
#endif
453
}
2,147,483,647✔
454

455
void Particle::event_revive_from_secondary()
2,147,483,647✔
456
{
457
  // If particle has too many events, display warning and kill it
458
  ++n_event();
2,147,483,647✔
459
  if (n_event() == settings::max_particle_events) {
2,147,483,647!
460
    warning("Particle " + std::to_string(id()) +
×
461
            " underwent maximum number of events.");
462
    wgt() = 0.0;
×
463
  }
464

465
  // Check for secondary particles if this particle is dead
466
  if (!alive()) {
2,147,483,647✔
467
    // Write final position for this particle
468
    if (write_track()) {
229,587,414✔
469
      write_particle_track(*this);
6,674✔
470
    }
471

472
    // If no secondary particles, break out of event loop
473
    if (secondary_bank().empty())
229,587,414✔
474
      return;
167,076,081✔
475

476
    from_source(&secondary_bank().back());
62,511,333✔
477
    secondary_bank().pop_back();
62,511,333✔
478
    n_event() = 0;
62,511,333✔
479
    bank_second_E() = 0.0;
62,511,333✔
480

481
    // Subtract secondary particle energy from interim pulse-height results
482
    if (!model::active_pulse_height_tallies.empty() &&
62,526,832✔
483
        this->type() == ParticleType::photon) {
15,499✔
484
      // Since the birth cell of the particle has not been set we
485
      // have to determine it before the energy of the secondary particle can be
486
      // removed from the pulse-height of this cell.
487
      if (lowest_coord().cell() == C_NONE) {
605!
488
        bool verbose = settings::verbosity >= 10 || trace();
605!
489
        if (!exhaustive_find_cell(*this, verbose)) {
605!
490
          mark_as_lost("Could not find the cell containing particle " +
×
491
                       std::to_string(id()));
×
492
          return;
×
493
        }
494
        // Set birth cell attribute
495
        if (cell_born() == C_NONE)
605!
496
          cell_born() = lowest_coord().cell();
605✔
497

498
        // Initialize last cells from current cell
499
        for (int j = 0; j < n_coord(); ++j) {
1,210✔
500
          cell_last(j) = coord(j).cell();
605✔
501
        }
502
        n_coord_last() = n_coord();
605✔
503
      }
504
      pht_secondary_particles();
605✔
505
    }
506

507
    // Enter new particle in particle track file
508
    if (write_track())
62,511,333✔
509
      add_particle_track(*this);
5,604✔
510
  }
511
}
512

513
void Particle::event_death()
167,077,081✔
514
{
515
#ifdef OPENMC_DAGMC_ENABLED
516
  history().reset();
15,264,135✔
517
#endif
518

519
  // Finish particle track output.
520
  if (write_track()) {
167,077,081✔
521
    finalize_particle_track(*this);
1,070✔
522
  }
523

524
// Contribute tally reduction variables to global accumulator
525
#pragma omp atomic
91,950,277✔
526
  global_tally_absorption += keff_tally_absorption();
167,077,081✔
527
#pragma omp atomic
92,283,811✔
528
  global_tally_collision += keff_tally_collision();
167,077,081✔
529
#pragma omp atomic
91,627,804✔
530
  global_tally_tracklength += keff_tally_tracklength();
167,077,081✔
531
#pragma omp atomic
91,332,756✔
532
  global_tally_leakage += keff_tally_leakage();
167,077,081✔
533

534
  // Reset particle tallies once accumulated
535
  keff_tally_absorption() = 0.0;
167,077,081✔
536
  keff_tally_collision() = 0.0;
167,077,081✔
537
  keff_tally_tracklength() = 0.0;
167,077,081✔
538
  keff_tally_leakage() = 0.0;
167,077,081✔
539

540
  if (!model::active_pulse_height_tallies.empty()) {
167,077,081✔
541
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
542
  }
543

544
  // Record the number of progeny created by this particle.
545
  // This data will be used to efficiently sort the fission bank.
546
  if (settings::run_mode == RunMode::EIGENVALUE) {
167,077,081✔
547
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
140,925,700✔
548
    simulation::progeny_per_particle[offset] = n_progeny();
140,925,700✔
549
  }
550
}
167,077,081✔
551

NEW
552
void Particle::event_advance_pseudo(double& total_distance, double& mfp)
×
553
{
554
  // Find the distance to the nearest boundary
NEW
555
  boundary() = distance_to_boundary(*this);
×
556

NEW
557
  double speed = this->speed();
×
NEW
558
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
×
559
  double distance_cutoff =
NEW
560
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
×
561

NEW
562
  if (distance_cutoff < boundary().distance()) {
×
NEW
563
    wgt() = 0.0;
×
NEW
564
    return;
×
565
  }
566

567
  // Select smaller of the two distances
NEW
568
  double distance = std::min({boundary().distance(), total_distance});
×
569

570
  // Advance particle in space and time
NEW
571
  this->move_distance(distance);
×
NEW
572
  double dt = distance / speed;
×
NEW
573
  this->time() += dt;
×
NEW
574
  this->lifetime() += dt;
×
NEW
575
  mfp += distance * macro_xs().total;
×
NEW
576
  total_distance -= distance;
×
577
}
578

NEW
579
void Particle::event_cross_surface_pseudo()
×
580
{
581
  // Saving previous cell data
NEW
582
  for (int j = 0; j < n_coord(); ++j) {
×
NEW
583
    cell_last(j) = coord(j).cell();
×
584
  }
NEW
585
  n_coord_last() = n_coord();
×
586

587
  // Set surface that particle is on and adjust coordinate levels
NEW
588
  surface() = boundary().surface();
×
NEW
589
  n_coord() = boundary().coord_level();
×
590

NEW
591
  if (boundary().lattice_translation()[0] != 0 ||
×
NEW
592
      boundary().lattice_translation()[1] != 0 ||
×
NEW
593
      boundary().lattice_translation()[2] != 0) {
×
594
    // Particle crosses lattice boundary
595

NEW
596
    bool verbose = settings::verbosity >= 10 || trace();
×
NEW
597
    cross_lattice(*this, boundary(), verbose);
×
NEW
598
    event() = TallyEvent::LATTICE;
×
599
  } else {
600
    // Particle crosses surface
NEW
601
    const auto& surf {model::surfaces[surface_index()].get()};
×
NEW
602
    this->cross_surface(*surf);
×
NEW
603
    event() = TallyEvent::SURFACE;
×
604
  }
NEW
605
}
×
606

607
void Particle::pht_collision_energy()
2,024✔
608
{
609
  // Adds the energy particles lose in a collision to the pulse-height
610

611
  // determine index of cell in pulse_height_cells
612
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
613
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
614

615
  if (it != model::pulse_height_cells.end()) {
2,024!
616
    int index = std::distance(model::pulse_height_cells.begin(), it);
2,024✔
617
    pht_storage()[index] += E_last() - E();
2,024✔
618

619
    // If the energy of the particle is below the cutoff, it will not be sampled
620
    // so its energy is added to the pulse-height in the cell
621
    int photon = static_cast<int>(ParticleType::photon);
2,024✔
622
    if (E() < settings::energy_cutoff[photon]) {
2,024✔
623
      pht_storage()[index] += E();
825✔
624
    }
625
  }
626
}
2,024✔
627

628
void Particle::pht_secondary_particles()
605✔
629
{
630
  // Removes the energy of secondary produced particles from the pulse-height
631

632
  // determine index of cell in pulse_height_cells
633
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
634
    model::pulse_height_cells.end(), cell_born());
605✔
635

636
  if (it != model::pulse_height_cells.end()) {
605!
637
    int index = std::distance(model::pulse_height_cells.begin(), it);
605✔
638
    pht_storage()[index] -= E();
605✔
639
  }
640
}
605✔
641

642
void Particle::cross_surface(const Surface& surf)
1,508,877,445✔
643
{
644

645
  if (settings::verbosity >= 10 || trace()) {
1,508,877,445✔
646
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
647
  }
648

649
// if we're crossing a CSG surface, make sure the DAG history is reset
650
#ifdef OPENMC_DAGMC_ENABLED
651
  if (surf.geom_type() == GeometryType::CSG)
137,898,266✔
652
    history().reset();
137,843,147✔
653
#endif
654

655
  // Handle any applicable boundary conditions.
656
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647!
657
      settings::run_mode != RunMode::VOLUME) {
689,024,887✔
658
    surf.bc_->handle_particle(*this, surf);
688,904,943✔
659
    return;
688,904,943✔
660
  }
661

662
  // ==========================================================================
663
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
664

665
#ifdef OPENMC_DAGMC_ENABLED
666
  // in DAGMC, we know what the next cell should be
667
  if (surf.geom_type() == GeometryType::DAG) {
74,825,410✔
668
    int32_t i_cell = next_cell(surface_index(), cell_last(n_coord() - 1),
44,310✔
669
                       lowest_coord().universe()) -
44,310✔
670
                     1;
44,310✔
671
    // save material, temperature, and density multiplier
672
    material_last() = material();
44,310✔
673
    sqrtkT_last() = sqrtkT();
44,310✔
674
    density_mult_last() = density_mult();
44,310✔
675
    // set new cell value
676
    lowest_coord().cell() = i_cell;
44,310✔
677
    auto& cell = model::cells[i_cell];
44,310✔
678

679
    cell_instance() = 0;
44,310✔
680
    if (cell->distribcell_index_ >= 0)
44,310✔
681
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
43,286✔
682

683
    material() = cell->material(cell_instance());
44,310✔
684
    sqrtkT() = cell->sqrtkT(cell_instance());
44,310✔
685
    density_mult() = cell->density_mult(cell_instance());
44,310✔
686
    return;
44,310✔
687
  }
688
#endif
689

690
  bool verbose = settings::verbosity >= 10 || trace();
819,928,192!
691
  if (neighbor_list_find_cell(*this, verbose)) {
819,928,192✔
692
    return;
819,898,281✔
693
  }
694

695
  // ==========================================================================
696
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
697

698
  // Remove lower coordinate levels
699
  n_coord() = 1;
29,911✔
700
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
701

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

708
    surface() = SURFACE_NONE;
5,799✔
709
    n_coord() = 1;
5,799✔
710
    r() += TINY_BIT * u();
5,799✔
711

712
    // Couldn't find next cell anywhere! This probably means there is an actual
713
    // undefined region in the geometry.
714

715
    if (!exhaustive_find_cell(*this, verbose)) {
5,799!
716
      mark_as_lost("After particle " + std::to_string(id()) +
17,388✔
717
                   " crossed surface " + std::to_string(surf.id_) +
23,178✔
718
                   " it could not be located in any cell and it did not leak.");
719
      return;
5,790✔
720
    }
721
  }
722
}
723

724
void Particle::cross_vacuum_bc(const Surface& surf)
35,020,269✔
725
{
726
  // Score any surface current tallies -- note that the particle is moved
727
  // forward slightly so that if the mesh boundary is on the surface, it is
728
  // still processed
729

730
  if (!model::active_meshsurf_tallies.empty()) {
35,020,269✔
731
    // TODO: Find a better solution to score surface currents than
732
    // physically moving the particle forward slightly
733

734
    r() += TINY_BIT * u();
937,222✔
735
    score_surface_tally(*this, model::active_meshsurf_tallies);
937,222✔
736
  }
737

738
  // Score to global leakage tally
739
  keff_tally_leakage() += wgt();
35,020,269✔
740

741
  // Kill the particle
742
  wgt() = 0.0;
35,020,269✔
743

744
  // Display message
745
  if (settings::verbosity >= 10 || trace()) {
35,020,269!
746
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
747
  }
748
}
35,020,269✔
749

750
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
652,640,003✔
751
{
752
  // Do not handle reflective boundary conditions on lower universes
753
  if (n_coord() != 1) {
652,640,003!
754
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
755
                 " off surface in a lower universe.");
756
    return;
×
757
  }
758

759
  // Score surface currents since reflection causes the direction of the
760
  // particle to change. For surface filters, we need to score the tallies
761
  // twice, once before the particle's surface attribute has changed and
762
  // once after. For mesh surface filters, we need to artificially move
763
  // the particle slightly back in case the surface crossing is coincident
764
  // with a mesh boundary
765

766
  if (!model::active_surface_tallies.empty()) {
652,640,003✔
767
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
768
  }
769

770
  if (!model::active_meshsurf_tallies.empty()) {
652,640,003✔
771
    Position r {this->r()};
46,885,487✔
772
    this->r() -= TINY_BIT * u();
46,885,487✔
773
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,885,487✔
774
    this->r() = r;
46,885,487✔
775
  }
776

777
  // Set the new particle direction
778
  u() = new_u;
652,640,003✔
779

780
  // Reassign particle's cell and surface
781
  coord(0).cell() = cell_last(0);
652,640,003✔
782
  surface() = -surface();
652,640,003✔
783

784
  // If a reflective surface is coincident with a lattice or universe
785
  // boundary, it is necessary to redetermine the particle's coordinates in
786
  // the lower universes.
787
  // (unless we're using a dagmc model, which has exactly one universe)
788
  n_coord() = 1;
652,640,003✔
789
  if (surf.geom_type() != GeometryType::DAG &&
1,305,277,248!
790
      !neighbor_list_find_cell(*this)) {
652,637,245!
791
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
792
                 std::to_string(surf.id_) + ".");
×
793
    return;
×
794
  }
795

796
  // Set previous coordinate going slightly past surface crossing
797
  r_last_current() = r() + TINY_BIT * u();
652,640,003✔
798

799
  // Diagnostic message
800
  if (settings::verbosity >= 10 || trace()) {
652,640,003!
801
    write_message(1, "    Reflected from surface {}", surf.id_);
×
802
  }
803
}
804

805
void Particle::cross_periodic_bc(
2,250,137✔
806
  const Surface& surf, Position new_r, Direction new_u, int new_surface)
807
{
808
  // Do not handle periodic boundary conditions on lower universes
809
  if (n_coord() != 1) {
2,250,137!
810
    mark_as_lost(
×
811
      "Cannot transfer particle " + std::to_string(id()) +
×
812
      " across surface in a lower universe. Boundary conditions must be "
813
      "applied to root universe.");
814
    return;
×
815
  }
816

817
  // Score surface currents since reflection causes the direction of the
818
  // particle to change -- artificially move the particle slightly back in
819
  // case the surface crossing is coincident with a mesh boundary
820
  if (!model::active_meshsurf_tallies.empty()) {
2,250,137!
821
    Position r {this->r()};
×
822
    this->r() -= TINY_BIT * u();
×
823
    score_surface_tally(*this, model::active_meshsurf_tallies);
×
824
    this->r() = r;
×
825
  }
826

827
  // Adjust the particle's location and direction.
828
  r() = new_r;
2,250,137✔
829
  u() = new_u;
2,250,137✔
830

831
  // Reassign particle's surface
832
  surface() = new_surface;
2,250,137✔
833

834
  // Figure out what cell particle is in now
835
  n_coord() = 1;
2,250,137✔
836

837
  if (!neighbor_list_find_cell(*this)) {
2,250,137!
838
    mark_as_lost("Couldn't find particle after hitting periodic "
×
839
                 "boundary on surface " +
×
840
                 std::to_string(surf.id_) + ".");
×
841
    return;
×
842
  }
843

844
  // Set previous coordinate going slightly past surface crossing
845
  r_last_current() = r() + TINY_BIT * u();
2,250,137✔
846

847
  // Diagnostic message
848
  if (settings::verbosity >= 10 || trace()) {
2,250,137!
849
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
850
  }
851
}
852

853
void Particle::mark_as_lost(const char* message)
5,799✔
854
{
855
  // Print warning and write lost particle file
856
  warning(message);
5,799✔
857
  if (settings::max_write_lost_particles < 0 ||
5,799✔
858
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
859
    write_restart();
379✔
860
  }
861
  // Increment number of lost particles
862
  wgt() = 0.0;
5,799✔
863
#pragma omp atomic
3,154✔
864
  simulation::n_lost_particles += 1;
2,645✔
865

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

870
  // Abort the simulation if the maximum number of lost particles has been
871
  // reached
872
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,799✔
873
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9!
874
    fatal_error("Maximum number of lost particles has been reached.");
9✔
875
  }
876
}
5,790✔
877

878
void Particle::write_restart() const
379✔
879
{
880
  // Dont write another restart file if in particle restart mode
881
  if (settings::run_mode == RunMode::PARTICLE)
379✔
882
    return;
22✔
883

884
  // Set up file name
885
  auto filename = fmt::format("{}particle_{}_{}.h5", settings::path_output,
886
    simulation::current_batch, id());
665✔
887

888
#pragma omp critical(WriteParticleRestart)
374✔
889
  {
890
    // Create file
891
    hid_t file_id = file_open(filename, 'w');
357✔
892

893
    // Write filetype and version info
894
    write_attribute(file_id, "filetype", "particle restart");
357✔
895
    write_attribute(file_id, "version", VERSION_PARTICLE_RESTART);
357✔
896
    write_attribute(file_id, "openmc_version", VERSION);
357✔
897
#ifdef GIT_SHA1
898
    write_attr_string(file_id, "git_sha1", GIT_SHA1);
899
#endif
900

901
    // Write data to file
902
    write_dataset(file_id, "current_batch", simulation::current_batch);
357✔
903
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
357✔
904
    write_dataset(file_id, "current_generation", simulation::current_gen);
357✔
905
    write_dataset(file_id, "n_particles", settings::n_particles);
357✔
906
    switch (settings::run_mode) {
357!
907
    case RunMode::FIXED_SOURCE:
225✔
908
      write_dataset(file_id, "run_mode", "fixed source");
225✔
909
      break;
225✔
910
    case RunMode::EIGENVALUE:
132✔
911
      write_dataset(file_id, "run_mode", "eigenvalue");
132✔
912
      break;
132✔
913
    case RunMode::PARTICLE:
×
914
      write_dataset(file_id, "run_mode", "particle restart");
×
915
      break;
×
916
    default:
×
917
      break;
×
918
    }
919
    write_dataset(file_id, "id", id());
357✔
920
    write_dataset(file_id, "type", static_cast<int>(type()));
357✔
921

922
    int64_t i = current_work();
357✔
923
    if (settings::run_mode == RunMode::EIGENVALUE) {
357✔
924
      // take source data from primary bank for eigenvalue simulation
925
      write_dataset(file_id, "weight", simulation::source_bank[i - 1].wgt);
132✔
926
      write_dataset(file_id, "energy", simulation::source_bank[i - 1].E);
132✔
927
      write_dataset(file_id, "xyz", simulation::source_bank[i - 1].r);
132✔
928
      write_dataset(file_id, "uvw", simulation::source_bank[i - 1].u);
132✔
929
      write_dataset(file_id, "time", simulation::source_bank[i - 1].time);
132✔
930
    } else if (settings::run_mode == RunMode::FIXED_SOURCE) {
225!
931
      // re-sample using rng random number seed used to generate source particle
932
      int64_t id = (simulation::total_gen + overall_generation() - 1) *
225✔
933
                     settings::n_particles +
225✔
934
                   simulation::work_index[mpi::rank] + i;
225✔
935
      uint64_t seed = init_seed(id, STREAM_SOURCE);
225✔
936
      // re-sample source site
937
      auto site = sample_external_source(&seed);
225✔
938
      write_dataset(file_id, "weight", site.wgt);
225✔
939
      write_dataset(file_id, "energy", site.E);
225✔
940
      write_dataset(file_id, "xyz", site.r);
225✔
941
      write_dataset(file_id, "uvw", site.u);
225✔
942
      write_dataset(file_id, "time", site.time);
225✔
943
    }
944

945
    // Close file
946
    file_close(file_id);
357✔
947
  } // #pragma omp critical
948
}
357✔
949

950
void Particle::update_neutron_xs(
2,147,483,647✔
951
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
952
{
953
  // Get microscopic cross section cache
954
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
955

956
  // If the cache doesn't match, recalculate micro xs
957
  if (this->E() != micro.last_E || this->sqrtkT() != micro.last_sqrtkT ||
2,147,483,647✔
958
      i_sab != micro.index_sab || sab_frac != micro.sab_frac ||
2,147,483,647✔
959
      ncrystal_xs != micro.ncrystal_xs) {
2,147,483,647!
960
    data::nuclides[i_nuclide]->calculate_xs(i_sab, i_grid, sab_frac, *this);
2,147,483,647✔
961

962
    // If NCrystal is being used, update micro cross section cache
963
    micro.ncrystal_xs = ncrystal_xs;
2,147,483,647✔
964
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
965
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
966
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
967
    }
968
  }
969
}
2,147,483,647✔
970

971
//==============================================================================
972
// Non-method functions
973
//==============================================================================
974

975
std::string particle_type_to_str(ParticleType type)
3,130,197✔
976
{
977
  switch (type) {
3,130,197!
978
  case ParticleType::neutron:
2,399,940✔
979
    return "neutron";
2,399,940✔
980
  case ParticleType::photon:
729,993✔
981
    return "photon";
729,993✔
982
  case ParticleType::electron:
132✔
983
    return "electron";
132✔
984
  case ParticleType::positron:
132✔
985
    return "positron";
132✔
986
  }
987
  UNREACHABLE();
×
988
}
989

990
ParticleType str_to_particle_type(std::string str)
3,316,579✔
991
{
992
  if (str == "neutron") {
3,316,579✔
993
    return ParticleType::neutron;
774,597✔
994
  } else if (str == "photon") {
2,541,982✔
995
    return ParticleType::photon;
2,541,896✔
996
  } else if (str == "electron") {
86✔
997
    return ParticleType::electron;
43✔
998
  } else if (str == "positron") {
43!
999
    return ParticleType::positron;
43✔
1000
  } else {
1001
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
1002
  }
1003
}
1004

1005
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,505,773,575✔
1006
{
1007
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
1008
      simulation::surf_source_bank.full()) {
1,178,697,985✔
1009
    return;
1,505,643,921✔
1010
  }
1011

1012
  // If a cell/cellfrom/cellto parameter is defined
1013
  if (settings::ssw_cell_id != C_NONE) {
337,084✔
1014

1015
    // Retrieve cell index and storage type
1016
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,438✔
1017

1018
    if (surf.bc_) {
254,438✔
1019
      // Leave if cellto with vacuum boundary condition
1020
      if (surf.bc_->type() == "vacuum" &&
182,558!
1021
          settings::ssw_cell_type == SSWCellType::To) {
33,099✔
1022
        return;
12,136✔
1023
      }
1024

1025
      // Leave if other boundary condition than vacuum
1026
      if (surf.bc_->type() != "vacuum") {
137,323✔
1027
        return;
116,360✔
1028
      }
1029
    }
1030

1031
    // Check if the cell of interest has been exited
1032
    bool exited = false;
125,942✔
1033
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,673✔
1034
      if (p.cell_last(i) == cell_idx) {
207,731✔
1035
        exited = true;
73,765✔
1036
      }
1037
    }
1038

1039
    // Check if the cell of interest has been entered
1040
    bool entered = false;
125,942✔
1041
    for (int i = 0; i < p.n_coord(); ++i) {
297,975✔
1042
      if (p.coord(i).cell() == cell_idx) {
172,033✔
1043
        entered = true;
57,516✔
1044
      }
1045
    }
1046

1047
    // Vacuum boundary conditions: return if cell is not exited
1048
    if (surf.bc_) {
125,942✔
1049
      if (surf.bc_->type() == "vacuum" && !exited) {
20,963!
1050
        return;
14,663✔
1051
      }
1052
    } else {
1053

1054
      // If we both enter and exit the cell of interest
1055
      if (entered && exited) {
104,979✔
1056
        return;
27,203✔
1057
      }
1058

1059
      // If we did not enter nor exit the cell of interest
1060
      if (!entered && !exited) {
77,776✔
1061
        return;
13,501✔
1062
      }
1063

1064
      // If cellfrom and the cell before crossing is not the cell of
1065
      // interest
1066
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,275✔
1067
        return;
11,542✔
1068
      }
1069

1070
      // If cellto and the cell after crossing is not the cell of interest
1071
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,733✔
1072
        return;
12,025✔
1073
      }
1074
    }
1075
  }
1076

1077
  SourceSite site;
129,654✔
1078
  site.r = p.r();
129,654✔
1079
  site.u = p.u();
129,654✔
1080
  site.E = p.E();
129,654✔
1081
  site.time = p.time();
129,654✔
1082
  site.wgt = p.wgt();
129,654✔
1083
  site.delayed_group = p.delayed_group();
129,654✔
1084
  site.surf_id = surf.id_;
129,654✔
1085
  site.particle = p.type();
129,654✔
1086
  site.parent_id = p.id();
129,654✔
1087
  site.progeny_id = p.n_progeny();
129,654✔
1088
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,654✔
1089
}
1090

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