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

openmc-dev / openmc / 17248995070

26 Aug 2025 07:57PM UTC coverage: 85.157% (-0.05%) from 85.204%
17248995070

Pull #3547

github

web-flow
Merge b3020d1a3 into d1df80a21
Pull Request #3547: Tally spectrum of secondary particles

23 of 59 new or added lines in 8 files covered. (38.98%)

1 existing line in 1 file now uncovered.

52954 of 62184 relevant lines covered (85.16%)

37627977.62 hits per line

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

91.37
/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
//==============================================================================
42
// Particle implementation
43
//==============================================================================
44

45
double Particle::speed() const
2,147,483,647✔
46
{
47
  if (settings::run_CE) {
2,147,483,647✔
48
    // Determine mass in eV/c^2
49
    double mass;
50
    switch (this->type()) {
1,715,953,646✔
51
    case ParticleType::neutron:
1,647,091,618✔
52
      mass = MASS_NEUTRON_EV;
1,647,091,618✔
53
      break;
1,647,091,618✔
54
    case ParticleType::photon:
17,444,209✔
55
      mass = 0.0;
17,444,209✔
56
      break;
17,444,209✔
57
    case ParticleType::electron:
51,417,819✔
58
    case ParticleType::positron:
59
      mass = MASS_ELECTRON_EV;
51,417,819✔
60
      break;
51,417,819✔
61
    }
62
    // Equivalent to C * sqrt(1-(m/(m+E))^2) without problem at E<<m:
63
    return C_LIGHT * std::sqrt(this->E() * (this->E() + 2 * mass)) /
1,715,953,646✔
64
           (this->E() + mass);
1,715,953,646✔
65
  } else {
66
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,062,680,774✔
67
    int macro_t = this->mg_xs_cache().t;
2,062,680,774✔
68
    int macro_a = macro_xs.get_angle_index(this->u());
2,062,680,774✔
69
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,062,680,774✔
70
                   nullptr, nullptr, macro_t, macro_a);
2,062,680,774✔
71
  }
72
}
73

74
bool Particle::create_secondary(
107,392,027✔
75
  double wgt, Direction u, double E, ParticleType type)
76
{
77
  // If energy is below cutoff for this particle, don't create secondary
78
  // particle
79
  if (E < settings::energy_cutoff[static_cast<int>(type)]) {
107,392,027✔
80
    return false;
51,368,017✔
81
  }
82

83
  auto& bank = secondary_bank().emplace_back();
56,024,010✔
84
  bank.particle = type;
56,024,010✔
85
  bank.wgt = wgt;
56,024,010✔
86
  bank.r = r();
56,024,010✔
87
  bank.u = u;
56,024,010✔
88
  bank.E = settings::run_CE ? E : g();
56,024,010✔
89
  bank.time = time();
56,024,010✔
90
  bank_second_E() += bank.E;
56,024,010✔
91

92
  // Score tallies affected by secondary particles
93
  if (!model::active_particleout_analog_tallies.empty()) {
56,024,010✔
94
    // Create secondary particle for tallying purposes only
NEW
95
    Particle p;
×
NEW
96
    p.from_source(&bank);
×
NEW
97
    p.u_last() = this->u();
×
NEW
98
    p.r_last() = this->r();
×
NEW
99
    p.E_last() = this->E();
×
NEW
100
    p.type_last() = this->type();
×
101

NEW
102
    if (settings::run_CE) {
×
NEW
103
      score_analog_tally_ce(p, model::active_particleout_analog_tallies);
×
104
    } else {
NEW
105
      score_analog_tally_mg(p, model::active_particleout_analog_tallies);
×
106
    }
107
  }
108
  return true;
56,024,010✔
109
}
110

111
void Particle::split(double wgt)
4,082,237✔
112
{
113
  auto& bank = secondary_bank().emplace_back();
4,082,237✔
114
  bank.particle = type();
4,082,237✔
115
  bank.wgt = wgt;
4,082,237✔
116
  bank.r = r();
4,082,237✔
117
  bank.u = u();
4,082,237✔
118
  bank.E = settings::run_CE ? E() : g();
4,082,237✔
119
  bank.time = time();
4,082,237✔
120

121
  // Convert signed index to a signed surface ID
122
  if (surface() == SURFACE_NONE) {
4,082,237✔
123
    bank.surf_id = SURFACE_NONE;
4,082,217✔
124
  } else {
125
    int surf_id = model::surfaces[surface_index()]->id_;
20✔
126
    bank.surf_id = (surface() > 0) ? surf_id : -surf_id;
20✔
127
  }
128
}
4,082,237✔
129

130
void Particle::from_source(const SourceSite* src)
220,071,301✔
131
{
132
  // Reset some attributes
133
  clear();
220,071,301✔
134
  surface() = SURFACE_NONE;
220,071,301✔
135
  cell_born() = C_NONE;
220,071,301✔
136
  material() = C_NONE;
220,071,301✔
137
  n_collision() = 0;
220,071,301✔
138
  fission() = false;
220,071,301✔
139
  zero_flux_derivs();
220,071,301✔
140
  lifetime() = 0.0;
220,071,301✔
141

142
  // Copy attributes from source bank site
143
  type() = src->particle;
220,071,301✔
144
  type_last() = src->particle;
220,071,301✔
145
  wgt() = src->wgt;
220,071,301✔
146
  wgt_last() = src->wgt;
220,071,301✔
147
  r() = src->r;
220,071,301✔
148
  u() = src->u;
220,071,301✔
149
  r_born() = src->r;
220,071,301✔
150
  r_last_current() = src->r;
220,071,301✔
151
  r_last() = src->r;
220,071,301✔
152
  u_last() = src->u;
220,071,301✔
153
  if (settings::run_CE) {
220,071,301✔
154
    E() = src->E;
104,440,484✔
155
    g() = 0;
104,440,484✔
156
  } else {
157
    g() = static_cast<int>(src->E);
115,630,817✔
158
    g_last() = static_cast<int>(src->E);
115,630,817✔
159
    E() = data::mg.energy_bin_avg_[g()];
115,630,817✔
160
  }
161
  E_last() = E();
220,071,301✔
162
  time() = src->time;
220,071,301✔
163
  time_last() = src->time;
220,071,301✔
164
  parent_nuclide() = src->parent_nuclide;
220,071,301✔
165

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

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

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

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

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

201
    // Set birth cell attribute
202
    if (cell_born() == C_NONE)
217,196,204✔
203
      cell_born() = lowest_coord().cell();
217,196,204✔
204

205
    // Initialize last cells from current cell
206
    for (int j = 0; j < n_coord(); ++j) {
450,238,385✔
207
      cell_last(j) = coord(j).cell();
233,042,181✔
208
    }
209
    n_coord_last() = n_coord();
217,196,204✔
210
  }
211

212
  // Write particle track.
213
  if (write_track())
2,147,483,647✔
214
    write_particle_track(*this);
10,836✔
215

216
  if (settings::check_overlaps)
2,147,483,647✔
217
    check_cell_overlap(*this);
×
218

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

234
      // Update the particle's group while we know we are multi-group
235
      g_last() = g();
2,062,680,774✔
236
    }
237
  } else {
238
    macro_xs().total = 0.0;
67,283,586✔
239
    macro_xs().absorption = 0.0;
67,283,586✔
240
    macro_xs().fission = 0.0;
67,283,586✔
241
    macro_xs().nu_fission = 0.0;
67,283,586✔
242
  }
243
}
244

245
void Particle::event_advance()
2,147,483,647✔
246
{
247
  // Find the distance to the nearest boundary
248
  boundary() = distance_to_boundary(*this);
2,147,483,647✔
249

250
  // Sample a distance to collision
251
  if (type() == ParticleType::electron || type() == ParticleType::positron) {
2,147,483,647✔
252
    collision_distance() = 0.0;
51,417,819✔
253
  } else if (macro_xs().total == 0.0) {
2,147,483,647✔
254
    collision_distance() = INFINITY;
67,283,586✔
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[static_cast<int>(type())];
2,147,483,647✔
261
  double distance_cutoff =
262
    (time_cutoff < INFTY) ? (time_cutoff - time()) * speed : INFTY;
2,147,483,647✔
263

264
  // Select smaller of the three distances
265
  double distance =
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 track-length tallies
275
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
276
    score_tracklength_tally(*this, distance);
1,235,538,623✔
277
  }
278

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

285
  // Score flux derivative accumulators for differential tallies.
286
  if (!model::active_tallies.empty()) {
2,147,483,647✔
287
    score_track_derivative(*this, distance);
1,391,796,658✔
288
  }
289

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

296
void Particle::event_cross_surface()
2,021,171,358✔
297
{
298
  // Saving previous cell data
299
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
300
    cell_last(j) = coord(j).cell();
2,147,483,647✔
301
  }
302
  n_coord_last() = n_coord();
2,021,171,358✔
303

304
  // Set surface that particle is on and adjust coordinate levels
305
  surface() = boundary().surface();
2,021,171,358✔
306
  n_coord() = boundary().coord_level();
2,021,171,358✔
307

308
  if (boundary().lattice_translation()[0] != 0 ||
2,021,171,358✔
309
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
310
      boundary().lattice_translation()[2] != 0) {
1,528,605,072✔
311
    // Particle crosses lattice boundary
312

313
    bool verbose = settings::verbosity >= 10 || trace();
678,948,434✔
314
    cross_lattice(*this, boundary(), verbose);
678,948,434✔
315
    event() = TallyEvent::LATTICE;
678,948,434✔
316
  } else {
317
    // Particle crosses surface
318
    const auto& surf {model::surfaces[surface_index()].get()};
1,342,222,924✔
319
    // If BC, add particle to surface source before crossing surface
320
    if (surf->surf_source_ && surf->bc_) {
1,342,222,924✔
321
      add_surf_source_to_bank(*this, *surf);
628,330,639✔
322
    }
323
    this->cross_surface(*surf);
1,342,222,924✔
324
    // If no BC, add particle to surface source after crossing surface
325
    if (surf->surf_source_ && !surf->bc_) {
1,342,222,915✔
326
      add_surf_source_to_bank(*this, *surf);
712,658,867✔
327
    }
328
    if (settings::weight_window_checkpoint_surface) {
1,342,222,915✔
329
      apply_weight_windows(*this);
396✔
330
    }
331
    event() = TallyEvent::SURFACE;
1,342,222,915✔
332
  }
333
  // Score cell to cell partial currents
334
  if (!model::active_surface_tallies.empty()) {
2,021,171,349✔
335
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
336
  }
337
}
2,021,171,349✔
338

339
void Particle::event_collide()
2,147,483,647✔
340
{
341
  // Score collision estimate of keff
342
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
343
      type() == ParticleType::neutron) {
2,129,870,155✔
344
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,090,547,971✔
345
  }
346

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

351
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
352
    score_surface_tally(*this, model::active_meshsurf_tallies);
62,915,094✔
353

354
  // Clear surface component
355
  surface() = SURFACE_NONE;
2,147,483,647✔
356

357
  if (settings::run_CE) {
2,147,483,647✔
358
    collision(*this);
717,184,093✔
359
  } else {
360
    collision_mg(*this);
1,781,763,302✔
361
  }
362

363
  // Score collision estimator tallies -- this is done after a collision
364
  // has occurred rather than before because we need information on the
365
  // outgoing energy for any tallies with an outgoing energy filter
366
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
367
    score_collision_tally(*this);
97,813,123✔
368
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
369
    if (settings::run_CE) {
107,867,287✔
370
      score_analog_tally_ce(*this, model::active_analog_tallies);
106,666,076✔
371
    } else {
372
      score_analog_tally_mg(*this, model::active_analog_tallies);
1,201,211✔
373
    }
374
  }
375

376
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
377
      type() == ParticleType::photon) {
16,918✔
378
    pht_collision_energy();
2,024✔
379
  }
380

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

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

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

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

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

411
  // Score flux derivative accumulators for differential tallies.
412
  if (!model::active_tallies.empty())
2,147,483,647✔
413
    score_collision_derivative(*this);
614,966,829✔
414

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

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

430
  // Check for secondary particles if this particle is dead
431
  if (!alive()) {
2,147,483,647✔
432
    // Write final position for this particle
433
    if (write_track()) {
217,195,800✔
434
      write_particle_track(*this);
6,674✔
435
    }
436

437
    // If no secondary particles, break out of event loop
438
    if (secondary_bank().empty())
217,195,800✔
439
      return;
156,750,798✔
440

441
    from_source(&secondary_bank().back());
60,445,002✔
442
    secondary_bank().pop_back();
60,445,002✔
443
    n_event() = 0;
60,445,002✔
444
    bank_second_E() = 0.0;
60,445,002✔
445

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

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

472
    // Enter new particle in particle track file
473
    if (write_track())
60,445,002✔
474
      add_particle_track(*this);
5,604✔
475
  }
476
}
477

478
void Particle::event_death()
156,751,798✔
479
{
480
#ifdef OPENMC_DAGMC_ENABLED
481
  history().reset();
14,326,682✔
482
#endif
483

484
  // Finish particle track output.
485
  if (write_track()) {
156,751,798✔
486
    finalize_particle_track(*this);
1,070✔
487
  }
488

489
// Contribute tally reduction variables to global accumulator
490
#pragma omp atomic
86,192,397✔
491
  global_tally_absorption += keff_tally_absorption();
156,751,798✔
492
#pragma omp atomic
86,160,861✔
493
  global_tally_collision += keff_tally_collision();
156,751,798✔
494
#pragma omp atomic
85,950,420✔
495
  global_tally_tracklength += keff_tally_tracklength();
156,751,798✔
496
#pragma omp atomic
85,688,483✔
497
  global_tally_leakage += keff_tally_leakage();
156,751,798✔
498

499
  // Reset particle tallies once accumulated
500
  keff_tally_absorption() = 0.0;
156,751,798✔
501
  keff_tally_collision() = 0.0;
156,751,798✔
502
  keff_tally_tracklength() = 0.0;
156,751,798✔
503
  keff_tally_leakage() = 0.0;
156,751,798✔
504

505
  if (!model::active_pulse_height_tallies.empty()) {
156,751,798✔
506
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
507
  }
508

509
  // Record the number of progeny created by this particle.
510
  // This data will be used to efficiently sort the fission bank.
511
  if (settings::run_mode == RunMode::EIGENVALUE) {
156,751,798✔
512
    int64_t offset = id() - 1 - simulation::work_index[mpi::rank];
133,615,800✔
513
    simulation::progeny_per_particle[offset] = n_progeny();
133,615,800✔
514
  }
515
}
156,751,798✔
516

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

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

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

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

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

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

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

552
void Particle::cross_surface(const Surface& surf)
1,343,206,192✔
553
{
554

555
  if (settings::verbosity >= 10 || trace()) {
1,343,206,192✔
556
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
557
  }
558

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

565
  // Handle any applicable boundary conditions.
566
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,343,206,192✔
567
    surf.bc_->handle_particle(*this, surf);
628,678,256✔
568
    return;
628,678,256✔
569
  }
570

571
  // ==========================================================================
572
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
573

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

587
    cell_instance() = 0;
36,997✔
588
    if (cell->distribcell_index_ >= 0)
36,997✔
589
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
35,996✔
590

591
    material() = cell->material(cell_instance());
36,997✔
592
    sqrtkT() = cell->sqrtkT(cell_instance());
36,997✔
593
    return;
36,997✔
594
  }
595
#endif
596

597
  bool verbose = settings::verbosity >= 10 || trace();
714,490,939✔
598
  if (neighbor_list_find_cell(*this, verbose)) {
714,490,939✔
599
    return;
714,462,920✔
600
  }
601

602
  // ==========================================================================
603
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
604

605
  // Remove lower coordinate levels
606
  n_coord() = 1;
28,019✔
607
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
608

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

615
    surface() = SURFACE_NONE;
5,744✔
616
    n_coord() = 1;
5,744✔
617
    r() += TINY_BIT * u();
5,744✔
618

619
    // Couldn't find next cell anywhere! This probably means there is an actual
620
    // undefined region in the geometry.
621

622
    if (!exhaustive_find_cell(*this, verbose)) {
5,744✔
623
      mark_as_lost("After particle " + std::to_string(id()) +
17,223✔
624
                   " crossed surface " + std::to_string(surf.id_) +
22,958✔
625
                   " it could not be located in any cell and it did not leak.");
626
      return;
5,735✔
627
    }
628
  }
629
}
630

631
void Particle::cross_vacuum_bc(const Surface& surf)
30,902,349✔
632
{
633
  // Score any surface current tallies -- note that the particle is moved
634
  // forward slightly so that if the mesh boundary is on the surface, it is
635
  // still processed
636

637
  if (!model::active_meshsurf_tallies.empty()) {
30,902,349✔
638
    // TODO: Find a better solution to score surface currents than
639
    // physically moving the particle forward slightly
640

641
    r() += TINY_BIT * u();
945,450✔
642
    score_surface_tally(*this, model::active_meshsurf_tallies);
945,450✔
643
  }
644

645
  // Score to global leakage tally
646
  keff_tally_leakage() += wgt();
30,902,349✔
647

648
  // Kill the particle
649
  wgt() = 0.0;
30,902,349✔
650

651
  // Display message
652
  if (settings::verbosity >= 10 || trace()) {
30,902,349✔
653
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
654
  }
655
}
30,902,349✔
656

657
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
598,136,945✔
658
{
659
  // Do not handle reflective boundary conditions on lower universes
660
  if (n_coord() != 1) {
598,136,945✔
661
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
662
                 " off surface in a lower universe.");
663
    return;
×
664
  }
665

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

673
  if (!model::active_surface_tallies.empty()) {
598,136,945✔
674
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
675
  }
676

677
  if (!model::active_meshsurf_tallies.empty()) {
598,136,945✔
678
    Position r {this->r()};
46,625,403✔
679
    this->r() -= TINY_BIT * u();
46,625,403✔
680
    score_surface_tally(*this, model::active_meshsurf_tallies);
46,625,403✔
681
    this->r() = r;
46,625,403✔
682
  }
683

684
  // Set the new particle direction
685
  u() = new_u;
598,136,945✔
686

687
  // Reassign particle's cell and surface
688
  coord(0).cell() = cell_last(0);
598,136,945✔
689
  surface() = -surface();
598,136,945✔
690

691
  // If a reflective surface is coincident with a lattice or universe
692
  // boundary, it is necessary to redetermine the particle's coordinates in
693
  // the lower universes.
694
  // (unless we're using a dagmc model, which has exactly one universe)
695
  n_coord() = 1;
598,136,945✔
696
  if (surf.geom_type() != GeometryType::DAG &&
1,196,271,351✔
697
      !neighbor_list_find_cell(*this)) {
598,134,406✔
698
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
699
                 std::to_string(surf.id_) + ".");
×
700
    return;
×
701
  }
702

703
  // Set previous coordinate going slightly past surface crossing
704
  r_last_current() = r() + TINY_BIT * u();
598,136,945✔
705

706
  // Diagnostic message
707
  if (settings::verbosity >= 10 || trace()) {
598,136,945✔
708
    write_message(1, "    Reflected from surface {}", surf.id_);
×
709
  }
710
}
711

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

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

734
  // Adjust the particle's location and direction.
735
  r() = new_r;
666,318✔
736
  u() = new_u;
666,318✔
737

738
  // Reassign particle's surface
739
  surface() = new_surface;
666,318✔
740

741
  // Figure out what cell particle is in now
742
  n_coord() = 1;
666,318✔
743

744
  if (!neighbor_list_find_cell(*this)) {
666,318✔
745
    mark_as_lost("Couldn't find particle after hitting periodic "
×
746
                 "boundary on surface " +
×
747
                 std::to_string(surf.id_) +
×
748
                 ". The normal vector "
749
                 "of one periodic surface may need to be reversed.");
750
    return;
×
751
  }
752

753
  // Set previous coordinate going slightly past surface crossing
754
  r_last_current() = r() + TINY_BIT * u();
666,318✔
755

756
  // Diagnostic message
757
  if (settings::verbosity >= 10 || trace()) {
666,318✔
758
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
759
  }
760
}
761

762
void Particle::mark_as_lost(const char* message)
5,744✔
763
{
764
  // Print warning and write lost particle file
765
  warning(message);
5,744✔
766
  if (settings::max_write_lost_particles < 0 ||
5,744✔
767
      simulation::n_lost_particles < settings::max_write_lost_particles) {
5,500✔
768
    write_restart();
324✔
769
  }
770
  // Increment number of lost particles
771
  wgt() = 0.0;
5,744✔
772
#pragma omp atomic
3,124✔
773
  simulation::n_lost_particles += 1;
2,620✔
774

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

779
  // Abort the simulation if the maximum number of lost particles has been
780
  // reached
781
  if (simulation::n_lost_particles >= settings::max_lost_particles &&
5,744✔
782
      simulation::n_lost_particles >= settings::rel_max_lost_particles * n) {
9✔
783
    fatal_error("Maximum number of lost particles has been reached.");
9✔
784
  }
785
}
5,735✔
786

787
void Particle::write_restart() const
324✔
788
{
789
  // Dont write another restart file if in particle restart mode
790
  if (settings::run_mode == RunMode::PARTICLE)
324✔
791
    return;
22✔
792

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

797
#pragma omp critical(WriteParticleRestart)
314✔
798
  {
799
    // Create file
800
    hid_t file_id = file_open(filename, 'w');
302✔
801

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

810
    // Write data to file
811
    write_dataset(file_id, "current_batch", simulation::current_batch);
302✔
812
    write_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
302✔
813
    write_dataset(file_id, "current_generation", simulation::current_gen);
302✔
814
    write_dataset(file_id, "n_particles", settings::n_particles);
302✔
815
    switch (settings::run_mode) {
302✔
816
    case RunMode::FIXED_SOURCE:
225✔
817
      write_dataset(file_id, "run_mode", "fixed source");
225✔
818
      break;
225✔
819
    case RunMode::EIGENVALUE:
77✔
820
      write_dataset(file_id, "run_mode", "eigenvalue");
77✔
821
      break;
77✔
822
    case RunMode::PARTICLE:
×
823
      write_dataset(file_id, "run_mode", "particle restart");
×
824
      break;
×
825
    default:
×
826
      break;
×
827
    }
828
    write_dataset(file_id, "id", id());
302✔
829
    write_dataset(file_id, "type", static_cast<int>(type()));
302✔
830

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

854
    // Close file
855
    file_close(file_id);
302✔
856
  } // #pragma omp critical
857
}
302✔
858

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

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

870
    // If NCrystal is being used, update micro cross section cache
871
    if (ncrystal_xs >= 0.0) {
2,147,483,647✔
872
      data::nuclides[i_nuclide]->calculate_elastic_xs(*this);
11,018,953✔
873
      ncrystal_update_micro(ncrystal_xs, micro);
11,018,953✔
874
    }
875
  }
876
}
2,147,483,647✔
877

878
//==============================================================================
879
// Non-method functions
880
//==============================================================================
881

882
std::string particle_type_to_str(ParticleType type)
3,130,197✔
883
{
884
  switch (type) {
3,130,197✔
885
  case ParticleType::neutron:
2,399,940✔
886
    return "neutron";
2,399,940✔
887
  case ParticleType::photon:
729,993✔
888
    return "photon";
729,993✔
889
  case ParticleType::electron:
132✔
890
    return "electron";
132✔
891
  case ParticleType::positron:
132✔
892
    return "positron";
132✔
893
  }
894
  UNREACHABLE();
×
895
}
896

897
ParticleType str_to_particle_type(std::string str)
2,975,768✔
898
{
899
  if (str == "neutron") {
2,975,768✔
900
    return ParticleType::neutron;
679,535✔
901
  } else if (str == "photon") {
2,296,233✔
902
    return ParticleType::photon;
2,296,147✔
903
  } else if (str == "electron") {
86✔
904
    return ParticleType::electron;
43✔
905
  } else if (str == "positron") {
43✔
906
    return ParticleType::positron;
43✔
907
  } else {
908
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
909
  }
910
}
911

912
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,340,989,506✔
913
{
914
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
915
      simulation::surf_source_bank.full()) {
1,055,977,922✔
916
    return;
1,340,860,741✔
917
  }
918

919
  // If a cell/cellfrom/cellto parameter is defined
920
  if (settings::ssw_cell_id != C_NONE) {
341,267✔
921

922
    // Retrieve cell index and storage type
923
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,706✔
924

925
    if (surf.bc_) {
258,706✔
926
      // Leave if cellto with vacuum boundary condition
927
      if (surf.bc_->type() == "vacuum" &&
184,448✔
928
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
929
        return;
11,953✔
930
      }
931

932
      // Leave if other boundary condition than vacuum
933
      if (surf.bc_->type() != "vacuum") {
140,281✔
934
        return;
120,020✔
935
      }
936
    }
937

938
    // Check if the cell of interest has been exited
939
    bool exited = false;
126,733✔
940
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,343✔
941
      if (p.cell_last(i) == cell_idx) {
208,610✔
942
        exited = true;
74,235✔
943
      }
944
    }
945

946
    // Check if the cell of interest has been entered
947
    bool entered = false;
126,733✔
948
    for (int i = 0; i < p.n_coord(); ++i) {
301,039✔
949
      if (p.coord(i).cell() == cell_idx) {
174,306✔
950
        entered = true;
59,099✔
951
      }
952
    }
953

954
    // Vacuum boundary conditions: return if cell is not exited
955
    if (surf.bc_) {
126,733✔
956
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
957
        return;
13,961✔
958
      }
959
    } else {
960

961
      // If we both enter and exit the cell of interest
962
      if (entered && exited) {
106,472✔
963
        return;
28,613✔
964
      }
965

966
      // If we did not enter nor exit the cell of interest
967
      if (!entered && !exited) {
77,859✔
968
        return;
14,351✔
969
      }
970

971
      // If cellfrom and the cell before crossing is not the cell of
972
      // interest
973
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,508✔
974
        return;
11,566✔
975
      }
976

977
      // If cellto and the cell after crossing is not the cell of interest
978
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
51,942✔
979
        return;
12,038✔
980
      }
981
    }
982
  }
983

984
  SourceSite site;
128,765✔
985
  site.r = p.r();
128,765✔
986
  site.u = p.u();
128,765✔
987
  site.E = p.E();
128,765✔
988
  site.time = p.time();
128,765✔
989
  site.wgt = p.wgt();
128,765✔
990
  site.delayed_group = p.delayed_group();
128,765✔
991
  site.surf_id = surf.id_;
128,765✔
992
  site.particle = p.type();
128,765✔
993
  site.parent_id = p.id();
128,765✔
994
  site.progeny_id = p.n_progeny();
128,765✔
995
  int64_t idx = simulation::surf_source_bank.thread_safe_append(site);
128,765✔
996
}
997

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