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

openmc-dev / openmc / 23084721708

14 Mar 2026 08:56AM UTC coverage: 81.599% (-0.5%) from 82.058%
23084721708

Pull #2693

github

web-flow
Merge 0ed23ee59 into bc9c31e0f
Pull Request #2693: Add reactivity control to coupled transport-depletion analyses

17575 of 25275 branches covered (69.54%)

Branch coverage included in aggregate %.

74 of 85 new or added lines in 4 files covered. (87.06%)

3755 existing lines in 99 files now uncovered.

58074 of 67433 relevant lines covered (86.12%)

47252067.37 hits per line

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

84.77
/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)
1,267,520,471✔
44
{
45
  // Add to collision counter for particle
46
  ++(p.n_collision());
1,267,520,471✔
47
  p.secondary_bank_index() = p.secondary_bank().size();
1,267,520,471!
48

49
  // Sample reaction for the material the particle is in
50
  switch (p.type().pdg_number()) {
1,267,520,471!
51
  case PDG_NEUTRON:
1,195,607,770✔
52
    sample_neutron_reaction(p);
1,195,607,770✔
53
    break;
1,195,607,770✔
54
  case PDG_PHOTON:
17,750,357✔
55
    sample_photon_reaction(p);
17,750,357✔
56
    break;
17,750,357✔
57
  case PDG_ELECTRON:
54,074,605✔
58
    sample_electron_reaction(p);
54,074,605✔
59
    break;
54,074,605✔
60
  case PDG_POSITRON:
87,739✔
61
    sample_positron_reaction(p);
87,739✔
62
    break;
87,739✔
UNCOV
63
  default:
×
UNCOV
64
    fatal_error("Unsupported particle PDG for collision sampling.");
×
65
  }
66

67
  if (settings::weight_windows_on) {
1,267,520,471✔
68
    auto [ww_found, ww] = search_weight_window(p);
83,944,651✔
69
    if (!ww_found && p.type() == ParticleType::neutron()) {
83,944,651✔
70
      // if the weight window is not valid, apply russian roulette for neutrons
71
      // (regardless of weight window collision checkpoint setting)
72
      apply_russian_roulette(p);
66,995✔
73
    } else if (settings::weight_window_checkpoint_collision) {
83,877,656!
74
      // if collision checkpointing is on, apply weight window
75
      apply_weight_window(p, ww);
83,877,656✔
76
    }
77
  }
78

79
  // Kill particle if energy falls below cutoff
80
  int type = p.type().transport_index();
1,267,520,471!
81
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
1,267,520,471!
82
    p.wgt() = 0.0;
5,335,683✔
83
  }
84

85
  // Display information about collision
86
  if (settings::verbosity >= 10 || p.trace()) {
1,267,520,471!
87
    std::string msg;
66!
88
    if (p.event() == TallyEvent::KILL) {
66!
UNCOV
89
      msg = fmt::format("    Killed. Energy = {} eV.", p.E());
×
90
    } else if (p.type().is_neutron()) {
66!
91
      msg = fmt::format("    {} with {}. Energy = {} eV.",
132✔
92
        reaction_name(p.event_mt()), data::nuclides[p.event_nuclide()]->name_,
132✔
93
        p.E());
66✔
UNCOV
94
    } else if (p.type().is_photon()) {
×
UNCOV
95
      msg = fmt::format("    {} with {}. Energy = {} eV.",
×
UNCOV
96
        reaction_name(p.event_mt()),
×
UNCOV
97
        to_element(data::nuclides[p.event_nuclide()]->name_), p.E());
×
98
    } else {
UNCOV
99
      msg = fmt::format("    Disappeared. Energy = {} eV.", p.E());
×
100
    }
101
    write_message(msg, 1);
66✔
102
  }
66✔
103
}
1,267,520,471✔
104

105
void sample_neutron_reaction(Particle& p)
1,195,607,770✔
106
{
107
  // Sample a nuclide within the material
108
  int i_nuclide = sample_nuclide(p);
1,195,607,770✔
109

110
  // Save which nuclide particle had collision with
111
  p.event_nuclide() = i_nuclide;
1,195,607,770✔
112

113
  // Create fission bank sites. Note that while a fission reaction is sampled,
114
  // it never actually "happens", i.e. the weight of the particle does not
115
  // change when sampling fission sites. The following block handles all
116
  // absorption (including fission)
117

118
  const auto& nuc {data::nuclides[i_nuclide]};
1,195,607,770✔
119

120
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
1,195,607,770✔
121
    auto& rx = sample_fission(i_nuclide, p);
168,990,167✔
122
    if (settings::run_mode == RunMode::EIGENVALUE) {
168,990,167✔
123
      create_fission_sites(p, i_nuclide, rx);
143,986,045✔
124
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
25,004,122✔
125
               settings::create_fission_neutrons) {
126
      create_fission_sites(p, i_nuclide, rx);
558,074✔
127

128
      // Make sure particle population doesn't grow out of control for
129
      // subcritical multiplication problems.
130
      if (p.secondary_bank().size() >= settings::max_secondaries) {
558,074!
UNCOV
131
        fatal_error(
×
132
          "The secondary particle bank appears to be growing without "
133
          "bound. You are likely running a subcritical multiplication problem "
134
          "with k-effective close to or greater than one.");
135
      }
136
    }
137
    p.event_mt() = rx.mt_;
168,990,167✔
138
  }
139

140
  // Create secondary photons
141
  if (settings::photon_transport) {
1,195,607,770✔
142
    sample_secondary_photons(p, i_nuclide);
8,382,044✔
143
  }
144

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

148
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
1,195,607,770✔
149
    absorption(p, i_nuclide);
1,195,494,325✔
150
  }
151
  if (!p.alive())
1,195,607,770✔
152
    return;
153

154
  // Sample a scattering reaction and determine the secondary energy of the
155
  // exiting neutron
156
  const auto& ncrystal_mat = model::materials[p.material()]->ncrystal_mat();
1,165,666,376✔
157
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
1,165,666,376!
158
    ncrystal_mat.scatter(p);
158,829✔
159
  } else {
160
    scatter(p, i_nuclide);
1,165,507,547✔
161
  }
162

163
  // Advance URR seed stream 'N' times after energy changes
164
  if (p.E() != p.E_last()) {
1,165,666,376✔
165
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
1,165,347,145✔
166
  }
167

168
  // Play russian roulette if there are no weight windows
169
  if (!settings::weight_windows_on)
1,165,666,376✔
170
    apply_russian_roulette(p);
1,102,067,723✔
171
}
172

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

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

184
  // Sample the number of neutrons produced
185
  int nu = static_cast<int>(nu_t);
144,544,119✔
186
  if (prn(p.current_seed()) <= (nu_t - nu))
144,544,119✔
187
    ++nu;
24,099,494✔
188

189
  // If no neutrons were produced then don't continue
190
  if (nu == 0)
144,544,119✔
191
    return;
114,604,141✔
192

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

197
  // Clear out particle's nu fission bank
198
  p.nu_bank().clear();
29,939,978✔
199

200
  p.fission() = true;
29,939,978✔
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);
29,939,978✔
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;
29,939,978✔
209

210
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
68,951,579✔
211
    // Initialize fission site object with particle data
212
    SourceSite site;
39,011,601✔
213
    site.r = p.r();
39,011,601✔
214
    site.particle = ParticleType::neutron();
39,011,601✔
215
    site.time = p.time();
39,011,601✔
216
    site.wgt = 1. / weight;
39,011,601✔
217
    site.surf_id = 0;
39,011,601✔
218

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

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

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

234
    // Store fission site in bank
235
    if (use_fission_bank) {
39,011,601✔
236
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
38,808,082✔
237
      if (idx == -1) {
38,808,082!
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.
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) {
38,808,082✔
253
        ifp(p, idx);
1,352,626✔
254
      }
255
    } else {
256
      p.secondary_bank().push_back(site);
203,519✔
257
      p.n_secondaries()++;
203,519✔
258
    }
259

260
    // Increment the number of neutrons born delayed
261
    if (site.delayed_group > 0) {
39,011,601✔
262
      nu_d[site.delayed_group - 1]++;
257,159✔
263
    }
264

265
    // Write fission particles to nuBank
266
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
39,011,601✔
267
    nu_bank_entry.wgt = site.wgt;
39,011,601✔
268
    nu_bank_entry.E = site.E;
39,011,601✔
269
    nu_bank_entry.delayed_group = site.delayed_group;
39,011,601✔
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) {
29,939,978!
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;
29,939,978✔
282

283
  // Store the total weight banked for analog fission tallies
284
  p.n_bank() = nu;
29,939,978✔
285
  p.wgt_bank() = nu / weight;
29,939,978✔
286
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
269,459,802✔
287
    p.n_delayed_bank(d) = nu_d[d];
239,519,824✔
288
  }
289
}
290

291
void sample_photon_reaction(Particle& p)
17,750,357✔
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();
17,750,357✔
297
  if (p.E() < settings::energy_cutoff[photon]) {
17,750,357!
UNCOV
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);
17,750,357✔
305
  const auto& micro {p.photon_xs(i_element)};
17,750,357✔
306
  const auto& element {*data::elements[i_element]};
17,750,357✔
307

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

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

326
  // Incoherent (Compton) scattering
327
  prob += micro.incoherent;
16,773,331✔
328
  if (prob > cutoff) {
16,773,331✔
329
    double alpha_out;
11,448,571✔
330
    int i_shell;
11,448,571✔
331
    element.compton_scatter(
11,448,571✔
332
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
11,448,571✔
333

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

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

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

371
  // Photoelectric effect
372
  double prob_after = prob + micro.photoelectric;
5,324,760✔
373

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

383
    for (int i_shell = 0; i_shell < element.shells_.size(); ++i_shell) {
24,489,949!
384
      const auto& shell {element.shells_[i_shell]};
24,489,949✔
385

386
      // Check threshold of reaction
387
      if (xs_lower(i_shell) == 0)
24,489,949✔
388
        continue;
10,266,385✔
389

390
      //  Evaluation subshell photoionization cross section
391
      prob += std::exp(
14,223,564✔
392
        xs_lower(i_shell) + f * (xs_upper(i_shell) - xs_lower(i_shell)));
14,223,564✔
393

394
      if (prob > cutoff) {
14,223,564✔
395
        // Determine binding energy based on whether atomic relaxation data is
396
        // present (if not, use value from Compton profile data)
397
        double binding_energy = element.has_atomic_relaxation_
5,237,021✔
398
                                  ? shell.binding_energy
5,237,021!
UNCOV
399
                                  : element.binding_energy_[i_shell];
×
400

401
        // Determine energy of secondary electron
402
        double E_electron = p.E() - binding_energy;
5,237,021✔
403

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

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

426
        // Create secondary electron
427
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
5,237,021✔
428

429
        // Allow electrons to fill orbital and produce auger electrons
430
        // and fluorescent photons
431
        if (settings::atomic_relaxation) {
5,237,021✔
432
          element.atomic_relaxation(i_shell, p);
5,127,021✔
433
        }
434
        p.event() = TallyEvent::ABSORB;
5,237,021✔
435
        p.event_mt() = 533 + shell.index_subshell;
5,237,021✔
436
        p.wgt() = 0.0;
5,237,021✔
437
        p.E() = 0.0;
5,237,021✔
438
        return;
5,237,021✔
439
      }
440
    }
441
  }
10,474,042✔
442
  prob = prob_after;
87,739✔
443

444
  // Pair production
445
  prob += micro.pair_production;
87,739✔
446
  if (prob > cutoff) {
87,739!
447
    double E_electron, E_positron;
87,739✔
448
    double mu_electron, mu_positron;
87,739✔
449
    element.pair_production(alpha, &E_electron, &E_positron, &mu_electron,
87,739✔
450
      &mu_positron, p.current_seed());
451

452
    // Create secondary electron
453
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
87,739✔
454
    p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
87,739✔
455

456
    // Create secondary positron
457
    u = rotate_angle(p.u(), mu_positron, nullptr, p.current_seed());
87,739✔
458
    p.create_secondary(p.wgt(), u, E_positron, ParticleType::positron());
87,739✔
459
    p.event() = TallyEvent::ABSORB;
87,739✔
460
    p.event_mt() = PAIR_PROD;
87,739✔
461
    p.wgt() = 0.0;
87,739✔
462
    p.E() = 0.0;
87,739✔
463
  }
464
}
465

466
void sample_electron_reaction(Particle& p)
54,074,605✔
467
{
468
  // TODO: create reaction types
469

470
  if (settings::electron_treatment == ElectronTreatment::TTB) {
54,074,605✔
471
    double E_lost;
53,530,215✔
472
    thick_target_bremsstrahlung(p, &E_lost);
53,530,215✔
473
  }
474

475
  p.E() = 0.0;
54,074,605✔
476
  p.wgt() = 0.0;
54,074,605✔
477
  p.event() = TallyEvent::ABSORB;
54,074,605✔
478
}
54,074,605✔
479

480
void sample_positron_reaction(Particle& p)
87,739✔
481
{
482
  // TODO: create reaction types
483

484
  if (settings::electron_treatment == ElectronTreatment::TTB) {
87,739✔
485
    double E_lost;
86,474✔
486
    thick_target_bremsstrahlung(p, &E_lost);
86,474✔
487
  }
488

489
  // Sample angle isotropically
490
  Direction u = isotropic_direction(p.current_seed());
87,739✔
491

492
  // Create annihilation photon pair traveling in opposite directions
493
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon());
87,739✔
494
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon());
87,739✔
495

496
  p.E() = 0.0;
87,739✔
497
  p.wgt() = 0.0;
87,739✔
498
  p.event() = TallyEvent::ABSORB;
87,739✔
499
}
87,739✔
500

501
int sample_nuclide(Particle& p)
1,195,607,770✔
502
{
503
  // Sample cumulative distribution function
504
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,195,607,770✔
505

506
  // Get pointers to nuclide/density arrays
507
  const auto& mat {model::materials[p.material()]};
1,195,607,770✔
508
  int n = mat->nuclide_.size();
1,195,607,770✔
509

510
  double prob = 0.0;
1,195,607,770✔
511
  for (int i = 0; i < n; ++i) {
2,147,483,647!
512
    // Get atom density
513
    int i_nuclide = mat->nuclide_[i];
2,147,483,647✔
514
    double atom_density = mat->atom_density(i, p.density_mult());
2,147,483,647✔
515

516
    // Increment probability to compare to cutoff
517
    prob += atom_density * p.neutron_xs(i_nuclide).total;
2,147,483,647✔
518
    if (prob >= cutoff)
2,147,483,647✔
519
      return i_nuclide;
1,195,607,770✔
520
  }
521

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

527
int sample_element(Particle& p)
17,750,357✔
528
{
529
  // Sample cumulative distribution function
530
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
17,750,357✔
531

532
  // Get pointers to elements, densities
533
  const auto& mat {model::materials[p.material()]};
17,750,357✔
534

535
  double prob = 0.0;
17,750,357✔
536
  for (int i = 0; i < mat->element_.size(); ++i) {
41,668,858!
537
    // Find atom density
538
    int i_element = mat->element_[i];
41,668,858✔
539
    double atom_density = mat->atom_density(i, p.density_mult());
41,668,858✔
540

541
    // Determine microscopic cross section
542
    double sigma = atom_density * p.photon_xs(i_element).total;
41,668,858✔
543

544
    // Increment probability to compare to cutoff
545
    prob += sigma;
41,668,858✔
546
    if (prob > cutoff) {
41,668,858✔
547
      // Save which nuclide particle had collision with for tally purpose
548
      p.event_nuclide() = mat->nuclide_[i];
17,750,357✔
549

550
      return i_element;
17,750,357✔
551
    }
552
  }
553

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

559
Reaction& sample_fission(int i_nuclide, Particle& p)
168,990,167✔
560
{
561
  // Get pointer to nuclide
562
  const auto& nuc {data::nuclides[i_nuclide]};
168,990,167✔
563

564
  // If we're in the URR, by default use the first fission reaction. We also
565
  // default to the first reaction if we know that there are no partial fission
566
  // reactions
567
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
168,990,167✔
568
    return *nuc->fission_rx_[0];
168,932,552✔
569
  }
570

571
  // Check to see if we are in a windowed multipole range.  WMP only supports
572
  // the first fission reaction.
573
  if (nuc->multipole_) {
57,615✔
574
    if (p.E() >= nuc->multipole_->E_min_ && p.E() <= nuc->multipole_->E_max_) {
2,849!
575
      return *nuc->fission_rx_[0];
1,991✔
576
    }
577
  }
578

579
  // Get grid index and interpolation factor and sample fission cdf
580
  const auto& micro = p.neutron_xs(i_nuclide);
55,624✔
581
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
55,624✔
582
  double prob = 0.0;
55,624✔
583

584
  // Loop through each partial fission reaction type
585
  for (auto& rx : nuc->fission_rx_) {
55,688!
586
    // add to cumulative probability
587
    prob += rx->xs(micro);
55,688✔
588

589
    // Create fission bank sites if fission occurs
590
    if (prob > cutoff)
55,688✔
591
      return *rx;
55,624✔
592
  }
593

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

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

607
  // Loop through each reaction type
608
  const auto& nuc {data::nuclides[i_nuclide]};
1,326,754✔
609
  for (int i = 0; i < nuc->reactions_.size(); ++i) {
21,735,494!
610
    // Evaluate neutron cross section
611
    const auto& rx = nuc->reactions_[i];
21,735,494✔
612
    double xs = rx->xs(micro);
21,735,494✔
613

614
    // if cross section is zero for this reaction, skip it
615
    if (xs == 0.0)
21,735,494✔
616
      continue;
6,746,410✔
617

618
    for (int j = 0; j < rx->products_.size(); ++j) {
69,344,330✔
619
      if (rx->products_[j].particle_.is_photon()) {
55,682,000✔
620
        // For fission, artificially increase the photon yield to account
621
        // for delayed photons
622
        double f = 1.0;
43,099,089✔
623
        if (settings::delayed_photon_scaling) {
43,099,089!
624
          if (is_fission(rx->mt_)) {
43,099,089✔
625
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
540,221!
626
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
540,221✔
627
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
540,221✔
628
              f = (energy_prompt + energy_delayed) / (energy_prompt);
540,221✔
629
            }
630
          }
631
        }
632

633
        // add to cumulative probability
634
        prob += f * (*rx->products_[j].yield_)(p.E()) * xs;
43,099,089✔
635

636
        *i_rx = i;
43,099,089✔
637
        *i_product = j;
43,099,089✔
638
        if (prob > cutoff)
43,099,089✔
639
          return;
640
      }
641
    }
642
  }
643
}
644

645
void absorption(Particle& p, int i_nuclide)
1,195,494,325✔
646
{
647
  if (settings::survival_biasing) {
1,195,494,325✔
648
    // Determine weight absorbed in survival biasing
649
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
5,744,970✔
650
                              p.neutron_xs(i_nuclide).total;
5,744,970✔
651

652
    // Adjust weight of particle by probability of absorption
653
    p.wgt() -= wgt_absorb;
5,744,970✔
654

655
    // Score implicit absorption estimate of keff
656
    if (settings::run_mode == RunMode::EIGENVALUE) {
5,744,970✔
657
      p.keff_tally_absorption() += wgt_absorb *
499,950✔
658
                                   p.neutron_xs(i_nuclide).nu_fission /
499,950✔
659
                                   p.neutron_xs(i_nuclide).absorption;
499,950✔
660
    }
661
  } else {
662
    // See if disappearance reaction happens
663
    if (p.neutron_xs(i_nuclide).absorption >
1,189,749,355✔
664
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
1,189,749,355✔
665
      // Score absorption estimate of keff
666
      if (settings::run_mode == RunMode::EIGENVALUE) {
29,940,437✔
667
        p.keff_tally_absorption() += p.wgt() *
24,249,042✔
668
                                     p.neutron_xs(i_nuclide).nu_fission /
24,249,042✔
669
                                     p.neutron_xs(i_nuclide).absorption;
24,249,042✔
670
      }
671

672
      p.wgt() = 0.0;
29,940,437✔
673
      p.event() = TallyEvent::ABSORB;
29,940,437✔
674
      if (!p.fission()) {
29,940,437✔
675
        p.event_mt() = N_DISAPPEAR;
17,597,675✔
676
      }
677
    }
678
  }
679
}
1,195,494,325✔
680

681
void scatter(Particle& p, int i_nuclide)
1,165,507,547✔
682
{
683
  // copy incoming direction
684
  Direction u_old {p.u()};
1,165,507,547✔
685

686
  // Get pointer to nuclide and grid index/interpolation factor
687
  const auto& nuc {data::nuclides[i_nuclide]};
1,165,507,547✔
688
  const auto& micro {p.neutron_xs(i_nuclide)};
1,165,507,547✔
689
  int i_temp = micro.index_temp;
1,165,507,547✔
690

691
  // For tallying purposes, this routine might be called directly. In that
692
  // case, we need to sample a reaction via the cutoff variable
693
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
1,165,507,547✔
694
  bool sampled = false;
1,165,507,547✔
695

696
  // Calculate elastic cross section if it wasn't precalculated
697
  if (micro.elastic == CACHE_INVALID) {
1,165,507,547✔
698
    nuc->calculate_elastic_xs(p);
912,606,183✔
699
  }
700

701
  double prob = micro.elastic - micro.thermal;
1,165,507,547✔
702
  if (prob > cutoff) {
1,165,507,547✔
703
    // =======================================================================
704
    // NON-S(A,B) ELASTIC SCATTERING
705

706
    // Determine temperature
707
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
1,014,091,464✔
708

709
    // Perform collision physics for elastic scattering
710
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
1,014,091,464✔
711

712
    p.event_mt() = ELASTIC;
1,014,091,464✔
713
    sampled = true;
1,014,091,464✔
714
  }
715

716
  prob = micro.elastic;
1,165,507,547✔
717
  if (prob > cutoff && !sampled) {
1,165,507,547✔
718
    // =======================================================================
719
    // S(A,B) SCATTERING
720

721
    sab_scatter(i_nuclide, micro.index_sab, p);
127,478,075✔
722

723
    p.event_mt() = ELASTIC;
127,478,075✔
724
    sampled = true;
127,478,075✔
725
  }
726

727
  if (!sampled) {
1,165,507,547✔
728
    // =======================================================================
729
    // INELASTIC SCATTERING
730

731
    int n = nuc->index_inelastic_scatter_.size();
23,938,008✔
732
    int i = 0;
23,938,008✔
733
    for (int j = 0; j < n && prob < cutoff; ++j) {
449,393,194✔
734
      i = nuc->index_inelastic_scatter_[j];
425,455,186✔
735

736
      // add to cumulative probability
737
      prob += nuc->reactions_[i]->xs(micro);
425,455,186✔
738
    }
739

740
    // Perform collision physics for inelastic scattering
741
    const auto& rx {nuc->reactions_[i]};
23,938,008✔
742
    inelastic_scatter(*nuc, *rx, p);
23,938,008✔
743
    p.event_mt() = rx->mt_;
23,938,008✔
744
  }
745

746
  // Set event component
747
  p.event() = TallyEvent::SCATTER;
1,165,507,547✔
748

749
  // Sample new outgoing angle for isotropic-in-lab scattering
750
  const auto& mat {model::materials[p.material()]};
1,165,507,547!
751
  if (!mat->p0_.empty()) {
1,165,507,547!
752
    int i_nuc_mat = mat->mat_nuclide_index_[i_nuclide];
326,370✔
753
    if (mat->p0_[i_nuc_mat]) {
326,370!
754
      // Sample isotropic-in-lab outgoing direction
755
      p.u() = isotropic_direction(p.current_seed());
326,370✔
756
      p.mu() = u_old.dot(p.u());
326,370✔
757
    }
758
  }
759
}
1,165,507,547✔
760

761
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
1,014,091,464✔
762
{
763
  // get pointer to nuclide
764
  const auto& nuc {data::nuclides[i_nuclide]};
1,014,091,464✔
765

766
  double vel = std::sqrt(p.E());
1,014,091,464✔
767
  double awr = nuc->awr_;
1,014,091,464✔
768

769
  // Neutron velocity in LAB
770
  Direction v_n = vel * p.u();
1,014,091,464✔
771

772
  // Sample velocity of target nucleus
773
  Direction v_t {};
1,014,091,464✔
774
  if (!p.neutron_xs(i_nuclide).use_ptable) {
1,014,091,464✔
775
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
969,065,233✔
776
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
969,065,233✔
777
  }
778

779
  // Velocity of center-of-mass
780
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
1,014,091,464✔
781

782
  // Transform to CM frame
783
  v_n -= v_cm;
1,014,091,464✔
784

785
  // Find speed of neutron in CM
786
  vel = v_n.norm();
1,014,091,464✔
787

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

799
  // Determine direction cosines in CM
800
  Direction u_cm = v_n / vel;
1,014,091,464✔
801

802
  // Rotate neutron velocity vector to new angle -- note that the speed of the
803
  // neutron in CM does not change in elastic scattering. However, the speed
804
  // will change when we convert back to LAB
805
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
1,014,091,464✔
806

807
  // Transform back to LAB frame
808
  v_n += v_cm;
1,014,091,464✔
809

810
  p.E() = v_n.dot(v_n);
1,014,091,464✔
811
  vel = std::sqrt(p.E());
1,014,091,464✔
812

813
  // compute cosine of scattering angle in LAB frame by taking dot product of
814
  // neutron's pre- and post-collision angle
815
  p.mu() = p.u().dot(v_n) / vel;
1,014,091,464✔
816

817
  // Set energy and direction of particle in LAB frame
818
  p.u() = v_n / vel;
1,014,091,464!
819

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

827
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
127,478,075✔
828
{
829
  // Determine temperature index
830
  const auto& micro {p.neutron_xs(i_nuclide)};
127,478,075✔
831
  int i_temp = micro.index_temp_sab;
127,478,075✔
832

833
  // Sample energy and angle
834
  double E_out;
127,478,075✔
835
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
127,478,075✔
836
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
127,478,075✔
837

838
  // Set energy to outgoing, change direction of particle
839
  p.E() = E_out;
127,478,075✔
840
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
127,478,075✔
841
}
127,478,075✔
842

843
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
969,065,233✔
844
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
845
{
846
  // check if nuclide is a resonant scatterer
847
  ResScatMethod sampling_method;
969,065,233✔
848
  if (nuc.resonant_) {
969,065,233✔
849

850
    // sampling method to use
851
    sampling_method = settings::res_scat_method;
84,557✔
852

853
    // upper resonance scattering energy bound (target is at rest above this E)
854
    if (E > settings::res_scat_energy_max) {
84,557✔
855
      return {};
40,755✔
856

857
      // lower resonance scattering energy bound (should be no resonances below)
858
    } else if (E < settings::res_scat_energy_min) {
43,802✔
859
      sampling_method = ResScatMethod::cxs;
860
    }
861

862
    // otherwise, use free gas model
863
  } else {
864
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
968,980,676✔
865
      return {};
462,130,765✔
866
    } else {
867
      sampling_method = ResScatMethod::cxs;
868
    }
869
  }
870

871
  // use appropriate target velocity sampling method
872
  switch (sampling_method) {
18,810!
873
  case ResScatMethod::cxs:
506,874,903✔
874

875
    // sample target velocity with the constant cross section (cxs) approx.
876
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
506,874,903✔
877

878
  case ResScatMethod::dbrc:
18,810✔
879
  case ResScatMethod::rvs: {
18,810✔
880
    double E_red = std::sqrt(nuc.awr_ * E / kT);
18,810✔
881
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
37,620!
882
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
18,810✔
883

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

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

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

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

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

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

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

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

959
      // cdf value at upper bound attainable energy
960
      double m = (nuc.xs_cdf_[i_E_up + 1] - nuc.xs_cdf_[i_E_up]) /
15,532✔
961
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
15,532✔
962
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
15,532✔
963

964
      while (true) {
325,908✔
965
        // directly sample Maxwellian
966
        double E_t = -kT * std::log(prn(seed));
170,720✔
967

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

979
        // perform rejection sampling on cosine between
980
        // neutron and target velocities
981
        double mu = (E_t + nuc.awr_ * (E - E_rel)) /
170,720✔
982
                    (2.0 * std::sqrt(nuc.awr_ * E * E_t));
170,720✔
983

984
        if (std::abs(mu) < 1.0) {
170,720✔
985
          // set and accept target velocity
986
          E_t /= nuc.awr_;
15,532✔
987
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
15,532✔
988
        }
989
      }
155,188✔
990
    }
991
  } // case RVS, DBRC
992
  } // switch (sampling_method)
993

UNCOV
994
  UNREACHABLE();
×
995
}
996

997
Direction sample_cxs_target_velocity(
506,878,181✔
998
  double awr, double E, Direction u, double kT, uint64_t* seed)
999
{
1000
  double beta_vn = std::sqrt(awr * E / kT);
506,878,181✔
1001
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
506,878,181✔
1002

1003
  double beta_vt_sq;
586,785,293✔
1004
  double mu;
586,785,293✔
1005
  while (true) {
586,785,293✔
1006
    // Sample two random numbers
1007
    double r1 = prn(seed);
586,785,293✔
1008
    double r2 = prn(seed);
586,785,293✔
1009

1010
    if (prn(seed) < alpha) {
586,785,293✔
1011
      // With probability alpha, we sample the distribution p(y) =
1012
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1013
      // Carlo sampler
1014

1015
      beta_vt_sq = -std::log(r1 * r2);
127,223,974✔
1016

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

1022
      double c = std::cos(PI / 2.0 * prn(seed));
459,561,319✔
1023
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
459,561,319✔
1024
    }
1025

1026
    // Determine beta * vt
1027
    double beta_vt = std::sqrt(beta_vt_sq);
586,785,293✔
1028

1029
    // Sample cosine of angle between neutron and target velocity
1030
    mu = uniform_distribution(-1., 1., seed);
586,785,293✔
1031

1032
    // Determine rejection probability
1033
    double accept_prob =
586,785,293✔
1034
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
586,785,293✔
1035
      (beta_vn + beta_vt);
586,785,293✔
1036

1037
    // Perform rejection sampling on vt and mu
1038
    if (prn(seed) < accept_prob)
586,785,293✔
1039
      break;
1040
  }
1041

1042
  // Determine speed of target nucleus
1043
  double vt = std::sqrt(beta_vt_sq * kT / awr);
506,878,181✔
1044

1045
  // Determine velocity vector of target nucleus based on neutron's velocity
1046
  // and the sampled angle between them
1047
  return vt * rotate_angle(u, mu, nullptr, seed);
506,878,181✔
1048
}
1049

1050
void sample_fission_neutron(
39,011,601✔
1051
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1052
{
1053
  // Get attributes of particle
1054
  double E_in = p.E();
39,011,601✔
1055
  uint64_t* seed = p.current_seed();
39,011,601✔
1056

1057
  // Determine total nu, delayed nu, and delayed neutron fraction
1058
  const auto& nuc {data::nuclides[i_nuclide]};
39,011,601✔
1059
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
39,011,601✔
1060
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
39,011,601✔
1061
  double beta = nu_d / nu_t;
39,011,601✔
1062

1063
  if (prn(seed) < beta) {
39,011,601✔
1064
    // ====================================================================
1065
    // DELAYED NEUTRON SAMPLED
1066

1067
    // sampled delayed precursor group
1068
    double xi = prn(seed) * nu_d;
257,159✔
1069
    double prob = 0.0;
257,159✔
1070
    int group;
257,159✔
1071
    for (group = 1; group < nuc->n_precursor_; ++group) {
959,030✔
1072
      // determine delayed neutron precursor yield for group j
1073
      double yield = (*rx.products_[group].yield_)(E_in);
940,355✔
1074

1075
      // Check if this group is sampled
1076
      prob += yield;
940,355✔
1077
      if (xi < prob)
940,355✔
1078
        break;
1079
    }
1080

1081
    // if the sum of the probabilities is slightly less than one and the
1082
    // random number is greater, j will be greater than nuc %
1083
    // n_precursor -- check for this condition
1084
    group = std::min(group, nuc->n_precursor_);
257,159!
1085

1086
    // set the delayed group for the particle born from fission
1087
    site->delayed_group = group;
257,159✔
1088

1089
    // Sample time of emission based on decay constant of precursor
1090
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
257,159✔
1091
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
257,159✔
1092

1093
  } else {
1094
    // ====================================================================
1095
    // PROMPT NEUTRON SAMPLED
1096

1097
    // set the delayed group for the particle born from fission to 0
1098
    site->delayed_group = 0;
38,754,442✔
1099
  }
1100

1101
  // sample from prompt neutron energy distribution
1102
  int n_sample = 0;
1103
  double mu;
39,011,604✔
1104
  while (true) {
39,011,604✔
1105
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
39,011,604✔
1106

1107
    // resample if energy is greater than maximum neutron energy
1108
    int neutron = ParticleType::neutron().transport_index();
39,011,604✔
1109
    if (site->E < data::energy_max[neutron])
39,011,604✔
1110
      break;
1111

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

1122
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1123
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
39,011,601✔
1124
}
39,011,601✔
1125

1126
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
23,938,008✔
1127
{
1128
  // copy energy of neutron
1129
  double E_in = p.E();
23,938,008✔
1130

1131
  // sample outgoing energy and scattering cosine
1132
  double E;
23,938,008✔
1133
  double mu;
23,938,008✔
1134
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
23,938,008✔
1135

1136
  // if scattering system is in center-of-mass, transfer cosine of scattering
1137
  // angle and outgoing energy from CM to LAB
1138
  if (rx.scatter_in_cm_) {
23,938,008✔
1139
    double E_cm = E;
23,882,704✔
1140

1141
    // determine outgoing energy in lab
1142
    double A = nuc.awr_;
23,882,704✔
1143
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
23,882,704✔
1144
                 ((A + 1.0) * (A + 1.0));
23,882,704✔
1145

1146
    // determine outgoing angle in lab
1147
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
23,882,704✔
1148
  }
1149

1150
  // Because of floating-point roundoff, it may be possible for mu to be
1151
  // outside of the range [-1,1). In these cases, we just set mu to exactly -1
1152
  // or 1
1153
  if (std::abs(mu) > 1.0)
23,938,008!
UNCOV
1154
    mu = std::copysign(1.0, mu);
×
1155

1156
  // Set outgoing energy and scattering angle
1157
  p.E() = E;
23,938,008✔
1158
  p.mu() = mu;
23,938,008✔
1159

1160
  // change direction of particle
1161
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
23,938,008✔
1162

1163
  // evaluate yield
1164
  double yield = (*rx.products_[0].yield_)(E_in);
23,938,008✔
1165
  if (std::floor(yield) == yield && yield > 0) {
23,938,008!
1166
    // If yield is integral, create exactly that many secondary particles
1167
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
24,067,930✔
1168
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
129,976✔
1169
    }
1170
  } else {
1171
    // Otherwise, change weight of particle based on yield
1172
    p.wgt() *= yield;
54✔
1173
  }
1174
}
23,938,008✔
1175

1176
void sample_secondary_photons(Particle& p, int i_nuclide)
8,382,044✔
1177
{
1178
  // Sample the number of photons produced
1179
  double y_t =
8,382,044✔
1180
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
8,382,044✔
1181
  double photon_wgt = p.wgt();
8,382,044✔
1182
  int y = 1;
8,382,044✔
1183

1184
  if (settings::use_decay_photons) {
8,382,044✔
1185
    // For decay photons, sample a single photon and modify the weight
1186
    if (y_t <= 0.0)
72,006✔
1187
      return;
1188
    photon_wgt *= y_t;
54,725✔
1189
  } else {
1190
    // For prompt photons, sample an integral number of photons with weight
1191
    // equal to the neutron's weight
1192
    y = static_cast<int>(y_t);
8,310,038✔
1193
    if (prn(p.current_seed()) <= y_t - y)
8,310,038✔
1194
      ++y;
560,857✔
1195
  }
1196

1197
  // Sample each secondary photon
1198
  for (int i = 0; i < y; ++i) {
9,691,517✔
1199
    // Sample the reaction and product
1200
    int i_rx;
1,326,754✔
1201
    int i_product;
1,326,754✔
1202
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
1,326,754✔
1203

1204
    // Sample the outgoing energy and angle
1205
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
1,326,754✔
1206
    double E;
1,326,754✔
1207
    double mu;
1,326,754✔
1208
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
1,326,754✔
1209

1210
    // Sample the new direction
1211
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,326,754✔
1212

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

1223
    // Create the secondary photon
1224
    bool created_photon = p.create_secondary(wgt, u, E, ParticleType::photon());
1,326,754✔
1225

1226
    // Tag secondary particle with parent nuclide
1227
    if (created_photon && settings::use_decay_photons) {
1,326,754✔
1228
      p.secondary_bank().back().parent_nuclide =
52,844✔
1229
        rx->products_[i_product].parent_nuclide_;
52,844✔
1230
    }
1231
  }
1232
}
1233

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