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

openmc-dev / openmc / 25472760865

07 May 2026 02:32AM UTC coverage: 80.952% (-0.4%) from 81.374%
25472760865

Pull #3757

github

web-flow
Merge 4928ac803 into e542b2f03
Pull Request #3757: Testing point detectors

17726 of 25786 branches covered (68.74%)

Branch coverage included in aggregate %.

44 of 386 new or added lines in 25 files covered. (11.4%)

81 existing lines in 3 files now uncovered.

58569 of 68461 relevant lines covered (85.55%)

47138839.61 hits per line

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

84.06
/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/tallies/tally_scoring.h"
29
#include "openmc/thermal.h"
30
#include "openmc/weight_windows.h"
31

32
#include <fmt/core.h>
33

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

38
namespace openmc {
39

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

44
void collision(Particle& p)
1,271,976,336✔
45
{
46
  // Add to collision counter for particle
47
  ++(p.n_collision());
1,271,976,336✔
48
  p.secondary_bank_index() = p.secondary_bank().size();
1,271,976,336!
49

50
  // Sample reaction for the material the particle is in
51
  switch (p.type().pdg_number()) {
1,271,976,336!
52
  case PDG_NEUTRON:
1,200,054,277✔
53
    sample_neutron_reaction(p);
1,200,054,277✔
54
    break;
1,200,054,277✔
55
  case PDG_PHOTON:
17,754,574✔
56
    sample_photon_reaction(p);
17,754,574✔
57
    break;
17,754,574✔
58
  case PDG_ELECTRON:
54,079,749✔
59
    sample_electron_reaction(p);
54,079,749✔
60
    break;
54,079,749✔
61
  case PDG_POSITRON:
87,736✔
62
    sample_positron_reaction(p);
87,736✔
63
    break;
87,736✔
64
  default:
×
65
    fatal_error("Unsupported particle PDG for collision sampling.");
×
66
  }
67

68
  if (settings::weight_windows_on) {
1,271,976,336✔
69
    auto [ww_found, ww] = search_weight_window(p);
83,960,557✔
70
    if (!ww_found && p.type() == ParticleType::neutron()) {
83,960,557✔
71
      // if the weight window is not valid, apply russian roulette for neutrons
72
      // (regardless of weight window collision checkpoint setting)
73
      apply_russian_roulette(p);
66,995✔
74
    } else if (settings::weight_window_checkpoint_collision) {
83,893,562!
75
      // if collision checkpointing is on, apply weight window
76
      apply_weight_window(p, ww);
83,893,562✔
77
    }
78
  }
79

80
  // Kill particle if energy falls below cutoff
81
  int type = p.type().transport_index();
1,271,976,336!
82
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
1,271,976,336!
83
    p.wgt() = 0.0;
5,337,190✔
84
  }
85

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

106
void sample_neutron_reaction(Particle& p)
1,200,054,277✔
107
{
108
  // Sample a nuclide within the material
109
  int i_nuclide = sample_nuclide(p);
1,200,054,277✔
110

111
  // Save which nuclide particle had collision with
112
  p.event_nuclide() = i_nuclide;
1,200,054,277✔
113

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

119
  const auto& nuc {data::nuclides[i_nuclide]};
1,200,054,277✔
120

121
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
1,200,054,277✔
122
    auto& rx = sample_fission(i_nuclide, p);
168,987,555✔
123
    if (settings::run_mode == RunMode::EIGENVALUE) {
168,987,555✔
124
      create_fission_sites(p, i_nuclide, rx);
143,983,433✔
125
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
25,004,122✔
126
               settings::create_fission_neutrons) {
127
      create_fission_sites(p, i_nuclide, rx);
558,074✔
128

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

141
  // Create secondary photons
142
  if (settings::photon_transport) {
1,200,054,277✔
143
    sample_secondary_photons(p, i_nuclide);
8,382,044✔
144
  }
145

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

149
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
1,200,054,277✔
150
    absorption(p, i_nuclide);
1,199,941,217✔
151
  }
152
  if (!p.alive())
1,200,054,277✔
153
    return;
154

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

164
  // Advance URR seed stream 'N' times after energy changes
165
  if (p.E() != p.E_last()) {
1,170,067,962✔
166
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
1,169,748,731✔
167
  }
168

169
  // Play russian roulette if there are no weight windows
170
  if (!settings::weight_windows_on)
1,170,067,962✔
171
    apply_russian_roulette(p);
1,106,461,779✔
172
}
173

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

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

185
  // Sample the number of neutrons produced
186
  int nu = static_cast<int>(nu_t);
144,541,507✔
187
  if (prn(p.current_seed()) <= (nu_t - nu))
144,541,507✔
188
    ++nu;
24,096,418✔
189

190
  // If no neutrons were produced then don't continue
191
  if (nu == 0)
144,541,507✔
192
    return;
114,602,245✔
193

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

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

201
  p.fission() = true;
29,939,262✔
202

203
  // Determine whether to place fission sites into the shared fission bank
204
  // or the secondary particle bank.
205
  bool use_fission_bank = (settings::run_mode == RunMode::EIGENVALUE);
29,939,262✔
206

207
  // Counter for the number of fission sites successfully stored to the shared
208
  // fission bank or the secondary particle bank
209
  int n_sites_stored;
29,939,262✔
210

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

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

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

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

235
    // Store fission site in bank
236
    if (use_fission_bank) {
39,004,202✔
237
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
38,800,683✔
238
      if (idx == -1) {
38,800,683!
239
        warning(
×
240
          "The shared fission bank is full. Additional fission sites created "
241
          "in this generation will not be banked. Results may be "
242
          "non-deterministic.");
243

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

249
        // Break out of loop as no more sites can be added to fission bank
250
        break;
×
251
      }
252
      // Iterated Fission Probability (IFP) method
253
      if (settings::ifp_on) {
38,800,683✔
254
        ifp(p, idx);
1,352,626✔
255
      }
256
    } else {
257
      p.secondary_bank().push_back(site);
203,519✔
258
      p.n_secondaries()++;
203,519✔
259
    }
260

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

266
    // Write fission particles to nuBank
267
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
39,004,202✔
268
    nu_bank_entry.wgt = site.wgt;
39,004,202✔
269
    nu_bank_entry.E = site.E;
39,004,202✔
270
    nu_bank_entry.delayed_group = site.delayed_group;
39,004,202✔
271
  }
272

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

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

284
  // Store the total weight banked for analog fission tallies
285
  p.n_bank() = nu;
29,939,262✔
286
  p.wgt_bank() = nu / weight;
29,939,262✔
287
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
269,453,358✔
288
    p.n_delayed_bank(d) = nu_d[d];
239,514,096✔
289
  }
290
}
291

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

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

309
  // Calculate photon energy over electron rest mass equivalent
310
  double alpha = p.E() / MASS_ELECTRON_EV;
17,754,574✔
311

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

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

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

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

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

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

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

372
  // Photoelectric effect
373
  double prob_after = prob + micro.photoelectric;
5,326,267✔
374

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

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

387
      // Check threshold of reaction
388
      if (xs_lower(i_shell) == 0)
24,491,808✔
389
        continue;
10,266,477✔
390

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

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

402
        // Determine energy of secondary electron
403
        double E_electron = p.E() - binding_energy;
5,238,531✔
404

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

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

427
        // Create secondary electron
428
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
5,238,531✔
429

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

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

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

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

467
void sample_electron_reaction(Particle& p)
54,079,749✔
468
{
469
  // TODO: create reaction types
470

471
  if (settings::electron_treatment == ElectronTreatment::TTB) {
54,079,749✔
472
    double E_lost;
53,535,359✔
473
    thick_target_bremsstrahlung(p, &E_lost);
53,535,359✔
474
  }
475

476
  p.E() = 0.0;
54,079,749✔
477
  p.wgt() = 0.0;
54,079,749✔
478
  p.event() = TallyEvent::ABSORB;
54,079,749✔
479
}
54,079,749✔
480

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

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

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

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

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

502
int sample_nuclide(Particle& p)
1,200,054,277✔
503
{
504
  // Sample cumulative distribution function
505
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,200,054,277✔
506

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

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

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

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

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

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

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

542
    // Determine microscopic cross section
543
    double sigma = atom_density * p.photon_xs(i_element).total;
41,677,020✔
544

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

551
      return i_element;
17,754,574✔
552
    }
553
  }
554

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

673
      p.wgt() = 0.0;
29,985,358✔
674
      p.event() = TallyEvent::ABSORB;
29,985,358✔
675
      if (!p.fission()) {
29,985,358✔
676
        p.event_mt() = N_DISAPPEAR;
17,642,754✔
677
      }
678
    }
679
  }
680
}
1,199,941,217✔
681

682
void scatter(Particle& p, int i_nuclide)
1,169,909,133✔
683
{
684
  // copy incoming direction
685
  Direction u_old {p.u()};
1,169,909,133✔
686

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

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

697
  // Calculate elastic cross section if it wasn't precalculated
698
  if (micro.elastic == CACHE_INVALID) {
1,169,909,133✔
699
    nuc->calculate_elastic_xs(p);
917,020,173✔
700
  }
701

702
  double prob = micro.elastic - micro.thermal;
1,169,909,133✔
703
  if (prob > cutoff) {
1,169,909,133✔
704
    // =======================================================================
705
    // NON-S(A,B) ELASTIC SCATTERING
706

707
    // Determine temperature
708
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
1,018,492,731✔
709

710
    // Perform collision physics for elastic scattering
711
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
1,018,492,731✔
712

713
    p.event_mt() = ELASTIC;
1,018,492,731✔
714
    sampled = true;
1,018,492,731✔
715
  }
716

717
  prob = micro.elastic;
1,169,909,133✔
718
  if (prob > cutoff && !sampled) {
1,169,909,133✔
719
    // =======================================================================
720
    // S(A,B) SCATTERING
721

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

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

728
  if (!sampled) {
1,169,909,133✔
729
    // =======================================================================
730
    // INELASTIC SCATTERING
731

732
    int n = nuc->index_inelastic_scatter_.size();
23,938,327✔
733
    int i = 0;
23,938,327✔
734
    for (int j = 0; j < n && prob < cutoff; ++j) {
449,372,296✔
735
      i = nuc->index_inelastic_scatter_[j];
425,433,969✔
736

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

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

747
  // Set event component
748
  p.event() = TallyEvent::SCATTER;
1,169,909,133✔
749

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

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

767
  double vel = std::sqrt(p.E());
1,018,492,731✔
768
  double awr = nuc->awr_;
1,018,492,731✔
769

770
  // Neutron velocity in LAB
771
  Direction v_n = vel * p.u();
1,018,492,731✔
772

773
  // Sample velocity of target nucleus
774
  Direction v_t {};
1,018,492,731✔
775
  if (!p.neutron_xs(i_nuclide).use_ptable) {
1,018,492,731✔
776
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
973,478,818✔
777
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
973,478,818✔
778
  }
779

780
  // Velocity of center-of-mass
781
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
1,018,492,731✔
782

783
  // Transform to CM frame
784
  v_n -= v_cm;
1,018,492,731✔
785

786
  // Find speed of neutron in CM
787
  vel = v_n.norm();
1,018,492,731✔
788

789
  if (!model::active_point_tallies.empty()) {
1,018,492,731!
NEW
790
    score_point_tally(p, i_nuclide, rx, 0, v_t);
×
791
  }
792

793
  // Sample scattering angle, checking if angle distribution is present (assume
794
  // isotropic otherwise)
795
  double mu_cm;
1,018,492,731✔
796
  auto& d = rx.products_[0].distribution_[0];
1,018,492,731!
797
  auto d_ = dynamic_cast<UncorrelatedAngleEnergy*>(d.get());
1,018,492,731!
798
  if (!d_->angle().empty()) {
1,018,492,731!
799
    mu_cm = d_->angle().sample(p.E(), p.current_seed());
1,018,492,731✔
800
  } else {
801
    mu_cm = uniform_distribution(-1., 1., p.current_seed());
×
802
  }
803

804
  // Determine direction cosines in CM
805
  Direction u_cm = v_n / vel;
1,018,492,731✔
806

807
  // Rotate neutron velocity vector to new angle -- note that the speed of the
808
  // neutron in CM does not change in elastic scattering. However, the speed
809
  // will change when we convert back to LAB
810
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
1,018,492,731✔
811

812
  // Transform back to LAB frame
813
  v_n += v_cm;
1,018,492,731✔
814

815
  p.E() = v_n.dot(v_n);
1,018,492,731✔
816
  vel = std::sqrt(p.E());
1,018,492,731✔
817

818
  // compute cosine of scattering angle in LAB frame by taking dot product of
819
  // neutron's pre- and post-collision angle
820
  p.mu() = p.u().dot(v_n) / vel;
1,018,492,731✔
821

822
  // Set energy and direction of particle in LAB frame
823
  p.u() = v_n / vel;
1,018,492,731!
824

825
  // Because of floating-point roundoff, it may be possible for mu_lab to be
826
  // outside of the range [-1,1). In these cases, we just set mu_lab to exactly
827
  // -1 or 1
828
  if (std::abs(p.mu()) > 1.0)
1,018,492,731!
829
    p.mu() = std::copysign(1.0, p.mu());
×
830
}
1,018,492,731✔
831

832
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
127,478,075✔
833
{
834
  // Determine temperature index
835
  const auto& micro {p.neutron_xs(i_nuclide)};
127,478,075!
836
  int i_temp = micro.index_temp_sab;
127,478,075✔
837

838
  // Sample energy and angle
839
  double E_out;
127,478,075✔
840
  auto& sab = data::thermal_scatt[i_sab]->data_[i_temp];
127,478,075!
841

842
  if (!model::active_point_tallies.empty()) {
127,478,075!
NEW
843
    score_point_tally(p, i_nuclide, sab, micro);
×
844
  }
845

846
  sab.sample(micro, p.E(), &E_out, &p.mu(), p.current_seed());
127,478,075✔
847

848
  // Set energy to outgoing, change direction of particle
849
  p.E() = E_out;
127,478,075✔
850
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
127,478,075✔
851
}
127,478,075✔
852

853
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
973,478,818✔
854
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
855
{
856
  // check if nuclide is a resonant scatterer
857
  ResScatMethod sampling_method;
973,478,818✔
858
  if (nuc.resonant_) {
973,478,818✔
859

860
    // sampling method to use
861
    sampling_method = settings::res_scat_method;
84,557✔
862

863
    // upper resonance scattering energy bound (target is at rest above this E)
864
    if (E > settings::res_scat_energy_max) {
84,557✔
865
      return {};
40,755✔
866

867
      // lower resonance scattering energy bound (should be no resonances below)
868
    } else if (E < settings::res_scat_energy_min) {
43,802✔
869
      sampling_method = ResScatMethod::cxs;
870
    }
871

872
    // otherwise, use free gas model
873
  } else {
874
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
973,394,261✔
875
      return {};
462,641,995✔
876
    } else {
877
      sampling_method = ResScatMethod::cxs;
878
    }
879
  }
880

881
  // use appropriate target velocity sampling method
882
  switch (sampling_method) {
18,810!
883
  case ResScatMethod::cxs:
510,777,258✔
884

885
    // sample target velocity with the constant cross section (cxs) approx.
886
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
510,777,258✔
887

888
  case ResScatMethod::dbrc:
18,810✔
889
  case ResScatMethod::rvs: {
18,810✔
890
    double E_red = std::sqrt(nuc.awr_ * E / kT);
18,810✔
891
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
37,620!
892
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
18,810✔
893

894
    // find lower and upper energy bound indices
895
    // lower index
896
    int i_E_low;
18,810✔
897
    if (E_low < nuc.energy_0K_.front()) {
18,810!
898
      i_E_low = 0;
899
    } else if (E_low > nuc.energy_0K_.back()) {
18,810!
900
      i_E_low = nuc.energy_0K_.size() - 2;
×
901
    } else {
902
      i_E_low =
18,810✔
903
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
18,810✔
904
    }
905

906
    // upper index
907
    int i_E_up;
18,810✔
908
    if (E_up < nuc.energy_0K_.front()) {
18,810!
909
      i_E_up = 0;
910
    } else if (E_up > nuc.energy_0K_.back()) {
18,810!
911
      i_E_up = nuc.energy_0K_.size() - 2;
×
912
    } else {
913
      i_E_up =
18,810✔
914
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_up);
18,810✔
915
    }
916

917
    if (i_E_up == i_E_low) {
18,810✔
918
      // Handle degenerate case -- if the upper/lower bounds occur for the same
919
      // index, then using cxs is probably a good approximation
920
      return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
18,810✔
921
    }
922

923
    if (sampling_method == ResScatMethod::dbrc) {
15,532!
924
      // interpolate xs since we're not exactly at the energy indices
925
      double xs_low = nuc.elastic_0K_[i_E_low];
×
926
      double m = (nuc.elastic_0K_[i_E_low + 1] - xs_low) /
×
927
                 (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
×
928
      xs_low += m * (E_low - nuc.energy_0K_[i_E_low]);
×
929
      double xs_up = nuc.elastic_0K_[i_E_up];
×
930
      m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) /
×
931
          (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
×
932
      xs_up += m * (E_up - nuc.energy_0K_[i_E_up]);
×
933

934
      // get max 0K xs value over range of practical relative energies
935
      double xs_max = *std::max_element(
×
936
        &nuc.elastic_0K_[i_E_low + 1], &nuc.elastic_0K_[i_E_up + 1]);
×
937
      xs_max = std::max({xs_low, xs_max, xs_up});
×
938

939
      while (true) {
×
940
        double E_rel;
×
941
        Direction v_target;
×
942
        while (true) {
×
943
          // sample target velocity with the constant cross section (cxs)
944
          // approx.
945
          v_target = sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
×
946
          Direction v_rel = v_neut - v_target;
×
947
          E_rel = v_rel.dot(v_rel);
×
948
          if (E_rel < E_up)
×
949
            break;
950
        }
951

952
        // perform Doppler broadening rejection correction (dbrc)
953
        double xs_0K = nuc.elastic_xs_0K(E_rel);
×
954
        double R = xs_0K / xs_max;
×
955
        if (prn(seed) < R)
×
956
          return v_target;
×
957
      }
958

959
    } else if (sampling_method == ResScatMethod::rvs) {
15,532✔
960
      // interpolate xs CDF since we're not exactly at the energy indices
961
      // cdf value at lower bound attainable energy
962
      double cdf_low = 0.0;
15,532✔
963
      if (E_low > nuc.energy_0K_.front()) {
15,532!
964
        double m = (nuc.xs_cdf_[i_E_low + 1] - nuc.xs_cdf_[i_E_low]) /
15,532✔
965
                   (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
15,532✔
966
        cdf_low = nuc.xs_cdf_[i_E_low] + m * (E_low - nuc.energy_0K_[i_E_low]);
15,532✔
967
      }
968

969
      // cdf value at upper bound attainable energy
970
      double m = (nuc.xs_cdf_[i_E_up + 1] - nuc.xs_cdf_[i_E_up]) /
15,532✔
971
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
15,532✔
972
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
15,532✔
973

974
      while (true) {
325,908✔
975
        // directly sample Maxwellian
976
        double E_t = -kT * std::log(prn(seed));
170,720✔
977

978
        // sample a relative energy using the xs cdf
979
        double cdf_rel = cdf_low + prn(seed) * (cdf_up - cdf_low);
170,720✔
980
        int i_E_rel = lower_bound_index(nuc.xs_cdf_.begin() + i_E_low,
170,720✔
981
          nuc.xs_cdf_.begin() + i_E_up + 2, cdf_rel);
170,720✔
982
        double E_rel = nuc.energy_0K_[i_E_low + i_E_rel];
170,720✔
983
        double m = (nuc.xs_cdf_[i_E_low + i_E_rel + 1] -
170,720✔
984
                     nuc.xs_cdf_[i_E_low + i_E_rel]) /
170,720✔
985
                   (nuc.energy_0K_[i_E_low + i_E_rel + 1] -
170,720✔
986
                     nuc.energy_0K_[i_E_low + i_E_rel]);
170,720✔
987
        E_rel += (cdf_rel - nuc.xs_cdf_[i_E_low + i_E_rel]) / m;
170,720✔
988

989
        // perform rejection sampling on cosine between
990
        // neutron and target velocities
991
        double mu = (E_t + nuc.awr_ * (E - E_rel)) /
170,720✔
992
                    (2.0 * std::sqrt(nuc.awr_ * E * E_t));
170,720✔
993

994
        if (std::abs(mu) < 1.0) {
170,720✔
995
          // set and accept target velocity
996
          E_t /= nuc.awr_;
15,532✔
997
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
15,532✔
998
        }
999
      }
155,188✔
1000
    }
1001
  } // case RVS, DBRC
1002
  } // switch (sampling_method)
1003

1004
  UNREACHABLE();
×
1005
}
1006

1007
Direction sample_cxs_target_velocity(
510,780,536✔
1008
  double awr, double E, Direction u, double kT, uint64_t* seed)
1009
{
1010
  double beta_vn = std::sqrt(awr * E / kT);
510,780,536✔
1011
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
510,780,536✔
1012

1013
  double beta_vt_sq;
591,741,595✔
1014
  double mu;
591,741,595✔
1015
  while (true) {
591,741,595✔
1016
    // Sample two random numbers
1017
    double r1 = prn(seed);
591,741,595✔
1018
    double r2 = prn(seed);
591,741,595✔
1019

1020
    if (prn(seed) < alpha) {
591,741,595✔
1021
      // With probability alpha, we sample the distribution p(y) =
1022
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1023
      // Carlo sampler
1024

1025
      beta_vt_sq = -std::log(r1 * r2);
128,938,298✔
1026

1027
    } else {
1028
      // With probability 1-alpha, we sample the distribution p(y) = y^2 *
1029
      // e^(-y^2). This can be done with sampling scheme C61 from the Monte
1030
      // Carlo sampler
1031

1032
      double c = std::cos(PI / 2.0 * prn(seed));
462,803,297✔
1033
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
462,803,297✔
1034
    }
1035

1036
    // Determine beta * vt
1037
    double beta_vt = std::sqrt(beta_vt_sq);
591,741,595✔
1038

1039
    // Sample cosine of angle between neutron and target velocity
1040
    mu = uniform_distribution(-1., 1., seed);
591,741,595✔
1041

1042
    // Determine rejection probability
1043
    double accept_prob =
591,741,595✔
1044
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
591,741,595✔
1045
      (beta_vn + beta_vt);
591,741,595✔
1046

1047
    // Perform rejection sampling on vt and mu
1048
    if (prn(seed) < accept_prob)
591,741,595✔
1049
      break;
1050
  }
1051

1052
  // Determine speed of target nucleus
1053
  double vt = std::sqrt(beta_vt_sq * kT / awr);
510,780,536✔
1054

1055
  // Determine velocity vector of target nucleus based on neutron's velocity
1056
  // and the sampled angle between them
1057
  return vt * rotate_angle(u, mu, nullptr, seed);
510,780,536✔
1058
}
1059

1060
void sample_fission_neutron(
39,004,202✔
1061
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1062
{
1063
  // Get attributes of particle
1064
  double E_in = p.E();
39,004,202✔
1065
  uint64_t* seed = p.current_seed();
39,004,202✔
1066

1067
  // Determine total nu, delayed nu, and delayed neutron fraction
1068
  const auto& nuc {data::nuclides[i_nuclide]};
39,004,202✔
1069
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
39,004,202✔
1070
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
39,004,202✔
1071
  double beta = nu_d / nu_t;
39,004,202✔
1072

1073
  if (prn(seed) < beta) {
39,004,202✔
1074
    // ====================================================================
1075
    // DELAYED NEUTRON SAMPLED
1076

1077
    // sampled delayed precursor group
1078
    double xi = prn(seed) * nu_d;
257,165✔
1079
    double prob = 0.0;
257,165✔
1080
    int group;
257,165✔
1081
    for (group = 1; group < nuc->n_precursor_; ++group) {
959,113✔
1082
      // determine delayed neutron precursor yield for group j
1083
      double yield = (*rx.products_[group].yield_)(E_in);
940,426✔
1084

1085
      // Check if this group is sampled
1086
      prob += yield;
940,426✔
1087
      if (xi < prob)
940,426✔
1088
        break;
1089
    }
1090

1091
    // if the sum of the probabilities is slightly less than one and the
1092
    // random number is greater, j will be greater than nuc %
1093
    // n_precursor -- check for this condition
1094
    group = std::min(group, nuc->n_precursor_);
257,165!
1095

1096
    // set the delayed group for the particle born from fission
1097
    site->delayed_group = group;
257,165✔
1098

1099
    // Sample time of emission based on decay constant of precursor
1100
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
257,165✔
1101
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
257,165✔
1102

1103
  } else {
1104
    // ====================================================================
1105
    // PROMPT NEUTRON SAMPLED
1106

1107
    // set the delayed group for the particle born from fission to 0
1108
    site->delayed_group = 0;
38,747,037✔
1109
  }
1110

1111
  if (!model::active_point_tallies.empty()) {
39,004,202!
NEW
1112
    score_point_tally(p, i_nuclide, rx, site->delayed_group);
×
1113
  }
1114

1115
  // sample from prompt neutron energy distribution
1116
  int n_sample = 0;
1117
  double mu;
39,004,203✔
1118
  while (true) {
39,004,203✔
1119
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
39,004,203✔
1120

1121
    // resample if energy is greater than maximum neutron energy
1122
    int neutron = ParticleType::neutron().transport_index();
39,004,203✔
1123
    if (site->E < data::energy_max[neutron])
39,004,203✔
1124
      break;
1125

1126
    // check for large number of resamples
1127
    ++n_sample;
1✔
1128
    if (n_sample == MAX_SAMPLE) {
1!
1129
      // particle_write_restart(p)
1130
      fatal_error("Resampled energy distribution maximum number of times "
×
1131
                  "for nuclide " +
×
1132
                  nuc->name_);
×
1133
    }
1134
  }
1135

1136
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1137
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
39,004,202✔
1138
}
39,004,202✔
1139

1140
void inelastic_scatter(int i_nuclide, const Reaction& rx, Particle& p)
23,938,327✔
1141
{
1142
  // Get pointer to nuclide
1143
  const auto& nuc {data::nuclides[i_nuclide]};
23,938,327✔
1144

1145
  // copy energy of neutron
1146
  double E_in = p.E();
23,938,327✔
1147

1148
  // sample outgoing energy and scattering cosine
1149
  double E;
23,938,327✔
1150
  double mu;
23,938,327✔
1151
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
23,938,327✔
1152

1153
  if (!model::active_point_tallies.empty()) {
23,938,327!
NEW
1154
    score_point_tally(p, i_nuclide, rx, 0);
×
1155
  }
1156

1157
  // if scattering system is in center-of-mass, transfer cosine of scattering
1158
  // angle and outgoing energy from CM to LAB
1159
  if (rx.scatter_in_cm_) {
23,938,327✔
1160
    double E_cm = E;
23,880,295✔
1161

1162
    // determine outgoing energy in lab
1163
    double A = nuc->awr_;
23,880,295✔
1164
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
23,880,295✔
1165
                 ((A + 1.0) * (A + 1.0));
23,880,295✔
1166

1167
    // determine outgoing angle in lab
1168
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
23,880,295✔
1169
  }
1170

1171
  // Because of floating-point roundoff, it may be possible for mu to be
1172
  // outside of the range [-1,1). In these cases, we just set mu to exactly -1
1173
  // or 1
1174
  if (std::abs(mu) > 1.0)
23,938,327!
1175
    mu = std::copysign(1.0, mu);
×
1176

1177
  // Set outgoing energy and scattering angle
1178
  p.E() = E;
23,938,327✔
1179
  p.mu() = mu;
23,938,327✔
1180

1181
  // change direction of particle
1182
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
23,938,327✔
1183

1184
  // evaluate yield
1185
  double yield = (*rx.products_[0].yield_)(E_in);
23,938,327✔
1186
  if (std::floor(yield) == yield && yield > 0) {
23,938,327!
1187
    // If yield is integral, create exactly that many secondary particles
1188
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
24,068,367✔
1189
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
130,094✔
1190
    }
1191
  } else {
1192
    // Otherwise, change weight of particle based on yield
1193
    p.wgt() *= yield;
54✔
1194
  }
1195
}
23,938,327✔
1196

1197
void sample_secondary_photons(Particle& p, int i_nuclide)
8,382,044✔
1198
{
1199
  // Sample the number of photons produced
1200
  double y_t =
8,382,044✔
1201
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
8,382,044✔
1202
  double photon_wgt = p.wgt();
8,382,044✔
1203
  int y = 1;
8,382,044✔
1204

1205
  if (settings::use_decay_photons) {
8,382,044✔
1206
    // For decay photons, sample a single photon and modify the weight
1207
    if (y_t <= 0.0)
72,006✔
1208
      return;
1209
    photon_wgt *= y_t;
54,725✔
1210
  } else {
1211
    // For prompt photons, sample an integral number of photons with weight
1212
    // equal to the neutron's weight
1213
    y = static_cast<int>(y_t);
8,310,038✔
1214
    if (prn(p.current_seed()) <= y_t - y)
8,310,038✔
1215
      ++y;
560,857✔
1216
  }
1217

1218
  // Sample each secondary photon
1219
  for (int i = 0; i < y; ++i) {
9,691,517✔
1220
    // Sample the reaction and product
1221
    int i_rx;
1,326,754✔
1222
    int i_product;
1,326,754✔
1223
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
1,326,754✔
1224

1225
    // Sample the outgoing energy and angle
1226
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
1,326,754✔
1227
    double E;
1,326,754✔
1228
    double mu;
1,326,754✔
1229
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
1,326,754✔
1230

1231
    // Sample the new direction
1232
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,326,754✔
1233

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

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

1247
    // Tag secondary particle with parent nuclide
1248
    if (created_photon && settings::use_decay_photons) {
1,326,754✔
1249
      p.secondary_bank().back().parent_nuclide =
52,844✔
1250
        rx->products_[i_product].parent_nuclide_;
52,844✔
1251
    }
1252
  }
1253
}
1254

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