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

openmc-dev / openmc / 22261613902

21 Feb 2026 06:02PM UTC coverage: 81.808% (+0.05%) from 81.763%
22261613902

Pull #3474

github

web-flow
Merge aea47008a into 139907c95
Pull Request #3474: Support arbitrary symmetry axis for CylindricalIndependent class

17351 of 24448 branches covered (70.97%)

Branch coverage included in aggregate %.

50 of 64 new or added lines in 2 files covered. (78.13%)

2915 existing lines in 63 files now uncovered.

57697 of 67289 relevant lines covered (85.75%)

45481208.67 hits per line

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

83.71
/src/physics.cpp
1
#include "openmc/physics.h"
2

3
#include "openmc/bank.h"
4
#include "openmc/bremsstrahlung.h"
5
#include "openmc/chain.h"
6
#include "openmc/constants.h"
7
#include "openmc/distribution_multi.h"
8
#include "openmc/eigenvalue.h"
9
#include "openmc/endf.h"
10
#include "openmc/error.h"
11
#include "openmc/ifp.h"
12
#include "openmc/material.h"
13
#include "openmc/math_functions.h"
14
#include "openmc/message_passing.h"
15
#include "openmc/ncrystal_interface.h"
16
#include "openmc/nuclide.h"
17
#include "openmc/photon.h"
18
#include "openmc/physics_common.h"
19
#include "openmc/random_dist.h"
20
#include "openmc/random_lcg.h"
21
#include "openmc/reaction.h"
22
#include "openmc/search.h"
23
#include "openmc/secondary_uncorrelated.h"
24
#include "openmc/settings.h"
25
#include "openmc/simulation.h"
26
#include "openmc/string_utils.h"
27
#include "openmc/tallies/tally.h"
28
#include "openmc/thermal.h"
29
#include "openmc/weight_windows.h"
30

31
#include <fmt/core.h>
32

33
#include "openmc/tensor.h"
34
#include <algorithm> // for max, min, max_element
35
#include <cmath>     // for sqrt, exp, log, abs, copysign
36

37
namespace openmc {
38

39
//==============================================================================
40
// Non-member functions
41
//==============================================================================
42

43
void collision(Particle& p)
969,483,935✔
44
{
45
  // Add to collision counter for particle
46
  ++(p.n_collision());
969,483,935✔
47
  p.secondary_bank_index() = p.secondary_bank().size();
969,483,935✔
48

49
  // Sample reaction for the material the particle is in
50
  switch (p.type().pdg_number()) {
969,483,935!
51
  case PDG_NEUTRON:
904,570,289✔
52
    sample_neutron_reaction(p);
904,570,289✔
53
    break;
904,570,289✔
54
  case PDG_PHOTON:
15,904,651✔
55
    sample_photon_reaction(p);
15,904,651✔
56
    break;
15,904,651✔
57
  case PDG_ELECTRON:
48,929,314✔
58
    sample_electron_reaction(p);
48,929,314✔
59
    break;
48,929,314✔
60
  case PDG_POSITRON:
79,681✔
61
    sample_positron_reaction(p);
79,681✔
62
    break;
79,681✔
63
  default:
×
UNCOV
64
    fatal_error("Unsupported particle PDG for collision sampling.");
×
65
  }
66

67
  if (settings::weight_window_checkpoint_collision)
969,483,935!
68
    apply_weight_windows(p);
969,483,935✔
69

70
  // Kill particle if energy falls below cutoff
71
  int type = p.type().transport_index();
969,483,935✔
72
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
969,483,935!
73
    p.wgt() = 0.0;
4,750,469✔
74
  }
75

76
  // Display information about collision
77
  if (settings::verbosity >= 10 || p.trace()) {
969,483,935!
78
    std::string msg;
60✔
79
    if (p.event() == TallyEvent::KILL) {
60!
UNCOV
80
      msg = fmt::format("    Killed. Energy = {} eV.", p.E());
×
81
    } else if (p.type().is_neutron()) {
60!
82
      msg = fmt::format("    {} with {}. Energy = {} eV.",
168✔
83
        reaction_name(p.event_mt()), data::nuclides[p.event_nuclide()]->name_,
120✔
84
        p.E());
60✔
85
    } else if (p.type().is_photon()) {
×
86
      msg = fmt::format("    {} with {}. Energy = {} eV.",
×
87
        reaction_name(p.event_mt()),
×
UNCOV
88
        to_element(data::nuclides[p.event_nuclide()]->name_), p.E());
×
89
    } else {
UNCOV
90
      msg = fmt::format("    Disappeared. Energy = {} eV.", p.E());
×
91
    }
92
    write_message(msg, 1);
60✔
93
  }
60✔
94
}
969,483,935✔
95

96
void sample_neutron_reaction(Particle& p)
904,570,289✔
97
{
98
  // Sample a nuclide within the material
99
  int i_nuclide = sample_nuclide(p);
904,570,289✔
100

101
  // Save which nuclide particle had collision with
102
  p.event_nuclide() = i_nuclide;
904,570,289✔
103

104
  // Create fission bank sites. Note that while a fission reaction is sampled,
105
  // it never actually "happens", i.e. the weight of the particle does not
106
  // change when sampling fission sites. The following block handles all
107
  // absorption (including fission)
108

109
  const auto& nuc {data::nuclides[i_nuclide]};
904,570,289✔
110

111
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
904,570,289✔
112
    auto& rx = sample_fission(i_nuclide, p);
114,134,697✔
113
    if (settings::run_mode == RunMode::EIGENVALUE) {
114,134,697✔
114
      create_fission_sites(p, i_nuclide, rx);
91,383,689✔
115
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
22,751,008✔
116
               settings::create_fission_neutrons) {
117
      create_fission_sites(p, i_nuclide, rx);
527,328✔
118

119
      // Make sure particle population doesn't grow out of control for
120
      // subcritical multiplication problems.
121
      if (p.secondary_bank().size() >= settings::max_secondaries) {
527,328!
UNCOV
122
        fatal_error(
×
123
          "The secondary particle bank appears to be growing without "
124
          "bound. You are likely running a subcritical multiplication problem "
125
          "with k-effective close to or greater than one.");
126
      }
127
    }
128
    p.event_mt() = rx.mt_;
114,134,697✔
129
  }
130

131
  // Create secondary photons
132
  if (settings::photon_transport) {
904,570,289✔
133
    sample_secondary_photons(p, i_nuclide);
7,608,910✔
134
  }
135

136
  // If survival biasing is being used, the following subroutine adjusts the
137
  // weight of the particle. Otherwise, it checks to see if absorption occurs
138

139
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
904,570,289✔
140
    absorption(p, i_nuclide);
904,567,089✔
141
  }
142
  if (!p.alive())
904,570,289✔
143
    return;
21,308,081✔
144

145
  // Sample a scattering reaction and determine the secondary energy of the
146
  // exiting neutron
147
  const auto& ncrystal_mat = model::materials[p.material()]->ncrystal_mat();
883,262,208✔
148
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
883,262,208!
149
    ncrystal_mat.scatter(p);
144,390✔
150
  } else {
151
    scatter(p, i_nuclide);
883,117,818✔
152
  }
153

154
  // Advance URR seed stream 'N' times after energy changes
155
  if (p.E() != p.E_last()) {
883,262,208✔
156
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
882,971,998✔
157
  }
158

159
  // Play russian roulette if survival biasing is turned on
160
  if (settings::survival_biasing) {
883,262,208✔
161
    // if survival normalization is on, use normalized weight cutoff and
162
    // normalized weight survive
163
    if (settings::survival_normalization) {
454,500!
164
      if (p.wgt() < settings::weight_cutoff * p.wgt_born()) {
×
UNCOV
165
        russian_roulette(p, settings::weight_survive * p.wgt_born());
×
166
      }
167
    } else if (p.wgt() < settings::weight_cutoff) {
454,500✔
168
      russian_roulette(p, settings::weight_survive);
51,810✔
169
    }
170
  }
171
}
172

173
void create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx)
91,911,017✔
174
{
175
  // If uniform fission source weighting is turned on, we increase or decrease
176
  // the expected number of fission sites produced
177
  double weight = settings::ufs_on ? ufs_get_weight(p) : 1.0;
91,911,017✔
178

179
  // Determine the expected number of neutrons produced
180
  double nu_t = p.wgt() / simulation::keff * weight *
91,911,017✔
181
                p.neutron_xs(i_nuclide).nu_fission /
91,911,017✔
182
                p.neutron_xs(i_nuclide).total;
91,911,017✔
183

184
  // Sample the number of neutrons produced
185
  int nu = static_cast<int>(nu_t);
91,911,017✔
186
  if (prn(p.current_seed()) <= (nu_t - nu))
91,911,017✔
187
    ++nu;
18,814,059✔
188

189
  // If no neutrons were produced then don't continue
190
  if (nu == 0)
91,911,017✔
191
    return;
69,444,103✔
192

193
  // Initialize the counter of delayed neutrons encountered for each delayed
194
  // group.
195
  double nu_d[MAX_DELAYED_GROUPS] = {0.};
22,466,914✔
196

197
  // Clear out particle's nu fission bank
198
  p.nu_bank().clear();
22,466,914✔
199

200
  p.fission() = true;
22,466,914✔
201

202
  // Determine whether to place fission sites into the shared fission bank
203
  // or the secondary particle bank.
204
  bool use_fission_bank = (settings::run_mode == RunMode::EIGENVALUE);
22,466,914✔
205

206
  // Counter for the number of fission sites successfully stored to the shared
207
  // fission bank or the secondary particle bank
208
  int n_sites_stored;
209

210
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
50,226,423✔
211
    // Initialize fission site object with particle data
212
    SourceSite site;
27,759,509✔
213
    site.r = p.r();
27,759,509✔
214
    site.particle = ParticleType::neutron();
27,759,509✔
215
    site.time = p.time();
27,759,509✔
216
    site.wgt = 1. / weight;
27,759,509✔
217
    site.surf_id = 0;
27,759,509✔
218

219
    // Sample delayed group and angle/energy for fission reaction
220
    sample_fission_neutron(i_nuclide, rx, &site, p);
27,759,509✔
221

222
    // Reject site if it exceeds time cutoff
223
    if (site.delayed_group > 0) {
27,759,509✔
224
      double t_cutoff = settings::time_cutoff[site.particle.transport_index()];
174,138✔
225
      if (site.time > t_cutoff) {
174,138!
UNCOV
226
        continue;
×
227
      }
228
    }
229

230
    // Set parent and progeny IDs
231
    site.parent_id = p.id();
27,759,509✔
232
    site.progeny_id = p.n_progeny()++;
27,759,509✔
233

234
    // Store fission site in bank
235
    if (use_fission_bank) {
27,759,509✔
236
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
27,556,022✔
237
      if (idx == -1) {
27,556,022!
UNCOV
238
        warning(
×
239
          "The shared fission bank is full. Additional fission sites created "
240
          "in this generation will not be banked. Results may be "
241
          "non-deterministic.");
242

243
        // Decrement number of particle progeny as storage was unsuccessful.
244
        // This step is needed so that the sum of all progeny is equal to the
245
        // size of the shared fission bank.
UNCOV
246
        p.n_progeny()--;
×
247

248
        // Break out of loop as no more sites can be added to fission bank
UNCOV
249
        break;
×
250
      }
251
      // Iterated Fission Probability (IFP) method
252
      if (settings::ifp_on) {
27,556,022✔
253
        ifp(p, idx);
1,229,660✔
254
      }
255
    } else {
256
      p.secondary_bank().push_back(site);
203,487✔
257
      p.n_secondaries()++;
203,487✔
258
    }
259

260
    // Increment the number of neutrons born delayed
261
    if (site.delayed_group > 0) {
27,759,509✔
262
      nu_d[site.delayed_group - 1]++;
174,138✔
263
    }
264

265
    // Write fission particles to nuBank
266
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
27,759,509✔
267
    nu_bank_entry.wgt = site.wgt;
27,759,509✔
268
    nu_bank_entry.E = site.E;
27,759,509✔
269
    nu_bank_entry.delayed_group = site.delayed_group;
27,759,509✔
270
  }
271

272
  // If shared fission bank was full, and no fissions could be added,
273
  // set the particle fission flag to false.
274
  if (n_sites_stored == 0) {
22,466,914!
UNCOV
275
    p.fission() = false;
×
UNCOV
276
    return;
×
277
  }
278

279
  // Set nu to the number of fission sites successfully stored. If the fission
280
  // bank was not found to be full then these values are already equivalent.
281
  nu = n_sites_stored;
22,466,914✔
282

283
  // Store the total weight banked for analog fission tallies
284
  p.n_bank() = nu;
22,466,914✔
285
  p.wgt_bank() = nu / weight;
22,466,914✔
286
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
202,202,226✔
287
    p.n_delayed_bank(d) = nu_d[d];
179,735,312✔
288
  }
289
}
290

291
void sample_photon_reaction(Particle& p)
15,904,651✔
292
{
293
  // Kill photon if below energy cutoff -- an extra check is made here because
294
  // photons with energy below the cutoff may have been produced by neutrons
295
  // reactions or atomic relaxation
296
  int photon = ParticleType::photon().transport_index();
15,904,651✔
297
  if (p.E() < settings::energy_cutoff[photon]) {
15,904,651!
298
    p.E() = 0.0;
×
UNCOV
299
    p.wgt() = 0.0;
×
UNCOV
300
    return;
×
301
  }
302

303
  // Sample element within material
304
  int i_element = sample_element(p);
15,904,651✔
305
  const auto& micro {p.photon_xs(i_element)};
15,904,651✔
306
  const auto& element {*data::elements[i_element]};
15,904,651✔
307

308
  // Calculate photon energy over electron rest mass equivalent
309
  double alpha = p.E() / MASS_ELECTRON_EV;
15,904,651✔
310

311
  // For tallying purposes, this routine might be called directly. In that
312
  // case, we need to sample a reaction via the cutoff variable
313
  double prob = 0.0;
15,904,651✔
314
  double cutoff = prn(p.current_seed()) * micro.total;
15,904,651✔
315

316
  // Coherent (Rayleigh) scattering
317
  prob += micro.coherent;
15,904,651✔
318
  if (prob > cutoff) {
15,904,651✔
319
    p.mu() = element.rayleigh_scatter(alpha, p.current_seed());
877,261✔
320
    p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
877,261✔
321
    p.event() = TallyEvent::SCATTER;
877,261✔
322
    p.event_mt() = COHERENT;
877,261✔
323
    return;
877,261✔
324
  }
325

326
  // Incoherent (Compton) scattering
327
  prob += micro.incoherent;
15,027,390✔
328
  if (prob > cutoff) {
15,027,390✔
329
    double alpha_out;
330
    int i_shell;
331
    element.compton_scatter(
20,573,702✔
332
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
10,286,851✔
333

334
    // Determine binding energy of shell. The binding energy is 0.0 if
335
    // doppler broadening is not used.
336
    double e_b;
337
    if (i_shell == -1) {
10,286,851!
UNCOV
338
      e_b = 0.0;
×
339
    } else {
340
      e_b = element.binding_energy_[i_shell];
10,286,851✔
341
    }
342

343
    // Create Compton electron
344
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
10,286,851✔
345
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
10,286,851✔
346
    int electron = ParticleType::electron().transport_index();
10,286,851✔
347
    if (E_electron >= settings::energy_cutoff[electron]) {
10,286,851✔
348
      double mu_electron = (alpha - alpha_out * p.mu()) /
10,190,262✔
349
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
20,380,524✔
350
                                     2.0 * alpha * alpha_out * p.mu());
10,190,262✔
351
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
10,190,262✔
352
      p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
10,190,262✔
353
    }
354

355
    // Allow electrons to fill orbital and produce Auger electrons and
356
    // fluorescent photons. Since Compton subshell data does not match atomic
357
    // relaxation data, use the mapping between the data to find the subshell
358
    if (i_shell >= 0 && element.subshell_map_[i_shell] >= 0) {
10,286,851!
359
      element.atomic_relaxation(element.subshell_map_[i_shell], p);
10,286,851✔
360
    }
361

362
    phi += PI;
10,286,851✔
363
    p.E() = alpha_out * MASS_ELECTRON_EV;
10,286,851✔
364
    p.u() = rotate_angle(p.u(), p.mu(), &phi, p.current_seed());
10,286,851✔
365
    p.event() = TallyEvent::SCATTER;
10,286,851✔
366
    p.event_mt() = INCOHERENT;
10,286,851✔
367
    return;
10,286,851✔
368
  }
369

370
  // Photoelectric effect
371
  double prob_after = prob + micro.photoelectric;
4,740,539✔
372

373
  if (prob_after > cutoff) {
4,740,539✔
374
    // Get grid index, interpolation factor, and bounding subshell
375
    // cross sections
376
    int i_grid = micro.index_grid;
4,660,858✔
377
    double f = micro.interp_factor;
4,660,858✔
378
    tensor::View<const double> xs_lower = element.cross_sections_.slice(i_grid);
4,660,858✔
379
    tensor::View<const double> xs_upper =
380
      element.cross_sections_.slice(i_grid + 1);
4,660,858✔
381

382
    for (int i_shell = 0; i_shell < element.shells_.size(); ++i_shell) {
22,116,812!
383
      const auto& shell {element.shells_[i_shell]};
22,116,812✔
384

385
      // Check threshold of reaction
386
      if (xs_lower(i_shell) == 0)
22,116,812✔
387
        continue;
9,333,153✔
388

389
      //  Evaluation subshell photoionization cross section
390
      prob += std::exp(
12,783,659✔
391
        xs_lower(i_shell) + f * (xs_upper(i_shell) - xs_lower(i_shell)));
12,783,659✔
392

393
      if (prob > cutoff) {
12,783,659✔
394
        // Determine binding energy based on whether atomic relaxation data is
395
        // present (if not, use value from Compton profile data)
396
        double binding_energy = element.has_atomic_relaxation_
4,660,858✔
397
                                  ? shell.binding_energy
4,660,858!
UNCOV
398
                                  : element.binding_energy_[i_shell];
×
399

400
        // Determine energy of secondary electron
401
        double E_electron = p.E() - binding_energy;
4,660,858✔
402

403
        // Sample mu using non-relativistic Sauter distribution.
404
        // See Eqns 3.19 and 3.20 in "Implementing a photon physics
405
        // model in Serpent 2" by Toni Kaltiaisenaho
406
        double mu;
407
        while (true) {
408
          double r = prn(p.current_seed());
6,992,051✔
409
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
6,992,051✔
410
            double rel_vel =
411
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
4,660,858✔
412
              (E_electron + MASS_ELECTRON_EV);
4,660,858✔
413
            mu =
4,660,858✔
414
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
4,660,858✔
415
            break;
4,660,858✔
416
          }
417
        }
2,331,193✔
418

419
        double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
4,660,858✔
420
        Direction u;
4,660,858✔
421
        u.x = mu;
4,660,858✔
422
        u.y = std::sqrt(1.0 - mu * mu) * std::cos(phi);
4,660,858✔
423
        u.z = std::sqrt(1.0 - mu * mu) * std::sin(phi);
4,660,858✔
424

425
        // Create secondary electron
426
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
4,660,858✔
427

428
        // Allow electrons to fill orbital and produce auger electrons
429
        // and fluorescent photons
430
        element.atomic_relaxation(i_shell, p);
4,660,858✔
431
        p.event() = TallyEvent::ABSORB;
4,660,858✔
432
        p.event_mt() = 533 + shell.index_subshell;
4,660,858✔
433
        p.wgt() = 0.0;
4,660,858✔
434
        p.E() = 0.0;
4,660,858✔
435
        return;
4,660,858✔
436
      }
437
    }
438
  }
9,321,716!
439
  prob = prob_after;
79,681✔
440

441
  // Pair production
442
  prob += micro.pair_production;
79,681✔
443
  if (prob > cutoff) {
79,681!
444
    double E_electron, E_positron;
445
    double mu_electron, mu_positron;
446
    element.pair_production(alpha, &E_electron, &E_positron, &mu_electron,
79,681✔
447
      &mu_positron, p.current_seed());
448

449
    // Create secondary electron
450
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
79,681✔
451
    p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
79,681✔
452

453
    // Create secondary positron
454
    u = rotate_angle(p.u(), mu_positron, nullptr, p.current_seed());
79,681✔
455
    p.create_secondary(p.wgt(), u, E_positron, ParticleType::positron());
79,681✔
456
    p.event() = TallyEvent::ABSORB;
79,681✔
457
    p.event_mt() = PAIR_PROD;
79,681✔
458
    p.wgt() = 0.0;
79,681✔
459
    p.E() = 0.0;
79,681✔
460
  }
461
}
462

463
void sample_electron_reaction(Particle& p)
48,929,314✔
464
{
465
  // TODO: create reaction types
466

467
  if (settings::electron_treatment == ElectronTreatment::TTB) {
48,929,314✔
468
    double E_lost;
469
    thick_target_bremsstrahlung(p, &E_lost);
48,653,264✔
470
  }
471

472
  p.E() = 0.0;
48,929,314✔
473
  p.wgt() = 0.0;
48,929,314✔
474
  p.event() = TallyEvent::ABSORB;
48,929,314✔
475
}
48,929,314✔
476

477
void sample_positron_reaction(Particle& p)
79,681✔
478
{
479
  // TODO: create reaction types
480

481
  if (settings::electron_treatment == ElectronTreatment::TTB) {
79,681✔
482
    double E_lost;
483
    thick_target_bremsstrahlung(p, &E_lost);
78,531✔
484
  }
485

486
  // Sample angle isotropically
487
  Direction u = isotropic_direction(p.current_seed());
79,681✔
488

489
  // Create annihilation photon pair traveling in opposite directions
490
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon());
79,681✔
491
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon());
79,681✔
492

493
  p.E() = 0.0;
79,681✔
494
  p.wgt() = 0.0;
79,681✔
495
  p.event() = TallyEvent::ABSORB;
79,681✔
496
}
79,681✔
497

498
int sample_nuclide(Particle& p)
904,570,289✔
499
{
500
  // Sample cumulative distribution function
501
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
904,570,289✔
502

503
  // Get pointers to nuclide/density arrays
504
  const auto& mat {model::materials[p.material()]};
904,570,289✔
505
  int n = mat->nuclide_.size();
904,570,289✔
506

507
  double prob = 0.0;
904,570,289✔
508
  for (int i = 0; i < n; ++i) {
1,914,287,943!
509
    // Get atom density
510
    int i_nuclide = mat->nuclide_[i];
1,914,287,943✔
511
    double atom_density = mat->atom_density(i, p.density_mult());
1,914,287,943✔
512

513
    // Increment probability to compare to cutoff
514
    prob += atom_density * p.neutron_xs(i_nuclide).total;
1,914,287,943✔
515
    if (prob >= cutoff)
1,914,287,943✔
516
      return i_nuclide;
904,570,289✔
517
  }
518

519
  // If we reach here, no nuclide was sampled
UNCOV
520
  p.write_restart();
×
UNCOV
521
  throw std::runtime_error {"Did not sample any nuclide during collision."};
×
522
}
523

524
int sample_element(Particle& p)
15,904,651✔
525
{
526
  // Sample cumulative distribution function
527
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
15,904,651✔
528

529
  // Get pointers to elements, densities
530
  const auto& mat {model::materials[p.material()]};
15,904,651✔
531

532
  double prob = 0.0;
15,904,651✔
533
  for (int i = 0; i < mat->element_.size(); ++i) {
37,640,041!
534
    // Find atom density
535
    int i_element = mat->element_[i];
37,640,041✔
536
    double atom_density = mat->atom_density(i, p.density_mult());
37,640,041✔
537

538
    // Determine microscopic cross section
539
    double sigma = atom_density * p.photon_xs(i_element).total;
37,640,041✔
540

541
    // Increment probability to compare to cutoff
542
    prob += sigma;
37,640,041✔
543
    if (prob > cutoff) {
37,640,041✔
544
      // Save which nuclide particle had collision with for tally purpose
545
      p.event_nuclide() = mat->nuclide_[i];
15,904,651✔
546

547
      return i_element;
15,904,651✔
548
    }
549
  }
550

551
  // If we made it here, no element was sampled
UNCOV
552
  p.write_restart();
×
UNCOV
553
  fatal_error("Did not sample any element during collision.");
×
554
}
555

556
Reaction& sample_fission(int i_nuclide, Particle& p)
114,134,697✔
557
{
558
  // Get pointer to nuclide
559
  const auto& nuc {data::nuclides[i_nuclide]};
114,134,697✔
560

561
  // If we're in the URR, by default use the first fission reaction. We also
562
  // default to the first reaction if we know that there are no partial fission
563
  // reactions
564
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
114,134,697✔
565
    return *nuc->fission_rx_[0];
114,106,422✔
566
  }
567

568
  // Check to see if we are in a windowed multipole range.  WMP only supports
569
  // the first fission reaction.
570
  if (nuc->multipole_) {
28,275✔
571
    if (p.E() >= nuc->multipole_->E_min_ && p.E() <= nuc->multipole_->E_max_) {
2,590!
572
      return *nuc->fission_rx_[0];
1,810✔
573
    }
574
  }
575

576
  // Get grid index and interpolation factor and sample fission cdf
577
  const auto& micro = p.neutron_xs(i_nuclide);
26,465✔
578
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
26,465✔
579
  double prob = 0.0;
26,465✔
580

581
  // Loop through each partial fission reaction type
582
  for (auto& rx : nuc->fission_rx_) {
26,522!
583
    // add to cumulative probability
584
    prob += rx->xs(micro);
26,522✔
585

586
    // Create fission bank sites if fission occurs
587
    if (prob > cutoff)
26,522✔
588
      return *rx;
26,465✔
589
  }
590

591
  // If we reached here, no reaction was sampled
UNCOV
592
  throw std::runtime_error {
×
UNCOV
593
    "No fission reaction was sampled for " + nuc->name_};
×
594
}
595

596
void sample_photon_product(
1,205,900✔
597
  int i_nuclide, Particle& p, int* i_rx, int* i_product)
598
{
599
  // Get grid index and interpolation factor and sample photon production cdf
600
  const auto& micro = p.neutron_xs(i_nuclide);
1,205,900✔
601
  double cutoff = prn(p.current_seed()) * micro.photon_prod;
1,205,900✔
602
  double prob = 0.0;
1,205,900✔
603

604
  // Loop through each reaction type
605
  const auto& nuc {data::nuclides[i_nuclide]};
1,205,900✔
606
  for (int i = 0; i < nuc->reactions_.size(); ++i) {
19,754,600!
607
    // Evaluate neutron cross section
608
    const auto& rx = nuc->reactions_[i];
19,754,600✔
609
    double xs = rx->xs(micro);
19,754,600✔
610

611
    // if cross section is zero for this reaction, skip it
612
    if (xs == 0.0)
19,754,600✔
613
      continue;
6,128,680✔
614

615
    for (int j = 0; j < rx->products_.size(); ++j) {
63,035,960✔
616
      if (rx->products_[j].particle_.is_photon()) {
50,615,940✔
617
        // For fission, artificially increase the photon yield to account
618
        // for delayed photons
619
        double f = 1.0;
39,177,670✔
620
        if (settings::delayed_photon_scaling) {
39,177,670!
621
          if (is_fission(rx->mt_)) {
39,177,670✔
622
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
491,110!
623
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
491,110✔
624
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
491,110✔
625
              f = (energy_prompt + energy_delayed) / (energy_prompt);
491,110✔
626
            }
627
          }
628
        }
629

630
        // add to cumulative probability
631
        prob += f * (*rx->products_[j].yield_)(p.E()) * xs;
39,177,670✔
632

633
        *i_rx = i;
39,177,670✔
634
        *i_product = j;
39,177,670✔
635
        if (prob > cutoff)
39,177,670✔
636
          return;
1,205,900✔
637
      }
638
    }
639
  }
640
}
641

642
void absorption(Particle& p, int i_nuclide)
904,567,089✔
643
{
644
  if (settings::survival_biasing) {
904,567,089✔
645
    // Determine weight absorbed in survival biasing
646
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
454,500✔
647
                              p.neutron_xs(i_nuclide).total;
454,500✔
648

649
    // Adjust weight of particle by probability of absorption
650
    p.wgt() -= wgt_absorb;
454,500✔
651

652
    // Score implicit absorption estimate of keff
653
    if (settings::run_mode == RunMode::EIGENVALUE) {
454,500!
654
      p.keff_tally_absorption() += wgt_absorb *
454,500✔
655
                                   p.neutron_xs(i_nuclide).nu_fission /
454,500✔
656
                                   p.neutron_xs(i_nuclide).absorption;
454,500✔
657
    }
658
  } else {
659
    // See if disappearance reaction happens
660
    if (p.neutron_xs(i_nuclide).absorption >
904,112,589✔
661
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
904,112,589✔
662
      // Score absorption estimate of keff
663
      if (settings::run_mode == RunMode::EIGENVALUE) {
21,308,081✔
664
        p.keff_tally_absorption() += p.wgt() *
32,256,978✔
665
                                     p.neutron_xs(i_nuclide).nu_fission /
16,128,489✔
666
                                     p.neutron_xs(i_nuclide).absorption;
16,128,489✔
667
      }
668

669
      p.wgt() = 0.0;
21,308,081✔
670
      p.event() = TallyEvent::ABSORB;
21,308,081✔
671
      if (!p.fission()) {
21,308,081✔
672
        p.event_mt() = N_DISAPPEAR;
13,320,475✔
673
      }
674
    }
675
  }
676
}
904,567,089✔
677

678
void scatter(Particle& p, int i_nuclide)
883,117,818✔
679
{
680
  // copy incoming direction
681
  Direction u_old {p.u()};
883,117,818✔
682

683
  // Get pointer to nuclide and grid index/interpolation factor
684
  const auto& nuc {data::nuclides[i_nuclide]};
883,117,818✔
685
  const auto& micro {p.neutron_xs(i_nuclide)};
883,117,818✔
686
  int i_temp = micro.index_temp;
883,117,818✔
687

688
  // For tallying purposes, this routine might be called directly. In that
689
  // case, we need to sample a reaction via the cutoff variable
690
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
883,117,818✔
691
  bool sampled = false;
883,117,818✔
692

693
  // Calculate elastic cross section if it wasn't precalculated
694
  if (micro.elastic == CACHE_INVALID) {
883,117,818✔
695
    nuc->calculate_elastic_xs(p);
661,028,956✔
696
  }
697

698
  double prob = micro.elastic - micro.thermal;
883,117,818✔
699
  if (prob > cutoff) {
883,117,818✔
700
    // =======================================================================
701
    // NON-S(A,B) ELASTIC SCATTERING
702

703
    // Determine temperature
704
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
750,222,412✔
705

706
    // Perform collision physics for elastic scattering
707
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
750,222,412✔
708

709
    p.event_mt() = ELASTIC;
750,222,412✔
710
    sampled = true;
750,222,412✔
711
  }
712

713
  prob = micro.elastic;
883,117,818✔
714
  if (prob > cutoff && !sampled) {
883,117,818✔
715
    // =======================================================================
716
    // S(A,B) SCATTERING
717

718
    sab_scatter(i_nuclide, micro.index_sab, p);
115,883,521✔
719

720
    p.event_mt() = ELASTIC;
115,883,521✔
721
    sampled = true;
115,883,521✔
722
  }
723

724
  if (!sampled) {
883,117,818✔
725
    // =======================================================================
726
    // INELASTIC SCATTERING
727

728
    int n = nuc->index_inelastic_scatter_.size();
17,011,885✔
729
    int i = 0;
17,011,885✔
730
    for (int j = 0; j < n && prob < cutoff; ++j) {
320,433,004✔
731
      i = nuc->index_inelastic_scatter_[j];
303,421,119✔
732

733
      // add to cumulative probability
734
      prob += nuc->reactions_[i]->xs(micro);
303,421,119✔
735
    }
736

737
    // Perform collision physics for inelastic scattering
738
    const auto& rx {nuc->reactions_[i]};
17,011,885✔
739
    inelastic_scatter(*nuc, *rx, p);
17,011,885✔
740
    p.event_mt() = rx->mt_;
17,011,885✔
741
  }
742

743
  // Set event component
744
  p.event() = TallyEvent::SCATTER;
883,117,818✔
745

746
  // Sample new outgoing angle for isotropic-in-lab scattering
747
  const auto& mat {model::materials[p.material()]};
883,117,818✔
748
  if (!mat->p0_.empty()) {
883,117,818✔
749
    int i_nuc_mat = mat->mat_nuclide_index_[i_nuclide];
296,700✔
750
    if (mat->p0_[i_nuc_mat]) {
296,700!
751
      // Sample isotropic-in-lab outgoing direction
752
      p.u() = isotropic_direction(p.current_seed());
296,700✔
753
      p.mu() = u_old.dot(p.u());
296,700✔
754
    }
755
  }
756
}
883,117,818✔
757

758
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
750,222,412✔
759
{
760
  // get pointer to nuclide
761
  const auto& nuc {data::nuclides[i_nuclide]};
750,222,412✔
762

763
  double vel = std::sqrt(p.E());
750,222,412✔
764
  double awr = nuc->awr_;
750,222,412✔
765

766
  // Neutron velocity in LAB
767
  Direction v_n = vel * p.u();
750,222,412✔
768

769
  // Sample velocity of target nucleus
770
  Direction v_t {};
750,222,412✔
771
  if (!p.neutron_xs(i_nuclide).use_ptable) {
750,222,412✔
772
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
1,433,957,900✔
773
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
716,978,950✔
774
  }
775

776
  // Velocity of center-of-mass
777
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
750,222,412✔
778

779
  // Transform to CM frame
780
  v_n -= v_cm;
750,222,412✔
781

782
  // Find speed of neutron in CM
783
  vel = v_n.norm();
750,222,412✔
784

785
  // Sample scattering angle, checking if angle distribution is present (assume
786
  // isotropic otherwise)
787
  double mu_cm;
788
  auto& d = rx.products_[0].distribution_[0];
750,222,412✔
789
  auto d_ = dynamic_cast<UncorrelatedAngleEnergy*>(d.get());
750,222,412!
790
  if (!d_->angle().empty()) {
750,222,412!
791
    mu_cm = d_->angle().sample(p.E(), p.current_seed());
750,222,412✔
792
  } else {
UNCOV
793
    mu_cm = uniform_distribution(-1., 1., p.current_seed());
×
794
  }
795

796
  // Determine direction cosines in CM
797
  Direction u_cm = v_n / vel;
750,222,412✔
798

799
  // Rotate neutron velocity vector to new angle -- note that the speed of the
800
  // neutron in CM does not change in elastic scattering. However, the speed
801
  // will change when we convert back to LAB
802
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
750,222,412✔
803

804
  // Transform back to LAB frame
805
  v_n += v_cm;
750,222,412✔
806

807
  p.E() = v_n.dot(v_n);
750,222,412✔
808
  vel = std::sqrt(p.E());
750,222,412✔
809

810
  // compute cosine of scattering angle in LAB frame by taking dot product of
811
  // neutron's pre- and post-collision angle
812
  p.mu() = p.u().dot(v_n) / vel;
750,222,412✔
813

814
  // Set energy and direction of particle in LAB frame
815
  p.u() = v_n / vel;
750,222,412✔
816

817
  // Because of floating-point roundoff, it may be possible for mu_lab to be
818
  // outside of the range [-1,1). In these cases, we just set mu_lab to exactly
819
  // -1 or 1
820
  if (std::abs(p.mu()) > 1.0)
750,222,412!
UNCOV
821
    p.mu() = std::copysign(1.0, p.mu());
×
822
}
750,222,412✔
823

824
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
115,883,521✔
825
{
826
  // Determine temperature index
827
  const auto& micro {p.neutron_xs(i_nuclide)};
115,883,521✔
828
  int i_temp = micro.index_temp_sab;
115,883,521✔
829

830
  // Sample energy and angle
831
  double E_out;
832
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
231,767,042✔
833
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
115,883,521✔
834

835
  // Set energy to outgoing, change direction of particle
836
  p.E() = E_out;
115,883,521✔
837
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
115,883,521✔
838
}
115,883,521✔
839

840
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
716,978,950✔
841
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
842
{
843
  // check if nuclide is a resonant scatterer
844
  ResScatMethod sampling_method;
845
  if (nuc.resonant_) {
716,978,950✔
846

847
    // sampling method to use
848
    sampling_method = settings::res_scat_method;
76,870✔
849

850
    // upper resonance scattering energy bound (target is at rest above this E)
851
    if (E > settings::res_scat_energy_max) {
76,870✔
852
      return {};
37,050✔
853

854
      // lower resonance scattering energy bound (should be no resonances below)
855
    } else if (E < settings::res_scat_energy_min) {
39,820✔
856
      sampling_method = ResScatMethod::cxs;
22,720✔
857
    }
858

859
    // otherwise, use free gas model
860
  } else {
861
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
716,902,080✔
862
      return {};
367,769,715✔
863
    } else {
864
      sampling_method = ResScatMethod::cxs;
349,132,365✔
865
    }
866
  }
867

868
  // use appropriate target velocity sampling method
869
  switch (sampling_method) {
349,172,185!
870
  case ResScatMethod::cxs:
349,155,085✔
871

872
    // sample target velocity with the constant cross section (cxs) approx.
873
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
349,155,085✔
874

875
  case ResScatMethod::dbrc:
17,100✔
876
  case ResScatMethod::rvs: {
877
    double E_red = std::sqrt(nuc.awr_ * E / kT);
17,100✔
878
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
17,100✔
879
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
17,100✔
880

881
    // find lower and upper energy bound indices
882
    // lower index
883
    int i_E_low;
884
    if (E_low < nuc.energy_0K_.front()) {
17,100!
UNCOV
885
      i_E_low = 0;
×
886
    } else if (E_low > nuc.energy_0K_.back()) {
17,100!
UNCOV
887
      i_E_low = nuc.energy_0K_.size() - 2;
×
888
    } else {
889
      i_E_low =
17,100✔
890
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
17,100✔
891
    }
892

893
    // upper index
894
    int i_E_up;
895
    if (E_up < nuc.energy_0K_.front()) {
17,100!
UNCOV
896
      i_E_up = 0;
×
897
    } else if (E_up > nuc.energy_0K_.back()) {
17,100!
UNCOV
898
      i_E_up = nuc.energy_0K_.size() - 2;
×
899
    } else {
900
      i_E_up =
17,100✔
901
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_up);
17,100✔
902
    }
903

904
    if (i_E_up == i_E_low) {
17,100✔
905
      // Handle degenerate case -- if the upper/lower bounds occur for the same
906
      // index, then using cxs is probably a good approximation
907
      return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
17,100✔
908
    }
909

910
    if (sampling_method == ResScatMethod::dbrc) {
14,120!
911
      // interpolate xs since we're not exactly at the energy indices
912
      double xs_low = nuc.elastic_0K_[i_E_low];
×
913
      double m = (nuc.elastic_0K_[i_E_low + 1] - xs_low) /
×
914
                 (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
×
915
      xs_low += m * (E_low - nuc.energy_0K_[i_E_low]);
×
916
      double xs_up = nuc.elastic_0K_[i_E_up];
×
UNCOV
917
      m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) /
×
UNCOV
918
          (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
×
919
      xs_up += m * (E_up - nuc.energy_0K_[i_E_up]);
×
920

921
      // get max 0K xs value over range of practical relative energies
UNCOV
922
      double xs_max = *std::max_element(
×
UNCOV
923
        &nuc.elastic_0K_[i_E_low + 1], &nuc.elastic_0K_[i_E_up + 1]);
×
UNCOV
924
      xs_max = std::max({xs_low, xs_max, xs_up});
×
925

926
      while (true) {
927
        double E_rel;
UNCOV
928
        Direction v_target;
×
929
        while (true) {
930
          // sample target velocity with the constant cross section (cxs)
931
          // approx.
932
          v_target = sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
×
933
          Direction v_rel = v_neut - v_target;
×
934
          E_rel = v_rel.dot(v_rel);
×
UNCOV
935
          if (E_rel < E_up)
×
UNCOV
936
            break;
×
937
        }
×
938

939
        // perform Doppler broadening rejection correction (dbrc)
940
        double xs_0K = nuc.elastic_xs_0K(E_rel);
×
941
        double R = xs_0K / xs_max;
×
UNCOV
942
        if (prn(seed) < R)
×
UNCOV
943
          return v_target;
×
UNCOV
944
      }
×
945

946
    } else if (sampling_method == ResScatMethod::rvs) {
14,120!
947
      // interpolate xs CDF since we're not exactly at the energy indices
948
      // cdf value at lower bound attainable energy
949
      double cdf_low = 0.0;
14,120✔
950
      if (E_low > nuc.energy_0K_.front()) {
14,120!
951
        double m = (nuc.xs_cdf_[i_E_low + 1] - nuc.xs_cdf_[i_E_low]) /
14,120✔
952
                   (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
14,120✔
953
        cdf_low = nuc.xs_cdf_[i_E_low] + m * (E_low - nuc.energy_0K_[i_E_low]);
14,120✔
954
      }
955

956
      // cdf value at upper bound attainable energy
957
      double m = (nuc.xs_cdf_[i_E_up + 1] - nuc.xs_cdf_[i_E_up]) /
14,120✔
958
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
14,120✔
959
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
14,120✔
960

961
      while (true) {
962
        // directly sample Maxwellian
963
        double E_t = -kT * std::log(prn(seed));
155,200✔
964

965
        // sample a relative energy using the xs cdf
966
        double cdf_rel = cdf_low + prn(seed) * (cdf_up - cdf_low);
155,200✔
967
        int i_E_rel = lower_bound_index(nuc.xs_cdf_.begin() + i_E_low,
155,200✔
968
          nuc.xs_cdf_.begin() + i_E_up + 2, cdf_rel);
155,200✔
969
        double E_rel = nuc.energy_0K_[i_E_low + i_E_rel];
155,200✔
970
        double m = (nuc.xs_cdf_[i_E_low + i_E_rel + 1] -
155,200✔
971
                     nuc.xs_cdf_[i_E_low + i_E_rel]) /
155,200✔
972
                   (nuc.energy_0K_[i_E_low + i_E_rel + 1] -
155,200✔
973
                     nuc.energy_0K_[i_E_low + i_E_rel]);
155,200✔
974
        E_rel += (cdf_rel - nuc.xs_cdf_[i_E_low + i_E_rel]) / m;
155,200✔
975

976
        // perform rejection sampling on cosine between
977
        // neutron and target velocities
978
        double mu = (E_t + nuc.awr_ * (E - E_rel)) /
155,200✔
979
                    (2.0 * std::sqrt(nuc.awr_ * E * E_t));
155,200✔
980

981
        if (std::abs(mu) < 1.0) {
155,200✔
982
          // set and accept target velocity
983
          E_t /= nuc.awr_;
14,120✔
984
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
14,120✔
985
        }
986
      }
141,080✔
987
    }
988
  } // case RVS, DBRC
989
  } // switch (sampling_method)
990

UNCOV
991
  UNREACHABLE();
×
992
}
993

994
Direction sample_cxs_target_velocity(
349,158,065✔
995
  double awr, double E, Direction u, double kT, uint64_t* seed)
996
{
997
  double beta_vn = std::sqrt(awr * E / kT);
349,158,065✔
998
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
349,158,065✔
999

1000
  double beta_vt_sq;
1001
  double mu;
1002
  while (true) {
1003
    // Sample two random numbers
1004
    double r1 = prn(seed);
407,405,797✔
1005
    double r2 = prn(seed);
407,405,797✔
1006

1007
    if (prn(seed) < alpha) {
407,405,797✔
1008
      // With probability alpha, we sample the distribution p(y) =
1009
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1010
      // Carlo sampler
1011

1012
      beta_vt_sq = -std::log(r1 * r2);
94,048,899✔
1013

1014
    } else {
1015
      // With probability 1-alpha, we sample the distribution p(y) = y^2 *
1016
      // e^(-y^2). This can be done with sampling scheme C61 from the Monte
1017
      // Carlo sampler
1018

1019
      double c = std::cos(PI / 2.0 * prn(seed));
313,356,898✔
1020
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
313,356,898✔
1021
    }
1022

1023
    // Determine beta * vt
1024
    double beta_vt = std::sqrt(beta_vt_sq);
407,405,797✔
1025

1026
    // Sample cosine of angle between neutron and target velocity
1027
    mu = uniform_distribution(-1., 1., seed);
407,405,797✔
1028

1029
    // Determine rejection probability
1030
    double accept_prob =
1031
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
407,405,797✔
1032
      (beta_vn + beta_vt);
407,405,797✔
1033

1034
    // Perform rejection sampling on vt and mu
1035
    if (prn(seed) < accept_prob)
407,405,797✔
1036
      break;
349,158,065✔
1037
  }
58,247,732✔
1038

1039
  // Determine speed of target nucleus
1040
  double vt = std::sqrt(beta_vt_sq * kT / awr);
349,158,065✔
1041

1042
  // Determine velocity vector of target nucleus based on neutron's velocity
1043
  // and the sampled angle between them
1044
  return vt * rotate_angle(u, mu, nullptr, seed);
349,158,065✔
1045
}
1046

1047
void sample_fission_neutron(
27,759,509✔
1048
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1049
{
1050
  // Get attributes of particle
1051
  double E_in = p.E();
27,759,509✔
1052
  uint64_t* seed = p.current_seed();
27,759,509✔
1053

1054
  // Determine total nu, delayed nu, and delayed neutron fraction
1055
  const auto& nuc {data::nuclides[i_nuclide]};
27,759,509✔
1056
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
27,759,509✔
1057
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
27,759,509✔
1058
  double beta = nu_d / nu_t;
27,759,509✔
1059

1060
  if (prn(seed) < beta) {
27,759,509✔
1061
    // ====================================================================
1062
    // DELAYED NEUTRON SAMPLED
1063

1064
    // sampled delayed precursor group
1065
    double xi = prn(seed) * nu_d;
174,138✔
1066
    double prob = 0.0;
174,138✔
1067
    int group;
1068
    for (group = 1; group < nuc->n_precursor_; ++group) {
648,526✔
1069
      // determine delayed neutron precursor yield for group j
1070
      double yield = (*rx.products_[group].yield_)(E_in);
636,212✔
1071

1072
      // Check if this group is sampled
1073
      prob += yield;
636,212✔
1074
      if (xi < prob)
636,212✔
1075
        break;
161,824✔
1076
    }
1077

1078
    // if the sum of the probabilities is slightly less than one and the
1079
    // random number is greater, j will be greater than nuc %
1080
    // n_precursor -- check for this condition
1081
    group = std::min(group, nuc->n_precursor_);
174,138✔
1082

1083
    // set the delayed group for the particle born from fission
1084
    site->delayed_group = group;
174,138✔
1085

1086
    // Sample time of emission based on decay constant of precursor
1087
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
174,138✔
1088
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
174,138✔
1089

1090
  } else {
1091
    // ====================================================================
1092
    // PROMPT NEUTRON SAMPLED
1093

1094
    // set the delayed group for the particle born from fission to 0
1095
    site->delayed_group = 0;
27,585,371✔
1096
  }
1097

1098
  // sample from prompt neutron energy distribution
1099
  int n_sample = 0;
27,759,509✔
1100
  double mu;
1101
  while (true) {
1102
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
27,759,509✔
1103

1104
    // resample if energy is greater than maximum neutron energy
1105
    int neutron = ParticleType::neutron().transport_index();
27,759,509✔
1106
    if (site->E < data::energy_max[neutron])
27,759,509!
1107
      break;
27,759,509✔
1108

1109
    // check for large number of resamples
1110
    ++n_sample;
×
1111
    if (n_sample == MAX_SAMPLE) {
×
1112
      // particle_write_restart(p)
UNCOV
1113
      fatal_error("Resampled energy distribution maximum number of times "
×
1114
                  "for nuclide " +
×
UNCOV
1115
                  nuc->name_);
×
1116
    }
UNCOV
1117
  }
×
1118

1119
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1120
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
27,759,509✔
1121
}
27,759,509✔
1122

1123
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
17,011,885✔
1124
{
1125
  // copy energy of neutron
1126
  double E_in = p.E();
17,011,885✔
1127

1128
  // sample outgoing energy and scattering cosine
1129
  double E;
1130
  double mu;
1131
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
17,011,885✔
1132

1133
  // if scattering system is in center-of-mass, transfer cosine of scattering
1134
  // angle and outgoing energy from CM to LAB
1135
  if (rx.scatter_in_cm_) {
17,011,885✔
1136
    double E_cm = E;
16,961,590✔
1137

1138
    // determine outgoing energy in lab
1139
    double A = nuc.awr_;
16,961,590✔
1140
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
16,961,590✔
1141
                 ((A + 1.0) * (A + 1.0));
16,961,590✔
1142

1143
    // determine outgoing angle in lab
1144
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
16,961,590✔
1145
  }
1146

1147
  // Because of floating-point roundoff, it may be possible for mu to be
1148
  // outside of the range [-1,1). In these cases, we just set mu to exactly -1
1149
  // or 1
1150
  if (std::abs(mu) > 1.0)
17,011,885!
UNCOV
1151
    mu = std::copysign(1.0, mu);
×
1152

1153
  // Set outgoing energy and scattering angle
1154
  p.E() = E;
17,011,885✔
1155
  p.mu() = mu;
17,011,885✔
1156

1157
  // change direction of particle
1158
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
17,011,885✔
1159

1160
  // evaluate yield
1161
  double yield = (*rx.products_[0].yield_)(E_in);
17,011,885✔
1162
  if (std::floor(yield) == yield && yield > 0) {
17,011,885!
1163
    // If yield is integral, create exactly that many secondary particles
1164
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
17,109,374✔
1165
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
97,543✔
1166
    }
1167
  } else {
17,011,831✔
1168
    // Otherwise, change weight of particle based on yield
1169
    p.wgt() *= yield;
54✔
1170
  }
1171
}
17,011,885✔
1172

1173
void sample_secondary_photons(Particle& p, int i_nuclide)
7,608,910✔
1174
{
1175
  // Sample the number of photons produced
1176
  double y_t =
1177
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
7,608,910✔
1178
  double photon_wgt = p.wgt();
7,608,910✔
1179
  int y = 1;
7,608,910✔
1180

1181
  if (settings::use_decay_photons) {
7,608,910✔
1182
    // For decay photons, sample a single photon and modify the weight
1183
    if (y_t <= 0.0)
65,460✔
1184
      return;
15,710✔
1185
    photon_wgt *= y_t;
49,750✔
1186
  } else {
1187
    // For prompt photons, sample an integral number of photons with weight
1188
    // equal to the neutron's weight
1189
    y = static_cast<int>(y_t);
7,543,450✔
1190
    if (prn(p.current_seed()) <= y_t - y)
7,543,450✔
1191
      ++y;
509,620✔
1192
  }
1193

1194
  // Sample each secondary photon
1195
  for (int i = 0; i < y; ++i) {
8,799,100✔
1196
    // Sample the reaction and product
1197
    int i_rx;
1198
    int i_product;
1199
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
1,205,900✔
1200

1201
    // Sample the outgoing energy and angle
1202
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
1,205,900✔
1203
    double E;
1204
    double mu;
1205
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
1,205,900✔
1206

1207
    // Sample the new direction
1208
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,205,900✔
1209

1210
    // In a k-eigenvalue simulation, it's necessary to provide higher weight to
1211
    // secondary photons from non-fission reactions to properly balance energy
1212
    // release and deposition. See D. P. Griesheimer, S. J. Douglass, and M. H.
1213
    // Stedry, "Self-consistent energy normalization for quasistatic reactor
1214
    // calculations", Proc. PHYSOR, Cambridge, UK, Mar 29-Apr 2, 2020.
1215
    double wgt = photon_wgt;
1,205,900✔
1216
    if (settings::run_mode == RunMode::EIGENVALUE && !is_fission(rx->mt_)) {
1,205,900✔
1217
      wgt *= simulation::keff;
316,480✔
1218
    }
1219

1220
    // Create the secondary photon
1221
    bool created_photon = p.create_secondary(wgt, u, E, ParticleType::photon());
1,205,900✔
1222

1223
    // Tag secondary particle with parent nuclide
1224
    if (created_photon && settings::use_decay_photons) {
1,205,900✔
1225
      p.secondary_bank().back().parent_nuclide =
48,040✔
1226
        rx->products_[i_product].parent_nuclide_;
48,040✔
1227
    }
1228
  }
1229
}
1230

1231
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc