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

openmc-dev / openmc / 17271335175

27 Aug 2025 03:30PM UTC coverage: 85.158% (-0.05%) from 85.204%
17271335175

Pull #3547

github

web-flow
Merge 4e47f041b into d1df80a21
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.

52954 of 62183 relevant lines covered (85.16%)

37874602.56 hits per line

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

91.55
/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,746,521,173✔
55
    case ParticleType::neutron:
1,677,659,145✔
56
      mass = MASS_NEUTRON_EV;
1,677,659,145✔
57
      break;
1,677,659,145✔
58
    case ParticleType::photon:
17,444,209✔
59
      mass = 0.0;
17,444,209✔
60
      break;
17,444,209✔
61
    case ParticleType::electron:
51,417,819✔
62
    case ParticleType::positron:
63
      mass = MASS_ELECTRON_EV;
51,417,819✔
64
      break;
51,417,819✔
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,746,521,173✔
68
           (this->E() + mass);
1,746,521,173✔
69
  } else {
70
    auto& macro_xs = data::mg.macro_xs_[this->material()];
2,062,680,774✔
71
    int macro_t = this->mg_xs_cache().t;
2,062,680,774✔
72
    int macro_a = macro_xs.get_angle_index(this->u());
2,062,680,774✔
73
    return 1.0 / macro_xs.get_xs(MgxsType::INVERSE_VELOCITY, this->g(), nullptr,
2,062,680,774✔
74
                   nullptr, nullptr, macro_t, macro_a);
2,062,680,774✔
75
  }
76
}
77

78
bool Particle::create_secondary(
107,393,702✔
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)]) {
107,393,702✔
84
    return false;
51,368,017✔
85
  }
86

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

96
  // Score tallies affected by secondary particles
97
  if (!model::active_particleout_analog_tallies.empty()) {
56,025,685✔
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,025,685✔
114
}
115

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

126
  // Convert signed index to a signed surface ID
127
  if (surface() == SURFACE_NONE) {
4,082,025✔
128
    bank.surf_id = SURFACE_NONE;
4,082,005✔
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,082,025✔
134

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

147
  // Copy attributes from source bank site
148
  type() = src->particle;
220,636,764✔
149
  type_last() = src->particle;
220,636,764✔
150
  wgt() = src->wgt;
220,636,764✔
151
  wgt_last() = src->wgt;
220,636,764✔
152
  r() = src->r;
220,636,764✔
153
  u() = src->u;
220,636,764✔
154
  r_born() = src->r;
220,636,764✔
155
  r_last_current() = src->r;
220,636,764✔
156
  r_last() = src->r;
220,636,764✔
157
  u_last() = src->u;
220,636,764✔
158
  if (settings::run_CE) {
220,636,764✔
159
    E() = src->E;
105,005,947✔
160
    g() = 0;
105,005,947✔
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();
220,636,764✔
167
  time() = src->time;
220,636,764✔
168
  time_last() = src->time;
220,636,764✔
169
  parent_nuclide() = src->parent_nuclide;
220,636,764✔
170

171
  // Convert signed surface ID to signed index
172
  if (src->surf_id != SURFACE_NONE) {
220,636,764✔
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
}
220,636,764✔
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)) {
217,761,667✔
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)
217,761,667✔
208
      cell_born() = lowest_coord().cell();
217,761,667✔
209

210
    // Initialize last cells from current cell
211
    for (int j = 0; j < n_coord(); ++j) {
451,499,524✔
212
      cell_last(j) = coord(j).cell();
233,737,857✔
213
    }
214
    n_coord_last() = n_coord();
217,761,667✔
215
  }
216

217
  // Write particle track.
218
  if (write_track())
2,147,483,647✔
219
    write_particle_track(*this);
10,836✔
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()) {
1,655,782,888✔
228
        // If the material is the same as the last material and the
229
        // temperature hasn't changed, we don't need to lookup cross
230
        // sections again.
231
        model::materials[material()]->calculate_xs(*this);
1,321,841,152✔
232
      }
233
    } else {
234
      // Get the MG data; unlike the CE case above, we have to re-calculate
235
      // cross sections for every collision since the cross sections may
236
      // be angle-dependent
237
      data::mg.macro_xs_[material()].calculate_xs(*this);
2,062,680,774✔
238

239
      // Update the particle's group while we know we are multi-group
240
      g_last() = g();
2,062,680,774✔
241
    }
242
  } else {
243
    macro_xs().total = 0.0;
67,283,645✔
244
    macro_xs().absorption = 0.0;
67,283,645✔
245
    macro_xs().fission = 0.0;
67,283,645✔
246
    macro_xs().nu_fission = 0.0;
67,283,645✔
247
  }
248
}
249

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

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

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

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

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

279
  // Score track-length tallies
280
  if (!model::active_tracklength_tallies.empty()) {
2,147,483,647✔
281
    score_tracklength_tally(*this, distance);
1,252,278,025✔
282
  }
283

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

290
  // Score flux derivative accumulators for differential tallies.
291
  if (!model::active_tallies.empty()) {
2,147,483,647✔
292
    score_track_derivative(*this, distance);
1,422,364,126✔
293
  }
294

295
  // Set particle weight to zero if it hit the time boundary
296
  if (distance == distance_cutoff) {
2,147,483,647✔
297
    wgt() = 0.0;
11,000✔
298
  }
299
}
2,147,483,647✔
300

301
void Particle::event_cross_surface()
2,040,152,525✔
302
{
303
  // Saving previous cell data
304
  for (int j = 0; j < n_coord(); ++j) {
2,147,483,647✔
305
    cell_last(j) = coord(j).cell();
2,147,483,647✔
306
  }
307
  n_coord_last() = n_coord();
2,040,152,525✔
308

309
  // Set surface that particle is on and adjust coordinate levels
310
  surface() = boundary().surface();
2,040,152,525✔
311
  n_coord() = boundary().coord_level();
2,040,152,525✔
312

313
  if (boundary().lattice_translation()[0] != 0 ||
2,040,152,525✔
314
      boundary().lattice_translation()[1] != 0 ||
2,147,483,647✔
315
      boundary().lattice_translation()[2] != 0) {
1,546,370,733✔
316
    // Particle crosses lattice boundary
317

318
    bool verbose = settings::verbosity >= 10 || trace();
680,163,945✔
319
    cross_lattice(*this, boundary(), verbose);
680,163,945✔
320
    event() = TallyEvent::LATTICE;
680,163,945✔
321
  } else {
322
    // Particle crosses surface
323
    const auto& surf {model::surfaces[surface_index()].get()};
1,359,988,580✔
324
    // If BC, add particle to surface source before crossing surface
325
    if (surf->surf_source_ && surf->bc_) {
1,359,988,580✔
326
      add_surf_source_to_bank(*this, *surf);
637,455,319✔
327
    }
328
    this->cross_surface(*surf);
1,359,988,580✔
329
    // If no BC, add particle to surface source after crossing surface
330
    if (surf->surf_source_ && !surf->bc_) {
1,359,988,571✔
331
      add_surf_source_to_bank(*this, *surf);
721,299,843✔
332
    }
333
    if (settings::weight_window_checkpoint_surface) {
1,359,988,571✔
334
      apply_weight_windows(*this);
396✔
335
    }
336
    event() = TallyEvent::SURFACE;
1,359,988,571✔
337
  }
338
  // Score cell to cell partial currents
339
  if (!model::active_surface_tallies.empty()) {
2,040,152,516✔
340
    score_surface_tally(*this, model::active_surface_tallies);
34,896,015✔
341
  }
342
}
2,040,152,516✔
343

344
void Particle::event_collide()
2,147,483,647✔
345
{
346
  // Score collision estimate of keff
347
  if (settings::run_mode == RunMode::EIGENVALUE &&
2,147,483,647✔
348
      type() == ParticleType::neutron) {
2,141,455,851✔
349
    keff_tally_collision() += wgt() * macro_xs().nu_fission / macro_xs().total;
2,102,133,667✔
350
  }
351

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

356
  if (!model::active_meshsurf_tallies.empty())
2,147,483,647✔
357
    score_surface_tally(*this, model::active_meshsurf_tallies);
74,216,648✔
358

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

362
  if (settings::run_CE) {
2,147,483,647✔
363
    collision(*this);
728,770,453✔
364
  } else {
365
    collision_mg(*this);
1,781,763,302✔
366
  }
367

368
  // Score collision estimator tallies -- this is done after a collision
369
  // has occurred rather than before because we need information on the
370
  // outgoing energy for any tallies with an outgoing energy filter
371
  if (!model::active_collision_tallies.empty())
2,147,483,647✔
372
    score_collision_tally(*this);
97,813,123✔
373
  if (!model::active_analog_tallies.empty()) {
2,147,483,647✔
374
    if (settings::run_CE) {
119,168,841✔
375
      score_analog_tally_ce(*this, model::active_analog_tallies);
117,967,630✔
376
    } else {
377
      score_analog_tally_mg(*this, model::active_analog_tallies);
1,201,211✔
378
    }
379
  }
380

381
  if (!model::active_pulse_height_tallies.empty() &&
2,147,483,647✔
382
      type() == ParticleType::photon) {
16,918✔
383
    pht_collision_energy();
2,024✔
384
  }
385

386
  // Reset banked weight during collision
387
  n_bank() = 0;
2,147,483,647✔
388
  bank_second_E() = 0.0;
2,147,483,647✔
389
  wgt_bank() = 0.0;
2,147,483,647✔
390
  zero_delayed_bank();
2,147,483,647✔
391

392
  // Reset fission logical
393
  fission() = false;
2,147,483,647✔
394

395
  // Save coordinates for tallying purposes
396
  r_last_current() = r();
2,147,483,647✔
397

398
  // Set last material to none since cross sections will need to be
399
  // re-evaluated
400
  material_last() = C_NONE;
2,147,483,647✔
401

402
  // Set all directions to base level -- right now, after a collision, only
403
  // the base level directions are changed
404
  for (int j = 0; j < n_coord() - 1; ++j) {
2,147,483,647✔
405
    if (coord(j + 1).rotated()) {
113,845,043✔
406
      // If next level is rotated, apply rotation matrix
407
      const auto& m {model::cells[coord(j).cell()]->rotation_};
10,394,285✔
408
      const auto& u {coord(j).u()};
10,394,285✔
409
      coord(j + 1).u() = u.rotate(m);
10,394,285✔
410
    } else {
411
      // Otherwise, copy this level's direction
412
      coord(j + 1).u() = coord(j).u();
103,450,758✔
413
    }
414
  }
415

416
  // Score flux derivative accumulators for differential tallies.
417
  if (!model::active_tallies.empty())
2,147,483,647✔
418
    score_collision_derivative(*this);
626,553,189✔
419

420
#ifdef OPENMC_DAGMC_ENABLED
421
  history().reset();
229,217,255✔
422
#endif
423
}
2,147,483,647✔
424

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

435
  // Check for secondary particles if this particle is dead
436
  if (!alive()) {
2,147,483,647✔
437
    // Write final position for this particle
438
    if (write_track()) {
217,761,263✔
439
      write_particle_track(*this);
6,674✔
440
    }
441

442
    // If no secondary particles, break out of event loop
443
    if (secondary_bank().empty())
217,761,263✔
444
      return;
157,314,798✔
445

446
    from_source(&secondary_bank().back());
60,446,465✔
447
    secondary_bank().pop_back();
60,446,465✔
448
    n_event() = 0;
60,446,465✔
449
    bank_second_E() = 0.0;
60,446,465✔
450

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

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

477
    // Enter new particle in particle track file
478
    if (write_track())
60,446,465✔
479
      add_particle_track(*this);
5,604✔
480
  }
481
}
482

483
void Particle::event_death()
157,315,798✔
484
{
485
#ifdef OPENMC_DAGMC_ENABLED
486
  history().reset();
14,326,682✔
487
#endif
488

489
  // Finish particle track output.
490
  if (write_track()) {
157,315,798✔
491
    finalize_particle_track(*this);
1,070✔
492
  }
493

494
// Contribute tally reduction variables to global accumulator
495
#pragma omp atomic
86,535,351✔
496
  global_tally_absorption += keff_tally_absorption();
157,315,798✔
497
#pragma omp atomic
86,907,421✔
498
  global_tally_collision += keff_tally_collision();
157,315,798✔
499
#pragma omp atomic
86,432,663✔
500
  global_tally_tracklength += keff_tally_tracklength();
157,315,798✔
501
#pragma omp atomic
86,049,720✔
502
  global_tally_leakage += keff_tally_leakage();
157,315,798✔
503

504
  // Reset particle tallies once accumulated
505
  keff_tally_absorption() = 0.0;
157,315,798✔
506
  keff_tally_collision() = 0.0;
157,315,798✔
507
  keff_tally_tracklength() = 0.0;
157,315,798✔
508
  keff_tally_leakage() = 0.0;
157,315,798✔
509

510
  if (!model::active_pulse_height_tallies.empty()) {
157,315,798✔
511
    score_pulse_height_tally(*this, model::active_pulse_height_tallies);
5,500✔
512
  }
513

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

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

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

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

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

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

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

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

557
void Particle::cross_surface(const Surface& surf)
1,360,971,848✔
558
{
559

560
  if (settings::verbosity >= 10 || trace()) {
1,360,971,848✔
561
    write_message(1, "    Crossing surface {}", surf.id_);
33✔
562
  }
563

564
// if we're crossing a CSG surface, make sure the DAG history is reset
565
#ifdef OPENMC_DAGMC_ENABLED
566
  if (surf.geom_type() == GeometryType::CSG)
123,100,666✔
567
    history().reset();
123,056,618✔
568
#endif
569

570
  // Handle any applicable boundary conditions.
571
  if (surf.bc_ && settings::run_mode != RunMode::PLOTTING) {
1,360,971,848✔
572
    surf.bc_->handle_particle(*this, surf);
637,802,936✔
573
    return;
637,802,936✔
574
  }
575

576
  // ==========================================================================
577
  // SEARCH NEIGHBOR LISTS FOR NEXT CELL
578

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

592
    cell_instance() = 0;
36,997✔
593
    if (cell->distribcell_index_ >= 0)
36,997✔
594
      cell_instance() = cell_instance_at_level(*this, n_coord() - 1);
35,996✔
595

596
    material() = cell->material(cell_instance());
36,997✔
597
    sqrtkT() = cell->sqrtkT(cell_instance());
36,997✔
598
    return;
36,997✔
599
  }
600
#endif
601

602
  bool verbose = settings::verbosity >= 10 || trace();
723,131,915✔
603
  if (neighbor_list_find_cell(*this, verbose)) {
723,131,915✔
604
    return;
723,103,896✔
605
  }
606

607
  // ==========================================================================
608
  // COULDN'T FIND PARTICLE IN NEIGHBORING CELLS, SEARCH ALL CELLS
609

610
  // Remove lower coordinate levels
611
  n_coord() = 1;
28,019✔
612
  bool found = exhaustive_find_cell(*this, verbose);
28,019✔
613

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

620
    surface() = SURFACE_NONE;
5,744✔
621
    n_coord() = 1;
5,744✔
622
    r() += TINY_BIT * u();
5,744✔
623

624
    // Couldn't find next cell anywhere! This probably means there is an actual
625
    // undefined region in the geometry.
626

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

636
void Particle::cross_vacuum_bc(const Surface& surf)
31,053,983✔
637
{
638
  // Score any surface current tallies -- note that the particle is moved
639
  // forward slightly so that if the mesh boundary is on the surface, it is
640
  // still processed
641

642
  if (!model::active_meshsurf_tallies.empty()) {
31,053,983✔
643
    // TODO: Find a better solution to score surface currents than
644
    // physically moving the particle forward slightly
645

646
    r() += TINY_BIT * u();
1,097,080✔
647
    score_surface_tally(*this, model::active_meshsurf_tallies);
1,097,080✔
648
  }
649

650
  // Score to global leakage tally
651
  keff_tally_leakage() += wgt();
31,053,983✔
652

653
  // Kill the particle
654
  wgt() = 0.0;
31,053,983✔
655

656
  // Display message
657
  if (settings::verbosity >= 10 || trace()) {
31,053,983✔
658
    write_message(1, "    Leaked out of surface {}", surf.id_);
11✔
659
  }
660
}
31,053,983✔
661

662
void Particle::cross_reflective_bc(const Surface& surf, Direction new_u)
607,109,991✔
663
{
664
  // Do not handle reflective boundary conditions on lower universes
665
  if (n_coord() != 1) {
607,109,991✔
666
    mark_as_lost("Cannot reflect particle " + std::to_string(id()) +
×
667
                 " off surface in a lower universe.");
668
    return;
×
669
  }
670

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

678
  if (!model::active_surface_tallies.empty()) {
607,109,991✔
679
    score_surface_tally(*this, model::active_surface_tallies);
281,809✔
680
  }
681

682
  if (!model::active_meshsurf_tallies.empty()) {
607,109,991✔
683
    Position r {this->r()};
54,998,215✔
684
    this->r() -= TINY_BIT * u();
54,998,215✔
685
    score_surface_tally(*this, model::active_meshsurf_tallies);
54,998,215✔
686
    this->r() = r;
54,998,215✔
687
  }
688

689
  // Set the new particle direction
690
  u() = new_u;
607,109,991✔
691

692
  // Reassign particle's cell and surface
693
  coord(0).cell() = cell_last(0);
607,109,991✔
694
  surface() = -surface();
607,109,991✔
695

696
  // If a reflective surface is coincident with a lattice or universe
697
  // boundary, it is necessary to redetermine the particle's coordinates in
698
  // the lower universes.
699
  // (unless we're using a dagmc model, which has exactly one universe)
700
  n_coord() = 1;
607,109,991✔
701
  if (surf.geom_type() != GeometryType::DAG &&
1,214,217,443✔
702
      !neighbor_list_find_cell(*this)) {
607,107,452✔
703
    mark_as_lost("Couldn't find particle after reflecting from surface " +
×
704
                 std::to_string(surf.id_) + ".");
×
705
    return;
×
706
  }
707

708
  // Set previous coordinate going slightly past surface crossing
709
  r_last_current() = r() + TINY_BIT * u();
607,109,991✔
710

711
  // Diagnostic message
712
  if (settings::verbosity >= 10 || trace()) {
607,109,991✔
713
    write_message(1, "    Reflected from surface {}", surf.id_);
×
714
  }
715
}
716

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

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

739
  // Adjust the particle's location and direction.
740
  r() = new_r;
666,318✔
741
  u() = new_u;
666,318✔
742

743
  // Reassign particle's surface
744
  surface() = new_surface;
666,318✔
745

746
  // Figure out what cell particle is in now
747
  n_coord() = 1;
666,318✔
748

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

758
  // Set previous coordinate going slightly past surface crossing
759
  r_last_current() = r() + TINY_BIT * u();
666,318✔
760

761
  // Diagnostic message
762
  if (settings::verbosity >= 10 || trace()) {
666,318✔
763
    write_message(1, "    Hit periodic boundary on surface {}", surf.id_);
×
764
  }
765
}
766

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

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

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

792
void Particle::write_restart() const
324✔
793
{
794
  // Dont write another restart file if in particle restart mode
795
  if (settings::run_mode == RunMode::PARTICLE)
324✔
796
    return;
22✔
797

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

802
#pragma omp critical(WriteParticleRestart)
314✔
803
  {
804
    // Create file
805
    hid_t file_id = file_open(filename, 'w');
302✔
806

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

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

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

859
    // Close file
860
    file_close(file_id);
302✔
861
  } // #pragma omp critical
862
}
302✔
863

864
void Particle::update_neutron_xs(
2,147,483,647✔
865
  int i_nuclide, int i_grid, int i_sab, double sab_frac, double ncrystal_xs)
866
{
867
  // Get microscopic cross section cache
868
  auto& micro = this->neutron_xs(i_nuclide);
2,147,483,647✔
869

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

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

883
//==============================================================================
884
// Non-method functions
885
//==============================================================================
886

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

902
ParticleType str_to_particle_type(std::string str)
3,022,571✔
903
{
904
  if (str == "neutron") {
3,022,571✔
905
    return ParticleType::neutron;
691,153✔
906
  } else if (str == "photon") {
2,331,418✔
907
    return ParticleType::photon;
2,331,332✔
908
  } else if (str == "electron") {
86✔
909
    return ParticleType::electron;
43✔
910
  } else if (str == "positron") {
43✔
911
    return ParticleType::positron;
43✔
912
  } else {
913
    throw std::invalid_argument {fmt::format("Invalid particle name: {}", str)};
×
914
  }
915
}
916

917
void add_surf_source_to_bank(Particle& p, const Surface& surf)
1,358,755,162✔
918
{
919
  if (simulation::current_batch <= settings::n_inactive ||
2,147,483,647✔
920
      simulation::surf_source_bank.full()) {
1,065,968,826✔
921
    return;
1,358,626,397✔
922
  }
923

924
  // If a cell/cellfrom/cellto parameter is defined
925
  if (settings::ssw_cell_id != C_NONE) {
341,269✔
926

927
    // Retrieve cell index and storage type
928
    int cell_idx = model::cell_map[settings::ssw_cell_id];
258,708✔
929

930
    if (surf.bc_) {
258,708✔
931
      // Leave if cellto with vacuum boundary condition
932
      if (surf.bc_->type() == "vacuum" &&
184,448✔
933
          settings::ssw_cell_type == SSWCellType::To) {
32,214✔
934
        return;
11,953✔
935
      }
936

937
      // Leave if other boundary condition than vacuum
938
      if (surf.bc_->type() != "vacuum") {
140,281✔
939
        return;
120,020✔
940
      }
941
    }
942

943
    // Check if the cell of interest has been exited
944
    bool exited = false;
126,735✔
945
    for (int i = 0; i < p.n_coord_last(); ++i) {
335,347✔
946
      if (p.cell_last(i) == cell_idx) {
208,612✔
947
        exited = true;
74,237✔
948
      }
949
    }
950

951
    // Check if the cell of interest has been entered
952
    bool entered = false;
126,735✔
953
    for (int i = 0; i < p.n_coord(); ++i) {
301,043✔
954
      if (p.coord(i).cell() == cell_idx) {
174,308✔
955
        entered = true;
59,099✔
956
      }
957
    }
958

959
    // Vacuum boundary conditions: return if cell is not exited
960
    if (surf.bc_) {
126,735✔
961
      if (surf.bc_->type() == "vacuum" && !exited) {
20,261✔
962
        return;
13,961✔
963
      }
964
    } else {
965

966
      // If we both enter and exit the cell of interest
967
      if (entered && exited) {
106,474✔
968
        return;
28,613✔
969
      }
970

971
      // If we did not enter nor exit the cell of interest
972
      if (!entered && !exited) {
77,861✔
973
        return;
14,351✔
974
      }
975

976
      // If cellfrom and the cell before crossing is not the cell of
977
      // interest
978
      if (settings::ssw_cell_type == SSWCellType::From && !exited) {
63,510✔
979
        return;
11,566✔
980
      }
981

982
      // If cellto and the cell after crossing is not the cell of interest
983
      if (settings::ssw_cell_type == SSWCellType::To && !entered) {
51,944✔
984
        return;
12,040✔
985
      }
986
    }
987
  }
988

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

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