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

openmc-dev / openmc / 23148760986

16 Mar 2026 02:27PM UTC coverage: 81.202% (-0.2%) from 81.435%
23148760986

Pull #3757

github

web-flow
Merge 6206e3966 into 157869812
Pull Request #3757: Testing point detectors

17624 of 25493 branches covered (69.13%)

Branch coverage included in aggregate %.

44 of 227 new or added lines in 14 files covered. (19.38%)

1 existing line in 1 file now uncovered.

58081 of 67737 relevant lines covered (85.74%)

44465291.14 hits per line

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

83.65
/src/physics.cpp
1
#include "openmc/physics.h"
2

3
#include "openmc/bank.h"
4
#include "openmc/bremsstrahlung.h"
5
#include "openmc/chain.h"
6
#include "openmc/constants.h"
7
#include "openmc/distribution_multi.h"
8
#include "openmc/eigenvalue.h"
9
#include "openmc/endf.h"
10
#include "openmc/error.h"
11
#include "openmc/ifp.h"
12
#include "openmc/material.h"
13
#include "openmc/math_functions.h"
14
#include "openmc/message_passing.h"
15
#include "openmc/ncrystal_interface.h"
16
#include "openmc/nuclide.h"
17
#include "openmc/photon.h"
18
#include "openmc/physics_common.h"
19
#include "openmc/random_dist.h"
20
#include "openmc/random_lcg.h"
21
#include "openmc/reaction.h"
22
#include "openmc/search.h"
23
#include "openmc/secondary_uncorrelated.h"
24
#include "openmc/settings.h"
25
#include "openmc/simulation.h"
26
#include "openmc/string_utils.h"
27
#include "openmc/tallies/tally.h"
28
#include "openmc/tallies/tally_scoring.h"
29
#include "openmc/thermal.h"
30
#include "openmc/weight_windows.h"
31

32
#include <fmt/core.h>
33

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

38
namespace openmc {
39

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

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

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

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

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

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

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

111
  // Save which nuclide particle had collision with
112
  p.event_nuclide() = i_nuclide;
1,000,056,917✔
113

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

119
  const auto& nuc {data::nuclides[i_nuclide]};
1,000,056,917✔
120

121
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
1,000,056,917✔
122
    auto& rx = sample_fission(i_nuclide, p);
125,749,080✔
123
    if (settings::run_mode == RunMode::EIGENVALUE) {
125,749,080✔
124
      create_fission_sites(p, i_nuclide, rx);
100,744,958✔
125
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
25,004,122✔
126
               settings::create_fission_neutrons) {
127
      create_fission_sites(p, i_nuclide, rx);
558,074✔
128

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

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

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

149
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
1,000,056,917✔
150
    absorption(p, i_nuclide);
1,000,053,397✔
151
  }
152
  if (!p.alive())
1,000,056,917✔
153
    return;
154

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

164
  // Advance URR seed stream 'N' times after energy changes
165
  if (p.E() != p.E_last()) {
976,589,961✔
166
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
976,270,730✔
167
  }
168

169
  // Play russian roulette if there are no weight windows
170
  if (!settings::weight_windows_on)
976,589,961✔
171
    apply_russian_roulette(p);
912,986,116✔
172
}
173

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

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

185
  // Sample the number of neutrons produced
186
  int nu = static_cast<int>(nu_t);
101,303,032✔
187
  if (prn(p.current_seed()) <= (nu_t - nu))
101,303,032✔
188
    ++nu;
20,790,715✔
189

190
  // If no neutrons were produced then don't continue
191
  if (nu == 0)
101,303,032✔
192
    return;
76,496,717✔
193

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

198
  // Clear out particle's nu fission bank
199
  p.nu_bank().clear();
24,806,315✔
200

201
  p.fission() = true;
24,806,315✔
202

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

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

211
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
55,428,085✔
212
    // Initialize fission site object with particle data
213
    SourceSite site;
30,621,770✔
214
    site.r = p.r();
30,621,770✔
215
    site.particle = ParticleType::neutron();
30,621,770✔
216
    site.time = p.time();
30,621,770✔
217
    site.wgt = 1. / weight;
30,621,770✔
218
    site.surf_id = 0;
30,621,770✔
219

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

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

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

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

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

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

261
    // Increment the number of neutrons born delayed
262
    if (site.delayed_group > 0) {
30,621,770✔
263
      nu_d[site.delayed_group - 1]++;
192,067✔
264
    }
265

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

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

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

284
  // Store the total weight banked for analog fission tallies
285
  p.n_bank() = nu;
24,806,315✔
286
  p.wgt_bank() = nu / weight;
24,806,315✔
287
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
223,256,835✔
288
    p.n_delayed_bank(d) = nu_d[d];
198,450,520✔
289
  }
290
}
291

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

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

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

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

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

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

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

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

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

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

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

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

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

387
      // Check threshold of reaction
388
      if (xs_lower(i_shell) == 0)
24,490,667✔
389
        continue;
10,265,941✔
390

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

511
  double prob = 0.0;
1,000,056,917✔
512
  for (int i = 0; i < n; ++i) {
2,124,487,640!
513
    // Get atom density
514
    int i_nuclide = mat->nuclide_[i];
2,124,487,640✔
515
    double atom_density = mat->atom_density(i, p.density_mult());
2,124,487,640✔
516

517
    // Increment probability to compare to cutoff
518
    prob += atom_density * p.neutron_xs(i_nuclide).total;
2,124,487,640✔
519
    if (prob >= cutoff)
2,124,487,640✔
520
      return i_nuclide;
1,000,056,917✔
521
  }
522

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

656
    // Score implicit absorption estimate of keff
657
    if (settings::run_mode == RunMode::EIGENVALUE) {
5,744,970✔
658
      p.keff_tally_absorption() += wgt_absorb *
499,950✔
659
                                   p.neutron_xs(i_nuclide).nu_fission /
499,950✔
660
                                   p.neutron_xs(i_nuclide).absorption;
499,950✔
661
    }
662
  } else {
663
    // See if disappearance reaction happens
664
    if (p.neutron_xs(i_nuclide).absorption >
994,308,427✔
665
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
994,308,427✔
666
      // Score absorption estimate of keff
667
      if (settings::run_mode == RunMode::EIGENVALUE) {
23,465,999✔
668
        p.keff_tally_absorption() += p.wgt() *
17,779,573✔
669
                                     p.neutron_xs(i_nuclide).nu_fission /
17,779,573✔
670
                                     p.neutron_xs(i_nuclide).absorption;
17,779,573✔
671
      }
672

673
      p.wgt() = 0.0;
23,465,999✔
674
      p.event() = TallyEvent::ABSORB;
23,465,999✔
675
      if (!p.fission()) {
23,465,999✔
676
        p.event_mt() = N_DISAPPEAR;
14,665,447✔
677
      }
678
    }
679
  }
680
}
1,000,053,397✔
681

682
void scatter(Particle& p, int i_nuclide)
976,431,132✔
683
{
684
  // copy incoming direction
685
  Direction u_old {p.u()};
976,431,132✔
686

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

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

697
  // Calculate elastic cross section if it wasn't precalculated
698
  if (micro.elastic == CACHE_INVALID) {
976,431,132✔
699
    nuc->calculate_elastic_xs(p);
729,341,584✔
700
  }
701

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

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

710
    // Perform collision physics for elastic scattering
711
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
830,166,404✔
712

713
    p.event_mt() = ELASTIC;
830,166,404✔
714
    sampled = true;
830,166,404✔
715
  }
716

717
  prob = micro.elastic;
976,431,132✔
718
  if (prob > cutoff && !sampled) {
976,431,132✔
719
    // =======================================================================
720
    // S(A,B) SCATTERING
721

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

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

728
  if (!sampled) {
976,431,132✔
729
    // =======================================================================
730
    // INELASTIC SCATTERING
731

732
    int n = nuc->index_inelastic_scatter_.size();
18,786,653✔
733
    int i = 0;
18,786,653✔
734
    for (int j = 0; j < n && prob < cutoff; ++j) {
353,809,448✔
735
      i = nuc->index_inelastic_scatter_[j];
335,022,795✔
736

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

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

747
  // Set event component
748
  p.event() = TallyEvent::SCATTER;
976,431,132✔
749

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

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

767
  double vel = std::sqrt(p.E());
830,166,404✔
768
  double awr = nuc->awr_;
830,166,404✔
769

770
  // Neutron velocity in LAB
771
  Direction v_n = vel * p.u();
830,166,404✔
772

773
  // Sample velocity of target nucleus
774
  Direction v_t {};
830,166,404✔
775
  if (!p.neutron_xs(i_nuclide).use_ptable) {
830,166,404✔
776
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
790,813,793✔
777
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
790,813,793✔
778
  }
779

780
  // Velocity of center-of-mass
781
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
830,166,404✔
782

783
  // Transform to CM frame
784
  v_n -= v_cm;
830,166,404✔
785

786
  // Find speed of neutron in CM
787
  vel = v_n.norm();
830,166,404✔
788

789
  if (!model::active_point_tallies.empty()) {
830,166,404!
NEW
790
    score_point_tally(p, i_nuclide, rx, 0, &v_t);
×
791
  }
792

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

804
  // Determine direction cosines in CM
805
  Direction u_cm = v_n / vel;
830,166,404✔
806

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

812
  // Transform back to LAB frame
813
  v_n += v_cm;
830,166,404✔
814

815
  p.E() = v_n.dot(v_n);
830,166,404✔
816
  vel = std::sqrt(p.E());
830,166,404✔
817

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

822
  // Set energy and direction of particle in LAB frame
823
  p.u() = v_n / vel;
830,166,404!
824

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

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

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

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

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

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

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

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

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

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

872
    // otherwise, use free gas model
873
  } else {
874
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
790,729,236✔
875
      return {};
406,560,429✔
876
    } else {
877
      sampling_method = ResScatMethod::cxs;
878
    }
879
  }
880

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1004
  UNREACHABLE();
×
1005
}
1006

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

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

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

1025
      beta_vt_sq = -std::log(r1 * r2);
103,295,331✔
1026

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

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

1036
    // Determine beta * vt
1037
    double beta_vt = std::sqrt(beta_vt_sq);
448,178,393✔
1038

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

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

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

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

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

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

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

1073
  if (prn(seed) < beta) {
30,621,770✔
1074
    // ====================================================================
1075
    // DELAYED NEUTRON SAMPLED
1076

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

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

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

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

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

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

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

1111
  if (!model::active_point_tallies.empty()) {
30,621,770!
NEW
1112
    score_point_tally(p, i_nuclide, rx, site->delayed_group, nullptr);
×
1113
  }
1114

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

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

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

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

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

1145
  // copy energy of neutron
1146
  double E_in = p.E();
18,786,653✔
1147

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

1153
  if (!model::active_point_tallies.empty()) {
18,786,653!
NEW
1154
    score_point_tally(p, i_nuclide, rx, 0, nullptr);
×
1155
  }
1156

1157
  // if scattering system is in center-of-mass, transfer cosine of scattering
1158
  // angle and outgoing energy from CM to LAB
1159
  if (rx.scatter_in_cm_) {
18,786,653✔
1160
    double E_cm = E;
18,731,349✔
1161

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

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

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

1177
  // Set outgoing energy and scattering angle
1178
  p.E() = E;
18,786,653✔
1179
  p.mu() = mu;
18,786,653✔
1180

1181
  // change direction of particle
1182
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
18,786,653✔
1183

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

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

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

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

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

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

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

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

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

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

© 2026 Coveralls, Inc