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

openmc-dev / openmc / 34706149409

12 Sep 2026 04:44PM UTC coverage: 81.583% (+0.05%) from 81.533%
34706149409

Pull #3757

github

web-flow
Merge cb572b66d into 0888e2ff3
Pull Request #3757: Implementation of point detectors

19338 of 27923 branches covered (69.25%)

Branch coverage included in aggregate %.

460 of 548 new or added lines in 25 files covered. (83.94%)

113 existing lines in 3 files now uncovered.

61602 of 71289 relevant lines covered (86.41%)

49748801.28 hits per line

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

83.27
/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/next_event_scoring.h"
28
#include "openmc/tallies/tally.h"
29
#include "openmc/tallies/tally_scoring.h"
30
#include "openmc/thermal.h"
31
#include "openmc/weight_windows.h"
32

33
#include <fmt/core.h>
34

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

39
namespace openmc {
40

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

45
void collision(Particle& p)
1,608,748,601 ✔
46
{
47
  // Add to collision counter for particle
48
  ++(p.n_collision());
1,608,748,601 ✔
49
  p.secondary_bank_index() = p.local_secondary_bank().size();
1,608,748,601 !
50

51
  // Sample reaction for the material the particle is in
52
  switch (p.type().pdg_number()) {
1,608,748,601 !
53
  case PDG_NEUTRON:
1,574,299,225 ✔
54
    sample_neutron_reaction(p);
1,574,299,225 ✔
55
    break;
1,574,299,225 ✔
56
  case PDG_PHOTON:
34,339,376 ✔
57
    sample_photon_reaction(p);
34,339,376 ✔
58
    break;
34,339,376 ✔
59
  case PDG_ELECTRON:
110,000 ✔
60
    sample_electron_reaction(p);
110,000 ✔
61
    break;
110,000 ✔
62
  case PDG_POSITRON:
×
63
    sample_positron_reaction(p);
×
64
    break;
×
65
  default:
×
66
    fatal_error("Unsupported particle PDG for collision sampling.");
×
67
  }
68

69
  if (settings::weight_windows_on) {
1,608,748,601 ✔
70
    auto [ww_found, ww] = search_weight_window(p);
417,639,735 ✔
71
    if (!ww_found && p.type() == ParticleType::neutron()) {
417,639,735 ✔
72
      // if the weight window is not valid, apply russian roulette for neutrons
73
      // (regardless of weight window collision checkpoint setting)
74
      apply_russian_roulette(p);
66,274 ✔
75
    } else if (settings::weight_window_checkpoint_collision) {
417,573,461 !
76
      // if collision checkpointing is on, apply weight window
77
      apply_weight_window(p, ww);
417,573,461 ✔
78
    }
79
  }
80

81
  // Kill particle if energy falls below cutoff
82
  int type = p.type().transport_index();
1,608,748,601 !
83
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
1,608,748,601 !
84
    p.wgt() = 0.0;
8,106,085 ✔
85
  }
86

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

107
void sample_neutron_reaction(Particle& p)
1,574,299,225 ✔
108
{
109
  // Sample a nuclide within the material
110
  int i_nuclide = sample_nuclide(p);
1,574,299,225 ✔
111

112
  // Save which nuclide particle had collision with
113
  p.event_nuclide() = i_nuclide;
1,574,299,225 ✔
114

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

120
  const auto& nuc {data::nuclides[i_nuclide]};
1,574,299,225 ✔
121

122
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
1,574,299,225 ✔
123
    auto& rx = sample_fission(i_nuclide, p);
176,648,107 ✔
124
    if (settings::run_mode == RunMode::EIGENVALUE) {
176,648,107 ✔
125
      create_fission_sites(p, i_nuclide, rx);
151,621,062 ✔
126
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
25,027,045 ✔
127
               settings::create_fission_neutrons) {
128
      create_fission_sites(p, i_nuclide, rx);
580,997 ✔
129

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

143
  // Create secondary photons
144
  if (settings::photon_transport) {
1,574,299,225 ✔
145
    sample_secondary_photons(p, i_nuclide);
77,894,784 ✔
146
  }
147

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

151
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
1,574,299,225 ✔
152
    absorption(p, i_nuclide);
1,574,186,287 ✔
153
  }
154
  if (!p.alive())
1,574,299,225 ✔
155
    return;
156

157
  // Sample a scattering reaction and determine the secondary energy of the
158
  // exiting neutron
159
  const auto& ncrystal_mat = model::materials[p.material()]->ncrystal_mat();
1,538,471,849 ✔
160
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
1,538,471,849 !
161
    if (!model::active_point_tallies.empty())
158,829 !
NEW
162
      fatal_error("Next-Event estimator does not support ncrystal materials");
×
163
    ncrystal_mat.scatter(p);
158,829 ✔
164
  } else {
165
    scatter(p, i_nuclide);
1,538,313,020 ✔
166
  }
167

168
  // Advance URR seed stream 'N' times after energy changes
169
  if (p.E() != p.E_last()) {
1,538,471,849 ✔
170
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
1,538,152,618 ✔
171
  }
172

173
  // Play russian roulette if there are no weight windows
174
  if (!settings::weight_windows_on)
1,538,471,849 ✔
175
    apply_russian_roulette(p);
1,149,657,658 ✔
176
}
177

178
void create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx)
152,202,059 ✔
179
{
180
  // If uniform fission source weighting is turned on, we increase or decrease
181
  // the expected number of fission sites produced
182
  double weight = settings::ufs_on ? ufs_get_weight(p) : 1.0;
152,202,059 ✔
183

184
  // Determine the expected number of neutrons produced
185
  double nu_t = p.wgt() / simulation::keff * weight *
152,202,059 ✔
186
                p.neutron_xs(i_nuclide).nu_fission /
152,202,059 ✔
187
                p.neutron_xs(i_nuclide).total;
152,202,059 ✔
188

189
  // Sample the number of neutrons produced
190
  int nu = static_cast<int>(nu_t);
152,202,059 ✔
191
  if (prn(p.current_seed()) <= (nu_t - nu))
152,202,059 ✔
192
    ++nu;
26,615,416 ✔
193

194
  // If no neutrons were produced then don't continue
195
  if (nu == 0)
152,202,059 ✔
196
    return;
119,704,157 ✔
197

198
  // Initialize the counter of delayed neutrons encountered for each delayed
199
  // group.
200
  double nu_d[MAX_DELAYED_GROUPS] = {0.};
32,497,902 ✔
201

202
  // Clear out particle's nu fission bank
203
  p.nu_bank().clear();
32,497,902 ✔
204

205
  p.fission() = true;
32,497,902 ✔
206

207
  // Determine whether to place fission sites into the shared fission bank
208
  // or the secondary particle bank.
209
  bool use_fission_bank = (settings::run_mode == RunMode::EIGENVALUE);
32,497,902 ✔
210

211
  // Counter for the number of fission sites successfully stored to the shared
212
  // fission bank or the secondary particle bank
213
  int n_sites_stored;
32,497,902 ✔
214

215
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
74,040,237 ✔
216
    // Initialize fission site object with particle data
217
    SourceSite site;
41,542,335 ✔
218
    site.r = p.r();
41,542,335 ✔
219
    site.particle = ParticleType::neutron();
41,542,335 ✔
220
    site.time = p.time();
41,542,335 ✔
221
    site.wgt = 1. / weight;
41,542,335 ✔
222
    site.surf_id = 0;
41,542,335 ✔
223

224
    // Sample delayed group and angle/energy for fission reaction
225
    sample_fission_neutron(i_nuclide, rx, &site, p);
41,542,335 ✔
226

227
    // Reject site if it exceeds time cutoff
228
    if (site.delayed_group > 0) {
41,542,335 ✔
229
      double t_cutoff = settings::time_cutoff[site.particle.transport_index()];
274,800 !
230
      if (site.time > t_cutoff) {
274,800 !
231
        continue;
×
232
      }
233
    }
234

235
    // Set parent and progeny IDs
236
    site.parent_id = p.current_work();
41,542,335 ✔
237
    site.progeny_id = p.n_progeny()++;
41,542,335 ✔
238

239
    // Store fission site in bank
240
    if (use_fission_bank) {
41,542,335 ✔
241
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
41,327,550 ✔
242
      if (idx == -1) {
41,327,550 !
243
        warning(
×
244
          "The shared fission bank is full. Additional fission sites created "
245
          "in this generation will not be banked. Results may be "
246
          "non-deterministic.");
247

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

253
        // Break out of loop as no more sites can be added to fission bank
254
        break;
×
255
      }
256
      // Iterated Fission Probability (IFP) method
257
      if (settings::ifp_on()) {
41,327,550 ✔
258
        ifp(p, idx);
2,451,108 ✔
259
      }
260
    } else {
261
      site.wgt_born = p.wgt_born();
214,785 ✔
262
      site.wgt_ww_born = p.wgt_ww_born();
214,785 ✔
263
      site.n_split = p.n_split();
214,785 ✔
264
      p.local_secondary_bank().push_back(site);
214,785 ✔
265
      p.n_secondaries()++;
214,785 ✔
266
    }
267

268
    // Increment the number of neutrons born delayed
269
    if (site.delayed_group > 0) {
41,542,335 ✔
270
      nu_d[site.delayed_group - 1]++;
274,800 ✔
271
    }
272

273
    // Write fission particles to nuBank
274
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
41,542,335 ✔
275
    nu_bank_entry.wgt = site.wgt;
41,542,335 ✔
276
    nu_bank_entry.E = site.E;
41,542,335 ✔
277
    nu_bank_entry.delayed_group = site.delayed_group;
41,542,335 ✔
278

279
    // Score the next-event contribution of this fission neutron. It is done
280
    // here, rather than inside sample_fission_neutron(), so that the site is
281
    // known to have survived the time cutoff and to have been banked -- a
282
    // rejected site is never born and must not contribute. The emitted
283
    // particle is the site, not the colliding neutron, so it carries the
284
    // site's weight and (for delayed neutrons) its precursor decay time.
285
    if (!model::active_point_tallies.empty()) {
41,542,335 ✔
286
      score_point_tally_fission(p, i_nuclide, rx, site);
54,087 ✔
287
    }
288
  }
289

290
  // If shared fission bank was full, and no fissions could be added,
291
  // set the particle fission flag to false.
292
  if (n_sites_stored == 0) {
32,497,902 !
293
    p.fission() = false;
×
294
    return;
×
295
  }
296

297
  // Set nu to the number of fission sites successfully stored. If the fission
298
  // bank was not found to be full then these values are already equivalent.
299
  nu = n_sites_stored;
32,497,902 ✔
300

301
  // Store the total weight banked for analog fission tallies
302
  p.n_bank() = nu;
32,497,902 ✔
303
  p.wgt_bank() = nu / weight;
32,497,902 ✔
304
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
292,481,118 ✔
305
    p.n_delayed_bank(d) = nu_d[d];
259,983,216 ✔
306
  }
307
}
308

309
void sample_photon_reaction(Particle& p)
34,339,376 ✔
310
{
311
  // Kill photon if below energy cutoff -- an extra check is made here because
312
  // photons with energy below the cutoff may have been produced by neutrons
313
  // reactions or atomic relaxation
314
  int photon = ParticleType::photon().transport_index();
34,339,376 ✔
315
  if (p.E() < settings::energy_cutoff[photon]) {
34,339,376 ✔
316
    p.E() = 0.0;
55 ✔
317
    p.wgt() = 0.0;
55 ✔
318
    return;
55 ✔
319
  }
320

321
  // Sample element within material
322
  int i_element = sample_element(p);
34,339,321 ✔
323
  const auto& micro {p.photon_xs(i_element)};
34,339,321 ✔
324
  const auto& element {*data::elements[i_element]};
34,339,321 ✔
325

326
  // Calculate photon energy over electron rest mass equivalent
327
  double alpha = p.E() / MASS_ELECTRON_EV;
34,339,321 ✔
328

329
  // For tallying purposes, this routine might be called directly. In that
330
  // case, we need to sample a reaction via the cutoff variable
331
  double prob = 0.0;
34,339,321 ✔
332
  double cutoff = prn(p.current_seed()) * micro.total;
34,339,321 ✔
333

334
  // Coherent (Rayleigh) scattering
335
  prob += micro.coherent;
34,339,321 ✔
336
  if (prob > cutoff) {
34,339,321 ✔
337
    p.mu() = element.rayleigh_scatter(alpha, p.current_seed());
1,667,002 ✔
338
    p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
1,667,002 ✔
339
    p.event() = TallyEvent::SCATTER;
1,667,002 ✔
340
    p.event_mt() = COHERENT;
1,667,002 ✔
341
    return;
1,667,002 ✔
342
  }
343

344
  // Incoherent (Compton) scattering
345
  prob += micro.incoherent;
32,672,319 ✔
346
  if (prob > cutoff) {
32,672,319 ✔
347
    double alpha_out;
24,582,712 ✔
348
    int i_shell;
24,582,712 ✔
349
    element.compton_scatter(
24,582,712 ✔
350
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
24,582,712 ✔
351

352
    // Determine binding energy of shell. The binding energy is 0.0 if
353
    // doppler broadening is not used.
354
    double e_b;
24,582,712 ✔
355
    if (i_shell == -1) {
24,582,712 !
356
      e_b = 0.0;
357
    } else {
358
      e_b = element.binding_energy_[i_shell];
24,582,712 ✔
359
    }
360

361
    // Create Compton electron
362
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
24,582,712 ✔
363
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
24,582,712 ✔
364
    int electron = ParticleType::electron().transport_index();
24,582,712 ✔
365
    if (E_electron >= settings::energy_cutoff[electron]) {
24,582,712 !
366
      double mu_electron = (alpha - alpha_out * p.mu()) /
24,582,712 ✔
367
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
24,582,712 ✔
368
                                     2.0 * alpha * alpha_out * p.mu());
24,582,712 ✔
369
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
24,582,712 ✔
370
      process_charged_secondary(p, u, E_electron, ParticleType::electron());
24,582,712 ✔
371
    }
372

373
    // Allow electrons to fill orbital and produce Auger electrons and
374
    // fluorescent photons. Since Compton subshell data does not match atomic
375
    // relaxation data, use the mapping between the data to find the subshell
376
    if (settings::atomic_relaxation && element.has_atomic_relaxation_ &&
24,425,654 !
377
        i_shell >= 0 && element.subshell_map_[i_shell] >= 0) {
49,008,366 !
378
      element.atomic_relaxation(element.subshell_map_[i_shell], p);
24,425,654 ✔
379
    }
380

381
    phi += PI;
24,582,712 ✔
382
    p.E() = alpha_out * MASS_ELECTRON_EV;
24,582,712 ✔
383
    p.u() = rotate_angle(p.u(), p.mu(), &phi, p.current_seed());
24,582,712 ✔
384
    p.event() = TallyEvent::SCATTER;
24,582,712 ✔
385
    p.event_mt() = INCOHERENT;
24,582,712 ✔
386
    return;
24,582,712 ✔
387
  }
388

389
  // Photoelectric effect
390
  double prob_after = prob + micro.photoelectric;
8,089,607 ✔
391

392
  if (prob_after > cutoff) {
8,089,607 ✔
393
    // Get grid index, interpolation factor, and bounding subshell
394
    // cross sections
395
    int i_grid = micro.index_grid;
7,892,102 ✔
396
    double f = micro.interp_factor;
7,892,102 ✔
397
    tensor::View<const double> xs_lower = element.cross_sections_.slice(i_grid);
7,892,102 ✔
398
    tensor::View<const double> xs_upper =
7,892,102 ✔
399
      element.cross_sections_.slice(i_grid + 1);
7,892,102 ✔
400

401
    for (int i_shell = 0; i_shell < element.shells_.size(); ++i_shell) {
27,649,589 !
402
      const auto& shell {element.shells_[i_shell]};
27,649,589 ✔
403

404
      // Check threshold of reaction
405
      if (xs_lower(i_shell) == 0)
27,649,589 ✔
406
        continue;
10,384,038 ✔
407

408
      //  Evaluation subshell photoionization cross section
409
      prob += std::exp(
17,265,551 ✔
410
        xs_lower(i_shell) + f * (xs_upper(i_shell) - xs_lower(i_shell)));
17,265,551 ✔
411

412
      if (prob > cutoff) {
17,265,551 ✔
413
        // Determine binding energy based on whether atomic relaxation data is
414
        // present (if not, use value from Compton profile data)
415
        double binding_energy = element.has_atomic_relaxation_
7,892,102 ✔
416
                                  ? shell.binding_energy
7,892,102 !
417
                                  : element.binding_energy_[i_shell];
×
418

419
        // Determine energy of secondary electron
420
        double E_electron = p.E() - binding_energy;
7,892,102 ✔
421

422
        // Sample mu using non-relativistic Sauter distribution.
423
        // See Eqns 3.19 and 3.20 in "Implementing a photon physics
424
        // model in Serpent 2" by Toni Kaltiaisenaho
425
        double mu;
11,844,465 ✔
426
        while (true) {
11,844,465 ✔
427
          double r = prn(p.current_seed());
11,844,465 ✔
428
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
11,844,465 ✔
429
            double rel_vel =
7,892,102 ✔
430
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
7,892,102 ✔
431
              (E_electron + MASS_ELECTRON_EV);
7,892,102 ✔
432
            mu =
7,892,102 ✔
433
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
7,892,102 ✔
434
            break;
7,892,102 ✔
435
          }
436
        }
437

438
        double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
7,892,102 ✔
439
        Direction u;
7,892,102 ✔
440
        u.x = mu;
7,892,102 ✔
441
        u.y = std::sqrt(1.0 - mu * mu) * std::cos(phi);
7,892,102 ✔
442
        u.z = std::sqrt(1.0 - mu * mu) * std::sin(phi);
7,892,102 ✔
443

444
        // Process secondary electron at the photon collision site.
445
        process_charged_secondary(p, u, E_electron, ParticleType::electron());
7,892,102 ✔
446

447
        // Allow electrons to fill orbital and produce auger electrons
448
        // and fluorescent photons
449
        if (settings::atomic_relaxation) {
7,892,102 ✔
450
          element.atomic_relaxation(i_shell, p);
7,672,102 ✔
451
        }
452
        p.event() = TallyEvent::ABSORB;
7,892,102 ✔
453
        p.event_mt() = 533 + shell.index_subshell;
7,892,102 ✔
454
        p.wgt() = 0.0;
7,892,102 ✔
455
        p.E() = 0.0;
7,892,102 ✔
456
        return;
7,892,102 ✔
457
      }
458
    }
459
  }
15,784,204 ✔
460
  prob = prob_after;
197,505 ✔
461

462
  // Pair production
463
  prob += micro.pair_production;
197,505 ✔
464
  if (prob > cutoff) {
197,505 !
465
    double E_electron, E_positron;
197,505 ✔
466
    double mu_electron, mu_positron;
197,505 ✔
467
    element.pair_production(alpha, &E_electron, &E_positron, &mu_electron,
197,505 ✔
468
      &mu_positron, p.current_seed());
469

470
    // Process secondary electron at the photon collision site.
471
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
197,505 ✔
472
    process_charged_secondary(p, u, E_electron, ParticleType::electron());
197,505 ✔
473

474
    // Process secondary positron at the photon collision site.
475
    u = rotate_angle(p.u(), mu_positron, nullptr, p.current_seed());
197,505 ✔
476
    process_charged_secondary(p, u, E_positron, ParticleType::positron());
197,505 ✔
477
    p.event() = TallyEvent::ABSORB;
197,505 ✔
478
    p.event_mt() = PAIR_PROD;
197,505 ✔
479
    p.wgt() = 0.0;
197,505 ✔
480
    p.E() = 0.0;
197,505 ✔
481
  }
482
}
483

484
void process_charged_secondary(
87,544,948 ✔
485
  Particle& p, Direction u, double E, ParticleType type)
486
{
487
  int idx = type.transport_index();
87,544,948 ✔
488
  if (idx == C_NONE || E < settings::energy_cutoff[idx])
87,544,948 !
489
    return;
490

491
  if (settings::electron_treatment == ElectronTreatment::TTB) {
87,544,948 ✔
492
    thick_target_bremsstrahlung(p, type, u, E);
87,049,486 ✔
493
  }
494

495
  if (type == ParticleType::positron()) {
87,544,948 ✔
496
    Direction photon_u = isotropic_direction(p.current_seed());
197,505 ✔
497
    p.create_secondary(
197,505 ✔
498
      p.wgt(), photon_u, MASS_ELECTRON_EV, ParticleType::photon());
197,505 ✔
499
    p.create_secondary(
197,505 ✔
500
      p.wgt(), -photon_u, MASS_ELECTRON_EV, ParticleType::photon());
197,505 ✔
501

502
    // The annihilation photons are now emitted during the parent photon
503
    // collision. Offset the pair-production Q value in the energy balance so
504
    // heating matches the prior explicit positron slowing-down sequence.
505
    p.bank_second_E() -= 2 * MASS_ELECTRON_EV;
197,505 ✔
506
  }
507
}
508

509
void sample_electron_reaction(Particle& p)
110,000 ✔
510
{
511
  // TODO: create reaction types
512

513
  if (settings::electron_treatment == ElectronTreatment::TTB) {
110,000 !
514
    thick_target_bremsstrahlung(p);
110,000 ✔
515
  }
516

517
  p.E() = 0.0;
110,000 ✔
518
  p.wgt() = 0.0;
110,000 ✔
519
  p.event() = TallyEvent::ABSORB;
110,000 ✔
520
}
110,000 ✔
521

522
void sample_positron_reaction(Particle& p)
×
523
{
524
  // TODO: create reaction types
525

526
  if (settings::electron_treatment == ElectronTreatment::TTB) {
×
527
    thick_target_bremsstrahlung(p);
×
528
  }
529

530
  // Sample angle isotropically
531
  Direction u = isotropic_direction(p.current_seed());
×
532

533
  // Create annihilation photon pair traveling in opposite directions
534
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon());
×
535
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon());
×
536

537
  p.E() = 0.0;
×
538
  p.wgt() = 0.0;
×
539
  p.event() = TallyEvent::ABSORB;
×
540
}
×
541

542
int sample_nuclide(Particle& p)
1,574,299,225 ✔
543
{
544
  // Sample cumulative distribution function
545
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,574,299,225 ✔
546

547
  // Get pointers to nuclide/density arrays
548
  const auto& mat {model::materials[p.material()]};
1,574,299,225 ✔
549
  int n = mat->nuclide_.size();
1,574,299,225 ✔
550

551
  double prob = 0.0;
1,574,299,225 ✔
552
  for (int i = 0; i < n; ++i) {
2,147,483,647 !
553
    // Get atom density
554
    int i_nuclide = mat->nuclide_[i];
2,147,483,647 ✔
555
    double atom_density = mat->atom_density(i, p.density_mult());
2,147,483,647 ✔
556

557
    // Increment probability to compare to cutoff
558
    prob += atom_density * p.neutron_xs(i_nuclide).total;
2,147,483,647 ✔
559
    if (prob >= cutoff)
2,147,483,647 ✔
560
      return i_nuclide;
1,574,299,225 ✔
561
  }
562

563
  // If we reach here, no nuclide was sampled
564
  p.write_restart();
×
565
  throw std::runtime_error {"Did not sample any nuclide during collision."};
×
566
}
567

568
int sample_element(Particle& p)
34,339,321 ✔
569
{
570
  // Sample cumulative distribution function
571
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
34,339,321 ✔
572

573
  // Get pointers to elements, densities
574
  const auto& mat {model::materials[p.material()]};
34,339,321 ✔
575

576
  double prob = 0.0;
34,339,321 ✔
577
  for (int i = 0; i < mat->element_.size(); ++i) {
138,553,079 !
578
    // Find atom density
579
    int i_element = mat->element_[i];
138,553,079 ✔
580
    double atom_density = mat->atom_density(i, p.density_mult());
138,553,079 ✔
581

582
    // Determine microscopic cross section
583
    double sigma = atom_density * p.photon_xs(i_element).total;
138,553,079 ✔
584

585
    // Increment probability to compare to cutoff
586
    prob += sigma;
138,553,079 ✔
587
    if (prob > cutoff) {
138,553,079 ✔
588
      // Save which nuclide particle had collision with for tally purpose
589
      p.event_nuclide() = mat->nuclide_[i];
34,339,321 ✔
590

591
      return i_element;
34,339,321 ✔
592
    }
593
  }
594

595
  // If we made it here, no element was sampled
596
  p.write_restart();
×
597
  fatal_error("Did not sample any element during collision.");
×
598
}
599

600
Reaction& sample_fission(int i_nuclide, Particle& p)
176,648,107 ✔
601
{
602
  // Get pointer to nuclide
603
  const auto& nuc {data::nuclides[i_nuclide]};
176,648,107 ✔
604

605
  // If we're in the URR, by default use the first fission reaction. We also
606
  // default to the first reaction if we know that there are no partial fission
607
  // reactions
608
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
176,648,107 ✔
609
    return *nuc->fission_rx_[0];
176,591,174 ✔
610
  }
611

612
  // Check to see if we are in a windowed multipole range.  WMP only supports
613
  // the first fission reaction.
614
  if (nuc->multipole_) {
56,933 ✔
615
    if (p.E() >= nuc->multipole_->E_min_ && p.E() <= nuc->multipole_->E_max_) {
2,849 !
616
      return *nuc->fission_rx_[0];
1,991 ✔
617
    }
618
  }
619

620
  // Get grid index and interpolation factor and sample fission cdf
621
  const auto& micro = p.neutron_xs(i_nuclide);
54,942 ✔
622
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
54,942 ✔
623
  double prob = 0.0;
54,942 ✔
624

625
  // Loop through each partial fission reaction type
626
  for (auto& rx : nuc->fission_rx_) {
55,052 !
627
    // add to cumulative probability
628
    prob += rx->xs(micro);
55,052 ✔
629

630
    // Create fission bank sites if fission occurs
631
    if (prob > cutoff)
55,052 ✔
632
      return *rx;
54,942 ✔
633
  }
634

635
  // If we reached here, no reaction was sampled
636
  throw std::runtime_error {
×
637
    "No fission reaction was sampled for " + nuc->name_};
×
638
}
639

640
void sample_photon_product(
2,937,187 ✔
641
  int i_nuclide, Particle& p, int* i_rx, int* i_product)
642
{
643
  // Get grid index and interpolation factor and sample photon production cdf
644
  const auto& micro = p.neutron_xs(i_nuclide);
2,937,187 ✔
645
  double cutoff = prn(p.current_seed()) * micro.photon_prod;
2,937,187 ✔
646
  double prob = 0.0;
2,937,187 ✔
647

648
  // Loop through each reaction type
649
  const auto& nuc {data::nuclides[i_nuclide]};
2,937,187 ✔
650
  for (int i = 0; i < nuc->reactions_.size(); ++i) {
54,189,773 !
651
    // Evaluate neutron cross section
652
    const auto& rx = nuc->reactions_[i];
54,189,773 ✔
653
    double xs = rx->xs(micro);
54,189,773 ✔
654

655
    // if cross section is zero for this reaction, skip it
656
    if (xs == 0.0)
54,189,773 ✔
657
      continue;
33,772,475 ✔
658

659
    for (int j = 0; j < rx->products_.size(); ++j) {
148,911,565 ✔
660
      if (rx->products_[j].particle_.is_photon()) {
131,431,454 ✔
661
        // For fission, artificially increase the photon yield to account
662
        // for delayed photons
663
        double f = 1.0;
115,952,606 ✔
664
        if (settings::delayed_photon_scaling) {
115,952,606 !
665
          if (is_fission(rx->mt_)) {
115,952,606 ✔
666
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
540,826 !
667
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
540,826 ✔
668
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
540,826 ✔
669
              f = (energy_prompt + energy_delayed) / (energy_prompt);
540,826 ✔
670
            }
671
          }
672
        }
673

674
        // add to cumulative probability
675
        prob += f * (*rx->products_[j].yield_)(p.E()) * xs;
115,952,606 ✔
676

677
        *i_rx = i;
115,952,606 ✔
678
        *i_product = j;
115,952,606 ✔
679
        if (prob > cutoff)
115,952,606 ✔
680
          return;
681
      }
682
    }
683
  }
684
}
685

686
void absorption(Particle& p, int i_nuclide)
1,574,186,287 ✔
687
{
688
  if (settings::survival_biasing) {
1,574,186,287 ✔
689
    // Determine weight absorbed in survival biasing
690
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
44,534,919 ✔
691
                              p.neutron_xs(i_nuclide).total;
44,534,919 ✔
692

693
    // Adjust weight of particle by probability of absorption
694
    p.wgt() -= wgt_absorb;
44,534,919 ✔
695

696
    // Score implicit absorption estimate of keff
697
    if (settings::run_mode == RunMode::EIGENVALUE) {
44,534,919 ✔
698
      p.keff_tally_absorption() += wgt_absorb *
499,950 ✔
699
                                   p.neutron_xs(i_nuclide).nu_fission /
499,950 ✔
700
                                   p.neutron_xs(i_nuclide).absorption;
499,950 ✔
701
    }
702
  } else {
703
    // See if disappearance reaction happens
704
    if (p.neutron_xs(i_nuclide).absorption >
1,529,651,368 ✔
705
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
1,529,651,368 ✔
706
      // Score absorption estimate of keff
707
      if (settings::run_mode == RunMode::EIGENVALUE) {
35,825,858 ✔
708
        p.keff_tally_absorption() += p.wgt() *
25,473,972 ✔
709
                                     p.neutron_xs(i_nuclide).nu_fission /
25,473,972 ✔
710
                                     p.neutron_xs(i_nuclide).absorption;
25,473,972 ✔
711
      }
712

713
      p.wgt() = 0.0;
35,825,858 ✔
714
      p.event() = TallyEvent::ABSORB;
35,825,858 ✔
715
      if (!p.fission()) {
35,825,858 ✔
716
        p.event_mt() = N_DISAPPEAR;
23,011,748 ✔
717
      }
718
    }
719
  }
720
}
1,574,186,287 ✔
721

722
void scatter(Particle& p, int i_nuclide)
1,538,313,020 ✔
723
{
724
  // copy incoming direction
725
  Direction u_old {p.u()};
1,538,313,020 ✔
726

727
  // Get pointer to nuclide and grid index/interpolation factor
728
  const auto& nuc {data::nuclides[i_nuclide]};
1,538,313,020 ✔
729
  const auto& micro {p.neutron_xs(i_nuclide)};
1,538,313,020 ✔
730
  int i_temp = micro.index_temp;
1,538,313,020 ✔
731

732
  // For tallying purposes, this routine might be called directly. In that
733
  // case, we need to sample a reaction via the cutoff variable
734
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
1,538,313,020 ✔
735
  bool sampled = false;
1,538,313,020 ✔
736

737
  // Calculate elastic cross section if it wasn't precalculated
738
  if (micro.elastic == CACHE_INVALID) {
1,538,313,020 ✔
739
    nuc->calculate_elastic_xs(p);
1,274,484,461 ✔
740
  }
741

742
  double prob = micro.elastic - micro.thermal;
1,538,313,020 ✔
743
  if (prob > cutoff) {
1,538,313,020 ✔
744
    // =======================================================================
745
    // NON-S(A,B) ELASTIC SCATTERING
746

747
    // Determine temperature
748
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
1,376,807,884 ✔
749

750
    // Perform collision physics for elastic scattering
751
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
1,376,807,884 ✔
752

753
    p.event_mt() = ELASTIC;
1,376,807,884 ✔
754
    sampled = true;
1,376,807,884 ✔
755
  }
756

757
  prob = micro.elastic;
1,538,313,020 ✔
758
  if (prob > cutoff && !sampled) {
1,538,313,020 ✔
759
    // =======================================================================
760
    // S(A,B) SCATTERING
761

762
    sab_scatter(i_nuclide, micro.index_sab, p);
135,576,552 ✔
763

764
    p.event_mt() = ELASTIC;
135,576,552 ✔
765
    sampled = true;
135,576,552 ✔
766
  }
767

768
  if (!sampled) {
1,538,313,020 ✔
769
    // =======================================================================
770
    // INELASTIC SCATTERING
771

772
    int n = nuc->index_inelastic_scatter_.size();
25,928,584 ✔
773
    int i = 0;
25,928,584 ✔
774
    for (int j = 0; j < n && prob < cutoff; ++j) {
491,465,281 ✔
775
      i = nuc->index_inelastic_scatter_[j];
465,536,697 ✔
776

777
      // add to cumulative probability
778
      prob += nuc->reactions_[i]->xs(micro);
465,536,697 ✔
779
    }
780

781
    // Perform collision physics for inelastic scattering
782
    const auto& rx {nuc->reactions_[i]};
25,928,584 ✔
783
    inelastic_scatter(i_nuclide, *rx, p);
25,928,584 ✔
784
    p.event_mt() = rx->mt_;
25,928,584 ✔
785
  }
786

787
  // Set event component
788
  p.event() = TallyEvent::SCATTER;
1,538,313,020 ✔
789

790
  // Sample new outgoing angle for isotropic-in-lab scattering
791
  const auto& mat {model::materials[p.material()]};
1,538,313,020 !
792
  if (!mat->p0_.empty()) {
1,538,313,020 !
793
    int i_nuc_mat = mat->mat_nuclide_index_[i_nuclide];
326,370 ✔
794
    if (mat->p0_[i_nuc_mat]) {
326,370 !
795
      // Sample isotropic-in-lab outgoing direction
796
      p.u() = isotropic_direction(p.current_seed());
326,370 ✔
797
      p.mu() = u_old.dot(p.u());
326,370 ✔
798
    }
799
  }
800
}
1,538,313,020 ✔
801

802
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
1,376,807,884 ✔
803
{
804
  // get pointer to nuclide
805
  const auto& nuc {data::nuclides[i_nuclide]};
1,376,807,884 ✔
806

807
  double vel = std::sqrt(p.E());
1,376,807,884 ✔
808
  double awr = nuc->awr_;
1,376,807,884 ✔
809

810
  // Neutron velocity in LAB
811
  Direction v_n = vel * p.u();
1,376,807,884 ✔
812

813
  // Sample velocity of target nucleus
814
  Direction v_t {};
1,376,807,884 ✔
815
  if (!p.neutron_xs(i_nuclide).use_ptable) {
1,376,807,884 ✔
816
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
1,329,153,042 ✔
817
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
1,329,153,042 ✔
818
  }
819

820
  // Velocity of center-of-mass
821
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
1,376,807,884 ✔
822

823
  // Transform to CM frame
824
  v_n -= v_cm;
1,376,807,884 ✔
825

826
  // Find speed of neutron in CM
827
  vel = v_n.norm();
1,376,807,884 ✔
828

829
  if (!model::active_point_tallies.empty()) {
1,376,807,884 ✔
830
    score_point_tally_elastic(p, i_nuclide, rx, 0, v_t);
6,496,677 ✔
831
  }
832

833
  // Sample scattering angle, checking if angle distribution is present (assume
834
  // isotropic otherwise)
835
  double mu_cm;
1,376,807,884 ✔
836
  auto& d = rx.products_[0].distribution_[0];
1,376,807,884 !
837
  auto d_ = dynamic_cast<UncorrelatedAngleEnergy*>(d.get());
1,376,807,884 !
838
  if (!d_->angle().empty()) {
1,376,807,884 !
839
    mu_cm = d_->angle().sample(p.E(), p.current_seed());
1,376,807,884 ✔
840
  } else {
841
    mu_cm = uniform_distribution(-1., 1., p.current_seed());
×
842
  }
843

844
  // Determine direction cosines in CM
845
  Direction u_cm = v_n / vel;
1,376,807,884 ✔
846

847
  // Rotate neutron velocity vector to new angle -- note that the speed of the
848
  // neutron in CM does not change in elastic scattering. However, the speed
849
  // will change when we convert back to LAB
850
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
1,376,807,884 ✔
851

852
  // Transform back to LAB frame
853
  v_n += v_cm;
1,376,807,884 ✔
854

855
  p.E() = v_n.dot(v_n);
1,376,807,884 ✔
856
  vel = std::sqrt(p.E());
1,376,807,884 ✔
857

858
  // compute cosine of scattering angle in LAB frame by taking dot product of
859
  // neutron's pre- and post-collision angle
860
  p.mu() = p.u().dot(v_n) / vel;
1,376,807,884 ✔
861

862
  // Set energy and direction of particle in LAB frame
863
  p.u() = v_n / vel;
1,376,807,884 !
864

865
  // Because of floating-point roundoff, it may be possible for mu_lab to be
866
  // outside of the range [-1,1). In these cases, we just set mu_lab to exactly
867
  // -1 or 1
868
  if (std::abs(p.mu()) > 1.0)
1,376,807,884 !
869
    p.mu() = std::copysign(1.0, p.mu());
×
870
}
1,376,807,884 ✔
871

872
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
135,576,552 ✔
873
{
874
  // Determine temperature index
875
  const auto& micro {p.neutron_xs(i_nuclide)};
135,576,552 ✔
876
  int i_temp = micro.index_temp_sab;
135,576,552 ✔
877

878
  // Sample energy and angle
879
  double E_out;
135,576,552 ✔
880
  auto& sab = data::thermal_scatt[i_sab]->data_[i_temp];
135,576,552 ✔
881

882
  if (!model::active_point_tallies.empty()) {
135,576,552 ✔
883
    score_point_tally_sab(p, i_nuclide, sab, micro);
4,715,304 ✔
884
  }
885

886
  sab.sample(micro, p.E(), &E_out, &p.mu(), p.current_seed());
135,576,552 ✔
887

888
  // Set energy to outgoing, change direction of particle
889
  p.E() = E_out;
135,576,552 ✔
890
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
135,576,552 ✔
891
}
135,576,552 ✔
892

893
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
1,329,153,042 ✔
894
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
895
{
896
  // check if nuclide is a resonant scatterer
897
  ResScatMethod sampling_method;
1,329,153,042 ✔
898
  if (nuc.resonant_) {
1,329,153,042 ✔
899

900
    // sampling method to use
901
    sampling_method = settings::res_scat_method;
84,557 ✔
902

903
    // upper resonance scattering energy bound (target is at rest above this E)
904
    if (E > settings::res_scat_energy_max) {
84,557 ✔
905
      return {};
40,755 ✔
906

907
      // lower resonance scattering energy bound (should be no resonances below)
908
    } else if (E < settings::res_scat_energy_min) {
43,802 ✔
909
      sampling_method = ResScatMethod::cxs;
910
    }
911

912
    // otherwise, use free gas model
913
  } else {
914
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
1,329,068,485 ✔
915
      return {};
493,798,483 ✔
916
    } else {
917
      sampling_method = ResScatMethod::cxs;
918
    }
919
  }
920

921
  // use appropriate target velocity sampling method
922
  switch (sampling_method) {
18,810 !
923
  case ResScatMethod::cxs:
835,294,994 ✔
924

925
    // sample target velocity with the constant cross section (cxs) approx.
926
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
835,294,994 ✔
927

928
  case ResScatMethod::dbrc:
18,810 ✔
929
  case ResScatMethod::rvs: {
18,810 ✔
930
    double E_red = std::sqrt(nuc.awr_ * E / kT);
18,810 ✔
931
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
37,620 !
932
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
18,810 ✔
933

934
    // find lower and upper energy bound indices
935
    // lower index
936
    int i_E_low;
18,810 ✔
937
    if (E_low < nuc.energy_0K_.front()) {
18,810 !
938
      i_E_low = 0;
939
    } else if (E_low > nuc.energy_0K_.back()) {
18,810 !
940
      i_E_low = nuc.energy_0K_.size() - 2;
×
941
    } else {
942
      i_E_low =
18,810 ✔
943
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
18,810 ✔
944
    }
945

946
    // upper index
947
    int i_E_up;
18,810 ✔
948
    if (E_up < nuc.energy_0K_.front()) {
18,810 !
949
      i_E_up = 0;
950
    } else if (E_up > nuc.energy_0K_.back()) {
18,810 !
951
      i_E_up = nuc.energy_0K_.size() - 2;
×
952
    } else {
953
      i_E_up =
18,810 ✔
954
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_up);
18,810 ✔
955
    }
956

957
    if (i_E_up == i_E_low) {
18,810 ✔
958
      // Handle degenerate case -- if the upper/lower bounds occur for the same
959
      // index, then using cxs is probably a good approximation
960
      return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
18,810 ✔
961
    }
962

963
    if (sampling_method == ResScatMethod::dbrc) {
15,532 !
964
      // interpolate xs since we're not exactly at the energy indices
965
      double xs_low = nuc.elastic_0K_[i_E_low];
×
966
      double m = (nuc.elastic_0K_[i_E_low + 1] - xs_low) /
×
967
                 (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
×
968
      xs_low += m * (E_low - nuc.energy_0K_[i_E_low]);
×
969
      double xs_up = nuc.elastic_0K_[i_E_up];
×
970
      m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) /
×
971
          (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
×
972
      xs_up += m * (E_up - nuc.energy_0K_[i_E_up]);
×
973

974
      // get max 0K xs value over range of practical relative energies
975
      double xs_max = *std::max_element(
×
976
        &nuc.elastic_0K_[i_E_low + 1], &nuc.elastic_0K_[i_E_up + 1]);
×
977
      xs_max = std::max({xs_low, xs_max, xs_up});
×
978

979
      while (true) {
×
980
        double E_rel;
×
981
        Direction v_target;
×
982
        while (true) {
×
983
          // sample target velocity with the constant cross section (cxs)
984
          // approx.
985
          v_target = sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
×
986
          Direction v_rel = v_neut - v_target;
×
987
          E_rel = v_rel.dot(v_rel);
×
988
          if (E_rel < E_up)
×
989
            break;
990
        }
991

992
        // perform Doppler broadening rejection correction (dbrc)
993
        double xs_0K = nuc.elastic_xs_0K(E_rel);
×
994
        double R = xs_0K / xs_max;
×
995
        if (prn(seed) < R)
×
996
          return v_target;
×
997
      }
998

999
    } else if (sampling_method == ResScatMethod::rvs) {
15,532 ✔
1000
      // interpolate xs CDF since we're not exactly at the energy indices
1001
      // cdf value at lower bound attainable energy
1002
      double cdf_low = 0.0;
15,532 ✔
1003
      if (E_low > nuc.energy_0K_.front()) {
15,532 !
1004
        double m = (nuc.xs_cdf_[i_E_low + 1] - nuc.xs_cdf_[i_E_low]) /
15,532 ✔
1005
                   (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
15,532 ✔
1006
        cdf_low = nuc.xs_cdf_[i_E_low] + m * (E_low - nuc.energy_0K_[i_E_low]);
15,532 ✔
1007
      }
1008

1009
      // cdf value at upper bound attainable energy
1010
      double m = (nuc.xs_cdf_[i_E_up + 1] - nuc.xs_cdf_[i_E_up]) /
15,532 ✔
1011
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
15,532 ✔
1012
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
15,532 ✔
1013

1014
      while (true) {
325,908 ✔
1015
        // directly sample Maxwellian
1016
        double E_t = -kT * std::log(prn(seed));
170,720 ✔
1017

1018
        // sample a relative energy using the xs cdf
1019
        double cdf_rel = cdf_low + prn(seed) * (cdf_up - cdf_low);
170,720 ✔
1020
        int i_E_rel = lower_bound_index(nuc.xs_cdf_.begin() + i_E_low,
170,720 ✔
1021
          nuc.xs_cdf_.begin() + i_E_up + 2, cdf_rel);
170,720 ✔
1022
        double E_rel = nuc.energy_0K_[i_E_low + i_E_rel];
170,720 ✔
1023
        double m = (nuc.xs_cdf_[i_E_low + i_E_rel + 1] -
170,720 ✔
1024
                     nuc.xs_cdf_[i_E_low + i_E_rel]) /
170,720 ✔
1025
                   (nuc.energy_0K_[i_E_low + i_E_rel + 1] -
170,720 ✔
1026
                     nuc.energy_0K_[i_E_low + i_E_rel]);
170,720 ✔
1027
        E_rel += (cdf_rel - nuc.xs_cdf_[i_E_low + i_E_rel]) / m;
170,720 ✔
1028

1029
        // perform rejection sampling on cosine between
1030
        // neutron and target velocities
1031
        double mu = (E_t + nuc.awr_ * (E - E_rel)) /
170,720 ✔
1032
                    (2.0 * std::sqrt(nuc.awr_ * E * E_t));
170,720 ✔
1033

1034
        if (std::abs(mu) < 1.0) {
170,720 ✔
1035
          // set and accept target velocity
1036
          E_t /= nuc.awr_;
15,532 ✔
1037
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
15,532 ✔
1038
        }
1039
      }
155,188 ✔
1040
    }
1041
  } // case RVS, DBRC
1042
  } // switch (sampling_method)
1043

1044
  UNREACHABLE();
×
1045
}
1046

1047
Direction sample_cxs_target_velocity(
835,298,272 ✔
1048
  double awr, double E, Direction u, double kT, uint64_t* seed)
1049
{
1050
  double beta_vn = std::sqrt(awr * E / kT);
835,298,272 ✔
1051
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
835,298,272 ✔
1052

1053
  double beta_vt_sq;
1,019,454,007 ✔
1054
  double mu;
1,019,454,007 ✔
1055
  while (true) {
1,019,454,007 ✔
1056
    // Sample two random numbers
1057
    double r1 = prn(seed);
1,019,454,007 ✔
1058
    double r2 = prn(seed);
1,019,454,007 ✔
1059

1060
    if (prn(seed) < alpha) {
1,019,454,007 ✔
1061
      // With probability alpha, we sample the distribution p(y) =
1062
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1063
      // Carlo sampler
1064

1065
      beta_vt_sq = -std::log(r1 * r2);
292,996,249 ✔
1066

1067
    } else {
1068
      // With probability 1-alpha, we sample the distribution p(y) = y^2 *
1069
      // e^(-y^2). This can be done with sampling scheme C61 from the Monte
1070
      // Carlo sampler
1071

1072
      double c = std::cos(PI / 2.0 * prn(seed));
726,457,758 ✔
1073
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
726,457,758 ✔
1074
    }
1075

1076
    // Determine beta * vt
1077
    double beta_vt = std::sqrt(beta_vt_sq);
1,019,454,007 ✔
1078

1079
    // Sample cosine of angle between neutron and target velocity
1080
    mu = uniform_distribution(-1., 1., seed);
1,019,454,007 ✔
1081

1082
    // Determine rejection probability
1083
    double accept_prob =
1,019,454,007 ✔
1084
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
1,019,454,007 ✔
1085
      (beta_vn + beta_vt);
1,019,454,007 ✔
1086

1087
    // Perform rejection sampling on vt and mu
1088
    if (prn(seed) < accept_prob)
1,019,454,007 ✔
1089
      break;
1090
  }
1091

1092
  // Determine speed of target nucleus
1093
  double vt = std::sqrt(beta_vt_sq * kT / awr);
835,298,272 ✔
1094

1095
  // Determine velocity vector of target nucleus based on neutron's velocity
1096
  // and the sampled angle between them
1097
  return vt * rotate_angle(u, mu, nullptr, seed);
835,298,272 ✔
1098
}
1099

1100
void sample_fission_neutron(
41,542,335 ✔
1101
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1102
{
1103
  // Get attributes of particle
1104
  double E_in = p.E();
41,542,335 ✔
1105
  uint64_t* seed = p.current_seed();
41,542,335 ✔
1106

1107
  // Determine total nu, delayed nu, and delayed neutron fraction
1108
  const auto& nuc {data::nuclides[i_nuclide]};
41,542,335 ✔
1109
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
41,542,335 ✔
1110
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
41,542,335 ✔
1111
  double beta = nu_d / nu_t;
41,542,335 ✔
1112

1113
  if (prn(seed) < beta) {
41,542,335 ✔
1114
    // ====================================================================
1115
    // DELAYED NEUTRON SAMPLED
1116

1117
    // sampled delayed precursor group
1118
    double xi = prn(seed) * nu_d;
274,800 ✔
1119
    double prob = 0.0;
274,800 ✔
1120
    int group;
274,800 ✔
1121
    for (group = 1; group < nuc->n_precursor_; ++group) {
1,024,882 ✔
1122
      // determine delayed neutron precursor yield for group j
1123
      double yield = (*rx.products_[group].yield_)(E_in);
1,005,116 ✔
1124

1125
      // Check if this group is sampled
1126
      prob += yield;
1,005,116 ✔
1127
      if (xi < prob)
1,005,116 ✔
1128
        break;
1129
    }
1130

1131
    // if the sum of the probabilities is slightly less than one and the
1132
    // random number is greater, j will be greater than nuc %
1133
    // n_precursor -- check for this condition
1134
    group = std::min(group, nuc->n_precursor_);
274,800 !
1135

1136
    // set the delayed group for the particle born from fission
1137
    site->delayed_group = group;
274,800 ✔
1138

1139
    // Sample time of emission based on decay constant of precursor
1140
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
274,800 ✔
1141
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
274,800 ✔
1142

1143
  } else {
1144
    // ====================================================================
1145
    // PROMPT NEUTRON SAMPLED
1146

1147
    // set the delayed group for the particle born from fission to 0
1148
    site->delayed_group = 0;
41,267,535 ✔
1149
  }
1150

1151
  // sample from prompt neutron energy distribution
1152
  int n_sample = 0;
1153
  double mu;
41,542,338 ✔
1154
  while (true) {
41,542,338 ✔
1155
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
41,542,338 ✔
1156

1157
    // resample if energy is greater than maximum neutron energy
1158
    int neutron = ParticleType::neutron().transport_index();
41,542,338 ✔
1159
    if (site->E < data::energy_max[neutron])
41,542,338 ✔
1160
      break;
1161

1162
    // check for large number of resamples
1163
    ++n_sample;
3 ✔
1164
    if (n_sample == MAX_SAMPLE) {
3 !
1165
      // particle_write_restart(p)
1166
      fatal_error("Resampled energy distribution maximum number of times "
×
1167
                  "for nuclide " +
×
1168
                  nuc->name_);
×
1169
    }
1170
  }
1171

1172
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1173
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
41,542,335 ✔
1174
}
41,542,335 ✔
1175

1176
void inelastic_scatter(int i_nuclide, const Reaction& rx, Particle& p)
25,928,584 ✔
1177
{
1178
  // Get pointer to nuclide
1179
  const auto& nuc {data::nuclides[i_nuclide]};
25,928,584 ✔
1180

1181
  // copy energy of neutron
1182
  double E_in = p.E();
25,928,584 ✔
1183

1184
  // sample outgoing energy and scattering cosine
1185
  double E;
25,928,584 ✔
1186
  double mu;
25,928,584 ✔
1187
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
25,928,584 ✔
1188

1189
  double yield = (*rx.products_[0].yield_)(E_in);
25,928,584 ✔
1190

1191
  if (!model::active_point_tallies.empty()) {
25,928,584 ✔
1192
    score_point_tally_inelastic(p, i_nuclide, rx, 0, yield);
13,508 ✔
1193
  }
1194

1195
  // if scattering system is in center-of-mass, transfer cosine of scattering
1196
  // angle and outgoing energy from CM to LAB
1197
  if (rx.scatter_in_cm_) {
25,928,584 ✔
1198
    double E_cm = E;
25,834,714 ✔
1199

1200
    // determine outgoing energy in lab
1201
    double A = nuc->awr_;
25,834,714 ✔
1202
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
25,834,714 ✔
1203
                 ((A + 1.0) * (A + 1.0));
25,834,714 ✔
1204

1205
    // determine outgoing angle in lab
1206
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
25,834,714 ✔
1207
  }
1208

1209
  // Because of floating-point roundoff, it may be possible for mu to be
1210
  // outside of the range [-1,1). In these cases, we just set mu to exactly -1
1211
  // or 1
1212
  if (std::abs(mu) > 1.0)
25,928,584 !
1213
    mu = std::copysign(1.0, mu);
×
1214

1215
  // Set outgoing energy and scattering angle
1216
  p.E() = E;
25,928,584 ✔
1217
  p.mu() = mu;
25,928,584 ✔
1218

1219
  // change direction of particle
1220
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
25,928,584 !
1221

1222
  if (std::floor(yield) == yield && yield > 0) {
25,928,584 !
1223
    // If yield is integral, create exactly that many secondary particles
1224
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
26,069,574 ✔
1225
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
141,044 ✔
1226
    }
1227
  } else {
1228
    // Otherwise, change weight of particle based on yield
1229
    p.wgt() *= yield;
54 ✔
1230
  }
1231
}
25,928,584 ✔
1232

1233
void sample_secondary_photons(Particle& p, int i_nuclide)
77,894,784 ✔
1234
{
1235
  // Sample the number of photons produced
1236
  double y_t =
77,894,784 ✔
1237
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
77,894,784 ✔
1238
  double photon_wgt = p.wgt();
77,894,784 ✔
1239
  int y = 1;
77,894,784 ✔
1240

1241
  if (settings::use_decay_photons) {
77,894,784 ✔
1242
    // For decay photons, sample a single photon and modify the weight
1243
    if (y_t <= 0.0)
72,006 ✔
1244
      return;
1245
    photon_wgt *= y_t;
54,725 ✔
1246
  } else {
1247
    // For prompt photons, sample an integral number of photons with weight
1248
    // equal to the neutron's weight
1249
    y = static_cast<int>(y_t);
77,822,778 ✔
1250
    if (prn(p.current_seed()) <= y_t - y)
77,822,778 ✔
1251
      ++y;
2,119,271 ✔
1252
  }
1253

1254
  // Sample each secondary photon
1255
  for (int i = 0; i < y; ++i) {
80,814,690 ✔
1256
    // Sample the reaction and product
1257
    int i_rx;
2,937,187 ✔
1258
    int i_product;
2,937,187 ✔
1259
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
2,937,187 ✔
1260

1261
    // Sample the outgoing energy and angle
1262
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
2,937,187 ✔
1263
    double E;
2,937,187 ✔
1264
    double mu;
2,937,187 ✔
1265
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
2,937,187 ✔
1266

1267
    // Sample the new direction
1268
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
2,937,187 ✔
1269

1270
    // In a k-eigenvalue simulation, it's necessary to provide higher weight to
1271
    // secondary photons from non-fission reactions to properly balance energy
1272
    // release and deposition. See D. P. Griesheimer, S. J. Douglass, and M. H.
1273
    // Stedry, "Self-consistent energy normalization for quasistatic reactor
1274
    // calculations", Proc. PHYSOR, Cambridge, UK, Mar 29-Apr 2, 2020.
1275
    double wgt = photon_wgt;
2,937,187 ✔
1276
    if (settings::run_mode == RunMode::EIGENVALUE && !is_fission(rx->mt_)) {
2,937,187 ✔
1277
      wgt *= simulation::keff;
351,406 ✔
1278
    }
1279

1280
    // Create the secondary photon
1281
    bool created_photon = p.create_secondary(wgt, u, E, ParticleType::photon());
2,937,187 ✔
1282

1283
    // Pre-add photon energy to pht_storage so pht_secondary_particles()
1284
    // subtraction results in net zero
1285
    if (created_photon && !model::active_pulse_height_tallies.empty()) {
2,937,187 ✔
1286
      auto it = std::find(model::pulse_height_cells.begin(),
528 ✔
1287
        model::pulse_height_cells.end(), p.lowest_coord().cell());
528 !
1288
      if (it != model::pulse_height_cells.end()) {
528 !
1289
        int index = std::distance(model::pulse_height_cells.begin(), it);
528 ✔
1290
        p.pht_storage()[index] += E;
528 ✔
1291
      }
1292
    }
1293

1294
    // Tag secondary particle with parent nuclide
1295
    if (created_photon && settings::use_decay_photons) {
2,937,187 ✔
1296
      p.local_secondary_bank().back().parent_nuclide =
52,844 ✔
1297
        rx->products_[i_product].parent_nuclide_;
52,844 ✔
1298
    }
1299
  }
1300
}
1301

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

© 2026 Coveralls, Inc