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

openmc-dev / openmc / 22109060455

17 Feb 2026 05:38PM UTC coverage: 81.693% (-0.03%) from 81.721%
22109060455

Pull #3813

github

web-flow
Merge d2d368c60 into 977ade79a
Pull Request #3813: Check for positive radii

16733 of 23304 branches covered (71.8%)

Branch coverage included in aggregate %.

4 of 11 new or added lines in 1 file covered. (36.36%)

1361 existing lines in 48 files now uncovered.

56648 of 66521 relevant lines covered (85.16%)

43301606.31 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)
870,452,010✔
44
{
45
  // Add to collision counter for particle
46
  ++(p.n_collision());
870,452,010✔
47
  p.secondary_bank_index() = p.secondary_bank().size();
870,452,010✔
48

49
  // Sample reaction for the material the particle is in
50
  switch (p.type().pdg_number()) {
870,452,010!
51
  case PDG_NEUTRON:
812,019,086✔
52
    sample_neutron_reaction(p);
812,019,086✔
53
    break;
812,019,086✔
54
  case PDG_PHOTON:
14,315,934✔
55
    sample_photon_reaction(p);
14,315,934✔
56
    break;
14,315,934✔
57
  case PDG_ELECTRON:
44,045,278✔
58
    sample_electron_reaction(p);
44,045,278✔
59
    break;
44,045,278✔
60
  case PDG_POSITRON:
71,712✔
61
    sample_positron_reaction(p);
71,712✔
62
    break;
71,712✔
63
  default:
×
64
    fatal_error("Unsupported particle PDG for collision sampling.");
×
65
  }
66

67
  if (settings::weight_window_checkpoint_collision)
870,452,010!
68
    apply_weight_windows(p);
870,452,010✔
69

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

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

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

101
  // Save which nuclide particle had collision with
102
  p.event_nuclide() = i_nuclide;
812,019,086✔
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]};
812,019,086✔
110

111
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
812,019,086✔
112
    auto& rx = sample_fission(i_nuclide, p);
102,365,403✔
113
    if (settings::run_mode == RunMode::EIGENVALUE) {
102,365,403✔
114
      create_fission_sites(p, i_nuclide, rx);
81,966,609✔
115
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
20,398,794✔
116
               settings::create_fission_neutrons) {
117
      create_fission_sites(p, i_nuclide, rx);
397,482✔
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) {
397,482!
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_;
102,365,403✔
129
  }
130

131
  // Create secondary photons
132
  if (settings::photon_transport) {
812,019,086✔
133
    sample_secondary_photons(p, i_nuclide);
6,848,019✔
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) {
812,019,086✔
140
    absorption(p, i_nuclide);
812,016,206✔
141
  }
142
  if (!p.alive())
812,019,086✔
143
    return;
19,092,385✔
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();
792,926,701✔
148
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
792,926,701!
149
    ncrystal_mat.scatter(p);
129,951✔
150
  } else {
151
    scatter(p, i_nuclide);
792,796,750✔
152
  }
153

154
  // Advance URR seed stream 'N' times after energy changes
155
  if (p.E() != p.E_last()) {
792,926,701✔
156
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
792,665,512✔
157
  }
158

159
  // Play russian roulette if survival biasing is turned on
160
  if (settings::survival_biasing) {
792,926,701✔
161
    // if survival normalization is on, use normalized weight cutoff and
162
    // normalized weight survive
163
    if (settings::survival_normalization) {
409,050!
164
      if (p.wgt() < settings::weight_cutoff * p.wgt_born()) {
×
165
        russian_roulette(p, settings::weight_survive * p.wgt_born());
×
166
      }
167
    } else if (p.wgt() < settings::weight_cutoff) {
409,050✔
168
      russian_roulette(p, settings::weight_survive);
46,629✔
169
    }
170
  }
171
}
172

173
void create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx)
82,364,091✔
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;
82,364,091✔
178

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

184
  // Sample the number of neutrons produced
185
  int nu = static_cast<int>(nu_t);
82,364,091✔
186
  if (prn(p.current_seed()) <= (nu_t - nu))
82,364,091✔
187
    ++nu;
16,831,493✔
188

189
  // If no neutrons were produced then don't continue
190
  if (nu == 0)
82,364,091✔
191
    return;
62,258,886✔
192

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

197
  // Clear out particle's nu fission bank
198
  p.nu_bank().clear();
20,105,205✔
199

200
  p.fission() = true;
20,105,205✔
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);
20,105,205✔
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++) {
44,953,100✔
211
    // Initialize fission site object with particle data
212
    SourceSite site;
24,847,895✔
213
    site.r = p.r();
24,847,895✔
214
    site.particle = ParticleType::neutron();
24,847,895✔
215
    site.time = p.time();
24,847,895✔
216
    site.wgt = 1. / weight;
24,847,895✔
217
    site.surf_id = 0;
24,847,895✔
218

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

222
    // Reject site if it exceeds time cutoff
223
    if (site.delayed_group > 0) {
24,847,895✔
224
      double t_cutoff = settings::time_cutoff[site.particle.transport_index()];
156,087✔
225
      if (site.time > t_cutoff) {
156,087!
226
        continue;
×
227
      }
228
    }
229

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

234
    // Store fission site in bank
235
    if (use_fission_bank) {
24,847,895✔
236
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
24,736,185✔
237
      if (idx == -1) {
24,736,185!
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.
246
        p.n_progeny()--;
×
247

248
        // Break out of loop as no more sites can be added to fission bank
249
        break;
×
250
      }
251
      // Iterated Fission Probability (IFP) method
252
      if (settings::ifp_on) {
24,736,185✔
253
        ifp(p, idx);
1,106,694✔
254
      }
255
    } else {
256
      p.secondary_bank().push_back(site);
111,710✔
257
      p.n_secondaries()++;
111,710✔
258
    }
259

260
    // Increment the number of neutrons born delayed
261
    if (site.delayed_group > 0) {
24,847,895✔
262
      nu_d[site.delayed_group - 1]++;
156,087✔
263
    }
264

265
    // Write fission particles to nuBank
266
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
24,847,895✔
267
    nu_bank_entry.wgt = site.wgt;
24,847,895✔
268
    nu_bank_entry.E = site.E;
24,847,895✔
269
    nu_bank_entry.delayed_group = site.delayed_group;
24,847,895✔
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) {
20,105,205!
275
    p.fission() = false;
×
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;
20,105,205✔
282

283
  // Store the total weight banked for analog fission tallies
284
  p.n_bank() = nu;
20,105,205✔
285
  p.wgt_bank() = nu / weight;
20,105,205✔
286
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
180,946,845✔
287
    p.n_delayed_bank(d) = nu_d[d];
160,841,640✔
288
  }
289
}
290

291
void sample_photon_reaction(Particle& p)
14,315,934✔
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();
14,315,934✔
297
  if (p.E() < settings::energy_cutoff[photon]) {
14,315,934!
298
    p.E() = 0.0;
×
299
    p.wgt() = 0.0;
×
300
    return;
×
301
  }
302

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

308
  // Calculate photon energy over electron rest mass equivalent
309
  double alpha = p.E() / MASS_ELECTRON_EV;
14,315,934✔
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;
14,315,934✔
314
  double cutoff = prn(p.current_seed()) * micro.total;
14,315,934✔
315

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

326
  // Incoherent (Compton) scattering
327
  prob += micro.incoherent;
13,526,044✔
328
  if (prob > cutoff) {
13,526,044✔
329
    double alpha_out;
330
    int i_shell;
331
    element.compton_scatter(
18,517,060✔
332
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
9,258,530✔
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) {
9,258,530!
338
      e_b = 0.0;
×
339
    } else {
340
      e_b = element.binding_energy_[i_shell];
9,258,530✔
341
    }
342

343
    // Create Compton electron
344
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
9,258,530✔
345
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
9,258,530✔
346
    int electron = ParticleType::electron().transport_index();
9,258,530✔
347
    if (E_electron >= settings::energy_cutoff[electron]) {
9,258,530✔
348
      double mu_electron = (alpha - alpha_out * p.mu()) /
9,171,556✔
349
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
18,343,112✔
350
                                     2.0 * alpha * alpha_out * p.mu());
9,171,556✔
351
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
9,171,556✔
352
      p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
9,171,556✔
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) {
9,258,530!
359
      element.atomic_relaxation(element.subshell_map_[i_shell], p);
9,258,530✔
360
    }
361

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

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

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

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

385
      // Check threshold of reaction
386
      if (xs_lower(i_shell) == 0)
19,905,796✔
387
        continue;
8,399,577✔
388

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

393
      if (prob > cutoff) {
11,506,219✔
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,195,802✔
397
                                  ? shell.binding_energy
4,195,802!
UNCOV
398
                                  : element.binding_energy_[i_shell];
×
399

400
        // Determine energy of secondary electron
401
        double E_electron = p.E() - binding_energy;
4,195,802✔
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,294,494✔
409
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
6,294,494✔
410
            double rel_vel =
411
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
4,195,802✔
412
              (E_electron + MASS_ELECTRON_EV);
4,195,802✔
413
            mu =
4,195,802✔
414
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
4,195,802✔
415
            break;
4,195,802✔
416
          }
417
        }
2,098,692✔
418

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

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

428
        // Allow electrons to fill orbital and produce auger electrons
429
        // and fluorescent photons
430
        element.atomic_relaxation(i_shell, p);
4,195,802✔
431
        p.event() = TallyEvent::ABSORB;
4,195,802✔
432
        p.event_mt() = 533 + shell.index_subshell;
4,195,802✔
433
        p.wgt() = 0.0;
4,195,802✔
434
        p.E() = 0.0;
4,195,802✔
435
        return;
4,195,802✔
436
      }
437
    }
438
  }
8,391,604!
439
  prob = prob_after;
71,712✔
440

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

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

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

463
void sample_electron_reaction(Particle& p)
44,045,278✔
464
{
465
  // TODO: create reaction types
466

467
  if (settings::electron_treatment == ElectronTreatment::TTB) {
44,045,278✔
468
    double E_lost;
469
    thick_target_bremsstrahlung(p, &E_lost);
43,796,833✔
470
  }
471

472
  p.E() = 0.0;
44,045,278✔
473
  p.wgt() = 0.0;
44,045,278✔
474
  p.event() = TallyEvent::ABSORB;
44,045,278✔
475
}
44,045,278✔
476

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

481
  if (settings::electron_treatment == ElectronTreatment::TTB) {
71,712✔
482
    double E_lost;
483
    thick_target_bremsstrahlung(p, &E_lost);
70,677✔
484
  }
485

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

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

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

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

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

507
  double prob = 0.0;
812,019,086✔
508
  for (int i = 0; i < n; ++i) {
1,720,279,605!
509
    // Get atom density
510
    int i_nuclide = mat->nuclide_[i];
1,720,279,605✔
511
    double atom_density = mat->atom_density(i, p.density_mult());
1,720,279,605✔
512

513
    // Increment probability to compare to cutoff
514
    prob += atom_density * p.neutron_xs(i_nuclide).total;
1,720,279,605✔
515
    if (prob >= cutoff)
1,720,279,605✔
516
      return i_nuclide;
812,019,086✔
517
  }
518

519
  // If we reach here, no nuclide was sampled
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)
14,315,934✔
525
{
526
  // Sample cumulative distribution function
527
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
14,315,934✔
528

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

532
  double prob = 0.0;
14,315,934✔
533
  for (int i = 0; i < mat->element_.size(); ++i) {
33,878,832!
534
    // Find atom density
535
    int i_element = mat->element_[i];
33,878,832✔
536
    double atom_density = mat->atom_density(i, p.density_mult());
33,878,832✔
537

538
    // Determine microscopic cross section
539
    double sigma = atom_density * p.photon_xs(i_element).total;
33,878,832✔
540

541
    // Increment probability to compare to cutoff
542
    prob += sigma;
33,878,832✔
543
    if (prob > cutoff) {
33,878,832✔
544
      // Save which nuclide particle had collision with for tally purpose
545
      p.event_nuclide() = mat->nuclide_[i];
14,315,934✔
546

547
      return i_element;
14,315,934✔
548
    }
549
  }
550

551
  // If we made it here, no element was sampled
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)
102,365,403✔
557
{
558
  // Get pointer to nuclide
559
  const auto& nuc {data::nuclides[i_nuclide]};
102,365,403✔
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_) {
102,365,403✔
565
    return *nuc->fission_rx_[0];
102,344,247✔
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_) {
21,156✔
571
    if (p.E() >= nuc->multipole_->E_min_ && p.E() <= nuc->multipole_->E_max_) {
2,331!
572
      return *nuc->fission_rx_[0];
1,629✔
573
    }
574
  }
575

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

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

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

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

596
void sample_photon_product(
1,085,310✔
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,085,310✔
601
  double cutoff = prn(p.current_seed()) * micro.photon_prod;
1,085,310✔
602
  double prob = 0.0;
1,085,310✔
603

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

611
    // if cross section is zero for this reaction, skip it
612
    if (xs == 0.0)
17,779,140✔
613
      continue;
5,515,812✔
614

615
    for (int j = 0; j < rx->products_.size(); ++j) {
56,732,364✔
616
      if (rx->products_[j].particle_.is_photon()) {
45,554,346✔
617
        // For fission, artificially increase the photon yield to account
618
        // for delayed photons
619
        double f = 1.0;
35,259,903✔
620
        if (settings::delayed_photon_scaling) {
35,259,903!
621
          if (is_fission(rx->mt_)) {
35,259,903✔
622
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
441,999!
623
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
441,999✔
624
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
441,999✔
625
              f = (energy_prompt + energy_delayed) / (energy_prompt);
441,999✔
626
            }
627
          }
628
        }
629

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

633
        *i_rx = i;
35,259,903✔
634
        *i_product = j;
35,259,903✔
635
        if (prob > cutoff)
35,259,903✔
636
          return;
1,085,310✔
637
      }
638
    }
639
  }
640
}
641

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

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

652
    // Score implicit absorption estimate of keff
653
    if (settings::run_mode == RunMode::EIGENVALUE) {
409,050!
654
      p.keff_tally_absorption() += wgt_absorb *
409,050✔
655
                                   p.neutron_xs(i_nuclide).nu_fission /
409,050✔
656
                                   p.neutron_xs(i_nuclide).absorption;
409,050✔
657
    }
658
  } else {
659
    // See if disappearance reaction happens
660
    if (p.neutron_xs(i_nuclide).absorption >
811,607,156✔
661
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
811,607,156✔
662
      // Score absorption estimate of keff
663
      if (settings::run_mode == RunMode::EIGENVALUE) {
19,092,385✔
664
        p.keff_tally_absorption() += p.wgt() *
28,935,492✔
665
                                     p.neutron_xs(i_nuclide).nu_fission /
14,467,746✔
666
                                     p.neutron_xs(i_nuclide).absorption;
14,467,746✔
667
      }
668

669
      p.wgt() = 0.0;
19,092,385✔
670
      p.event() = TallyEvent::ABSORB;
19,092,385✔
671
      if (!p.fission()) {
19,092,385✔
672
        p.event_mt() = N_DISAPPEAR;
11,933,251✔
673
      }
674
    }
675
  }
676
}
812,016,206✔
677

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

683
  // Get pointer to nuclide and grid index/interpolation factor
684
  const auto& nuc {data::nuclides[i_nuclide]};
792,796,750✔
685
  const auto& micro {p.neutron_xs(i_nuclide)};
792,796,750✔
686
  int i_temp = micro.index_temp;
792,796,750✔
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);
792,796,750✔
691
  bool sampled = false;
792,796,750✔
692

693
  // Calculate elastic cross section if it wasn't precalculated
694
  if (micro.elastic == CACHE_INVALID) {
792,796,750✔
695
    nuc->calculate_elastic_xs(p);
592,969,047✔
696
  }
697

698
  double prob = micro.elastic - micro.thermal;
792,796,750✔
699
  if (prob > cutoff) {
792,796,750✔
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];
673,240,272✔
705

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

709
    p.event_mt() = ELASTIC;
673,240,272✔
710
    sampled = true;
673,240,272✔
711
  }
712

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

718
    sab_scatter(i_nuclide, micro.index_sab, p);
104,289,993✔
719

720
    p.event_mt() = ELASTIC;
104,289,993✔
721
    sampled = true;
104,289,993✔
722
  }
723

724
  if (!sampled) {
792,796,750✔
725
    // =======================================================================
726
    // INELASTIC SCATTERING
727

728
    int n = nuc->index_inelastic_scatter_.size();
15,266,485✔
729
    int i = 0;
15,266,485✔
730
    for (int j = 0; j < n && prob < cutoff; ++j) {
286,959,333✔
731
      i = nuc->index_inelastic_scatter_[j];
271,692,848✔
732

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

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

743
  // Set event component
744
  p.event() = TallyEvent::SCATTER;
792,796,750✔
745

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

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

763
  double vel = std::sqrt(p.E());
673,240,272✔
764
  double awr = nuc->awr_;
673,240,272✔
765

766
  // Neutron velocity in LAB
767
  Direction v_n = vel * p.u();
673,240,272✔
768

769
  // Sample velocity of target nucleus
770
  Direction v_t {};
673,240,272✔
771
  if (!p.neutron_xs(i_nuclide).use_ptable) {
673,240,272✔
772
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
1,286,736,342✔
773
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
643,368,171✔
774
  }
775

776
  // Velocity of center-of-mass
777
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
673,240,272✔
778

779
  // Transform to CM frame
780
  v_n -= v_cm;
673,240,272✔
781

782
  // Find speed of neutron in CM
783
  vel = v_n.norm();
673,240,272✔
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];
673,240,272✔
789
  auto d_ = dynamic_cast<UncorrelatedAngleEnergy*>(d.get());
673,240,272!
790
  if (!d_->angle().empty()) {
673,240,272!
791
    mu_cm = d_->angle().sample(p.E(), p.current_seed());
673,240,272✔
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;
673,240,272✔
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());
673,240,272✔
803

804
  // Transform back to LAB frame
805
  v_n += v_cm;
673,240,272✔
806

807
  p.E() = v_n.dot(v_n);
673,240,272✔
808
  vel = std::sqrt(p.E());
673,240,272✔
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;
673,240,272✔
813

814
  // Set energy and direction of particle in LAB frame
815
  p.u() = v_n / vel;
673,240,272✔
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)
673,240,272!
UNCOV
821
    p.mu() = std::copysign(1.0, p.mu());
×
822
}
673,240,272✔
823

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

830
  // Sample energy and angle
831
  double E_out;
832
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
208,579,986✔
833
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
104,289,993✔
834

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

840
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
643,368,171✔
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_) {
643,368,171✔
846

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

850
    // upper resonance scattering energy bound (target is at rest above this E)
851
    if (E > settings::res_scat_energy_max) {
69,183✔
852
      return {};
33,345✔
853

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

859
    // otherwise, use free gas model
860
  } else {
861
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
643,298,988✔
862
      return {};
330,770,460✔
863
    } else {
864
      sampling_method = ResScatMethod::cxs;
312,528,528✔
865
    }
866
  }
867

868
  // use appropriate target velocity sampling method
869
  switch (sampling_method) {
312,564,366!
870
  case ResScatMethod::cxs:
312,548,976✔
871

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

875
  case ResScatMethod::dbrc:
15,390✔
876
  case ResScatMethod::rvs: {
877
    double E_red = std::sqrt(nuc.awr_ * E / kT);
15,390✔
878
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
15,390✔
879
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
15,390✔
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()) {
15,390!
UNCOV
885
      i_E_low = 0;
×
886
    } else if (E_low > nuc.energy_0K_.back()) {
15,390!
UNCOV
887
      i_E_low = nuc.energy_0K_.size() - 2;
×
888
    } else {
889
      i_E_low =
15,390✔
890
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
15,390✔
891
    }
892

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

904
    if (i_E_up == i_E_low) {
15,390✔
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);
15,390✔
908
    }
909

910
    if (sampling_method == ResScatMethod::dbrc) {
12,708!
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];
×
917
      m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) /
×
918
          (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
×
UNCOV
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
922
      double xs_max = *std::max_element(
×
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);
×
935
          if (E_rel < E_up)
×
936
            break;
×
UNCOV
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;
×
942
        if (prn(seed) < R)
×
943
          return v_target;
×
UNCOV
944
      }
×
945

946
    } else if (sampling_method == ResScatMethod::rvs) {
12,708!
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;
12,708✔
950
      if (E_low > nuc.energy_0K_.front()) {
12,708!
951
        double m = (nuc.xs_cdf_[i_E_low + 1] - nuc.xs_cdf_[i_E_low]) /
12,708✔
952
                   (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
12,708✔
953
        cdf_low = nuc.xs_cdf_[i_E_low] + m * (E_low - nuc.energy_0K_[i_E_low]);
12,708✔
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]) /
12,708✔
958
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
12,708✔
959
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
12,708✔
960

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

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

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

981
        if (std::abs(mu) < 1.0) {
139,680✔
982
          // set and accept target velocity
983
          E_t /= nuc.awr_;
12,708✔
984
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
12,708✔
985
        }
986
      }
126,972✔
987
    }
988
  } // case RVS, DBRC
989
  } // switch (sampling_method)
990

UNCOV
991
  UNREACHABLE();
×
992
}
993

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

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

1007
    if (prn(seed) < alpha) {
364,531,336✔
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);
83,910,398✔
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));
280,620,938✔
1020
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
280,620,938✔
1021
    }
1022

1023
    // Determine beta * vt
1024
    double beta_vt = std::sqrt(beta_vt_sq);
364,531,336✔
1025

1026
    // Sample cosine of angle between neutron and target velocity
1027
    mu = uniform_distribution(-1., 1., seed);
364,531,336✔
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) /
364,531,336✔
1032
      (beta_vn + beta_vt);
364,531,336✔
1033

1034
    // Perform rejection sampling on vt and mu
1035
    if (prn(seed) < accept_prob)
364,531,336✔
1036
      break;
312,551,658✔
1037
  }
51,979,678✔
1038

1039
  // Determine speed of target nucleus
1040
  double vt = std::sqrt(beta_vt_sq * kT / awr);
312,551,658✔
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);
312,551,658✔
1045
}
1046

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

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

1060
  if (prn(seed) < beta) {
24,847,895✔
1061
    // ====================================================================
1062
    // DELAYED NEUTRON SAMPLED
1063

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

1072
      // Check if this group is sampled
1073
      prob += yield;
570,068✔
1074
      if (xi < prob)
570,068✔
1075
        break;
145,061✔
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_);
156,087✔
1082

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

1086
    // Sample time of emission based on decay constant of precursor
1087
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
156,087✔
1088
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
156,087✔
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;
24,691,808✔
1096
  }
1097

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

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

1109
    // check for large number of resamples
1110
    ++n_sample;
×
UNCOV
1111
    if (n_sample == MAX_SAMPLE) {
×
1112
      // particle_write_restart(p)
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);
24,847,895✔
1121
}
24,847,895✔
1122

1123
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
15,266,485✔
1124
{
1125
  // copy energy of neutron
1126
  double E_in = p.E();
15,266,485✔
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());
15,266,485✔
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_) {
15,266,485✔
1136
    double E_cm = E;
15,221,407✔
1137

1138
    // determine outgoing energy in lab
1139
    double A = nuc.awr_;
15,221,407✔
1140
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
15,221,407✔
1141
                 ((A + 1.0) * (A + 1.0));
15,221,407✔
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);
15,221,407✔
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)
15,266,485!
UNCOV
1151
    mu = std::copysign(1.0, mu);
×
1152

1153
  // Set outgoing energy and scattering angle
1154
  p.E() = E;
15,266,485✔
1155
  p.mu() = mu;
15,266,485✔
1156

1157
  // change direction of particle
1158
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
15,266,485✔
1159

1160
  // evaluate yield
1161
  double yield = (*rx.products_[0].yield_)(E_in);
15,266,485✔
1162
  if (std::floor(yield) == yield && yield > 0) {
15,266,485!
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) {
15,347,689✔
1165
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
81,234✔
1166
    }
1167
  } else {
15,266,455✔
1168
    // Otherwise, change weight of particle based on yield
1169
    p.wgt() *= yield;
30✔
1170
  }
1171
}
15,266,485✔
1172

1173
void sample_secondary_photons(Particle& p, int i_nuclide)
6,848,019✔
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;
6,848,019✔
1178
  double photon_wgt = p.wgt();
6,848,019✔
1179
  int y = 1;
6,848,019✔
1180

1181
  if (settings::use_decay_photons) {
6,848,019✔
1182
    // For decay photons, sample a single photon and modify the weight
1183
    if (y_t <= 0.0)
58,914✔
1184
      return;
14,139✔
1185
    photon_wgt *= y_t;
44,775✔
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);
6,789,105✔
1190
    if (prn(p.current_seed()) <= y_t - y)
6,789,105✔
1191
      ++y;
458,658✔
1192
  }
1193

1194
  // Sample each secondary photon
1195
  for (int i = 0; i < y; ++i) {
7,919,190✔
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,085,310✔
1200

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

1207
    // Sample the new direction
1208
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,085,310✔
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,085,310✔
1216
    if (settings::run_mode == RunMode::EIGENVALUE && !is_fission(rx->mt_)) {
1,085,310✔
1217
      wgt *= simulation::keff;
284,832✔
1218
    }
1219

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

1223
    // Tag secondary particle with parent nuclide
1224
    if (created_photon && settings::use_decay_photons) {
1,085,310✔
1225
      p.secondary_bank().back().parent_nuclide =
43,236✔
1226
        rx->products_[i_product].parent_nuclide_;
43,236✔
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