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

openmc-dev / openmc / 22282433317

22 Feb 2026 06:05PM UTC coverage: 81.033% (-0.7%) from 81.688%
22282433317

Pull #3817

github

web-flow
Merge 155a36c12 into 83a30f686
Pull Request #3817: Fix MeshFilter.get_pandas_dataframe to handle all mesh types

16085 of 22646 branches covered (71.03%)

Branch coverage included in aggregate %.

23 of 25 new or added lines in 4 files covered. (92.0%)

1149 existing lines in 38 files now uncovered.

55961 of 66264 relevant lines covered (84.45%)

9160039.43 hits per line

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

83.49
/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 "openmc/tensor.h"
34
#include <algorithm> // for max, min, max_element
35
#include <cmath>     // for sqrt, exp, log, abs, copysign
36

37
namespace openmc {
38

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

43
void collision(Particle& p)
96,667,445✔
44
{
45
  // Add to collision counter for particle
46
  ++(p.n_collision());
96,667,445✔
47
  p.secondary_bank_index() = p.secondary_bank().size();
96,667,445✔
48

49
  // Sample reaction for the material the particle is in
50
  switch (p.type().pdg_number()) {
96,667,445!
51
  case PDG_NEUTRON:
90,174,110✔
52
    sample_neutron_reaction(p);
90,174,110✔
53
    break;
90,174,110✔
54
  case PDG_PHOTON:
1,591,115✔
55
    sample_photon_reaction(p);
1,591,115✔
56
    break;
1,591,115✔
57
  case PDG_ELECTRON:
4,894,252✔
58
    sample_electron_reaction(p);
4,894,252✔
59
    break;
4,894,252✔
60
  case PDG_POSITRON:
7,968✔
61
    sample_positron_reaction(p);
7,968✔
62
    break;
7,968✔
63
  default:
×
64
    fatal_error("Unsupported particle PDG for collision sampling.");
×
65
  }
66

67
  if (settings::weight_window_checkpoint_collision)
96,667,445!
68
    apply_weight_windows(p);
96,667,445✔
69

70
  // Kill particle if energy falls below cutoff
71
  int type = p.type().transport_index();
96,667,445✔
72
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
96,667,445!
73
    p.wgt() = 0.0;
475,249✔
74
  }
75

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

96
void sample_neutron_reaction(Particle& p)
90,174,110✔
97
{
98
  // Sample a nuclide within the material
99
  int i_nuclide = sample_nuclide(p);
90,174,110✔
100

101
  // Save which nuclide particle had collision with
102
  p.event_nuclide() = i_nuclide;
90,174,110✔
103

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

109
  const auto& nuc {data::nuclides[i_nuclide]};
90,174,110✔
110

111
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
90,174,110✔
112
    auto& rx = sample_fission(i_nuclide, p);
11,396,205✔
113
    if (settings::run_mode == RunMode::EIGENVALUE) {
11,396,205✔
114
      create_fission_sites(p, i_nuclide, rx);
9,143,091✔
115
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
2,253,114✔
116
               settings::create_fission_neutrons) {
117
      create_fission_sites(p, i_nuclide, rx);
30,746✔
118

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

131
  // Create secondary photons
132
  if (settings::photon_transport) {
90,174,110✔
133
    sample_secondary_photons(p, i_nuclide);
760,891✔
134
  }
135

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

139
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
90,174,110✔
140
    absorption(p, i_nuclide);
90,173,790✔
141
  }
142
  if (!p.alive())
90,174,110✔
143
    return;
2,123,456✔
144

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

154
  // Advance URR seed stream 'N' times after energy changes
155
  if (p.E() != p.E_last()) {
88,050,654✔
156
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
88,021,633✔
157
  }
158

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

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

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

184
  // Sample the number of neutrons produced
185
  int nu = static_cast<int>(nu_t);
9,173,837✔
186
  if (prn(p.current_seed()) <= (nu_t - nu))
9,173,837✔
187
    ++nu;
1,870,733✔
188

189
  // If no neutrons were produced then don't continue
190
  if (nu == 0)
9,173,837✔
191
    return;
6,941,245✔
192

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

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

200
  p.fission() = true;
2,232,592✔
201

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

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

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

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

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

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

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

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

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

260
    // Increment the number of neutrons born delayed
261
    if (site.delayed_group > 0) {
2,756,604✔
262
      nu_d[site.delayed_group - 1]++;
17,370✔
263
    }
264

265
    // Write fission particles to nuBank
266
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
2,756,604✔
267
    nu_bank_entry.wgt = site.wgt;
2,756,604✔
268
    nu_bank_entry.E = site.E;
2,756,604✔
269
    nu_bank_entry.delayed_group = site.delayed_group;
2,756,604✔
270
  }
271

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

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

283
  // Store the total weight banked for analog fission tallies
284
  p.n_bank() = nu;
2,232,592✔
285
  p.wgt_bank() = nu / weight;
2,232,592✔
286
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
20,093,328✔
287
    p.n_delayed_bank(d) = nu_d[d];
17,860,736✔
288
  }
289
}
290

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

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

308
  // Calculate photon energy over electron rest mass equivalent
309
  double alpha = p.E() / MASS_ELECTRON_EV;
1,591,115✔
310

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

316
  // Coherent (Rayleigh) scattering
317
  prob += micro.coherent;
1,591,115✔
318
  if (prob > cutoff) {
1,591,115✔
319
    p.mu() = element.rayleigh_scatter(alpha, p.current_seed());
87,801✔
320
    p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
87,801✔
321
    p.event() = TallyEvent::SCATTER;
87,801✔
322
    p.event_mt() = COHERENT;
87,801✔
323
    return;
87,801✔
324
  }
325

326
  // Incoherent (Compton) scattering
327
  prob += micro.incoherent;
1,503,314✔
328
  if (prob > cutoff) {
1,503,314✔
329
    double alpha_out;
330
    int i_shell;
331
    element.compton_scatter(
2,058,116✔
332
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
1,029,058✔
333

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

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

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

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

370
  // Photoelectric effect
371
  double prob_after = prob + micro.photoelectric;
474,256✔
372

373
  if (prob_after > cutoff) {
474,256✔
374
    // Get grid index, interpolation factor, and bounding subshell
375
    // cross sections
376
    int i_grid = micro.index_grid;
466,288✔
377
    double f = micro.interp_factor;
466,288✔
378
    tensor::View<const double> xs_lower = element.cross_sections_.slice(i_grid);
466,288✔
379
    tensor::View<const double> xs_upper =
380
      element.cross_sections_.slice(i_grid + 1);
466,288✔
381

382
    for (int i_shell = 0; i_shell < element.shells_.size(); ++i_shell) {
2,211,796!
383
      const auto& shell {element.shells_[i_shell]};
2,211,796✔
384

385
      // Check threshold of reaction
386
      if (xs_lower(i_shell) == 0)
2,211,796✔
387
        continue;
933,237✔
388

389
      //  Evaluation subshell photoionization cross section
390
      prob += std::exp(
1,278,559✔
391
        xs_lower(i_shell) + f * (xs_upper(i_shell) - xs_lower(i_shell)));
1,278,559✔
392

393
      if (prob > cutoff) {
1,278,559✔
394
        // Determine binding energy based on whether atomic relaxation data is
395
        // present (if not, use value from Compton profile data)
396
        double binding_energy = element.has_atomic_relaxation_
466,288✔
397
                                  ? shell.binding_energy
466,288!
398
                                  : element.binding_energy_[i_shell];
×
399

400
        // Determine energy of secondary electron
401
        double E_electron = p.E() - binding_energy;
466,288✔
402

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

419
        double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
466,288✔
420
        Direction u;
466,288✔
421
        u.x = mu;
466,288✔
422
        u.y = std::sqrt(1.0 - mu * mu) * std::cos(phi);
466,288✔
423
        u.z = std::sqrt(1.0 - mu * mu) * std::sin(phi);
466,288✔
424

425
        // Create secondary electron
426
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
466,288✔
427

428
        // Allow electrons to fill orbital and produce auger electrons
429
        // and fluorescent photons
430
        element.atomic_relaxation(i_shell, p);
466,288✔
431
        p.event() = TallyEvent::ABSORB;
466,288✔
432
        p.event_mt() = 533 + shell.index_subshell;
466,288✔
433
        p.wgt() = 0.0;
466,288✔
434
        p.E() = 0.0;
466,288✔
435
        return;
466,288✔
436
      }
437
    }
438
  }
932,576!
439
  prob = prob_after;
7,968✔
440

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

449
    // Create secondary electron
450
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
7,968✔
451
    p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
7,968✔
452

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

463
void sample_electron_reaction(Particle& p)
4,894,252✔
464
{
465
  // TODO: create reaction types
466

467
  if (settings::electron_treatment == ElectronTreatment::TTB) {
4,894,252✔
468
    double E_lost;
469
    thick_target_bremsstrahlung(p, &E_lost);
4,866,647✔
470
  }
471

472
  p.E() = 0.0;
4,894,252✔
473
  p.wgt() = 0.0;
4,894,252✔
474
  p.event() = TallyEvent::ABSORB;
4,894,252✔
475
}
4,894,252✔
476

477
void sample_positron_reaction(Particle& p)
7,968✔
478
{
479
  // TODO: create reaction types
480

481
  if (settings::electron_treatment == ElectronTreatment::TTB) {
7,968✔
482
    double E_lost;
483
    thick_target_bremsstrahlung(p, &E_lost);
7,853✔
484
  }
485

486
  // Sample angle isotropically
487
  Direction u = isotropic_direction(p.current_seed());
7,968✔
488

489
  // Create annihilation photon pair traveling in opposite directions
490
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon());
7,968✔
491
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon());
7,968✔
492

493
  p.E() = 0.0;
7,968✔
494
  p.wgt() = 0.0;
7,968✔
495
  p.event() = TallyEvent::ABSORB;
7,968✔
496
}
7,968✔
497

498
int sample_nuclide(Particle& p)
90,174,110✔
499
{
500
  // Sample cumulative distribution function
501
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
90,174,110✔
502

503
  // Get pointers to nuclide/density arrays
504
  const auto& mat {model::materials[p.material()]};
90,174,110✔
505
  int n = mat->nuclide_.size();
90,174,110✔
506

507
  double prob = 0.0;
90,174,110✔
508
  for (int i = 0; i < n; ++i) {
191,176,688!
509
    // Get atom density
510
    int i_nuclide = mat->nuclide_[i];
191,176,688✔
511
    double atom_density = mat->atom_density(i, p.density_mult());
191,176,688✔
512

513
    // Increment probability to compare to cutoff
514
    prob += atom_density * p.neutron_xs(i_nuclide).total;
191,176,688✔
515
    if (prob >= cutoff)
191,176,688✔
516
      return i_nuclide;
90,174,110✔
517
  }
518

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

524
int sample_element(Particle& p)
1,591,115✔
525
{
526
  // Sample cumulative distribution function
527
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,591,115✔
528

529
  // Get pointers to elements, densities
530
  const auto& mat {model::materials[p.material()]};
1,591,115✔
531

532
  double prob = 0.0;
1,591,115✔
533
  for (int i = 0; i < mat->element_.size(); ++i) {
3,765,252!
534
    // Find atom density
535
    int i_element = mat->element_[i];
3,765,252✔
536
    double atom_density = mat->atom_density(i, p.density_mult());
3,765,252✔
537

538
    // Determine microscopic cross section
539
    double sigma = atom_density * p.photon_xs(i_element).total;
3,765,252✔
540

541
    // Increment probability to compare to cutoff
542
    prob += sigma;
3,765,252✔
543
    if (prob > cutoff) {
3,765,252✔
544
      // Save which nuclide particle had collision with for tally purpose
545
      p.event_nuclide() = mat->nuclide_[i];
1,591,115✔
546

547
      return i_element;
1,591,115✔
548
    }
549
  }
550

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

556
Reaction& sample_fission(int i_nuclide, Particle& p)
11,396,205✔
557
{
558
  // Get pointer to nuclide
559
  const auto& nuc {data::nuclides[i_nuclide]};
11,396,205✔
560

561
  // If we're in the URR, by default use the first fission reaction. We also
562
  // default to the first reaction if we know that there are no partial fission
563
  // reactions
564
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
11,396,205✔
565
    return *nuc->fission_rx_[0];
11,393,847✔
566
  }
567

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

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

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

586
    // Create fission bank sites if fission occurs
587
    if (prob > cutoff)
2,180✔
588
      return *rx;
2,177✔
589
  }
590

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

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

604
  // Loop through each reaction type
605
  const auto& nuc {data::nuclides[i_nuclide]};
120,590✔
606
  for (int i = 0; i < nuc->reactions_.size(); ++i) {
1,975,460!
607
    // Evaluate neutron cross section
608
    const auto& rx = nuc->reactions_[i];
1,975,460✔
609
    double xs = rx->xs(micro);
1,975,460✔
610

611
    // if cross section is zero for this reaction, skip it
612
    if (xs == 0.0)
1,975,460✔
613
      continue;
612,868✔
614

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

630
        // add to cumulative probability
631
        prob += f * (*rx->products_[j].yield_)(p.E()) * xs;
3,917,767✔
632

633
        *i_rx = i;
3,917,767✔
634
        *i_product = j;
3,917,767✔
635
        if (prob > cutoff)
3,917,767✔
636
          return;
120,590✔
637
      }
638
    }
639
  }
640
}
641

642
void absorption(Particle& p, int i_nuclide)
90,173,790✔
643
{
644
  if (settings::survival_biasing) {
90,173,790✔
645
    // Determine weight absorbed in survival biasing
646
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
45,450✔
647
                              p.neutron_xs(i_nuclide).total;
45,450✔
648

649
    // Adjust weight of particle by probability of absorption
650
    p.wgt() -= wgt_absorb;
45,450✔
651

652
    // Score implicit absorption estimate of keff
653
    if (settings::run_mode == RunMode::EIGENVALUE) {
45,450!
654
      p.keff_tally_absorption() += wgt_absorb *
45,450✔
655
                                   p.neutron_xs(i_nuclide).nu_fission /
45,450✔
656
                                   p.neutron_xs(i_nuclide).absorption;
45,450✔
657
    }
658
  } else {
659
    // See if disappearance reaction happens
660
    if (p.neutron_xs(i_nuclide).absorption >
90,128,340✔
661
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
90,128,340✔
662
      // Score absorption estimate of keff
663
      if (settings::run_mode == RunMode::EIGENVALUE) {
2,123,456✔
664
        p.keff_tally_absorption() += p.wgt() *
3,228,418✔
665
                                     p.neutron_xs(i_nuclide).nu_fission /
1,614,209✔
666
                                     p.neutron_xs(i_nuclide).absorption;
1,614,209✔
667
      }
668

669
      p.wgt() = 0.0;
2,123,456✔
670
      p.event() = TallyEvent::ABSORB;
2,123,456✔
671
      if (!p.fission()) {
2,123,456✔
672
        p.event_mt() = N_DISAPPEAR;
1,329,152✔
673
      }
674
    }
675
  }
676
}
90,173,790✔
677

678
void scatter(Particle& p, int i_nuclide)
88,036,215✔
679
{
680
  // copy incoming direction
681
  Direction u_old {p.u()};
88,036,215✔
682

683
  // Get pointer to nuclide and grid index/interpolation factor
684
  const auto& nuc {data::nuclides[i_nuclide]};
88,036,215✔
685
  const auto& micro {p.neutron_xs(i_nuclide)};
88,036,215✔
686
  int i_temp = micro.index_temp;
88,036,215✔
687

688
  // For tallying purposes, this routine might be called directly. In that
689
  // case, we need to sample a reaction via the cutoff variable
690
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
88,036,215✔
691
  bool sampled = false;
88,036,215✔
692

693
  // Calculate elastic cross section if it wasn't precalculated
694
  if (micro.elastic == CACHE_INVALID) {
88,036,215✔
695
    nuc->calculate_elastic_xs(p);
65,817,491✔
696
  }
697

698
  double prob = micro.elastic - micro.thermal;
88,036,215✔
699
  if (prob > cutoff) {
88,036,215✔
700
    // =======================================================================
701
    // NON-S(A,B) ELASTIC SCATTERING
702

703
    // Determine temperature
704
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
74,719,197✔
705

706
    // Perform collision physics for elastic scattering
707
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
74,719,197✔
708

709
    p.event_mt() = ELASTIC;
74,719,197✔
710
    sampled = true;
74,719,197✔
711
  }
712

713
  prob = micro.elastic;
88,036,215✔
714
  if (prob > cutoff && !sampled) {
88,036,215✔
715
    // =======================================================================
716
    // S(A,B) SCATTERING
717

718
    sab_scatter(i_nuclide, micro.index_sab, p);
11,594,554✔
719

720
    p.event_mt() = ELASTIC;
11,594,554✔
721
    sampled = true;
11,594,554✔
722
  }
723

724
  if (!sampled) {
88,036,215✔
725
    // =======================================================================
726
    // INELASTIC SCATTERING
727

728
    int n = nuc->index_inelastic_scatter_.size();
1,722,464✔
729
    int i = 0;
1,722,464✔
730
    for (int j = 0; j < n && prob < cutoff; ++j) {
32,159,879✔
731
      i = nuc->index_inelastic_scatter_[j];
30,437,415✔
732

733
      // add to cumulative probability
734
      prob += nuc->reactions_[i]->xs(micro);
30,437,415✔
735
    }
736

737
    // Perform collision physics for inelastic scattering
738
    const auto& rx {nuc->reactions_[i]};
1,722,464✔
739
    inelastic_scatter(*nuc, *rx, p);
1,722,464✔
740
    p.event_mt() = rx->mt_;
1,722,464✔
741
  }
742

743
  // Set event component
744
  p.event() = TallyEvent::SCATTER;
88,036,215✔
745

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

758
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
74,719,197✔
759
{
760
  // get pointer to nuclide
761
  const auto& nuc {data::nuclides[i_nuclide]};
74,719,197✔
762

763
  double vel = std::sqrt(p.E());
74,719,197✔
764
  double awr = nuc->awr_;
74,719,197✔
765

766
  // Neutron velocity in LAB
767
  Direction v_n = vel * p.u();
74,719,197✔
768

769
  // Sample velocity of target nucleus
770
  Direction v_t {};
74,719,197✔
771
  if (!p.neutron_xs(i_nuclide).use_ptable) {
74,719,197✔
772
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
142,782,500✔
773
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
71,391,250✔
774
  }
775

776
  // Velocity of center-of-mass
777
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
74,719,197✔
778

779
  // Transform to CM frame
780
  v_n -= v_cm;
74,719,197✔
781

782
  // Find speed of neutron in CM
783
  vel = v_n.norm();
74,719,197✔
784

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

796
  // Determine direction cosines in CM
797
  Direction u_cm = v_n / vel;
74,719,197✔
798

799
  // Rotate neutron velocity vector to new angle -- note that the speed of the
800
  // neutron in CM does not change in elastic scattering. However, the speed
801
  // will change when we convert back to LAB
802
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
74,719,197✔
803

804
  // Transform back to LAB frame
805
  v_n += v_cm;
74,719,197✔
806

807
  p.E() = v_n.dot(v_n);
74,719,197✔
808
  vel = std::sqrt(p.E());
74,719,197✔
809

810
  // compute cosine of scattering angle in LAB frame by taking dot product of
811
  // neutron's pre- and post-collision angle
812
  p.mu() = p.u().dot(v_n) / vel;
74,719,197✔
813

814
  // Set energy and direction of particle in LAB frame
815
  p.u() = v_n / vel;
74,719,197✔
816

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

824
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
11,594,554✔
825
{
826
  // Determine temperature index
827
  const auto& micro {p.neutron_xs(i_nuclide)};
11,594,554✔
828
  int i_temp = micro.index_temp_sab;
11,594,554✔
829

830
  // Sample energy and angle
831
  double E_out;
832
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
23,189,108✔
833
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
11,594,554✔
834

835
  // Set energy to outgoing, change direction of particle
836
  p.E() = E_out;
11,594,554✔
837
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
11,594,554✔
838
}
11,594,554✔
839

840
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
71,391,250✔
841
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
842
{
843
  // check if nuclide is a resonant scatterer
844
  ResScatMethod sampling_method;
845
  if (nuc.resonant_) {
71,391,250✔
846

847
    // sampling method to use
848
    sampling_method = settings::res_scat_method;
7,687✔
849

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

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

859
    // otherwise, use free gas model
860
  } else {
861
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
71,383,563✔
862
      return {};
36,849,146✔
863
    } else {
864
      sampling_method = ResScatMethod::cxs;
34,534,417✔
865
    }
866
  }
867

868
  // use appropriate target velocity sampling method
869
  switch (sampling_method) {
34,538,399!
870
  case ResScatMethod::cxs:
34,536,689✔
871

872
    // sample target velocity with the constant cross section (cxs) approx.
873
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
34,536,689✔
874

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

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

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

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

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

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

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

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

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

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

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

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

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

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

991
  UNREACHABLE();
×
992
}
993

994
Direction sample_cxs_target_velocity(
34,536,987✔
995
  double awr, double E, Direction u, double kT, uint64_t* seed)
996
{
997
  double beta_vn = std::sqrt(awr * E / kT);
34,536,987✔
998
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
34,536,987✔
999

1000
  double beta_vt_sq;
1001
  double mu;
1002
  while (true) {
1003
    // Sample two random numbers
1004
    double r1 = prn(seed);
40,261,883✔
1005
    double r2 = prn(seed);
40,261,883✔
1006

1007
    if (prn(seed) < alpha) {
40,261,883✔
1008
      // With probability alpha, we sample the distribution p(y) =
1009
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1010
      // Carlo sampler
1011

1012
      beta_vt_sq = -std::log(r1 * r2);
9,240,846✔
1013

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

1019
      double c = std::cos(PI / 2.0 * prn(seed));
31,021,037✔
1020
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
31,021,037✔
1021
    }
1022

1023
    // Determine beta * vt
1024
    double beta_vt = std::sqrt(beta_vt_sq);
40,261,883✔
1025

1026
    // Sample cosine of angle between neutron and target velocity
1027
    mu = uniform_distribution(-1., 1., seed);
40,261,883✔
1028

1029
    // Determine rejection probability
1030
    double accept_prob =
1031
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
40,261,883✔
1032
      (beta_vn + beta_vt);
40,261,883✔
1033

1034
    // Perform rejection sampling on vt and mu
1035
    if (prn(seed) < accept_prob)
40,261,883✔
1036
      break;
34,536,987✔
1037
  }
5,724,896✔
1038

1039
  // Determine speed of target nucleus
1040
  double vt = std::sqrt(beta_vt_sq * kT / awr);
34,536,987✔
1041

1042
  // Determine velocity vector of target nucleus based on neutron's velocity
1043
  // and the sampled angle between them
1044
  return vt * rotate_angle(u, mu, nullptr, seed);
34,536,987✔
1045
}
1046

1047
void sample_fission_neutron(
2,756,604✔
1048
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1049
{
1050
  // Get attributes of particle
1051
  double E_in = p.E();
2,756,604✔
1052
  uint64_t* seed = p.current_seed();
2,756,604✔
1053

1054
  // Determine total nu, delayed nu, and delayed neutron fraction
1055
  const auto& nuc {data::nuclides[i_nuclide]};
2,756,604✔
1056
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
2,756,604✔
1057
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
2,756,604✔
1058
  double beta = nu_d / nu_t;
2,756,604✔
1059

1060
  if (prn(seed) < beta) {
2,756,604✔
1061
    // ====================================================================
1062
    // DELAYED NEUTRON SAMPLED
1063

1064
    // sampled delayed precursor group
1065
    double xi = prn(seed) * nu_d;
17,370✔
1066
    double prob = 0.0;
17,370✔
1067
    int group;
1068
    for (group = 1; group < nuc->n_precursor_; ++group) {
64,645✔
1069
      // determine delayed neutron precursor yield for group j
1070
      double yield = (*rx.products_[group].yield_)(E_in);
63,422✔
1071

1072
      // Check if this group is sampled
1073
      prob += yield;
63,422✔
1074
      if (xi < prob)
63,422✔
1075
        break;
16,147✔
1076
    }
1077

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

1083
    // set the delayed group for the particle born from fission
1084
    site->delayed_group = group;
17,370✔
1085

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

1090
  } else {
1091
    // ====================================================================
1092
    // PROMPT NEUTRON SAMPLED
1093

1094
    // set the delayed group for the particle born from fission to 0
1095
    site->delayed_group = 0;
2,739,234✔
1096
  }
1097

1098
  // sample from prompt neutron energy distribution
1099
  int n_sample = 0;
2,756,604✔
1100
  double mu;
1101
  while (true) {
1102
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
2,756,604✔
1103

1104
    // resample if energy is greater than maximum neutron energy
1105
    int neutron = ParticleType::neutron().transport_index();
2,756,604✔
1106
    if (site->E < data::energy_max[neutron])
2,756,604!
1107
      break;
2,756,604✔
1108

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

1119
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1120
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
2,756,604✔
1121
}
2,756,604✔
1122

1123
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
1,722,464✔
1124
{
1125
  // copy energy of neutron
1126
  double E_in = p.E();
1,722,464✔
1127

1128
  // sample outgoing energy and scattering cosine
1129
  double E;
1130
  double mu;
1131
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
1,722,464✔
1132

1133
  // if scattering system is in center-of-mass, transfer cosine of scattering
1134
  // angle and outgoing energy from CM to LAB
1135
  if (rx.scatter_in_cm_) {
1,722,464✔
1136
    double E_cm = E;
1,717,455✔
1137

1138
    // determine outgoing energy in lab
1139
    double A = nuc.awr_;
1,717,455✔
1140
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
1,717,455✔
1141
                 ((A + 1.0) * (A + 1.0));
1,717,455✔
1142

1143
    // determine outgoing angle in lab
1144
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
1,717,455✔
1145
  }
1146

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

1153
  // Set outgoing energy and scattering angle
1154
  p.E() = E;
1,722,464✔
1155
  p.mu() = mu;
1,722,464✔
1156

1157
  // change direction of particle
1158
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,722,464✔
1159

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

1173
void sample_secondary_photons(Particle& p, int i_nuclide)
760,891✔
1174
{
1175
  // Sample the number of photons produced
1176
  double y_t =
1177
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
760,891✔
1178
  double photon_wgt = p.wgt();
760,891✔
1179
  int y = 1;
760,891✔
1180

1181
  if (settings::use_decay_photons) {
760,891✔
1182
    // For decay photons, sample a single photon and modify the weight
1183
    if (y_t <= 0.0)
6,546✔
1184
      return;
1,571✔
1185
    photon_wgt *= y_t;
4,975✔
1186
  } else {
1187
    // For prompt photons, sample an integral number of photons with weight
1188
    // equal to the neutron's weight
1189
    y = static_cast<int>(y_t);
754,345✔
1190
    if (prn(p.current_seed()) <= y_t - y)
754,345✔
1191
      ++y;
50,962✔
1192
  }
1193

1194
  // Sample each secondary photon
1195
  for (int i = 0; i < y; ++i) {
879,910✔
1196
    // Sample the reaction and product
1197
    int i_rx;
1198
    int i_product;
1199
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
120,590✔
1200

1201
    // Sample the outgoing energy and angle
1202
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
120,590✔
1203
    double E;
1204
    double mu;
1205
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
120,590✔
1206

1207
    // Sample the new direction
1208
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
120,590✔
1209

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

1220
    // Create the secondary photon
1221
    bool created_photon = p.create_secondary(wgt, u, E, ParticleType::photon());
120,590✔
1222

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

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