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

openmc-dev / openmc / 17856681851

19 Sep 2025 11:13AM UTC coverage: 85.15% (-0.05%) from 85.197%
17856681851

Pull #3547

github

web-flow
Merge d9f67baed into ecb0a3361
Pull Request #3547: Tally spectrum of secondary particles

23 of 58 new or added lines in 8 files covered. (39.66%)

1 existing line in 1 file now uncovered.

53181 of 62456 relevant lines covered (85.15%)

39166200.17 hits per line

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

91.65
/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/constants.h"
12
#include "openmc/dagmc.h"
13
#include "openmc/error.h"
14
#include "openmc/geometry.h"
15
#include "openmc/hdf5_interface.h"
16
#include "openmc/material.h"
17
#include "openmc/message_passing.h"
18
#include "openmc/mgxs_interface.h"
19
#include "openmc/nuclide.h"
20
#include "openmc/particle_data.h"
21
#include "openmc/photon.h"
22
#include "openmc/physics.h"
23
#include "openmc/physics_mg.h"
24
#include "openmc/random_lcg.h"
25
#include "openmc/settings.h"
26
#include "openmc/simulation.h"
27
#include "openmc/source.h"
28
#include "openmc/surface.h"
29
#include "openmc/tallies/derivative.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/tallies/tally_scoring.h"
32
#include "openmc/track_output.h"
33
#include "openmc/weight_windows.h"
34

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

39
namespace openmc {
40

41
namespace simulation {
42
thread_local Particle tmp_particle;
43
}
44

45
//==============================================================================
46
// Particle implementation
47
//==============================================================================
48

49
double Particle::speed() const
2,147,483,647✔
50
{
51
  if (settings::run_CE) {
2,147,483,647✔
52
    // Determine mass in eV/c^2
53
    double mass;
54
    switch (this->type()) {
1,966,855,567✔
55
    case ParticleType::neutron:
1,897,420,066✔
56
      mass = MASS_NEUTRON_EV;
1,897,420,066✔
57
      break;
1,897,420,066✔
58
    case ParticleType::photon:
17,503,677✔
59
      mass = 0.0;
17,503,677✔
60
      break;
17,503,677✔
61
    case ParticleType::electron:
51,931,824✔
62
    case ParticleType::positron:
63
      mass = MASS_ELECTRON_EV;
51,931,824✔
64
      break;
51,931,824✔
65
    }
66
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
67
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,966,855,567✔
68
           (this->E() + mass);
1,966,855,567✔
69
  } else {
70
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,063,937,414✔
71
    int macro_t = this->mg_xs_cache().t;
2,063,937,414✔
72
    int macro_a = macro_xs.get_angle_index(this->u());
2,063,937,414✔
73
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,063,937,414✔
74
                   nullptr, nullptr, macro_t, macro_a);
2,063,937,414✔
75
  }
76
}
77

78
bool Particle::create_secondary(
108,478,192✔
79
  double wgt, Direction u, double E, ParticleType type)
80
{
81
  // If energy is below cutoff for this particle, don't create secondary
82
  // particle
83
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
108,478,192✔
84
    return false;
51,882,465✔
85
  }
86

87
  auto& bank = secondary_bank().emplace_back();
56,595,727✔
88
  bank.particle = type;
56,595,727✔
89
  bank.wgt = wgt;
56,595,727✔
90
  bank.r = r();
56,595,727✔
91
  bank.u = u;
56,595,727✔
92
  bank.E = settings::run_CE ? E : g();
56,595,727✔
93
  bank.time = time();
56,595,727✔
94
  bank_second_E() += bank.E;
56,595,727✔
95

96
  // Score tallies affected by secondary particles
97
  if (!model::active_particleout_analog_tallies.empty()) {
56,595,727✔
98
    // Create secondary particle for tallying purposes only
NEW
99
    simulation::tmp_particle.from_source(&bank);
×
NEW
100
    simulation::tmp_particle.u_last() = this->u();
×
NEW
101
    simulation::tmp_particle.r_last() = this->r();
×
NEW
102
    simulation::tmp_particle.E_last() = this->E();
×
NEW
103
    simulation::tmp_particle.type_last() = this->type();
×
104

NEW
105
    if (settings::run_CE) {
×
NEW
106
      score_analog_tally_ce(
×
107
        simulation::tmp_particle, model::active_particleout_analog_tallies);
108
    } else {
NEW
109
      score_analog_tally_mg(
×
110
        simulation::tmp_particle, model::active_particleout_analog_tallies);
111
    }
112
  }
113
  return true;
56,595,727✔
114
}
115

116
void Particle::split(double wgt)
4,243,452✔
117
{
118
  auto& bank = secondary_bank().emplace_back();
4,243,452✔
119
  bank.particle = type();
4,243,452✔
120
  bank.wgt = wgt;
4,243,452✔
121
  bank.r = r();
4,243,452✔
122
  bank.u = u();
4,243,452✔
123
  bank.E = settings::run_CE ? E() : g();
4,243,452✔
124
  bank.time = time();
4,243,452✔
125

126
  // Convert signed index to a signed surface ID
127
  if (surface() == SURFACE_NONE) {
4,243,452✔
128
    bank.surf_id = SURFACE_NONE;
4,243,432✔
129
  } else {
130
    int surf_id = model::surfaces[surface_index()]->id_;
20✔
131
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
20✔
132
  }
133
}
4,243,452✔
134

135
void Particle::from_source(const SourceSite* src)
225,039,829✔
136
{
137
  // Reset some attributes
138
  clear();
225,039,829✔
139
  surface() = SURFACE_NONE;
225,039,829✔
140
  cell_born() = C_NONE;
225,039,829✔
141
  material() = C_NONE;
225,039,829✔
142
  n_collision() = 0;
225,039,829✔
143
  fission() = false;
225,039,829✔
144
  zero_flux_derivs();
225,039,829✔
145
  lifetime() = 0.0;
225,039,829✔
146

147
  // Copy attributes from source bank site
148
  type() = src->particle;
225,039,829✔
149
  type_last() = src->particle;
225,039,829✔
150
  wgt() = src->wgt;
225,039,829✔
151
  wgt_last() = src->wgt;
225,039,829✔
152
  r() = src->r;
225,039,829✔
153
  u() = src->u;
225,039,829✔
154
  r_born() = src->r;
225,039,829✔
155
  r_last_current() = src->r;
225,039,829✔
156
  r_last() = src->r;
225,039,829✔
157
  u_last() = src->u;
225,039,829✔
158
  if (settings::run_CE) {
225,039,829✔
159
    E() = src->E;
109,409,012✔
160
    g() = 0;
109,409,012✔
161
  } else {
162
    g() = static_cast<int>(src->E);
115,630,817✔
163
    g_last() = static_cast<int>(src->E);
115,630,817✔
164
    E() = data::mg.energy_bin_avg_[g()];
115,630,817✔
165
  }
166
  E_last() = E();
225,039,829✔
167
  time() = src->time;
225,039,829✔
168
  time_last() = src->time;
225,039,829✔
169
  parent_nuclide() = src->parent_nuclide;
225,039,829✔
170

171
  // Convert signed surface ID to signed index
172
  if (src->surf_id != SURFACE_NONE) {
225,039,829✔
173
    int index_plus_one = model::surface_map[std::abs(src->surf_id)] + 1;
110,020✔
174
    surface() = (src->surf_id > 0) ? index_plus_one : -index_plus_one;
110,020✔
175
  }
176
}
225,039,829✔
177

178
void Particle::event_calculate_xs()
2,147,483,647✔
179
{
180
  // Set the random number stream
181
  stream() = STREAM_TRACKING;
2,147,483,647✔
182

183
  // Store pre-collision particle properties
184
  wgt_last() = wgt();
2,147,483,647✔
185
  E_last() = E();
2,147,483,647✔
186
  type_last() = type();
2,147,483,647✔
187
  u_last() = u();
2,147,483,647✔
188
  r_last() = r();
2,147,483,647✔
189
  time_last() = time();
2,147,483,647✔
190

191
  // Reset event variables
192
  event() = TallyEvent::KILL;
2,147,483,647✔
193
  event_nuclide() = NUCLIDE_NONE;
2,147,483,647✔
194
  event_mt() = REACTION_NONE;
2,147,483,647✔
195

196
  // If the cell hasn't been determined based on the particle's location,
197
  // initiate a search for the current cell. This generally happens at the
198
  // beginning of the history and again for any secondary particles
199
  if (lowest_coord().cell() == C_NONE) {
2,147,483,647✔
200
    if (!exhaustive_find_cell(*this)) {
221,644,912✔
201
      mark_as_lost(
×
202
        "Could not find the cell containing particle " + std::to_string(id()));
×
203
      return;
×
204
    }
205

206
    // Set birth cell attribute
207
    if (cell_born() == C_NONE)
221,644,912✔
208
      cell_born() = lowest_coord().cell();
221,644,912✔
209

210
    // Initialize last cells from current cell
211
    for (int j = 0; j < n_coord(); ++j) {
460,611,433✔
212
      cell_last(j) = coord(j).cell();
238,966,521✔
213
    }
214
    n_coord_last() = n_coord();
221,644,912✔
215
  }
216

217
  // Write particle track.
218
  if (write_track())
2,147,483,647✔
219
    write_particle_track(*this);
10,814✔
220

221
  if (settings::check_overlaps)
2,147,483,647✔
222
    check_cell_overlap(*this);
×
223

224
  // Calculate microscopic and macroscopic cross sections
225
  if (material() != MATERIAL_VOID) {
2,147,483,647✔
226
    if (settings::run_CE) {
2,147,483,647✔
227
      if (material() != material_last() || sqrtkT() != sqrtkT_last() ||
2,147,483,647✔
228
          density_mult() != density_mult_last()) {
385,935,181✔
229
        // If the material is the same as the last material and the
230
        // temperature hasn't changed, we don't need to lookup cross
231
        // sections again.
232
        model::materials[material()]->calculate_xs(*this);
1,485,954,257✔
233
      }
234
    } else {
235
      // Get the MG data; unlike the CE case above, we have to re-calculate
236
      // cross sections for every collision since the cross sections may
237
      // be angle-dependent
238
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,063,937,414✔
239

240
      // Update the particle's group while we know we are multi-group
241
      g_last() = g();
2,063,937,414✔
242
    }
243
  } else {
244
    macro_xs().total = 0.0;
67,529,060✔
245
    macro_xs().absorption = 0.0;
67,529,060✔
246
    macro_xs().fission = 0.0;
67,529,060✔
247
    macro_xs().nu_fission = 0.0;
67,529,060✔
248
  }
249
}
250

251
void Particle::event_advance()
2,147,483,647✔
252
{
253
  // Find the distance to the nearest boundary
254
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
255

256
  // Sample a distance to collision
257
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
258
    collision_distance() = 0.0;
51,931,824✔
259
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
260
    collision_distance() = INFINITY;
67,529,060✔
261
  } else {
262
    collision_distance() = -std::log(prn(current_seed())) / macro_xs().total;
2,147,483,647✔
263
  }
264

265
  double speed = this->speed();
2,147,483,647✔
266
  double time_cutoff = settings::time_cutoff[static_cast<int>(type())];
2,147,483,647✔
267
  double distance_cutoff =
268
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
269

270
  // Select smaller of the three distances
271
  double distance =
272
    std::min({boundary().distance(), collision_distance(), distance_cutoff});
2,147,483,647✔
273

274
  // Advance particle in space and time
275
  this->move_distance(distance);
2,147,483,647✔
276
  double dt = distance / speed;
2,147,483,647✔
277
  this->time() += dt;
2,147,483,647✔
278
  this->lifetime() += dt;
2,147,483,647✔
279

280
  // Score timed track-length tallies
281
  if (!model::active_timed_tracklength_tallies.empty()) {
2,147,483,647✔
282
    score_timed_tracklength_tally(*this, distance);
3,628,317✔
283
  }
284

285
  // Score track-length tallies
286
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
287
    score_tracklength_tally(*this, distance);
1,436,468,380✔
288
  }
289

290
  // Score track-length estimate of k-eff
291
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
292
      type() == ParticleType::neutron) {
2,147,483,647✔
293
    keff_tally_tracklength() += wgt() * distance * macro_xs().nu_fission;
2,147,483,647✔
294
  }
295

296
  // Score flux derivative accumulators for differential tallies.
297
  if (!model::active_tallies.empty()) {
2,147,483,647✔
298
    score_track_derivative(*this, distance);
1,610,875,442✔
299
  }
300

301
  // Set particle weight to zero if it hit the time boundary
302
  if (distance == distance_cutoff) {
2,147,483,647✔
303
    wgt() = 0.0;
224,928✔
304
  }
305
}
2,147,483,647✔
306

307
void Particle::event_cross_surface()
2,147,483,647✔
308
{
309
  // Saving previous cell data
310
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
311
    cell_last(j) = coord(j).cell();
2,147,483,647✔
312
  }
313
  n_coord_last() = n_coord();
2,147,483,647✔
314

315
  // Set surface that particle is on and adjust coordinate levels
316
  surface() = boundary().surface();
2,147,483,647✔
317
  n_coord() = boundary().coord_level();
2,147,483,647✔
318

319
  if (boundary().lattice_translation()[0] != 0 ||
2,147,483,647✔
320
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
321
      boundary().lattice_translation()[2] != 0) {
1,705,362,019✔
322
    // Particle crosses lattice boundary
323

324
    bool verbose = settings::verbosity >= 10 || trace();
681,359,569✔
325
    cross_lattice(*this, boundary(), verbose);
681,359,569✔
326
    event() = TallyEvent::LATTICE;
681,359,569✔
327
  } else {
328
    // Particle crosses surface
329
    const auto& surf {model::surfaces[surface_index()].get()};
1,518,989,314✔
330
    // If BC, add particle to surface source before crossing surface
331
    if (surf->surf_source_ && surf->bc_) {
1,518,989,314✔
332
      add_surf_source_to_bank(*this, *surf);
690,121,662✔
333
    }
334
    this->cross_surface(*surf);
1,518,989,314✔
335
    // If no BC, add particle to surface source after crossing surface
336
    if (surf->surf_source_ && !surf->bc_) {
1,518,989,305✔
337
      add_surf_source_to_bank(*this, *surf);
827,629,816✔
338
    }
339
    if (settings::weight_window_checkpoint_surface) {
1,518,989,305✔
340
      apply_weight_windows(*this);
396✔
341
    }
342
    event() = TallyEvent::SURFACE;
1,518,989,305✔
343
  }
344
  // Score cell to cell partial currents
345
  if (!model::active_surface_tallies.empty()) {
2,147,483,647✔
346
    score_surface_tally(*this, model::active_surface_tallies);
34,900,767✔
347
  }
348
}
2,147,483,647✔
349

350
void Particle::event_collide()
2,147,483,647✔
351
{
352
  // Score collision estimate of keff
353
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
354
      type() == ParticleType::neutron) {
2,147,483,647✔
355
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,143,843,650✔
356
  }
357

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

362
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
363
    score_surface_tally(*this, model::active_meshsurf_tallies);
74,432,944✔
364

365
  // Clear surface component
366
  surface() = SURFACE_NONE;
2,147,483,647✔
367

368
  if (settings::run_CE) {
2,147,483,647✔
369
    collision(*this);
784,662,005✔
370
  } else {
371
    collision_mg(*this);
1,783,060,477✔
372
  }
373

374
  // Score collision estimator tallies -- this is done after a collision
375
  // has occurred rather than before because we need information on the
376
  // outgoing energy for any tallies with an outgoing energy filter
377
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
378
    score_collision_tally(*this);
102,545,543✔
379
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
380
    if (settings::run_CE) {
119,644,176✔
381
      score_analog_tally_ce(*this, model::active_analog_tallies);
118,435,914✔
382
    } else {
383
      score_analog_tally_mg(*this, model::active_analog_tallies);
1,208,262✔
384
    }
385
  }
386

387
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
388
      type() == ParticleType::photon) {
16,918✔
389
    pht_collision_energy();
2,024✔
390
  }
391

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

398
  // Reset fission logical
399
  fission() = false;
2,147,483,647✔
400

401
  // Save coordinates for tallying purposes
402
  r_last_current() = r();
2,147,483,647✔
403

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

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

422
  // Score flux derivative accumulators for differential tallies.
423
  if (!model::active_tallies.empty())
2,147,483,647✔
424
    score_collision_derivative(*this);
677,014,051✔
425

426
#ifdef OPENMC_DAGMC_ENABLED
427
  history().reset();
241,095,016✔
428
#endif
429
}
2,147,483,647✔
430

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

441
  // Check for secondary particles if this particle is dead
442
  if (!alive()) {
2,147,483,647✔
443
    // Write final position for this particle
444
    if (write_track()) {
221,644,508✔
445
      write_particle_track(*this);
6,674✔
446
    }
447

448
    // If no secondary particles, break out of event loop
449
    if (secondary_bank().empty())
221,644,508✔
450
      return;
160,466,598✔
451

452
    from_source(&secondary_bank().back());
61,177,910✔
453
    secondary_bank().pop_back();
61,177,910✔
454
    n_event() = 0;
61,177,910✔
455
    bank_second_E() = 0.0;
61,177,910✔
456

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

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

483
    // Enter new particle in particle track file
484
    if (write_track())
61,177,910✔
485
      add_particle_track(*this);
5,604✔
486
  }
487
}
488

489
void Particle::event_death()
160,467,598✔
490
{
491
#ifdef OPENMC_DAGMC_ENABLED
492
  history().reset();
15,058,382✔
493
#endif
494

495
  // Finish particle track output.
496
  if (write_track()) {
160,467,598✔
497
    finalize_particle_track(*this);
1,070✔
498
  }
499

500
// Contribute tally reduction variables to global accumulator
501
#pragma omp atomic
88,446,708✔
502
  global_tally_absorption += keff_tally_absorption();
160,467,598✔
503
#pragma omp atomic
88,307,305✔
504
  global_tally_collision += keff_tally_collision();
160,467,598✔
505
#pragma omp atomic
88,083,161✔
506
  global_tally_tracklength += keff_tally_tracklength();
160,467,598✔
507
#pragma omp atomic
87,836,261✔
508
  global_tally_leakage += keff_tally_leakage();
160,467,598✔
509

510
  // Reset particle tallies once accumulated
511
  keff_tally_absorption() = 0.0;
160,467,598✔
512
  keff_tally_collision() = 0.0;
160,467,598✔
513
  keff_tally_tracklength() = 0.0;
160,467,598✔
514
  keff_tally_leakage() = 0.0;
160,467,598✔
515

516
  if (!model::active_pulse_height_tallies.empty()) {
160,467,598✔
517
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
518
  }
519

520
  // Record the number of progeny created by this particle.
521
  // This data will be used to efficiently sort the fission bank.
522
  if (settings::run_mode == RunMode::EIGENVALUE) {
160,467,598✔
523
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
135,349,200✔
524
    simulation::progeny_per_particle[offset] = n_progeny();
135,349,200✔
525
  }
526
}
160,467,598✔
527

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

532
  // determine index of cell in pulse_height_cells
533
  auto it = std::find(model::pulse_height_cells.begin(),
2,024✔
534
    model::pulse_height_cells.end(), lowest_coord().cell());
2,024✔
535

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

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

549
void Particle::pht_secondary_particles()
605✔
550
{
551
  // Removes the energy of secondary produced particles from the pulse-height
552

553
  // determine index of cell in pulse_height_cells
554
  auto it = std::find(model::pulse_height_cells.begin(),
605✔
555
    model::pulse_height_cells.end(), cell_born());
605✔
556

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

563
void Particle::cross_surface(const Surface& surf)
1,520,534,584✔
564
{
565

566
  if (settings::verbosity >= 10 || trace()) {
1,520,534,584✔
567
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
568
  }
569

570
// if we're crossing a CSG surface, make sure the DAG history is reset
571
#ifdef OPENMC_DAGMC_ENABLED
572
  if (surf.geom_type() == GeometryType::CSG)
161,498,544✔
573
    history().reset();
161,453,767✔
574
#endif
575

576
  // Handle any applicable boundary conditions.
577
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING &&
2,147,483,647✔
578
      settings::run_mode != RunMode::VOLUME) {
690,637,330✔
579
    surf.bc_->handle_particle(*this, surf);
690,473,770✔
580
    return;
690,473,770✔
581
  }
582

583
  // ==========================================================================
584
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
585

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

600
    cell_instance() = 0;
37,445✔
601
    if (cell->distribcell_index_ >= 0)
37,445✔
602
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
36,421✔
603

604
    material() = cell->material(cell_instance());
37,445✔
605
    sqrtkT() = cell->sqrtkT(cell_instance());
37,445✔
606
    density_mult() = cell->density_mult(cell_instance());
37,445✔
607
    return;
37,445✔
608
  }
609
#endif
610

611
  bool verbose = settings::verbosity >= 10 || trace();
830,023,369✔
612
  if (neighbor_list_find_cell(*this, verbose)) {
830,023,369✔
613
    return;
829,993,458✔
614
  }
615

616
  // ==========================================================================
617
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
618

619
  // Remove lower coordinate levels
620
  n_coord() = 1;
29,911✔
621
  bool found = exhaustive_find_cell(*this, verbose);
29,911✔
622

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

629
    surface() = SURFACE_NONE;
5,799✔
630
    n_coord() = 1;
5,799✔
631
    r() += TINY_BIT * u();
5,799✔
632

633
    // Couldn't find next cell anywhere! This probably means there is an actual
634
    // undefined region in the geometry.
635

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

645
void Particle::cross_vacuum_bc(const Surface& surf)
32,538,751✔
646
{
647
  // Score any surface current tallies -- note that the particle is moved
648
  // forward slightly so that if the mesh boundary is on the surface, it is
649
  // still processed
650

651
  if (!model::active_meshsurf_tallies.empty()) {
32,538,751✔
652
    // TODO: Find a better solution to score surface currents than
653
    // physically moving the particle forward slightly
654

655
    r() += TINY_BIT * u();
1,087,206✔
656
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,087,206✔
657
  }
658

659
  // Score to global leakage tally
660
  keff_tally_leakage() += wgt();
32,538,751✔
661

662
  // Kill the particle
663
  wgt() = 0.0;
32,538,751✔
664

665
  // Display message
666
  if (settings::verbosity >= 10 || trace()) {
32,538,751✔
667
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
668
  }
669
}
32,538,751✔
670

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

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

687
  if (!model::active_surface_tallies.empty()) {
658,278,862✔
688
    score_surface_tally(*this, model::active_surface_tallies);
285,021✔
689
  }
690

691
  if (!model::active_meshsurf_tallies.empty()) {
658,278,862✔
692
    Position r {this->r()};
55,305,995✔
693
    this->r() -= TINY_BIT * u();
55,305,995✔
694
    score_surface_tally(*this, model::active_meshsurf_tallies);
55,305,995✔
695
    this->r() = r;
55,305,995✔
696
  }
697

698
  // Set the new particle direction
699
  u() = new_u;
658,278,862✔
700

701
  // Reassign particle's cell and surface
702
  coord(0).cell() = cell_last(0);
658,278,862✔
703
  surface() = -surface();
658,278,862✔
704

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

717
  // Set previous coordinate going slightly past surface crossing
718
  r_last_current() = r() + TINY_BIT * u();
658,278,862✔
719

720
  // Diagnostic message
721
  if (settings::verbosity >= 10 || trace()) {
658,278,862✔
722
    write_message(1, "    Reflected from surface {}", surf.id_);
×
723
  }
724
}
725

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

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

748
  // Adjust the particle's location and direction.
749
  r() = new_r;
661,623✔
750
  u() = new_u;
661,623✔
751

752
  // Reassign particle's surface
753
  surface() = new_surface;
661,623✔
754

755
  // Figure out what cell particle is in now
756
  n_coord() = 1;
661,623✔
757

758
  if (!neighbor_list_find_cell(*this)) {
661,623✔
759
    mark_as_lost("Couldn't find particle after hitting periodic "
×
760
                 "boundary on surface " +
×
761
                 std::to_string(surf.id_) +
×
762
                 ". The normal vector "
763
                 "of one periodic surface may need to be reversed.");
764
    return;
×
765
  }
766

767
  // Set previous coordinate going slightly past surface crossing
768
  r_last_current() = r() + TINY_BIT * u();
661,623✔
769

770
  // Diagnostic message
771
  if (settings::verbosity >= 10 || trace()) {
661,623✔
772
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
773
  }
774
}
775

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

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

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

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

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

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

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

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

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

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

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

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

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

892
//==============================================================================
893
// Non-method functions
894
//==============================================================================
895

896
std::string particle_type_to_str(ParticleType type)
3,387,343✔
897
{
898
  switch (type) {
3,387,343✔
899
  case ParticleType::neutron:
2,528,516✔
900
    return "neutron";
2,528,516✔
901
  case ParticleType::photon:
858,563✔
902
    return "photon";
858,563✔
903
  case ParticleType::electron:
132✔
904
    return "electron";
132✔
905
  case ParticleType::positron:
132✔
906
    return "positron";
132✔
907
  }
908
  UNREACHABLE();
×
909
}
910

911
ParticleType str_to_particle_type(std::string str)
3,356,664✔
912
{
913
  if (str == "neutron") {
3,356,664✔
914
    return ParticleType::neutron;
771,700✔
915
  } else if (str == "photon") {
2,584,964✔
916
    return ParticleType::photon;
2,584,878✔
917
  } else if (str == "electron") {
86✔
918
    return ParticleType::electron;
43✔
919
  } else if (str == "positron") {
43✔
920
    return ParticleType::positron;
43✔
921
  } else {
922
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
923
  }
924
}
925

926
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,517,751,478✔
927
{
928
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
929
      simulation::surf_source_bank.full()) {
1,204,285,666✔
930
    return;
1,517,621,825✔
931
  }
932

933
  // If a cell/cellfrom/cellto parameter is defined
934
  if (settings::ssw_cell_id != C_NONE) {
337,084✔
935

936
    // Retrieve cell index and storage type
937
    int cell_idx = model::cell_map[settings::ssw_cell_id];
254,439✔
938

939
    if (surf.bc_) {
254,439✔
940
      // Leave if cellto with vacuum boundary condition
941
      if (surf.bc_->type() == "vacuum" &&
182,560✔
942
          settings::ssw_cell_type == SSWCellType::To) {
33,100✔
943
        return;
12,136✔
944
      }
945

946
      // Leave if other boundary condition than vacuum
947
      if (surf.bc_->type() != "vacuum") {
137,324✔
948
        return;
116,360✔
949
      }
950
    }
951

952
    // Check if the cell of interest has been exited
953
    bool exited = false;
125,943✔
954
    for (int i = 0; i < p.n_coord_last(); ++i) {
333,675✔
955
      if (p.cell_last(i) == cell_idx) {
207,732✔
956
        exited = true;
73,765✔
957
      }
958
    }
959

960
    // Check if the cell of interest has been entered
961
    bool entered = false;
125,943✔
962
    for (int i = 0; i < p.n_coord(); ++i) {
297,977✔
963
      if (p.coord(i).cell() == cell_idx) {
172,034✔
964
        entered = true;
57,515✔
965
      }
966
    }
967

968
    // Vacuum boundary conditions: return if cell is not exited
969
    if (surf.bc_) {
125,943✔
970
      if (surf.bc_->type() == "vacuum" && !exited) {
20,964✔
971
        return;
14,664✔
972
      }
973
    } else {
974

975
      // If we both enter and exit the cell of interest
976
      if (entered && exited) {
104,979✔
977
        return;
27,203✔
978
      }
979

980
      // If we did not enter nor exit the cell of interest
981
      if (!entered && !exited) {
77,776✔
982
        return;
13,502✔
983
      }
984

985
      // If cellfrom and the cell before crossing is not the cell of
986
      // interest
987
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
64,274✔
988
        return;
11,541✔
989
      }
990

991
      // If cellto and the cell after crossing is not the cell of interest
992
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
52,733✔
993
        return;
12,025✔
994
      }
995
    }
996
  }
997

998
  SourceSite site;
129,653✔
999
  site.r = p.r();
129,653✔
1000
  site.u = p.u();
129,653✔
1001
  site.E = p.E();
129,653✔
1002
  site.time = p.time();
129,653✔
1003
  site.wgt = p.wgt();
129,653✔
1004
  site.delayed_group = p.delayed_group();
129,653✔
1005
  site.surf_id = surf.id_;
129,653✔
1006
  site.particle = p.type();
129,653✔
1007
  site.parent_id = p.id();
129,653✔
1008
  site.progeny_id = p.n_progeny();
129,653✔
1009
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
129,653✔
1010
}
1011

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

© 2025 Coveralls, Inc