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

openmc-dev / openmc / 38739185556

15 Oct 2026 01:01PM UTC coverage: 81.476%. First build
38739185556

Pull #3757

github

web-flow
Merge cb45408c9 into 46c4c6075
Pull Request #3757: Implementation of point detectors

20422 of 29653 branches covered (68.87%)

Branch coverage included in aggregate %.

465 of 556 new or added lines in 24 files covered. (83.63%)

63115 of 72876 relevant lines covered (86.61%)

42599939.22 hits per line

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

83.38
/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,176,283,634 ✔
46
{
47
  // Add to collision counter for particle
48
  ++(p.n_collision());
1,176,283,634 ✔
49
  p.secondary_bank_index() = p.local_secondary_bank().size();
1,176,283,634 !
50

51
  // Sample reaction for the material the particle is in
52
  switch (p.type().pdg_number()) {
1,176,283,634 !
53
  case PDG_NEUTRON:
1,151,206,825 ✔
54
    sample_neutron_reaction(p);
1,151,206,825 ✔
55
    break;
1,151,206,825 ✔
56
  case PDG_PHOTON:
24,996,809 ✔
57
    sample_photon_reaction(p);
24,996,809 ✔
58
    break;
24,996,809 ✔
59
  case PDG_ELECTRON:
80,000 ✔
60
    sample_electron_reaction(p);
80,000 ✔
61
    break;
80,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,176,283,634 ✔
70
    auto [ww_found, ww] = search_weight_window(p);
303,807,123 ✔
71
    if (!ww_found && p.type() == ParticleType::neutron()) {
303,807,123 ✔
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);
51,892 ✔
75
    } else if (settings::weight_window_checkpoint_collision) {
303,755,231 !
76
      // if collision checkpointing is on, apply weight window
77
      apply_weight_window(p, ww);
303,755,231 ✔
78
    }
79
  }
80

81
  // Kill particle if energy falls below cutoff
82
  int type = p.type().transport_index();
1,176,283,634 !
83
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
1,176,283,634 !
84
    p.wgt() = 0.0;
5,911,948 ✔
85
  }
86

87
  // Display information about collision
88
  if (settings::verbosity >= 10 || p.trace()) {
1,176,283,634 !
89
    std::string msg;
96 !
90
    if (p.event() == TallyEvent::KILL) {
96 !
91
      msg = fmt::format("    Killed. Energy = {} eV.", p.E());
×
92
    } else if (p.type().is_neutron()) {
96 !
93
      msg = fmt::format("    {} with {}. Energy = {} eV.",
192 ✔
94
        reaction_name(p.event_mt()), data::nuclides[p.event_nuclide()]->name_,
192 ✔
95
        p.E());
96 ✔
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);
96 ✔
104
  }
96 ✔
105
}
1,176,283,634 ✔
106

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

112
  // Save which nuclide particle had collision with
113
  p.event_nuclide() = i_nuclide;
1,151,206,825 ✔
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,151,206,825 ✔
121

122
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
1,151,206,825 ✔
123
    auto& rx = sample_fission(i_nuclide, p);
128,972,739 ✔
124
    if (settings::run_mode == RunMode::EIGENVALUE) {
128,972,739 ✔
125
      create_fission_sites(p, i_nuclide, rx);
110,654,297 ✔
126
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
18,318,442 ✔
127
               settings::create_fission_neutrons) {
128
      create_fission_sites(p, i_nuclide, rx);
539,498 ✔
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 &&
539,498 !
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_;
128,972,739 ✔
141
  }
142

143
  // Create secondary photons
144
  if (settings::photon_transport) {
1,151,206,825 ✔
145
    sample_secondary_photons(p, i_nuclide);
56,650,752 ✔
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,151,206,825 ✔
152
    absorption(p, i_nuclide);
1,151,124,550 ✔
153
  }
154
  if (!p.alive())
1,151,206,825 ✔
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,124,984,504 ✔
160
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
1,124,984,504 !
161
    if (!model::active_point_tallies.empty())
115,512 !
NEW
162
      fatal_error("Next-Event estimator does not support ncrystal materials");
×
163
    ncrystal_mat.scatter(p);
115,512 ✔
164
  } else {
165
    scatter(p, i_nuclide);
1,124,868,992 ✔
166
  }
167

168
  // Advance URR seed stream 'N' times after energy changes
169
  if (p.E() != p.E_last()) {
1,124,984,504 ✔
170
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
1,124,752,336 ✔
171
  }
172

173
  // Play russian roulette if there are no weight windows
174
  if (!settings::weight_windows_on)
1,124,984,504 ✔
175
    apply_russian_roulette(p);
842,142,373 ✔
176
}
177

178
void create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx)
111,193,795 ✔
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;
111,193,795 ✔
183

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

189
  // Sample the number of neutrons produced
190
  int nu = static_cast<int>(nu_t);
111,193,795 ✔
191
  if (prn(p.current_seed()) <= (nu_t - nu))
111,193,795 ✔
192
    ++nu;
19,454,426 ✔
193

194
  // If no neutrons were produced then don't continue
195
  if (nu == 0)
111,193,795 ✔
196
    return;
87,416,747 ✔
197

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

202
  // Clear out particle's nu fission bank
203
  p.nu_bank().clear();
23,777,048 ✔
204

205
  p.fission() = true;
23,777,048 ✔
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);
23,777,048 ✔
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;
23,777,048 ✔
214

215
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
54,197,640 ✔
216
    // Initialize fission site object with particle data
217
    SourceSite site;
30,420,592 ✔
218
    site.r = p.r();
30,420,592 ✔
219
    site.particle = ParticleType::neutron();
30,420,592 ✔
220
    site.time = p.time();
30,420,592 ✔
221
    site.wgt = 1. / weight;
30,420,592 ✔
222
    site.surf_id = 0;
30,420,592 ✔
223

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

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

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

239
    // Store fission site in bank
240
    if (use_fission_bank) {
30,420,592 ✔
241
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
30,158,481 ✔
242
      if (idx == -1) {
30,158,481 !
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()) {
30,158,481 ✔
258
        ifp(p, idx);
1,782,624 ✔
259
      }
260
    } else {
261
      site.wgt_born = p.wgt_born();
262,111 ✔
262
      site.wgt_ww_born = p.wgt_ww_born();
262,111 ✔
263
      site.n_split = p.n_split();
262,111 ✔
264
      p.local_secondary_bank().push_back(site);
262,111 ✔
265
      p.n_secondaries()++;
262,111 ✔
266
    }
267

268
    // Increment the number of neutrons born delayed
269
    if (site.delayed_group > 0) {
30,420,592 ✔
270
      nu_d[site.delayed_group - 1]++;
201,171 ✔
271
    }
272

273
    // Write fission particles to nuBank
274
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
30,420,592 ✔
275
    nu_bank_entry.wgt = site.wgt;
30,420,592 ✔
276
    nu_bank_entry.E = site.E;
30,420,592 ✔
277
    nu_bank_entry.delayed_group = site.delayed_group;
30,420,592 ✔
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()) {
30,420,592 ✔
286
      score_point_tally_fission(p, i_nuclide, rx, site);
39,336 ✔
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) {
23,777,048 !
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;
23,777,048 ✔
300

301
  // Store the total weight banked for analog fission tallies
302
  p.n_bank() = nu;
23,777,048 ✔
303
  p.wgt_bank() = nu / weight;
23,777,048 ✔
304
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
213,993,432 ✔
305
    p.n_delayed_bank(d) = nu_d[d];
190,216,384 ✔
306
  }
307
}
308

309
void sample_photon_reaction(Particle& p)
24,996,809 ✔
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();
24,996,809 ✔
315
  if (p.E() < settings::energy_cutoff[photon]) {
24,996,809 ✔
316
    p.E() = 0.0;
40 ✔
317
    p.wgt() = 0.0;
40 ✔
318
    return;
40 ✔
319
  }
320

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

326
  // Calculate photon energy over electron rest mass equivalent
327
  double alpha = p.E() / MASS_ELECTRON_EV;
24,996,769 ✔
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;
24,996,769 ✔
332
  double cutoff = prn(p.current_seed()) * micro.total;
24,996,769 ✔
333

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

344
  // Incoherent (Compton) scattering
345
  prob += micro.incoherent;
23,782,871 ✔
346
  if (prob > cutoff) {
23,782,871 ✔
347
    double alpha_out;
17,882,907 ✔
348
    int i_shell;
17,882,907 ✔
349
    element.compton_scatter(
17,882,907 ✔
350
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
17,882,907 ✔
351

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

361
    // Create Compton electron
362
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
17,882,907 ✔
363
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
17,882,907 ✔
364
    int electron = ParticleType::electron().transport_index();
17,882,907 ✔
365
    if (E_electron >= settings::energy_cutoff[electron]) {
17,882,907 !
366
      double mu_electron = (alpha - alpha_out * p.mu()) /
17,882,907 ✔
367
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
17,882,907 ✔
368
                                     2.0 * alpha * alpha_out * p.mu());
17,882,907 ✔
369
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
17,882,907 ✔
370
      process_charged_secondary(p, u, E_electron, ParticleType::electron());
17,882,907 ✔
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_ &&
17,768,683 !
377
        i_shell >= 0 && element.subshell_map_[i_shell] >= 0) {
35,651,590 !
378
      element.atomic_relaxation(element.subshell_map_[i_shell], p);
17,768,683 ✔
379
    }
380

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

389
  // Photoelectric effect
390
  double prob_after = prob + micro.photoelectric;
5,899,964 ✔
391

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

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

404
      // Check threshold of reaction
405
      if (xs_lower(i_shell) == 0)
20,168,001 ✔
406
        continue;
7,573,017 ✔
407

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

412
      if (prob > cutoff) {
12,594,984 ✔
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_
5,753,892 ✔
416
                                  ? shell.binding_energy
5,753,892 !
417
                                  : element.binding_energy_[i_shell];
×
418

419
        // Determine energy of secondary electron
420
        double E_electron = p.E() - binding_energy;
5,753,892 ✔
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;
8,634,766 ✔
426
        while (true) {
8,634,766 ✔
427
          double r = prn(p.current_seed());
8,634,766 ✔
428
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
8,634,766 ✔
429
            double rel_vel =
5,753,892 ✔
430
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
5,753,892 ✔
431
              (E_electron + MASS_ELECTRON_EV);
5,753,892 ✔
432
            mu =
5,753,892 ✔
433
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
5,753,892 ✔
434
            break;
5,753,892 ✔
435
          }
436
        }
437

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

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

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

462
  // Pair production
463
  prob += micro.pair_production;
146,072 ✔
464
  if (prob > cutoff) {
146,072 !
465
    double E_electron, E_positron;
146,072 ✔
466
    double mu_electron, mu_positron;
146,072 ✔
467
    element.pair_production(alpha, &E_electron, &E_positron, &mu_electron,
146,072 ✔
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());
146,072 ✔
472
    process_charged_secondary(p, u, E_electron, ParticleType::electron());
146,072 ✔
473

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

484
void process_charged_secondary(
63,855,976 ✔
485
  Particle& p, Direction u, double E, ParticleType type)
486
{
487
  int idx = type.transport_index();
63,855,976 ✔
488
  if (idx == C_NONE)
63,855,976 !
489
    return;
490

491
  // Below the energy cutoff, the kinetic energy is deposited locally without
492
  // producing bremsstrahlung
493
  if (E >= settings::energy_cutoff[idx] &&
63,855,976 ✔
494
      settings::electron_treatment == ElectronTreatment::TTB) {
63,854,760 ✔
495
    thick_target_bremsstrahlung(p, type, u, E);
63,314,824 ✔
496
  }
497

498
  // A positron annihilates regardless of its kinetic energy
499
  if (type == ParticleType::positron()) {
63,855,976 ✔
500
    Direction photon_u = isotropic_direction(p.current_seed());
146,072 ✔
501
    p.create_secondary(
146,072 ✔
502
      p.wgt(), photon_u, MASS_ELECTRON_EV, ParticleType::photon());
146,072 ✔
503
    p.create_secondary(
146,072 ✔
504
      p.wgt(), -photon_u, MASS_ELECTRON_EV, ParticleType::photon());
146,072 ✔
505

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

513
void sample_electron_reaction(Particle& p)
80,000 ✔
514
{
515
  // TODO: create reaction types
516

517
  if (settings::electron_treatment == ElectronTreatment::TTB) {
80,000 !
518
    thick_target_bremsstrahlung(p);
80,000 ✔
519
  }
520

521
  p.E() = 0.0;
80,000 ✔
522
  p.wgt() = 0.0;
80,000 ✔
523
  p.event() = TallyEvent::ABSORB;
80,000 ✔
524
}
80,000 ✔
525

526
void sample_positron_reaction(Particle& p)
×
527
{
528
  // TODO: create reaction types
529

530
  if (settings::electron_treatment == ElectronTreatment::TTB) {
×
531
    thick_target_bremsstrahlung(p);
×
532
  }
533

534
  // Sample angle isotropically
535
  Direction u = isotropic_direction(p.current_seed());
×
536

537
  // Create annihilation photon pair traveling in opposite directions
538
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon());
×
539
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon());
×
540

541
  p.E() = 0.0;
×
542
  p.wgt() = 0.0;
×
543
  p.event() = TallyEvent::ABSORB;
×
544
}
×
545

546
int sample_nuclide(Particle& p)
1,151,206,825 ✔
547
{
548
  // Sample cumulative distribution function
549
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,151,206,825 ✔
550

551
  // Get pointers to nuclide/density arrays
552
  const auto& mat {model::materials[p.material()]};
1,151,206,825 ✔
553
  int n = mat->nuclide_.size();
1,151,206,825 ✔
554

555
  double prob = 0.0;
1,151,206,825 ✔
556
  for (int i = 0; i < n; ++i) {
2,147,483,647 !
557
    // Get atom density
558
    int i_nuclide = mat->nuclide_[i];
2,147,483,647 ✔
559
    double atom_density = mat->atom_density(i, p.density_mult());
2,147,483,647 ✔
560

561
    // Increment probability to compare to cutoff
562
    prob += atom_density * p.neutron_xs(i_nuclide).total;
2,147,483,647 ✔
563
    if (prob >= cutoff)
2,147,483,647 ✔
564
      return i_nuclide;
1,151,206,825 ✔
565
  }
566

567
  // If we reach here, no nuclide was sampled
568
  p.write_restart();
×
569
  throw std::runtime_error {"Did not sample any nuclide during collision."};
×
570
}
571

572
int sample_element(Particle& p)
24,996,769 ✔
573
{
574
  // Sample cumulative distribution function
575
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
24,996,769 ✔
576

577
  // Get pointers to elements, densities
578
  const auto& mat {model::materials[p.material()]};
24,996,769 ✔
579

580
  double prob = 0.0;
24,996,769 ✔
581
  for (int i = 0; i < mat->element_.size(); ++i) {
100,788,593 !
582
    // Find atom density
583
    int i_element = mat->element_[i];
100,788,593 ✔
584
    double atom_density = mat->atom_density(i, p.density_mult());
100,788,593 ✔
585

586
    // Determine microscopic cross section
587
    double sigma = atom_density * p.photon_xs(i_element).total;
100,788,593 ✔
588

589
    // Increment probability to compare to cutoff
590
    prob += sigma;
100,788,593 ✔
591
    if (prob > cutoff) {
100,788,593 ✔
592
      // Save which nuclide particle had collision with for tally purpose
593
      p.event_nuclide() = mat->nuclide_[i];
24,996,769 ✔
594

595
      return i_element;
24,996,769 ✔
596
    }
597
  }
598

599
  // If we made it here, no element was sampled
600
  p.write_restart();
×
601
  fatal_error("Did not sample any element during collision.");
×
602
}
603

604
Reaction& sample_fission(int i_nuclide, Particle& p)
128,972,739 ✔
605
{
606
  // Get pointer to nuclide
607
  const auto& nuc {data::nuclides[i_nuclide]};
128,972,739 ✔
608

609
  // If we're in the URR, by default use the first fission reaction. We also
610
  // default to the first reaction if we know that there are no partial fission
611
  // reactions
612
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
128,972,739 ✔
613
    return *nuc->fission_rx_[0];
128,929,810 ✔
614
  }
615

616
  // Check to see if we are in a windowed multipole range.  WMP only supports
617
  // the first fission reaction.
618
  if (nuc->multipole_) {
42,929 ✔
619
    if (p.E() >= nuc->multipole_->E_min_ && p.E() <= nuc->multipole_->E_max_) {
2,072 !
620
      return *nuc->fission_rx_[0];
1,448 ✔
621
    }
622
  }
623

624
  // Get grid index and interpolation factor and sample fission cdf
625
  const auto& micro = p.neutron_xs(i_nuclide);
41,481 ✔
626
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
41,481 ✔
627
  double prob = 0.0;
41,481 ✔
628

629
  // Loop through each partial fission reaction type
630
  for (auto& rx : nuc->fission_rx_) {
41,566 !
631
    // add to cumulative probability
632
    prob += rx->xs(micro);
41,566 ✔
633

634
    // Create fission bank sites if fission occurs
635
    if (prob > cutoff)
41,566 ✔
636
      return *rx;
41,481 ✔
637
  }
638

639
  // If we reached here, no reaction was sampled
640
  throw std::runtime_error {
×
641
    "No fission reaction was sampled for " + nuc->name_};
×
642
}
643

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

652
  // Loop through each reaction type
653
  const auto& nuc {data::nuclides[i_nuclide]};
2,136,136 ✔
654
  for (int i = 0; i < nuc->reactions_.size(); ++i) {
39,410,744 !
655
    // Evaluate neutron cross section
656
    const auto& rx = nuc->reactions_[i];
39,410,744 ✔
657
    double xs = rx->xs(micro);
39,410,744 ✔
658

659
    // if cross section is zero for this reaction, skip it
660
    if (xs == 0.0)
39,410,744 ✔
661
      continue;
24,561,800 ✔
662

663
    for (int j = 0; j < rx->products_.size(); ++j) {
108,299,320 ✔
664
      if (rx->products_[j].particle_.is_photon()) {
95,586,512 ✔
665
        // For fission, artificially increase the photon yield to account
666
        // for delayed photons
667
        double f = 1.0;
84,329,168 ✔
668
        if (settings::delayed_photon_scaling) {
84,329,168 !
669
          if (is_fission(rx->mt_)) {
84,329,168 ✔
670
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
393,328 !
671
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
393,328 ✔
672
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
393,328 ✔
673
              f = (energy_prompt + energy_delayed) / (energy_prompt);
393,328 ✔
674
            }
675
          }
676
        }
677

678
        // add to cumulative probability
679
        prob += f * (*rx->products_[j].yield_)(p.E()) * xs;
84,329,168 ✔
680

681
        *i_rx = i;
84,329,168 ✔
682
        *i_product = j;
84,329,168 ✔
683
        if (prob > cutoff)
84,329,168 ✔
684
          return;
685
      }
686
    }
687
  }
688
}
689

690
void absorption(Particle& p, int i_nuclide)
1,151,124,550 ✔
691
{
692
  if (settings::survival_biasing) {
1,151,124,550 ✔
693
    // Determine weight absorbed in survival biasing
694
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
32,389,032 ✔
695
                              p.neutron_xs(i_nuclide).total;
32,389,032 ✔
696

697
    // Adjust weight of particle by probability of absorption
698
    p.wgt() -= wgt_absorb;
32,389,032 ✔
699

700
    // Score implicit absorption estimate of keff
701
    if (settings::run_mode == RunMode::EIGENVALUE) {
32,389,032 ✔
702
      p.keff_tally_absorption() += wgt_absorb *
363,600 ✔
703
                                   p.neutron_xs(i_nuclide).nu_fission /
363,600 ✔
704
                                   p.neutron_xs(i_nuclide).absorption;
363,600 ✔
705
    }
706
  } else {
707
    // See if disappearance reaction happens
708
    if (p.neutron_xs(i_nuclide).absorption >
1,118,735,518 ✔
709
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
1,118,735,518 ✔
710
      // Score absorption estimate of keff
711
      if (settings::run_mode == RunMode::EIGENVALUE) {
26,221,217 ✔
712
        p.keff_tally_absorption() += p.wgt() *
18,623,654 ✔
713
                                     p.neutron_xs(i_nuclide).nu_fission /
18,623,654 ✔
714
                                     p.neutron_xs(i_nuclide).absorption;
18,623,654 ✔
715
      }
716

717
      p.wgt() = 0.0;
26,221,217 ✔
718
      p.event() = TallyEvent::ABSORB;
26,221,217 ✔
719
      if (!p.fission()) {
26,221,217 ✔
720
        p.event_mt() = N_DISAPPEAR;
16,818,739 ✔
721
      }
722
    }
723
  }
724
}
1,151,124,550 ✔
725

726
void scatter(Particle& p, int i_nuclide)
1,124,868,992 ✔
727
{
728
  // copy incoming direction
729
  Direction u_old {p.u()};
1,124,868,992 ✔
730

731
  // Get pointer to nuclide and grid index/interpolation factor
732
  const auto& nuc {data::nuclides[i_nuclide]};
1,124,868,992 ✔
733
  const auto& micro {p.neutron_xs(i_nuclide)};
1,124,868,992 ✔
734
  int i_temp = micro.index_temp;
1,124,868,992 ✔
735

736
  // For tallying purposes, this routine might be called directly. In that
737
  // case, we need to sample a reaction via the cutoff variable
738
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
1,124,868,992 ✔
739
  bool sampled = false;
1,124,868,992 ✔
740

741
  // Calculate elastic cross section if it wasn't precalculated
742
  if (micro.elastic == CACHE_INVALID) {
1,124,868,992 ✔
743
    nuc->calculate_elastic_xs(p);
932,078,470 ✔
744
  }
745

746
  double prob = micro.elastic - micro.thermal;
1,124,868,992 ✔
747
  if (prob > cutoff) {
1,124,868,992 ✔
748
    // =======================================================================
749
    // NON-S(A,B) ELASTIC SCATTERING
750

751
    // Determine temperature
752
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
1,006,486,945 ✔
753

754
    // Perform collision physics for elastic scattering
755
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
1,006,486,945 ✔
756

757
    p.event_mt() = ELASTIC;
1,006,486,945 ✔
758
    sampled = true;
1,006,486,945 ✔
759
  }
760

761
  prob = micro.elastic;
1,124,868,992 ✔
762
  if (prob > cutoff && !sampled) {
1,124,868,992 ✔
763
    // =======================================================================
764
    // S(A,B) SCATTERING
765

766
    sab_scatter(i_nuclide, micro.index_sab, p);
99,496,079 ✔
767

768
    p.event_mt() = ELASTIC;
99,496,079 ✔
769
    sampled = true;
99,496,079 ✔
770
  }
771

772
  if (!sampled) {
1,124,868,992 ✔
773
    // =======================================================================
774
    // INELASTIC SCATTERING
775

776
    int n = nuc->index_inelastic_scatter_.size();
18,885,968 ✔
777
    int i = 0;
18,885,968 ✔
778
    for (int j = 0; j < n && prob < cutoff; ++j) {
358,411,850 ✔
779
      i = nuc->index_inelastic_scatter_[j];
339,525,882 ✔
780

781
      // add to cumulative probability
782
      prob += nuc->reactions_[i]->xs(micro);
339,525,882 ✔
783
    }
784

785
    // Perform collision physics for inelastic scattering
786
    const auto& rx {nuc->reactions_[i]};
18,885,968 ✔
787
    inelastic_scatter(i_nuclide, *rx, p);
18,885,968 ✔
788
    p.event_mt() = rx->mt_;
18,885,968 ✔
789
  }
790

791
  // Set event component
792
  p.event() = TallyEvent::SCATTER;
1,124,868,992 ✔
793

794
  // Sample new outgoing angle for isotropic-in-lab scattering
795
  const auto& mat {model::materials[p.material()]};
1,124,868,992 !
796
  if (!mat->p0_.empty()) {
1,124,868,992 !
797
    int i_nuc_mat = mat->mat_nuclide_index_[i_nuclide];
237,360 ✔
798
    if (mat->p0_[i_nuc_mat]) {
237,360 !
799
      // Sample isotropic-in-lab outgoing direction
800
      p.u() = isotropic_direction(p.current_seed());
237,360 ✔
801
      p.mu() = u_old.dot(p.u());
237,360 ✔
802
    }
803
  }
804
}
1,124,868,992 ✔
805

806
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
1,006,486,945 ✔
807
{
808
  // get pointer to nuclide
809
  const auto& nuc {data::nuclides[i_nuclide]};
1,006,486,945 ✔
810

811
  double vel = std::sqrt(p.E());
1,006,486,945 ✔
812
  double awr = nuc->awr_;
1,006,486,945 ✔
813

814
  // Neutron velocity in LAB
815
  Direction v_n = vel * p.u();
1,006,486,945 ✔
816

817
  // Sample velocity of target nucleus
818
  Direction v_t {};
1,006,486,945 ✔
819
  if (!p.neutron_xs(i_nuclide).use_ptable) {
1,006,486,945 ✔
820
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
971,809,265 ✔
821
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
971,809,265 ✔
822
  }
823

824
  // Velocity of center-of-mass
825
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
1,006,486,945 ✔
826

827
  // Transform to CM frame
828
  v_n -= v_cm;
1,006,486,945 ✔
829

830
  // Find speed of neutron in CM
831
  vel = v_n.norm();
1,006,486,945 ✔
832

833
  if (!model::active_point_tallies.empty()) {
1,006,486,945 ✔
834
    score_point_tally_elastic(p, i_nuclide, rx, 0, v_t);
4,724,856 ✔
835
  }
836

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

848
  // Determine direction cosines in CM
849
  Direction u_cm = v_n / vel;
1,006,486,945 ✔
850

851
  // Rotate neutron velocity vector to new angle -- note that the speed of the
852
  // neutron in CM does not change in elastic scattering. However, the speed
853
  // will change when we convert back to LAB
854
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
1,006,486,945 ✔
855

856
  // Transform back to LAB frame
857
  v_n += v_cm;
1,006,486,945 ✔
858

859
  p.E() = v_n.dot(v_n);
1,006,486,945 ✔
860
  vel = std::sqrt(p.E());
1,006,486,945 ✔
861

862
  // compute cosine of scattering angle in LAB frame by taking dot product of
863
  // neutron's pre- and post-collision angle
864
  p.mu() = p.u().dot(v_n) / vel;
1,006,486,945 ✔
865

866
  // Set energy and direction of particle in LAB frame
867
  p.u() = v_n / vel;
1,006,486,945 !
868

869
  // Because of floating-point roundoff, it may be possible for mu_lab to be
870
  // outside of the range [-1,1). In these cases, we just set mu_lab to exactly
871
  // -1 or 1
872
  if (std::abs(p.mu()) > 1.0)
1,006,486,945 !
873
    p.mu() = std::copysign(1.0, p.mu());
×
874
}
1,006,486,945 ✔
875

876
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
99,496,079 ✔
877
{
878
  // Determine temperature index
879
  const auto& micro {p.neutron_xs(i_nuclide)};
99,496,079 ✔
880
  int i_temp = micro.index_temp_sab;
99,496,079 ✔
881

882
  // Sample energy and angle
883
  double E_out;
99,496,079 ✔
884
  auto& sab = data::thermal_scatt[i_sab]->data_[i_temp];
99,496,079 ✔
885

886
  if (!model::active_point_tallies.empty()) {
99,496,079 ✔
887
    score_point_tally_sab(p, i_nuclide, sab, micro);
3,429,312 ✔
888
  }
889

890
  sab.sample(micro, p.E(), &E_out, &p.mu(), p.current_seed());
99,496,079 ✔
891

892
  // Set energy to outgoing, change direction of particle
893
  p.E() = E_out;
99,496,079 ✔
894
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
99,496,079 ✔
895
}
99,496,079 ✔
896

897
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
971,809,265 ✔
898
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
899
{
900
  // check if nuclide is a resonant scatterer
901
  ResScatMethod sampling_method;
971,809,265 ✔
902
  if (nuc.resonant_) {
971,809,265 ✔
903

904
    // sampling method to use
905
    sampling_method = settings::res_scat_method;
61,496 ✔
906

907
    // upper resonance scattering energy bound (target is at rest above this E)
908
    if (E > settings::res_scat_energy_max) {
61,496 ✔
909
      return {};
29,640 ✔
910

911
      // lower resonance scattering energy bound (should be no resonances below)
912
    } else if (E < settings::res_scat_energy_min) {
31,856 ✔
913
      sampling_method = ResScatMethod::cxs;
914
    }
915

916
    // otherwise, use free gas model
917
  } else {
918
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
971,747,769 ✔
919
      return {};
359,760,809 ✔
920
    } else {
921
      sampling_method = ResScatMethod::cxs;
922
    }
923
  }
924

925
  // use appropriate target velocity sampling method
926
  switch (sampling_method) {
13,680 !
927
  case ResScatMethod::cxs:
612,005,136 ✔
928

929
    // sample target velocity with the constant cross section (cxs) approx.
930
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
612,005,136 ✔
931

932
  case ResScatMethod::dbrc:
13,680 ✔
933
  case ResScatMethod::rvs: {
13,680 ✔
934
    double E_red = std::sqrt(nuc.awr_ * E / kT);
13,680 ✔
935
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
27,360 !
936
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
13,680 ✔
937

938
    // find lower and upper energy bound indices
939
    // lower index
940
    int i_E_low;
13,680 ✔
941
    if (E_low < nuc.energy_0K_.front()) {
13,680 !
942
      i_E_low = 0;
943
    } else if (E_low > nuc.energy_0K_.back()) {
13,680 !
944
      i_E_low = nuc.energy_0K_.size() - 2;
×
945
    } else {
946
      i_E_low =
13,680 ✔
947
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
13,680 ✔
948
    }
949

950
    // upper index
951
    int i_E_up;
13,680 ✔
952
    if (E_up < nuc.energy_0K_.front()) {
13,680 !
953
      i_E_up = 0;
954
    } else if (E_up > nuc.energy_0K_.back()) {
13,680 !
955
      i_E_up = nuc.energy_0K_.size() - 2;
×
956
    } else {
957
      i_E_up =
13,680 ✔
958
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_up);
13,680 ✔
959
    }
960

961
    if (i_E_up == i_E_low) {
13,680 ✔
962
      // Handle degenerate case -- if the upper/lower bounds occur for the same
963
      // index, then using cxs is probably a good approximation
964
      return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
13,680 ✔
965
    }
966

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

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

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

996
        // perform Doppler broadening rejection correction (dbrc)
997
        double xs_0K = nuc.elastic_xs_0K(E_rel);
×
998
        double R = xs_0K / xs_max;
×
999
        if (prn(seed) < R)
×
1000
          return v_target;
×
1001
      }
1002

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

1013
      // cdf value at upper bound attainable energy
1014
      double m = (nuc.xs_cdf_[i_E_up + 1] - nuc.xs_cdf_[i_E_up]) /
11,296 ✔
1015
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
11,296 ✔
1016
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
11,296 ✔
1017

1018
      while (true) {
237,024 ✔
1019
        // directly sample Maxwellian
1020
        double E_t = -kT * std::log(prn(seed));
124,160 ✔
1021

1022
        // sample a relative energy using the xs cdf
1023
        double cdf_rel = cdf_low + prn(seed) * (cdf_up - cdf_low);
124,160 ✔
1024
        int i_E_rel = lower_bound_index(nuc.xs_cdf_.begin() + i_E_low,
124,160 ✔
1025
          nuc.xs_cdf_.begin() + i_E_up + 2, cdf_rel);
124,160 ✔
1026
        double E_rel = nuc.energy_0K_[i_E_low + i_E_rel];
124,160 ✔
1027
        double m = (nuc.xs_cdf_[i_E_low + i_E_rel + 1] -
124,160 ✔
1028
                     nuc.xs_cdf_[i_E_low + i_E_rel]) /
124,160 ✔
1029
                   (nuc.energy_0K_[i_E_low + i_E_rel + 1] -
124,160 ✔
1030
                     nuc.energy_0K_[i_E_low + i_E_rel]);
124,160 ✔
1031
        E_rel += (cdf_rel - nuc.xs_cdf_[i_E_low + i_E_rel]) / m;
124,160 ✔
1032

1033
        // perform rejection sampling on cosine between
1034
        // neutron and target velocities
1035
        double mu = (E_t + nuc.awr_ * (E - E_rel)) /
124,160 ✔
1036
                    (2.0 * std::sqrt(nuc.awr_ * E * E_t));
124,160 ✔
1037

1038
        if (std::abs(mu) < 1.0) {
124,160 ✔
1039
          // set and accept target velocity
1040
          E_t /= nuc.awr_;
11,296 ✔
1041
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
11,296 ✔
1042
        }
1043
      }
112,864 ✔
1044
    }
1045
  } // case RVS, DBRC
1046
  } // switch (sampling_method)
1047

1048
  UNREACHABLE();
×
1049
}
1050

1051
Direction sample_cxs_target_velocity(
612,007,520 ✔
1052
  double awr, double E, Direction u, double kT, uint64_t* seed)
1053
{
1054
  double beta_vn = std::sqrt(awr * E / kT);
612,007,520 ✔
1055
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
612,007,520 ✔
1056

1057
  double beta_vt_sq;
746,747,258 ✔
1058
  double mu;
746,747,258 ✔
1059
  while (true) {
746,747,258 ✔
1060
    // Sample two random numbers
1061
    double r1 = prn(seed);
746,747,258 ✔
1062
    double r2 = prn(seed);
746,747,258 ✔
1063

1064
    if (prn(seed) < alpha) {
746,747,258 ✔
1065
      // With probability alpha, we sample the distribution p(y) =
1066
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1067
      // Carlo sampler
1068

1069
      beta_vt_sq = -std::log(r1 * r2);
214,399,441 ✔
1070

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

1076
      double c = std::cos(PI / 2.0 * prn(seed));
532,347,817 ✔
1077
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
532,347,817 ✔
1078
    }
1079

1080
    // Determine beta * vt
1081
    double beta_vt = std::sqrt(beta_vt_sq);
746,747,258 ✔
1082

1083
    // Sample cosine of angle between neutron and target velocity
1084
    mu = uniform_distribution(-1., 1., seed);
746,747,258 ✔
1085

1086
    // Determine rejection probability
1087
    double accept_prob =
746,747,258 ✔
1088
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
746,747,258 ✔
1089
      (beta_vn + beta_vt);
746,747,258 ✔
1090

1091
    // Perform rejection sampling on vt and mu
1092
    if (prn(seed) < accept_prob)
746,747,258 ✔
1093
      break;
1094
  }
1095

1096
  // Determine speed of target nucleus
1097
  double vt = std::sqrt(beta_vt_sq * kT / awr);
612,007,520 ✔
1098

1099
  // Determine velocity vector of target nucleus based on neutron's velocity
1100
  // and the sampled angle between them
1101
  return vt * rotate_angle(u, mu, nullptr, seed);
612,007,520 ✔
1102
}
1103

1104
void sample_fission_neutron(
30,420,592 ✔
1105
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1106
{
1107
  // Get attributes of particle
1108
  double E_in = p.E();
30,420,592 ✔
1109
  uint64_t* seed = p.current_seed();
30,420,592 ✔
1110

1111
  // Determine total nu, delayed nu, and delayed neutron fraction
1112
  const auto& nuc {data::nuclides[i_nuclide]};
30,420,592 ✔
1113
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
30,420,592 ✔
1114
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
30,420,592 ✔
1115
  double beta = nu_d / nu_t;
30,420,592 ✔
1116

1117
  if (prn(seed) < beta) {
30,420,592 ✔
1118
    // ====================================================================
1119
    // DELAYED NEUTRON SAMPLED
1120

1121
    // sampled delayed precursor group
1122
    double xi = prn(seed) * nu_d;
201,171 ✔
1123
    double prob = 0.0;
201,171 ✔
1124
    int group;
201,171 ✔
1125
    for (group = 1; group < nuc->n_precursor_; ++group) {
750,132 ✔
1126
      // determine delayed neutron precursor yield for group j
1127
      double yield = (*rx.products_[group].yield_)(E_in);
735,636 ✔
1128

1129
      // Check if this group is sampled
1130
      prob += yield;
735,636 ✔
1131
      if (xi < prob)
735,636 ✔
1132
        break;
1133
    }
1134

1135
    // if the sum of the probabilities is slightly less than one and the
1136
    // random number is greater, j will be greater than nuc %
1137
    // n_precursor -- check for this condition
1138
    group = std::min(group, nuc->n_precursor_);
201,171 !
1139

1140
    // set the delayed group for the particle born from fission
1141
    site->delayed_group = group;
201,171 ✔
1142

1143
    // Sample time of emission based on decay constant of precursor
1144
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
201,171 ✔
1145
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
201,171 ✔
1146

1147
  } else {
1148
    // ====================================================================
1149
    // PROMPT NEUTRON SAMPLED
1150

1151
    // set the delayed group for the particle born from fission to 0
1152
    site->delayed_group = 0;
30,219,421 ✔
1153
  }
1154

1155
  // sample from prompt neutron energy distribution
1156
  int n_sample = 0;
1157
  double mu;
30,420,593 ✔
1158
  while (true) {
30,420,593 ✔
1159
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
30,420,593 ✔
1160

1161
    // resample if energy is greater than maximum neutron energy
1162
    int neutron = ParticleType::neutron().transport_index();
30,420,593 ✔
1163
    if (site->E < data::energy_max[neutron])
30,420,593 ✔
1164
      break;
1165

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

1176
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1177
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
30,420,592 ✔
1178
}
30,420,592 ✔
1179

1180
void inelastic_scatter(int i_nuclide, const Reaction& rx, Particle& p)
18,885,968 ✔
1181
{
1182
  // Get pointer to nuclide
1183
  const auto& nuc {data::nuclides[i_nuclide]};
18,885,968 ✔
1184

1185
  // copy energy of neutron
1186
  double E_in = p.E();
18,885,968 ✔
1187

1188
  // sample outgoing energy and scattering cosine
1189
  double E;
18,885,968 ✔
1190
  double mu;
18,885,968 ✔
1191
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
18,885,968 ✔
1192

1193
  double yield = (*rx.products_[0].yield_)(E_in);
18,885,968 ✔
1194

1195
  if (!model::active_point_tallies.empty()) {
18,885,968 ✔
1196
    score_point_tally_inelastic(p, i_nuclide, rx, 0, yield);
9,824 ✔
1197
  }
1198

1199
  // if scattering system is in center-of-mass, transfer cosine of scattering
1200
  // angle and outgoing energy from CM to LAB
1201
  if (rx.scatter_in_cm_) {
18,885,968 ✔
1202
    double E_cm = E;
18,817,641 ✔
1203

1204
    // determine outgoing energy in lab
1205
    double A = nuc->awr_;
18,817,641 ✔
1206
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
18,817,641 ✔
1207
                 ((A + 1.0) * (A + 1.0));
18,817,641 ✔
1208

1209
    // determine outgoing angle in lab
1210
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
18,817,641 ✔
1211
  }
1212

1213
  // Because of floating-point roundoff, it may be possible for mu to be
1214
  // outside of the range [-1,1). In these cases, we just set mu to exactly -1
1215
  // or 1
1216
  if (std::abs(mu) > 1.0)
18,885,968 !
1217
    mu = std::copysign(1.0, mu);
×
1218

1219
  // Set outgoing energy and scattering angle
1220
  p.E() = E;
18,885,968 ✔
1221
  p.mu() = mu;
18,885,968 ✔
1222

1223
  // change direction of particle
1224
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
18,885,968 !
1225

1226
  if (std::floor(yield) == yield && yield > 0) {
18,885,968 !
1227
    // If yield is integral, create exactly that many secondary particles
1228
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
19,010,354 ✔
1229
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
124,554 ✔
1230
    }
1231
  } else {
1232
    // Otherwise, change weight of particle based on yield
1233
    p.wgt() *= yield;
168 ✔
1234
  }
1235
}
18,885,968 ✔
1236

1237
void sample_secondary_photons(Particle& p, int i_nuclide)
56,650,752 ✔
1238
{
1239
  // Sample the number of photons produced
1240
  double y_t =
56,650,752 ✔
1241
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
56,650,752 ✔
1242
  double photon_wgt = p.wgt();
56,650,752 ✔
1243
  int y = 1;
56,650,752 ✔
1244

1245
  if (settings::use_decay_photons) {
56,650,752 ✔
1246
    // For decay photons, sample a single photon and modify the weight
1247
    if (y_t <= 0.0)
52,368 ✔
1248
      return;
1249
    photon_wgt *= y_t;
39,800 ✔
1250
  } else {
1251
    // For prompt photons, sample an integral number of photons with weight
1252
    // equal to the neutron's weight
1253
    y = static_cast<int>(y_t);
56,598,384 ✔
1254
    if (prn(p.current_seed()) <= y_t - y)
56,598,384 ✔
1255
      ++y;
1,541,288 ✔
1256
  }
1257

1258
  // Sample each secondary photon
1259
  for (int i = 0; i < y; ++i) {
58,774,320 ✔
1260
    // Sample the reaction and product
1261
    int i_rx;
2,136,136 ✔
1262
    int i_product;
2,136,136 ✔
1263
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
2,136,136 ✔
1264

1265
    // Sample the outgoing energy and angle
1266
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
2,136,136 ✔
1267
    double E;
2,136,136 ✔
1268
    double mu;
2,136,136 ✔
1269
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
2,136,136 ✔
1270

1271
    // Sample the new direction
1272
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
2,136,136 ✔
1273

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

1284
    // Create the secondary photon
1285
    bool created_photon = p.create_secondary(wgt, u, E, ParticleType::photon());
2,136,136 ✔
1286

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

1298
    // Tag secondary particle with parent nuclide
1299
    if (created_photon && settings::use_decay_photons) {
2,136,136 ✔
1300
      p.local_secondary_bank().back().parent_nuclide =
38,432 ✔
1301
        rx->products_[i_product].parent_nuclide_;
38,432 ✔
1302
    }
1303
  }
1304
}
1305

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