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

openmc-dev / openmc / 25632480981

10 May 2026 03:25PM UTC coverage: 81.003% (-0.4%) from 81.388%
25632480981

Pull #3757

github

web-flow
Merge f7b7414eb into d56cda254
Pull Request #3757: Testing point detectors

17777 of 25846 branches covered (68.78%)

Branch coverage included in aggregate %.

51 of 372 new or added lines in 25 files covered. (13.71%)

3 existing lines in 2 files now uncovered.

58790 of 68678 relevant lines covered (85.6%)

46992975.87 hits per line

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

84.41
/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,270,027,718✔
46
{
47
  // Add to collision counter for particle
48
  ++(p.n_collision());
1,270,027,718✔
49
  p.secondary_bank_index() = p.secondary_bank().size();
1,270,027,718!
50

51
  // Sample reaction for the material the particle is in
52
  switch (p.type().pdg_number()) {
1,270,027,718!
53
  case PDG_NEUTRON:
1,195,367,012✔
54
    sample_neutron_reaction(p);
1,195,367,012✔
55
    break;
1,195,367,012✔
56
  case PDG_PHOTON:
18,459,233✔
57
    sample_photon_reaction(p);
18,459,233✔
58
    break;
18,459,233✔
59
  case PDG_ELECTRON:
56,114,748✔
60
    sample_electron_reaction(p);
56,114,748✔
61
    break;
56,114,748✔
62
  case PDG_POSITRON:
86,725✔
63
    sample_positron_reaction(p);
86,725✔
64
    break;
86,725✔
65
  default:
×
66
    fatal_error("Unsupported particle PDG for collision sampling.");
×
67
  }
68

69
  if (settings::weight_windows_on) {
1,270,027,718✔
70
    auto [ww_found, ww] = search_weight_window(p);
83,954,545✔
71
    if (!ww_found && p.type() == ParticleType::neutron()) {
83,954,545✔
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,995✔
75
    } else if (settings::weight_window_checkpoint_collision) {
83,887,550!
76
      // if collision checkpointing is on, apply weight window
77
      apply_weight_window(p, ww);
83,887,550✔
78
    }
79
  }
80

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

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

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

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

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

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

142
  // Create secondary photons
143
  if (settings::photon_transport) {
1,195,367,012✔
144
    sample_secondary_photons(p, i_nuclide);
8,382,044✔
145
  }
146

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

150
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
1,195,367,012✔
151
    absorption(p, i_nuclide);
1,195,253,666✔
152
  }
153
  if (!p.alive())
1,195,367,012✔
154
    return;
155

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

165
  // Advance URR seed stream 'N' times after energy changes
166
  if (p.E() != p.E_last()) {
1,165,427,885✔
167
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
1,165,108,654✔
168
  }
169

170
  // Play russian roulette if there are no weight windows
171
  if (!settings::weight_windows_on)
1,165,427,885✔
172
    apply_russian_roulette(p);
1,101,824,465✔
173
}
174

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

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

186
  // Sample the number of neutrons produced
187
  int nu = static_cast<int>(nu_t);
144,544,804✔
188
  if (prn(p.current_seed()) <= (nu_t - nu))
144,544,804✔
189
    ++nu;
24,097,964✔
190

191
  // If no neutrons were produced then don't continue
192
  if (nu == 0)
144,544,804✔
193
    return;
114,604,821✔
194

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

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

202
  p.fission() = true;
29,939,983✔
203

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

310
  // Calculate photon energy over electron rest mass equivalent
311
  double alpha = p.E() / MASS_ELECTRON_EV;
18,458,430✔
312

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

318
  // Coherent (Rayleigh) scattering
319
  prob += micro.coherent;
18,458,430✔
320
  if (prob > cutoff) {
18,458,430✔
321
    p.mu() = element.rayleigh_scatter(alpha, p.current_seed());
1,010,739✔
322
    p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
1,010,739✔
323
    p.event() = TallyEvent::SCATTER;
1,010,739✔
324
    p.event_mt() = COHERENT;
1,010,739✔
325
    return;
1,010,739✔
326
  }
327

328
  // Incoherent (Compton) scattering
329
  prob += micro.incoherent;
17,447,691✔
330
  if (prob > cutoff) {
17,447,691✔
331
    double alpha_out;
11,934,085✔
332
    int i_shell;
11,934,085✔
333
    element.compton_scatter(
11,934,085✔
334
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
11,934,085✔
335

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

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

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

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

373
  // Photoelectric effect
374
  double prob_after = prob + micro.photoelectric;
5,513,606✔
375

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

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

388
      // Check threshold of reaction
389
      if (xs_lower(i_shell) == 0)
24,881,786✔
390
        continue;
10,350,722✔
391

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

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

403
        // Determine energy of secondary electron
404
        double E_electron = p.E() - binding_energy;
5,426,881✔
405

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

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

428
        // Create secondary electron
429
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
5,426,881✔
430

431
        // Allow electrons to fill orbital and produce auger electrons
432
        // and fluorescent photons
433
        if (settings::atomic_relaxation) {
5,426,881✔
434
          element.atomic_relaxation(i_shell, p);
5,316,881✔
435
        }
436
        p.event() = TallyEvent::ABSORB;
5,426,881✔
437
        p.event_mt() = 533 + shell.index_subshell;
5,426,881✔
438
        p.wgt() = 0.0;
5,426,881✔
439
        p.E() = 0.0;
5,426,881✔
440
        return;
5,426,881✔
441
      }
442
    }
443
  }
10,853,762✔
444
  prob = prob_after;
86,725✔
445

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

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

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

468
void sample_electron_reaction(Particle& p)
56,114,748✔
469
{
470
  // TODO: create reaction types
471

472
  if (settings::electron_treatment == ElectronTreatment::TTB) {
56,114,748✔
473
    double E_lost;
53,532,707✔
474
    thick_target_bremsstrahlung(p, &E_lost);
53,532,707✔
475
  }
476

477
  p.E() = 0.0;
56,114,748✔
478
  p.wgt() = 0.0;
56,114,748✔
479
  p.event() = TallyEvent::ABSORB;
56,114,748✔
480
}
56,114,748✔
481

482
void sample_positron_reaction(Particle& p)
86,725✔
483
{
484
  // TODO: create reaction types
485

486
  if (settings::electron_treatment == ElectronTreatment::TTB) {
86,725✔
487
    double E_lost;
86,472✔
488
    thick_target_bremsstrahlung(p, &E_lost);
86,472✔
489
  }
490

491
  // Sample angle isotropically
492
  Direction u = isotropic_direction(p.current_seed());
86,725✔
493

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

498
  p.E() = 0.0;
86,725✔
499
  p.wgt() = 0.0;
86,725✔
500
  p.event() = TallyEvent::ABSORB;
86,725✔
501
}
86,725✔
502

503
int sample_nuclide(Particle& p)
1,195,367,012✔
504
{
505
  // Sample cumulative distribution function
506
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,195,367,012✔
507

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

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

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

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

529
int sample_element(Particle& p)
18,458,430✔
530
{
531
  // Sample cumulative distribution function
532
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
18,458,430✔
533

534
  // Get pointers to elements, densities
535
  const auto& mat {model::materials[p.material()]};
18,458,430✔
536

537
  double prob = 0.0;
18,458,430✔
538
  for (int i = 0; i < mat->element_.size(); ++i) {
42,670,919!
539
    // Find atom density
540
    int i_element = mat->element_[i];
42,670,919✔
541
    double atom_density = mat->atom_density(i, p.density_mult());
42,670,919✔
542

543
    // Determine microscopic cross section
544
    double sigma = atom_density * p.photon_xs(i_element).total;
42,670,919✔
545

546
    // Increment probability to compare to cutoff
547
    prob += sigma;
42,670,919✔
548
    if (prob > cutoff) {
42,670,919✔
549
      // Save which nuclide particle had collision with for tally purpose
550
      p.event_nuclide() = mat->nuclide_[i];
18,458,430✔
551

552
      return i_element;
18,458,430✔
553
    }
554
  }
555

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

674
      p.wgt() = 0.0;
29,938,170✔
675
      p.event() = TallyEvent::ABSORB;
29,938,170✔
676
      if (!p.fission()) {
29,938,170✔
677
        p.event_mt() = N_DISAPPEAR;
17,595,205✔
678
      }
679
    }
680
  }
681
}
1,195,253,666✔
682

683
void scatter(Particle& p, int i_nuclide)
1,165,269,056✔
684
{
685
  // copy incoming direction
686
  Direction u_old {p.u()};
1,165,269,056✔
687

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

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

698
  // Calculate elastic cross section if it wasn't precalculated
699
  if (micro.elastic == CACHE_INVALID) {
1,165,269,056✔
700
    nuc->calculate_elastic_xs(p);
912,393,672✔
701
  }
702

703
  double prob = micro.elastic - micro.thermal;
1,165,269,056✔
704
  if (prob > cutoff) {
1,165,269,056✔
705
    // =======================================================================
706
    // NON-S(A,B) ELASTIC SCATTERING
707

708
    // Determine temperature
709
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
1,013,879,995✔
710

711
    // Perform collision physics for elastic scattering
712
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
1,013,879,995✔
713

714
    p.event_mt() = ELASTIC;
1,013,879,995✔
715
    sampled = true;
1,013,879,995✔
716
  }
717

718
  prob = micro.elastic;
1,165,269,056✔
719
  if (prob > cutoff && !sampled) {
1,165,269,056✔
720
    // =======================================================================
721
    // S(A,B) SCATTERING
722

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

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

729
  if (!sampled) {
1,165,269,056✔
730
    // =======================================================================
731
    // INELASTIC SCATTERING
732

733
    int n = nuc->index_inelastic_scatter_.size();
23,910,986✔
734
    int i = 0;
23,910,986✔
735
    for (int j = 0; j < n && prob < cutoff; ++j) {
449,157,493✔
736
      i = nuc->index_inelastic_scatter_[j];
425,246,507✔
737

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

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

748
  // Set event component
749
  p.event() = TallyEvent::SCATTER;
1,165,269,056✔
750

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

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

768
  double vel = std::sqrt(p.E());
1,013,879,995✔
769
  double awr = nuc->awr_;
1,013,879,995✔
770

771
  // Neutron velocity in LAB
772
  Direction v_n = vel * p.u();
1,013,879,995✔
773

774
  // Sample velocity of target nucleus
775
  Direction v_t {};
1,013,879,995✔
776
  if (!p.neutron_xs(i_nuclide).use_ptable) {
1,013,879,995✔
777
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
968,879,863✔
778
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
968,879,863✔
779
  }
780

781
  // Velocity of center-of-mass
782
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
1,013,879,995✔
783

784
  // Transform to CM frame
785
  v_n -= v_cm;
1,013,879,995✔
786

787
  // Find speed of neutron in CM
788
  vel = v_n.norm();
1,013,879,995✔
789

790
  if (!model::active_point_tallies.empty()) {
1,013,879,995!
NEW
791
    score_point_tally_elastic(p, i_nuclide, rx, 0, v_t);
×
792
  }
793

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

805
  // Determine direction cosines in CM
806
  Direction u_cm = v_n / vel;
1,013,879,995✔
807

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

813
  // Transform back to LAB frame
814
  v_n += v_cm;
1,013,879,995✔
815

816
  p.E() = v_n.dot(v_n);
1,013,879,995✔
817
  vel = std::sqrt(p.E());
1,013,879,995✔
818

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

823
  // Set energy and direction of particle in LAB frame
824
  p.u() = v_n / vel;
1,013,879,995!
825

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

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

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

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

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

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

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

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

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

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

873
    // otherwise, use free gas model
874
  } else {
875
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
968,795,306✔
876
      return {};
461,980,029✔
877
    } else {
878
      sampling_method = ResScatMethod::cxs;
879
    }
880
  }
881

882
  // use appropriate target velocity sampling method
883
  switch (sampling_method) {
18,810!
884
  case ResScatMethod::cxs:
506,840,269✔
885

886
    // sample target velocity with the constant cross section (cxs) approx.
887
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
506,840,269✔
888

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1005
  UNREACHABLE();
×
1006
}
1007

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

1014
  double beta_vt_sq;
586,743,530✔
1015
  double mu;
586,743,530✔
1016
  while (true) {
586,743,530✔
1017
    // Sample two random numbers
1018
    double r1 = prn(seed);
586,743,530✔
1019
    double r2 = prn(seed);
586,743,530✔
1020

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

1026
      beta_vt_sq = -std::log(r1 * r2);
127,214,123✔
1027

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

1033
      double c = std::cos(PI / 2.0 * prn(seed));
459,529,407✔
1034
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
459,529,407✔
1035
    }
1036

1037
    // Determine beta * vt
1038
    double beta_vt = std::sqrt(beta_vt_sq);
586,743,530✔
1039

1040
    // Sample cosine of angle between neutron and target velocity
1041
    mu = uniform_distribution(-1., 1., seed);
586,743,530✔
1042

1043
    // Determine rejection probability
1044
    double accept_prob =
586,743,530✔
1045
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
586,743,530✔
1046
      (beta_vn + beta_vt);
586,743,530✔
1047

1048
    // Perform rejection sampling on vt and mu
1049
    if (prn(seed) < accept_prob)
586,743,530✔
1050
      break;
1051
  }
1052

1053
  // Determine speed of target nucleus
1054
  double vt = std::sqrt(beta_vt_sq * kT / awr);
506,843,547✔
1055

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

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

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

1074
  if (prn(seed) < beta) {
39,006,665✔
1075
    // ====================================================================
1076
    // DELAYED NEUTRON SAMPLED
1077

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

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

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

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

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

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

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

1112
  if (!model::active_point_tallies.empty()) {
39,006,665!
NEW
1113
    score_point_tally_fission(p, i_nuclide, rx, site->delayed_group);
×
1114
  }
1115

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

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

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

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

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

1146
  // copy energy of neutron
1147
  double E_in = p.E();
23,910,986✔
1148

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

1154
  double yield = (*rx.products_[0].yield_)(E_in);
23,910,986✔
1155

1156
  if (!model::active_point_tallies.empty()) {
23,910,986!
NEW
1157
    score_point_tally_inelastic(p, i_nuclide, rx, 0, yield);
×
1158
  }
1159

1160
  // if scattering system is in center-of-mass, transfer cosine of scattering
1161
  // angle and outgoing energy from CM to LAB
1162
  if (rx.scatter_in_cm_) {
23,910,986✔
1163
    double E_cm = E;
23,855,682✔
1164

1165
    // determine outgoing energy in lab
1166
    double A = nuc->awr_;
23,855,682✔
1167
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
23,855,682✔
1168
                 ((A + 1.0) * (A + 1.0));
23,855,682✔
1169

1170
    // determine outgoing angle in lab
1171
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
23,855,682✔
1172
  }
1173

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

1180
  // Set outgoing energy and scattering angle
1181
  p.E() = E;
23,910,986✔
1182
  p.mu() = mu;
23,910,986✔
1183

1184
  // change direction of particle
1185
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
23,910,986!
1186

1187
  if (std::floor(yield) == yield && yield > 0) {
23,910,986!
1188
    // If yield is integral, create exactly that many secondary particles
1189
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
24,040,916✔
1190
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
129,984✔
1191
    }
1192
  } else {
1193
    // Otherwise, change weight of particle based on yield
1194
    p.wgt() *= yield;
54✔
1195
  }
1196
}
23,910,986✔
1197

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

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

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

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

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

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

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

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

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

© 2026 Coveralls, Inc