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

openmc-dev / openmc / 21686031975

04 Feb 2026 07:50PM UTC coverage: 81.024% (-0.7%) from 81.763%
21686031975

Pull #3755

github

web-flow
Merge 27d6053a4 into b41e22f68
Pull Request #3755: Warn users that tally heating score with photon bin but without electron and positron bins.

16378 of 22828 branches covered (71.75%)

Branch coverage included in aggregate %.

22 of 23 new or added lines in 1 file covered. (95.65%)

862 existing lines in 51 files now uncovered.

54491 of 64639 relevant lines covered (84.3%)

8259986.93 hits per line

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

82.58
/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/thermal.h"
29
#include "openmc/weight_windows.h"
30

31
#include <fmt/core.h>
32

33
#include <algorithm> // for max, min, max_element
34
#include <cmath>     // for sqrt, exp, log, abs, copysign
35
#include <xtensor/xview.hpp>
36

37
namespace openmc {
38

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

43
void collision(Particle& p)
85,316,314✔
44
{
45
  // Add to collision counter for particle
46
  ++(p.n_collision());
85,316,314✔
47

48
  // Sample reaction for the material the particle is in
49
  switch (p.type().pdg_number()) {
85,316,314!
50
  case PDG_NEUTRON:
78,885,774✔
51
    sample_neutron_reaction(p);
78,885,774✔
52
    break;
78,885,774✔
53
  case PDG_PHOTON:
1,569,264✔
54
    sample_photon_reaction(p);
1,569,264✔
55
    break;
1,569,264✔
56
  case PDG_ELECTRON:
4,853,343✔
57
    sample_electron_reaction(p);
4,853,343✔
58
    break;
4,853,343✔
59
  case PDG_POSITRON:
7,933✔
60
    sample_positron_reaction(p);
7,933✔
61
    break;
7,933✔
62
  default:
×
63
    fatal_error("Unsupported particle PDG for collision sampling.");
×
64
  }
65

66
  if (settings::weight_window_checkpoint_collision)
85,316,314!
67
    apply_weight_windows(p);
85,316,314✔
68

69
  // Kill particle if energy falls below cutoff
70
  int type = p.type().transport_index();
85,316,314✔
71
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
85,316,314!
72
    p.wgt() = 0.0;
471,581✔
73
  }
74

75
  // Display information about collision
76
  if (settings::verbosity >= 10 || p.trace()) {
85,316,314!
77
    std::string msg;
6✔
78
    if (p.event() == TallyEvent::KILL) {
6!
79
      msg = fmt::format("    Killed. Energy = {} eV.", p.E());
×
80
    } else if (p.type().is_neutron()) {
6!
81
      msg = fmt::format("    {} with {}. Energy = {} eV.",
18✔
82
        reaction_name(p.event_mt()), data::nuclides[p.event_nuclide()]->name_,
12✔
83
        p.E());
6✔
84
    } else if (p.type().is_photon()) {
×
85
      msg = fmt::format("    {} with {}. Energy = {} eV.",
×
86
        reaction_name(p.event_mt()),
×
87
        to_element(data::nuclides[p.event_nuclide()]->name_), p.E());
×
88
    } else {
89
      msg = fmt::format("    Disappeared. Energy = {} eV.", p.E());
×
90
    }
91
    write_message(msg, 1);
6✔
92
  }
6✔
93
}
85,316,314✔
94

95
void sample_neutron_reaction(Particle& p)
78,885,774✔
96
{
97
  // Sample a nuclide within the material
98
  int i_nuclide = sample_nuclide(p);
78,885,774✔
99

100
  // Save which nuclide particle had collision with
101
  p.event_nuclide() = i_nuclide;
78,885,774✔
102

103
  // Create fission bank sites. Note that while a fission reaction is sampled,
104
  // it never actually "happens", i.e. the weight of the particle does not
105
  // change when sampling fission sites. The following block handles all
106
  // absorption (including fission)
107

108
  const auto& nuc {data::nuclides[i_nuclide]};
78,885,774✔
109

110
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
78,885,774✔
111
    auto& rx = sample_fission(i_nuclide, p);
10,386,325✔
112
    if (settings::run_mode == RunMode::EIGENVALUE) {
10,386,325✔
113
      create_fission_sites(p, i_nuclide, rx);
8,941,317✔
114
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
1,445,008✔
115
               settings::create_fission_neutrons) {
116
      create_fission_sites(p, i_nuclide, rx);
30,746✔
117

118
      // Make sure particle population doesn't grow out of control for
119
      // subcritical multiplication problems.
120
      if (p.secondary_bank().size() >= settings::max_secondaries) {
30,746!
121
        fatal_error(
×
122
          "The secondary particle bank appears to be growing without "
123
          "bound. You are likely running a subcritical multiplication problem "
124
          "with k-effective close to or greater than one.");
125
      }
126
    }
127
    p.event_mt() = rx.mt_;
10,386,325✔
128
  }
129

130
  // Create secondary photons
131
  if (settings::photon_transport) {
78,885,774✔
132
    sample_secondary_photons(p, i_nuclide);
800,868✔
133
  }
134

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

138
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
78,885,774✔
139
    absorption(p, i_nuclide);
78,885,454✔
140
  }
141
  if (!p.alive())
78,885,774✔
142
    return;
1,973,731✔
143

144
  // Sample a scattering reaction and determine the secondary energy of the
145
  // exiting neutron
146
  const auto& ncrystal_mat = model::materials[p.material()]->ncrystal_mat();
76,912,043✔
147
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
76,912,043!
148
    ncrystal_mat.scatter(p);
14,439✔
149
  } else {
150
    scatter(p, i_nuclide);
76,897,604✔
151
  }
152

153
  // Advance URR seed stream 'N' times after energy changes
154
  if (p.E() != p.E_last()) {
76,912,043✔
155
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
76,883,022✔
156
  }
157

158
  // Play russian roulette if survival biasing is turned on
159
  if (settings::survival_biasing) {
76,912,043✔
160
    // if survival normalization is on, use normalized weight cutoff and
161
    // normalized weight survive
162
    if (settings::survival_normalization) {
45,450!
163
      if (p.wgt() < settings::weight_cutoff * p.wgt_born()) {
×
164
        russian_roulette(p, settings::weight_survive * p.wgt_born());
×
165
      }
166
    } else if (p.wgt() < settings::weight_cutoff) {
45,450✔
167
      russian_roulette(p, settings::weight_survive);
5,181✔
168
    }
169
  }
170
}
171

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

178
  // Determine the expected number of neutrons produced
179
  double nu_t = p.wgt() / simulation::keff * weight *
8,972,063✔
180
                p.neutron_xs(i_nuclide).nu_fission /
8,972,063✔
181
                p.neutron_xs(i_nuclide).total;
8,972,063✔
182

183
  // Sample the number of neutrons produced
184
  int nu = static_cast<int>(nu_t);
8,972,063✔
185
  if (prn(p.current_seed()) <= (nu_t - nu))
8,972,063✔
186
    ++nu;
1,844,681✔
187

188
  // If no neutrons were produced then don't continue
189
  if (nu == 0)
8,972,063✔
190
    return;
6,773,749✔
191

192
  // Initialize the counter of delayed neutrons encountered for each delayed
193
  // group.
194
  double nu_d[MAX_DELAYED_GROUPS] = {0.};
2,198,314✔
195

196
  // Clear out particle's nu fission bank
197
  p.nu_bank().clear();
2,198,314✔
198

199
  p.fission() = true;
2,198,314✔
200

201
  // Determine whether to place fission sites into the shared fission bank
202
  // or the secondary particle bank.
203
  bool use_fission_bank = (settings::run_mode == RunMode::EIGENVALUE);
2,198,314✔
204

205
  // Counter for the number of fission sites successfully stored to the shared
206
  // fission bank or the secondary particle bank
207
  int n_sites_stored;
208

209
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
4,904,363✔
210
    // Initialize fission site object with particle data
211
    SourceSite site;
2,706,049✔
212
    site.r = p.r();
2,706,049✔
213
    site.particle = ParticleType::neutron();
2,706,049✔
214
    site.time = p.time();
2,706,049✔
215
    site.wgt = 1. / weight;
2,706,049✔
216
    site.surf_id = 0;
2,706,049✔
217

218
    // Sample delayed group and angle/energy for fission reaction
219
    sample_fission_neutron(i_nuclide, rx, &site, p);
2,706,049✔
220

221
    // Reject site if it exceeds time cutoff
222
    if (site.delayed_group > 0) {
2,706,049✔
223
      double t_cutoff = settings::time_cutoff[site.particle.transport_index()];
17,001✔
224
      if (site.time > t_cutoff) {
17,001!
225
        continue;
×
226
      }
227
    }
228

229
    // Set parent and progeny IDs
230
    site.parent_id = p.id();
2,706,049✔
231
    site.progeny_id = p.n_progeny()++;
2,706,049✔
232

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

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

247
        // Break out of loop as no more sites can be added to fission bank
248
        break;
×
249
      }
250
      // Iterated Fission Probability (IFP) method
251
      if (settings::ifp_on) {
2,706,017✔
252
        ifp(p, idx);
122,966✔
253
      }
254
    } else {
255
      p.secondary_bank().push_back(site);
32✔
256
    }
257

258
    // Increment the number of neutrons born delayed
259
    if (site.delayed_group > 0) {
2,706,049✔
260
      nu_d[site.delayed_group - 1]++;
17,001✔
261
    }
262

263
    // Write fission particles to nuBank
264
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
2,706,049✔
265
    nu_bank_entry.wgt = site.wgt;
2,706,049✔
266
    nu_bank_entry.E = site.E;
2,706,049✔
267
    nu_bank_entry.delayed_group = site.delayed_group;
2,706,049✔
268
  }
269

270
  // If shared fission bank was full, and no fissions could be added,
271
  // set the particle fission flag to false.
272
  if (n_sites_stored == 0) {
2,198,314!
273
    p.fission() = false;
×
274
    return;
×
275
  }
276

277
  // Set nu to the number of fission sites successfully stored. If the fission
278
  // bank was not found to be full then these values are already equivalent.
279
  nu = n_sites_stored;
2,198,314✔
280

281
  // Store the total weight banked for analog fission tallies
282
  p.n_bank() = nu;
2,198,314✔
283
  p.wgt_bank() = nu / weight;
2,198,314✔
284
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
19,784,826✔
285
    p.n_delayed_bank(d) = nu_d[d];
17,586,512✔
286
  }
287
}
288

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

301
  // Sample element within material
302
  int i_element = sample_element(p);
1,569,264✔
303
  const auto& micro {p.photon_xs(i_element)};
1,569,264✔
304
  const auto& element {*data::elements[i_element]};
1,569,264✔
305

306
  // Calculate photon energy over electron rest mass equivalent
307
  double alpha = p.E() / MASS_ELECTRON_EV;
1,569,264✔
308

309
  // For tallying purposes, this routine might be called directly. In that
310
  // case, we need to sample a reaction via the cutoff variable
311
  double prob = 0.0;
1,569,264✔
312
  double cutoff = prn(p.current_seed()) * micro.total;
1,569,264✔
313

314
  // Coherent (Rayleigh) scattering
315
  prob += micro.coherent;
1,569,264✔
316
  if (prob > cutoff) {
1,569,264✔
317
    p.mu() = element.rayleigh_scatter(alpha, p.current_seed());
86,438✔
318
    p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
86,438✔
319
    p.event() = TallyEvent::SCATTER;
86,438✔
320
    p.event_mt() = COHERENT;
86,438✔
321
    return;
86,438✔
322
  }
323

324
  // Incoherent (Compton) scattering
325
  prob += micro.incoherent;
1,482,826✔
326
  if (prob > cutoff) {
1,482,826✔
327
    double alpha_out;
328
    int i_shell;
329
    element.compton_scatter(
2,024,476✔
330
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
1,012,238✔
331

332
    // Determine binding energy of shell. The binding energy is 0.0 if
333
    // doppler broadening is not used.
334
    double e_b;
335
    if (i_shell == -1) {
1,012,238!
336
      e_b = 0.0;
×
337
    } else {
338
      e_b = element.binding_energy_[i_shell];
1,012,238✔
339
    }
340

341
    // Create Compton electron
342
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
1,012,238✔
343
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
1,012,238✔
344
    int electron = ParticleType::electron().transport_index();
1,012,238✔
345
    if (E_electron >= settings::energy_cutoff[electron]) {
1,012,238✔
346
      double mu_electron = (alpha - alpha_out * p.mu()) /
1,002,722✔
347
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
2,005,444✔
348
                                     2.0 * alpha * alpha_out * p.mu());
1,002,722✔
349
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
1,002,722✔
350
      p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
1,002,722✔
351
    }
352

353
    // Allow electrons to fill orbital and produce Auger electrons and
354
    // fluorescent photons. Since Compton subshell data does not match atomic
355
    // relaxation data, use the mapping between the data to find the subshell
356
    if (i_shell >= 0 && element.subshell_map_[i_shell] >= 0) {
1,012,238!
357
      element.atomic_relaxation(element.subshell_map_[i_shell], p);
1,012,238✔
358
    }
359

360
    phi += PI;
1,012,238✔
361
    p.E() = alpha_out * MASS_ELECTRON_EV;
1,012,238✔
362
    p.u() = rotate_angle(p.u(), p.mu(), &phi, p.current_seed());
1,012,238✔
363
    p.event() = TallyEvent::SCATTER;
1,012,238✔
364
    p.event_mt() = INCOHERENT;
1,012,238✔
365
    return;
1,012,238✔
366
  }
367

368
  // Photoelectric effect
369
  double prob_after = prob + micro.photoelectric;
470,588✔
370

371
  if (prob_after > cutoff) {
470,588✔
372
    // Get grid index, interpolation factor, and bounding subshell
373
    // cross sections
374
    int i_grid = micro.index_grid;
462,655✔
375
    double f = micro.interp_factor;
462,655✔
376
    const auto& xs_lower = xt::row(element.cross_sections_, i_grid);
462,655✔
377
    const auto& xs_upper = xt::row(element.cross_sections_, i_grid + 1);
462,655✔
378

379
    for (int i_shell = 0; i_shell < element.shells_.size(); ++i_shell) {
2,207,893!
380
      const auto& shell {element.shells_[i_shell]};
2,207,893✔
381

382
      // Check threshold of reaction
383
      if (xs_lower(i_shell) == 0)
2,207,893✔
384
        continue;
933,297✔
385

386
      //  Evaluation subshell photoionization cross section
387
      prob += std::exp(
1,274,596✔
388
        xs_lower(i_shell) + f * (xs_upper(i_shell) - xs_lower(i_shell)));
1,274,596✔
389

390
      if (prob > cutoff) {
1,274,596✔
391
        // Determine binding energy based on whether atomic relaxation data is
392
        // present (if not, use value from Compton profile data)
393
        double binding_energy = element.has_atomic_relaxation_
462,655✔
394
                                  ? shell.binding_energy
462,655!
395
                                  : element.binding_energy_[i_shell];
×
396

397
        // Determine energy of secondary electron
398
        double E_electron = p.E() - binding_energy;
462,655✔
399

400
        // Sample mu using non-relativistic Sauter distribution.
401
        // See Eqns 3.19 and 3.20 in "Implementing a photon physics
402
        // model in Serpent 2" by Toni Kaltiaisenaho
403
        double mu;
404
        while (true) {
405
          double r = prn(p.current_seed());
693,992✔
406
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
693,992✔
407
            double rel_vel =
408
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
462,655✔
409
              (E_electron + MASS_ELECTRON_EV);
462,655✔
410
            mu =
462,655✔
411
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
462,655✔
412
            break;
462,655✔
413
          }
414
        }
231,337✔
415

416
        double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
462,655✔
417
        Direction u;
462,655✔
418
        u.x = mu;
462,655✔
419
        u.y = std::sqrt(1.0 - mu * mu) * std::cos(phi);
462,655✔
420
        u.z = std::sqrt(1.0 - mu * mu) * std::sin(phi);
462,655✔
421

422
        // Create secondary electron
423
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
462,655✔
424

425
        // Allow electrons to fill orbital and produce auger electrons
426
        // and fluorescent photons
427
        element.atomic_relaxation(i_shell, p);
462,655✔
428
        p.event() = TallyEvent::ABSORB;
462,655✔
429
        p.event_mt() = 533 + shell.index_subshell;
462,655✔
430
        p.wgt() = 0.0;
462,655✔
431
        p.E() = 0.0;
462,655✔
432
        return;
462,655✔
433
      }
434
    }
435
  }
925,310!
436
  prob = prob_after;
7,933✔
437

438
  // Pair production
439
  prob += micro.pair_production;
7,933✔
440
  if (prob > cutoff) {
7,933!
441
    double E_electron, E_positron;
442
    double mu_electron, mu_positron;
443
    element.pair_production(alpha, &E_electron, &E_positron, &mu_electron,
7,933✔
444
      &mu_positron, p.current_seed());
445

446
    // Create secondary electron
447
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
7,933✔
448
    p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
7,933✔
449

450
    // Create secondary positron
451
    u = rotate_angle(p.u(), mu_positron, nullptr, p.current_seed());
7,933✔
452
    p.create_secondary(p.wgt(), u, E_positron, ParticleType::positron());
7,933✔
453
    p.event() = TallyEvent::ABSORB;
7,933✔
454
    p.event_mt() = PAIR_PROD;
7,933✔
455
    p.wgt() = 0.0;
7,933✔
456
    p.E() = 0.0;
7,933✔
457
  }
458
}
459

460
void sample_electron_reaction(Particle& p)
4,853,343✔
461
{
462
  // TODO: create reaction types
463

464
  if (settings::electron_treatment == ElectronTreatment::TTB) {
4,853,343✔
465
    double E_lost;
466
    thick_target_bremsstrahlung(p, &E_lost);
4,825,738✔
467
  }
468

469
  p.E() = 0.0;
4,853,343✔
470
  p.wgt() = 0.0;
4,853,343✔
471
  p.event() = TallyEvent::ABSORB;
4,853,343✔
472
}
4,853,343✔
473

474
void sample_positron_reaction(Particle& p)
7,933✔
475
{
476
  // TODO: create reaction types
477

478
  if (settings::electron_treatment == ElectronTreatment::TTB) {
7,933✔
479
    double E_lost;
480
    thick_target_bremsstrahlung(p, &E_lost);
7,818✔
481
  }
482

483
  // Sample angle isotropically
484
  Direction u = isotropic_direction(p.current_seed());
7,933✔
485

486
  // Create annihilation photon pair traveling in opposite directions
487
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon());
7,933✔
488
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon());
7,933✔
489

490
  p.E() = 0.0;
7,933✔
491
  p.wgt() = 0.0;
7,933✔
492
  p.event() = TallyEvent::ABSORB;
7,933✔
493
}
7,933✔
494

495
int sample_nuclide(Particle& p)
78,885,774✔
496
{
497
  // Sample cumulative distribution function
498
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
78,885,774✔
499

500
  // Get pointers to nuclide/density arrays
501
  const auto& mat {model::materials[p.material()]};
78,885,774✔
502
  int n = mat->nuclide_.size();
78,885,774✔
503

504
  double prob = 0.0;
78,885,774✔
505
  for (int i = 0; i < n; ++i) {
168,356,055!
506
    // Get atom density
507
    int i_nuclide = mat->nuclide_[i];
168,356,055✔
508
    double atom_density = mat->atom_density(i, p.density_mult());
168,356,055✔
509

510
    // Increment probability to compare to cutoff
511
    prob += atom_density * p.neutron_xs(i_nuclide).total;
168,356,055✔
512
    if (prob >= cutoff)
168,356,055✔
513
      return i_nuclide;
78,885,774✔
514
  }
515

516
  // If we reach here, no nuclide was sampled
517
  p.write_restart();
×
518
  throw std::runtime_error {"Did not sample any nuclide during collision."};
×
519
}
520

521
int sample_element(Particle& p)
1,569,264✔
522
{
523
  // Sample cumulative distribution function
524
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,569,264✔
525

526
  // Get pointers to elements, densities
527
  const auto& mat {model::materials[p.material()]};
1,569,264✔
528

529
  double prob = 0.0;
1,569,264✔
530
  for (int i = 0; i < mat->element_.size(); ++i) {
3,750,786!
531
    // Find atom density
532
    int i_element = mat->element_[i];
3,750,786✔
533
    double atom_density = mat->atom_density(i, p.density_mult());
3,750,786✔
534

535
    // Determine microscopic cross section
536
    double sigma = atom_density * p.photon_xs(i_element).total;
3,750,786✔
537

538
    // Increment probability to compare to cutoff
539
    prob += sigma;
3,750,786✔
540
    if (prob > cutoff) {
3,750,786✔
541
      // Save which nuclide particle had collision with for tally purpose
542
      p.event_nuclide() = mat->nuclide_[i];
1,569,264✔
543

544
      return i_element;
1,569,264✔
545
    }
546
  }
547

548
  // If we made it here, no element was sampled
549
  p.write_restart();
×
550
  fatal_error("Did not sample any element during collision.");
×
551
}
552

553
Reaction& sample_fission(int i_nuclide, Particle& p)
10,386,325✔
554
{
555
  // Get pointer to nuclide
556
  const auto& nuc {data::nuclides[i_nuclide]};
10,386,325✔
557

558
  // If we're in the URR, by default use the first fission reaction. We also
559
  // default to the first reaction if we know that there are no partial fission
560
  // reactions
561
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
10,386,325✔
562
    return *nuc->fission_rx_[0];
10,384,246✔
563
  }
564

565
  // Check to see if we are in a windowed multipole range.  WMP only supports
566
  // the first fission reaction.
567
  if (nuc->multipole_) {
2,079!
568
    if (p.E() >= nuc->multipole_->E_min_ && p.E() <= nuc->multipole_->E_max_) {
×
569
      return *nuc->fission_rx_[0];
×
570
    }
571
  }
572

573
  // Get grid index and interpolation factor and sample fission cdf
574
  const auto& micro = p.neutron_xs(i_nuclide);
2,079✔
575
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
2,079✔
576
  double prob = 0.0;
2,079✔
577

578
  // Loop through each partial fission reaction type
579
  for (auto& rx : nuc->fission_rx_) {
2,082!
580
    // add to cumulative probability
581
    prob += rx->xs(micro);
2,082✔
582

583
    // Create fission bank sites if fission occurs
584
    if (prob > cutoff)
2,082✔
585
      return *rx;
2,079✔
586
  }
587

588
  // If we reached here, no reaction was sampled
589
  throw std::runtime_error {
×
590
    "No fission reaction was sampled for " + nuc->name_};
×
591
}
592

593
void sample_photon_product(
121,604✔
594
  int i_nuclide, Particle& p, int* i_rx, int* i_product)
595
{
596
  // Get grid index and interpolation factor and sample photon production cdf
597
  const auto& micro = p.neutron_xs(i_nuclide);
121,604✔
598
  double cutoff = prn(p.current_seed()) * micro.photon_prod;
121,604✔
599
  double prob = 0.0;
121,604✔
600

601
  // Loop through each reaction type
602
  const auto& nuc {data::nuclides[i_nuclide]};
121,604✔
603
  for (int i = 0; i < nuc->reactions_.size(); ++i) {
1,999,621!
604
    // Evaluate neutron cross section
605
    const auto& rx = nuc->reactions_[i];
1,999,621✔
606
    double xs = rx->xs(micro);
1,999,621✔
607

608
    // if cross section is zero for this reaction, skip it
609
    if (xs == 0.0)
1,999,621✔
610
      continue;
653,765✔
611

612
    for (int j = 0; j < rx->products_.size(); ++j) {
6,325,227✔
613
      if (rx->products_[j].particle_.is_photon()) {
5,100,975✔
614
        // For fission, artificially increase the photon yield to account
615
        // for delayed photons
616
        double f = 1.0;
3,968,810✔
617
        if (settings::delayed_photon_scaling) {
3,968,810!
618
          if (is_fission(rx->mt_)) {
3,968,810✔
619
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
49,111!
620
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
49,111✔
621
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
49,111✔
622
              f = (energy_prompt + energy_delayed) / (energy_prompt);
49,111✔
623
            }
624
          }
625
        }
626

627
        // add to cumulative probability
628
        prob += f * (*rx->products_[j].yield_)(p.E()) * xs;
3,968,810✔
629

630
        *i_rx = i;
3,968,810✔
631
        *i_product = j;
3,968,810✔
632
        if (prob > cutoff)
3,968,810✔
633
          return;
121,604✔
634
      }
635
    }
636
  }
637
}
638

639
void absorption(Particle& p, int i_nuclide)
78,885,454✔
640
{
641
  if (settings::survival_biasing) {
78,885,454✔
642
    // Determine weight absorbed in survival biasing
643
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
45,450✔
644
                              p.neutron_xs(i_nuclide).total;
45,450✔
645

646
    // Adjust weight of particle by probability of absorption
647
    p.wgt() -= wgt_absorb;
45,450✔
648

649
    // Score implicit absorption estimate of keff
650
    if (settings::run_mode == RunMode::EIGENVALUE) {
45,450!
651
      p.keff_tally_absorption() += wgt_absorb *
45,450✔
652
                                   p.neutron_xs(i_nuclide).nu_fission /
45,450✔
653
                                   p.neutron_xs(i_nuclide).absorption;
45,450✔
654
    }
655
  } else {
656
    // See if disappearance reaction happens
657
    if (p.neutron_xs(i_nuclide).absorption >
78,840,004✔
658
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
78,840,004✔
659
      // Score absorption estimate of keff
660
      if (settings::run_mode == RunMode::EIGENVALUE) {
1,973,731✔
661
        p.keff_tally_absorption() += p.wgt() *
3,130,348✔
662
                                     p.neutron_xs(i_nuclide).nu_fission /
1,565,174✔
663
                                     p.neutron_xs(i_nuclide).absorption;
1,565,174✔
664
      }
665

666
      p.wgt() = 0.0;
1,973,731✔
667
      p.event() = TallyEvent::ABSORB;
1,973,731✔
668
      if (!p.fission()) {
1,973,731✔
669
        p.event_mt() = N_DISAPPEAR;
1,203,588✔
670
      }
671
    }
672
  }
673
}
78,885,454✔
674

675
void scatter(Particle& p, int i_nuclide)
76,897,604✔
676
{
677
  // copy incoming direction
678
  Direction u_old {p.u()};
76,897,604✔
679

680
  // Get pointer to nuclide and grid index/interpolation factor
681
  const auto& nuc {data::nuclides[i_nuclide]};
76,897,604✔
682
  const auto& micro {p.neutron_xs(i_nuclide)};
76,897,604✔
683
  int i_temp = micro.index_temp;
76,897,604✔
684

685
  // For tallying purposes, this routine might be called directly. In that
686
  // case, we need to sample a reaction via the cutoff variable
687
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
76,897,604✔
688
  bool sampled = false;
76,897,604✔
689

690
  // Calculate elastic cross section if it wasn't precalculated
691
  if (micro.elastic == CACHE_INVALID) {
76,897,604✔
692
    nuc->calculate_elastic_xs(p);
63,375,274✔
693
  }
694

695
  double prob = micro.elastic - micro.thermal;
76,897,604✔
696
  if (prob > cutoff) {
76,897,604✔
697
    // =======================================================================
698
    // NON-S(A,B) ELASTIC SCATTERING
699

700
    // Determine temperature
701
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
65,756,152✔
702

703
    // Perform collision physics for elastic scattering
704
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
65,756,152✔
705

706
    p.event_mt() = ELASTIC;
65,756,152✔
707
    sampled = true;
65,756,152✔
708
  }
709

710
  prob = micro.elastic;
76,897,604✔
711
  if (prob > cutoff && !sampled) {
76,897,604✔
712
    // =======================================================================
713
    // S(A,B) SCATTERING
714

715
    sab_scatter(i_nuclide, micro.index_sab, p);
9,560,152✔
716

717
    p.event_mt() = ELASTIC;
9,560,152✔
718
    sampled = true;
9,560,152✔
719
  }
720

721
  if (!sampled) {
76,897,604✔
722
    // =======================================================================
723
    // INELASTIC SCATTERING
724

725
    int n = nuc->index_inelastic_scatter_.size();
1,581,300✔
726
    int i = 0;
1,581,300✔
727
    for (int j = 0; j < n && prob < cutoff; ++j) {
30,351,904✔
728
      i = nuc->index_inelastic_scatter_[j];
28,770,604✔
729

730
      // add to cumulative probability
731
      prob += nuc->reactions_[i]->xs(micro);
28,770,604✔
732
    }
733

734
    // Perform collision physics for inelastic scattering
735
    const auto& rx {nuc->reactions_[i]};
1,581,300✔
736
    inelastic_scatter(*nuc, *rx, p);
1,581,300✔
737
    p.event_mt() = rx->mt_;
1,581,300✔
738
  }
739

740
  // Set event component
741
  p.event() = TallyEvent::SCATTER;
76,897,604✔
742

743
  // Sample new outgoing angle for isotropic-in-lab scattering
744
  const auto& mat {model::materials[p.material()]};
76,897,604✔
745
  if (!mat->p0_.empty()) {
76,897,604✔
746
    int i_nuc_mat = mat->mat_nuclide_index_[i_nuclide];
29,670✔
747
    if (mat->p0_[i_nuc_mat]) {
29,670!
748
      // Sample isotropic-in-lab outgoing direction
749
      p.u() = isotropic_direction(p.current_seed());
29,670✔
750
      p.mu() = u_old.dot(p.u());
29,670✔
751
    }
752
  }
753
}
76,897,604✔
754

755
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
65,756,152✔
756
{
757
  // get pointer to nuclide
758
  const auto& nuc {data::nuclides[i_nuclide]};
65,756,152✔
759

760
  double vel = std::sqrt(p.E());
65,756,152✔
761
  double awr = nuc->awr_;
65,756,152✔
762

763
  // Neutron velocity in LAB
764
  Direction v_n = vel * p.u();
65,756,152✔
765

766
  // Sample velocity of target nucleus
767
  Direction v_t {};
65,756,152✔
768
  if (!p.neutron_xs(i_nuclide).use_ptable) {
65,756,152✔
769
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
126,477,358✔
770
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
63,238,679✔
771
  }
772

773
  // Velocity of center-of-mass
774
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
65,756,152✔
775

776
  // Transform to CM frame
777
  v_n -= v_cm;
65,756,152✔
778

779
  // Find speed of neutron in CM
780
  vel = v_n.norm();
65,756,152✔
781

782
  // Sample scattering angle, checking if angle distribution is present (assume
783
  // isotropic otherwise)
784
  double mu_cm;
785
  auto& d = rx.products_[0].distribution_[0];
65,756,152✔
786
  auto d_ = dynamic_cast<UncorrelatedAngleEnergy*>(d.get());
65,756,152!
787
  if (!d_->angle().empty()) {
65,756,152!
788
    mu_cm = d_->angle().sample(p.E(), p.current_seed());
65,756,152✔
789
  } else {
790
    mu_cm = uniform_distribution(-1., 1., p.current_seed());
×
791
  }
792

793
  // Determine direction cosines in CM
794
  Direction u_cm = v_n / vel;
65,756,152✔
795

796
  // Rotate neutron velocity vector to new angle -- note that the speed of the
797
  // neutron in CM does not change in elastic scattering. However, the speed
798
  // will change when we convert back to LAB
799
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
65,756,152✔
800

801
  // Transform back to LAB frame
802
  v_n += v_cm;
65,756,152✔
803

804
  p.E() = v_n.dot(v_n);
65,756,152✔
805
  vel = std::sqrt(p.E());
65,756,152✔
806

807
  // compute cosine of scattering angle in LAB frame by taking dot product of
808
  // neutron's pre- and post-collision angle
809
  p.mu() = p.u().dot(v_n) / vel;
65,756,152✔
810

811
  // Set energy and direction of particle in LAB frame
812
  p.u() = v_n / vel;
65,756,152✔
813

814
  // Because of floating-point roundoff, it may be possible for mu_lab to be
815
  // outside of the range [-1,1). In these cases, we just set mu_lab to exactly
816
  // -1 or 1
817
  if (std::abs(p.mu()) > 1.0)
65,756,152!
818
    p.mu() = std::copysign(1.0, p.mu());
×
819
}
65,756,152✔
820

821
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
9,560,152✔
822
{
823
  // Determine temperature index
824
  const auto& micro {p.neutron_xs(i_nuclide)};
9,560,152✔
825
  int i_temp = micro.index_temp_sab;
9,560,152✔
826

827
  // Sample energy and angle
828
  double E_out;
829
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
19,120,304✔
830
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
9,560,152✔
831

832
  // Set energy to outgoing, change direction of particle
833
  p.E() = E_out;
9,560,152✔
834
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
9,560,152✔
835
}
9,560,152✔
836

837
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
63,238,679✔
838
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
839
{
840
  // check if nuclide is a resonant scatterer
841
  ResScatMethod sampling_method;
842
  if (nuc.resonant_) {
63,238,679✔
843

844
    // sampling method to use
845
    sampling_method = settings::res_scat_method;
7,687✔
846

847
    // upper resonance scattering energy bound (target is at rest above this E)
848
    if (E > settings::res_scat_energy_max) {
7,687✔
849
      return {};
3,705✔
850

851
      // lower resonance scattering energy bound (should be no resonances below)
852
    } else if (E < settings::res_scat_energy_min) {
3,982✔
853
      sampling_method = ResScatMethod::cxs;
2,272✔
854
    }
855

856
    // otherwise, use free gas model
857
  } else {
858
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
63,230,992✔
859
      return {};
30,497,117✔
860
    } else {
861
      sampling_method = ResScatMethod::cxs;
32,733,875✔
862
    }
863
  }
864

865
  // use appropriate target velocity sampling method
866
  switch (sampling_method) {
32,737,857!
867
  case ResScatMethod::cxs:
32,736,147✔
868

869
    // sample target velocity with the constant cross section (cxs) approx.
870
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
32,736,147✔
871

872
  case ResScatMethod::dbrc:
1,710✔
873
  case ResScatMethod::rvs: {
874
    double E_red = std::sqrt(nuc.awr_ * E / kT);
1,710✔
875
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
1,710✔
876
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
1,710✔
877

878
    // find lower and upper energy bound indices
879
    // lower index
880
    int i_E_low;
881
    if (E_low < nuc.energy_0K_.front()) {
1,710!
882
      i_E_low = 0;
×
883
    } else if (E_low > nuc.energy_0K_.back()) {
1,710!
884
      i_E_low = nuc.energy_0K_.size() - 2;
×
885
    } else {
886
      i_E_low =
1,710✔
887
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
1,710✔
888
    }
889

890
    // upper index
891
    int i_E_up;
892
    if (E_up < nuc.energy_0K_.front()) {
1,710!
893
      i_E_up = 0;
×
894
    } else if (E_up > nuc.energy_0K_.back()) {
1,710!
895
      i_E_up = nuc.energy_0K_.size() - 2;
×
896
    } else {
897
      i_E_up =
1,710✔
898
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_up);
1,710✔
899
    }
900

901
    if (i_E_up == i_E_low) {
1,710✔
902
      // Handle degenerate case -- if the upper/lower bounds occur for the same
903
      // index, then using cxs is probably a good approximation
904
      return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
1,710✔
905
    }
906

907
    if (sampling_method == ResScatMethod::dbrc) {
1,412!
908
      // interpolate xs since we're not exactly at the energy indices
909
      double xs_low = nuc.elastic_0K_[i_E_low];
×
910
      double m = (nuc.elastic_0K_[i_E_low + 1] - xs_low) /
×
911
                 (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
×
912
      xs_low += m * (E_low - nuc.energy_0K_[i_E_low]);
×
913
      double xs_up = nuc.elastic_0K_[i_E_up];
×
914
      m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) /
×
915
          (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
×
916
      xs_up += m * (E_up - nuc.energy_0K_[i_E_up]);
×
917

918
      // get max 0K xs value over range of practical relative energies
919
      double xs_max = *std::max_element(
×
920
        &nuc.elastic_0K_[i_E_low + 1], &nuc.elastic_0K_[i_E_up + 1]);
×
921
      xs_max = std::max({xs_low, xs_max, xs_up});
×
922

923
      while (true) {
924
        double E_rel;
925
        Direction v_target;
×
926
        while (true) {
927
          // sample target velocity with the constant cross section (cxs)
928
          // approx.
929
          v_target = sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
×
930
          Direction v_rel = v_neut - v_target;
×
931
          E_rel = v_rel.dot(v_rel);
×
932
          if (E_rel < E_up)
×
933
            break;
×
934
        }
×
935

936
        // perform Doppler broadening rejection correction (dbrc)
937
        double xs_0K = nuc.elastic_xs_0K(E_rel);
×
938
        double R = xs_0K / xs_max;
×
939
        if (prn(seed) < R)
×
940
          return v_target;
×
941
      }
×
942

943
    } else if (sampling_method == ResScatMethod::rvs) {
1,412!
944
      // interpolate xs CDF since we're not exactly at the energy indices
945
      // cdf value at lower bound attainable energy
946
      double cdf_low = 0.0;
1,412✔
947
      if (E_low > nuc.energy_0K_.front()) {
1,412!
948
        double m = (nuc.xs_cdf_[i_E_low + 1] - nuc.xs_cdf_[i_E_low]) /
1,412✔
949
                   (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
1,412✔
950
        cdf_low = nuc.xs_cdf_[i_E_low] + m * (E_low - nuc.energy_0K_[i_E_low]);
1,412✔
951
      }
952

953
      // cdf value at upper bound attainable energy
954
      double m = (nuc.xs_cdf_[i_E_up + 1] - nuc.xs_cdf_[i_E_up]) /
1,412✔
955
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
1,412✔
956
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
1,412✔
957

958
      while (true) {
959
        // directly sample Maxwellian
960
        double E_t = -kT * std::log(prn(seed));
15,520✔
961

962
        // sample a relative energy using the xs cdf
963
        double cdf_rel = cdf_low + prn(seed) * (cdf_up - cdf_low);
15,520✔
964
        int i_E_rel = lower_bound_index(nuc.xs_cdf_.begin() + i_E_low,
15,520✔
965
          nuc.xs_cdf_.begin() + i_E_up + 2, cdf_rel);
15,520✔
966
        double E_rel = nuc.energy_0K_[i_E_low + i_E_rel];
15,520✔
967
        double m = (nuc.xs_cdf_[i_E_low + i_E_rel + 1] -
15,520✔
968
                     nuc.xs_cdf_[i_E_low + i_E_rel]) /
15,520✔
969
                   (nuc.energy_0K_[i_E_low + i_E_rel + 1] -
15,520✔
970
                     nuc.energy_0K_[i_E_low + i_E_rel]);
15,520✔
971
        E_rel += (cdf_rel - nuc.xs_cdf_[i_E_low + i_E_rel]) / m;
15,520✔
972

973
        // perform rejection sampling on cosine between
974
        // neutron and target velocities
975
        double mu = (E_t + nuc.awr_ * (E - E_rel)) /
15,520✔
976
                    (2.0 * std::sqrt(nuc.awr_ * E * E_t));
15,520✔
977

978
        if (std::abs(mu) < 1.0) {
15,520✔
979
          // set and accept target velocity
980
          E_t /= nuc.awr_;
1,412✔
981
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
1,412✔
982
        }
983
      }
14,108✔
984
    }
985
  } // case RVS, DBRC
986
  } // switch (sampling_method)
987

988
  UNREACHABLE();
×
989
}
990

991
Direction sample_cxs_target_velocity(
32,736,445✔
992
  double awr, double E, Direction u, double kT, uint64_t* seed)
993
{
994
  double beta_vn = std::sqrt(awr * E / kT);
32,736,445✔
995
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
32,736,445✔
996

997
  double beta_vt_sq;
998
  double mu;
999
  while (true) {
1000
    // Sample two random numbers
1001
    double r1 = prn(seed);
38,443,282✔
1002
    double r2 = prn(seed);
38,443,282✔
1003

1004
    if (prn(seed) < alpha) {
38,443,282✔
1005
      // With probability alpha, we sample the distribution p(y) =
1006
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1007
      // Carlo sampler
1008

1009
      beta_vt_sq = -std::log(r1 * r2);
9,240,730✔
1010

1011
    } else {
1012
      // With probability 1-alpha, we sample the distribution p(y) = y^2 *
1013
      // e^(-y^2). This can be done with sampling scheme C61 from the Monte
1014
      // Carlo sampler
1015

1016
      double c = std::cos(PI / 2.0 * prn(seed));
29,202,552✔
1017
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
29,202,552✔
1018
    }
1019

1020
    // Determine beta * vt
1021
    double beta_vt = std::sqrt(beta_vt_sq);
38,443,282✔
1022

1023
    // Sample cosine of angle between neutron and target velocity
1024
    mu = uniform_distribution(-1., 1., seed);
38,443,282✔
1025

1026
    // Determine rejection probability
1027
    double accept_prob =
1028
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
38,443,282✔
1029
      (beta_vn + beta_vt);
38,443,282✔
1030

1031
    // Perform rejection sampling on vt and mu
1032
    if (prn(seed) < accept_prob)
38,443,282✔
1033
      break;
32,736,445✔
1034
  }
5,706,837✔
1035

1036
  // Determine speed of target nucleus
1037
  double vt = std::sqrt(beta_vt_sq * kT / awr);
32,736,445✔
1038

1039
  // Determine velocity vector of target nucleus based on neutron's velocity
1040
  // and the sampled angle between them
1041
  return vt * rotate_angle(u, mu, nullptr, seed);
32,736,445✔
1042
}
1043

1044
void sample_fission_neutron(
2,706,049✔
1045
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1046
{
1047
  // Get attributes of particle
1048
  double E_in = p.E();
2,706,049✔
1049
  uint64_t* seed = p.current_seed();
2,706,049✔
1050

1051
  // Determine total nu, delayed nu, and delayed neutron fraction
1052
  const auto& nuc {data::nuclides[i_nuclide]};
2,706,049✔
1053
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
2,706,049✔
1054
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
2,706,049✔
1055
  double beta = nu_d / nu_t;
2,706,049✔
1056

1057
  if (prn(seed) < beta) {
2,706,049✔
1058
    // ====================================================================
1059
    // DELAYED NEUTRON SAMPLED
1060

1061
    // sampled delayed precursor group
1062
    double xi = prn(seed) * nu_d;
17,001✔
1063
    double prob = 0.0;
17,001✔
1064
    int group;
1065
    for (group = 1; group < nuc->n_precursor_; ++group) {
63,280✔
1066
      // determine delayed neutron precursor yield for group j
1067
      double yield = (*rx.products_[group].yield_)(E_in);
62,089✔
1068

1069
      // Check if this group is sampled
1070
      prob += yield;
62,089✔
1071
      if (xi < prob)
62,089✔
1072
        break;
15,810✔
1073
    }
1074

1075
    // if the sum of the probabilities is slightly less than one and the
1076
    // random number is greater, j will be greater than nuc %
1077
    // n_precursor -- check for this condition
1078
    group = std::min(group, nuc->n_precursor_);
17,001✔
1079

1080
    // set the delayed group for the particle born from fission
1081
    site->delayed_group = group;
17,001✔
1082

1083
    // Sample time of emission based on decay constant of precursor
1084
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
17,001✔
1085
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
17,001✔
1086

1087
  } else {
1088
    // ====================================================================
1089
    // PROMPT NEUTRON SAMPLED
1090

1091
    // set the delayed group for the particle born from fission to 0
1092
    site->delayed_group = 0;
2,689,048✔
1093
  }
1094

1095
  // sample from prompt neutron energy distribution
1096
  int n_sample = 0;
2,706,049✔
1097
  double mu;
1098
  while (true) {
1099
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
2,706,049✔
1100

1101
    // resample if energy is greater than maximum neutron energy
1102
    int neutron = ParticleType::neutron().transport_index();
2,706,049✔
1103
    if (site->E < data::energy_max[neutron])
2,706,049!
1104
      break;
2,706,049✔
1105

1106
    // check for large number of resamples
1107
    ++n_sample;
×
1108
    if (n_sample == MAX_SAMPLE) {
×
1109
      // particle_write_restart(p)
1110
      fatal_error("Resampled energy distribution maximum number of times "
×
1111
                  "for nuclide " +
×
1112
                  nuc->name_);
×
1113
    }
1114
  }
×
1115

1116
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1117
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
2,706,049✔
1118
}
2,706,049✔
1119

1120
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
1,581,300✔
1121
{
1122
  // copy energy of neutron
1123
  double E_in = p.E();
1,581,300✔
1124

1125
  // sample outgoing energy and scattering cosine
1126
  double E;
1127
  double mu;
1128
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
1,581,300✔
1129

1130
  // if scattering system is in center-of-mass, transfer cosine of scattering
1131
  // angle and outgoing energy from CM to LAB
1132
  if (rx.scatter_in_cm_) {
1,581,300✔
1133
    double E_cm = E;
1,576,392✔
1134

1135
    // determine outgoing energy in lab
1136
    double A = nuc.awr_;
1,576,392✔
1137
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
1,576,392✔
1138
                 ((A + 1.0) * (A + 1.0));
1,576,392✔
1139

1140
    // determine outgoing angle in lab
1141
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
1,576,392✔
1142
  }
1143

1144
  // Because of floating-point roundoff, it may be possible for mu to be
1145
  // outside of the range [-1,1). In these cases, we just set mu to exactly -1
1146
  // or 1
1147
  if (std::abs(mu) > 1.0)
1,581,300!
1148
    mu = std::copysign(1.0, mu);
×
1149

1150
  // Set outgoing energy and scattering angle
1151
  p.E() = E;
1,581,300✔
1152
  p.mu() = mu;
1,581,300✔
1153

1154
  // change direction of particle
1155
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,581,300✔
1156

1157
  // evaluate yield
1158
  double yield = (*rx.products_[0].yield_)(E_in);
1,581,300✔
1159
  if (std::floor(yield) == yield && yield > 0) {
1,581,300!
1160
    // If yield is integral, create exactly that many secondary particles
1161
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
1,589,091✔
1162
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
7,791✔
1163
    }
1164
  } else {
1,581,300✔
1165
    // Otherwise, change weight of particle based on yield
UNCOV
1166
    p.wgt() *= yield;
×
1167
  }
1168
}
1,581,300✔
1169

1170
void sample_secondary_photons(Particle& p, int i_nuclide)
800,868✔
1171
{
1172
  // Sample the number of photons produced
1173
  double y_t =
1174
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
800,868✔
1175
  double photon_wgt = p.wgt();
800,868✔
1176
  int y = 1;
800,868✔
1177

1178
  if (settings::use_decay_photons) {
800,868✔
1179
    // For decay photons, sample a single photon and modify the weight
1180
    if (y_t <= 0.0)
6,546✔
1181
      return;
1,571✔
1182
    photon_wgt *= y_t;
4,975✔
1183
  } else {
1184
    // For prompt photons, sample an integral number of photons with weight
1185
    // equal to the neutron's weight
1186
    y = static_cast<int>(y_t);
794,322✔
1187
    if (prn(p.current_seed()) <= y_t - y)
794,322✔
1188
      ++y;
52,260✔
1189
  }
1190

1191
  // Sample each secondary photon
1192
  for (int i = 0; i < y; ++i) {
920,901✔
1193
    // Sample the reaction and product
1194
    int i_rx;
1195
    int i_product;
1196
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
121,604✔
1197

1198
    // Sample the outgoing energy and angle
1199
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
121,604✔
1200
    double E;
1201
    double mu;
1202
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
121,604✔
1203

1204
    // Sample the new direction
1205
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
121,604✔
1206

1207
    // In a k-eigenvalue simulation, it's necessary to provide higher weight to
1208
    // secondary photons from non-fission reactions to properly balance energy
1209
    // release and deposition. See D. P. Griesheimer, S. J. Douglass, and M. H.
1210
    // Stedry, "Self-consistent energy normalization for quasistatic reactor
1211
    // calculations", Proc. PHYSOR, Cambridge, UK, Mar 29-Apr 2, 2020.
1212
    double wgt = photon_wgt;
121,604✔
1213
    if (settings::run_mode == RunMode::EIGENVALUE && !is_fission(rx->mt_)) {
121,604✔
1214
      wgt *= simulation::keff;
31,648✔
1215
    }
1216

1217
    // Create the secondary photon
1218
    bool created_photon = p.create_secondary(wgt, u, E, ParticleType::photon());
121,604✔
1219

1220
    // Tag secondary particle with parent nuclide
1221
    if (created_photon && settings::use_decay_photons) {
121,604✔
1222
      p.secondary_bank().back().parent_nuclide =
4,804✔
1223
        rx->products_[i_product].parent_nuclide_;
4,804✔
1224
    }
1225
  }
1226
}
1227

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