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

openmc-dev / openmc / 21616189382

03 Feb 2026 03:49AM UTC coverage: 81.772% (-0.2%) from 81.993%
21616189382

Pull #3756

github

web-flow
Merge 46d05d381 into fc0d9eec6
Pull Request #3756: Refactor ParticleType to use PDG Monte Carlo numbering scheme

17310 of 24247 branches covered (71.39%)

Branch coverage included in aggregate %.

346 of 501 new or added lines in 32 files covered. (69.06%)

497 existing lines in 8 files now uncovered.

55908 of 65292 relevant lines covered (85.63%)

44288421.04 hits per line

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

82.8
/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)
943,953,921✔
44
{
45
  // Add to collision counter for particle
46
  ++(p.n_collision());
943,953,921✔
47

48
  // Sample reaction for the material the particle is in
49
  switch (p.type().pdg_number()) {
943,953,921!
50
  case PDG_NEUTRON:
873,243,261✔
51
    sample_neutron_reaction(p);
873,243,261✔
52
    break;
873,243,261✔
53
  case PDG_PHOTON:
17,254,311✔
54
    sample_photon_reaction(p);
17,254,311✔
55
    break;
17,254,311✔
56
  case PDG_ELECTRON:
53,369,085✔
57
    sample_electron_reaction(p);
53,369,085✔
58
    break;
53,369,085✔
59
  case PDG_POSITRON:
87,264✔
60
    sample_positron_reaction(p);
87,264✔
61
    break;
87,264✔
NEW
62
  default:
×
NEW
63
    fatal_error("Unsupported particle PDG for collision sampling.");
×
64
  }
65

66
  if (settings::weight_window_checkpoint_collision)
943,953,921!
67
    apply_weight_windows(p);
943,953,921✔
68

69
  // Kill particle if energy falls below cutoff
70
  int type = p.type().transport_index();
943,953,921✔
71
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
943,953,921!
72
    p.wgt() = 0.0;
5,185,091✔
73
  }
74

75
  // Display information about collision
76
  if (settings::verbosity >= 10 || p.trace()) {
943,953,921!
77
    std::string msg;
66✔
78
    if (p.event() == TallyEvent::KILL) {
66!
79
      msg = fmt::format("    Killed. Energy = {} eV.", p.E());
×
80
    } else if (p.type().is_neutron()) {
66!
81
      msg = fmt::format("    {} with {}. Energy = {} eV.",
186✔
82
        reaction_name(p.event_mt()), data::nuclides[p.event_nuclide()]->name_,
132✔
83
        p.E());
66✔
NEW
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);
66✔
92
  }
66✔
93
}
943,953,921✔
94

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

100
  // Save which nuclide particle had collision with
101
  p.event_nuclide() = i_nuclide;
873,243,261✔
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]};
873,243,261✔
109

110
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
873,243,261✔
111
    auto& rx = sample_fission(i_nuclide, p);
114,590,119✔
112
    if (settings::run_mode == RunMode::EIGENVALUE) {
114,590,119✔
113
      create_fission_sites(p, i_nuclide, rx);
98,475,163✔
114
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
16,114,956✔
115
               settings::create_fission_neutrons) {
116
      create_fission_sites(p, i_nuclide, rx);
558,074✔
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) {
558,074!
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_;
114,590,119✔
128
  }
129

130
  // Create secondary photons
131
  if (settings::photon_transport) {
873,243,261✔
132
    sample_secondary_photons(p, i_nuclide);
8,809,548✔
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) {
873,243,261✔
139
    absorption(p, i_nuclide);
873,239,741✔
140
  }
141
  if (!p.alive())
873,243,261✔
142
    return;
21,838,307✔
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();
851,404,954✔
147
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
851,404,954!
148
    ncrystal_mat.scatter(p);
158,829✔
149
  } else {
150
    scatter(p, i_nuclide);
851,246,125✔
151
  }
152

153
  // Advance URR seed stream 'N' times after energy changes
154
  if (p.E() != p.E_last()) {
851,404,954✔
155
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
851,085,723✔
156
  }
157

158
  // Play russian roulette if survival biasing is turned on
159
  if (settings::survival_biasing) {
851,404,954✔
160
    // if survival normalization is on, use normalized weight cutoff and
161
    // normalized weight survive
162
    if (settings::survival_normalization) {
499,950!
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) {
499,950✔
167
      russian_roulette(p, settings::weight_survive);
56,991✔
168
    }
169
  }
170
}
171

172
void create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx)
99,033,237✔
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;
99,033,237✔
177

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

183
  // Sample the number of neutrons produced
184
  int nu = static_cast<int>(nu_t);
99,033,237✔
185
  if (prn(p.current_seed()) <= (nu_t - nu))
99,033,237✔
186
    ++nu;
20,417,445✔
187

188
  // If no neutrons were produced then don't continue
189
  if (nu == 0)
99,033,237✔
190
    return;
74,683,826✔
191

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

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

199
  p.fission() = true;
24,349,411✔
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);
24,349,411✔
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++) {
54,352,625✔
210
    // Initialize fission site object with particle data
211
    SourceSite site;
30,003,214✔
212
    site.r = p.r();
30,003,214✔
213
    site.particle = ParticleType::neutron();
30,003,214✔
214
    site.time = p.time();
30,003,214✔
215
    site.wgt = 1. / weight;
30,003,214✔
216
    site.surf_id = 0;
30,003,214✔
217

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

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

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

233
    // Store fission site in bank
234
    if (use_fission_bank) {
30,003,214✔
235
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
29,799,695✔
236
      if (idx == -1) {
29,799,695!
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) {
29,799,695✔
252
        ifp(p, idx);
1,352,626✔
253
      }
254
    } else {
255
      p.secondary_bank().push_back(site);
203,519✔
256
    }
257

258
    // Increment the number of neutrons born delayed
259
    if (site.delayed_group > 0) {
30,003,214✔
260
      nu_d[site.delayed_group - 1]++;
187,926✔
261
    }
262

263
    // Write fission particles to nuBank
264
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
30,003,214✔
265
    nu_bank_entry.wgt = site.wgt;
30,003,214✔
266
    nu_bank_entry.E = site.E;
30,003,214✔
267
    nu_bank_entry.delayed_group = site.delayed_group;
30,003,214✔
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) {
24,349,411!
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;
24,349,411✔
280

281
  // Store the total weight banked for analog fission tallies
282
  p.n_bank() = nu;
24,349,411✔
283
  p.wgt_bank() = nu / weight;
24,349,411✔
284
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
219,144,699✔
285
    p.n_delayed_bank(d) = nu_d[d];
194,795,288✔
286
  }
287
}
288

289
void sample_photon_reaction(Particle& p)
17,254,311✔
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();
17,254,311✔
295
  if (p.E() < settings::energy_cutoff[photon]) {
17,254,311!
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);
17,254,311✔
303
  const auto& micro {p.photon_xs(i_element)};
17,254,311✔
304
  const auto& element {*data::elements[i_element]};
17,254,311✔
305

306
  // Calculate photon energy over electron rest mass equivalent
307
  double alpha = p.E() / MASS_ELECTRON_EV;
17,254,311✔
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;
17,254,311✔
312
  double cutoff = prn(p.current_seed()) * micro.total;
17,254,311✔
313

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

324
  // Incoherent (Compton) scattering
325
  prob += micro.incoherent;
16,304,491✔
326
  if (prob > cutoff) {
16,304,491✔
327
    double alpha_out;
328
    int i_shell;
329
    element.compton_scatter(
22,260,646✔
330
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
11,130,323✔
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) {
11,130,323!
336
      e_b = 0.0;
×
337
    } else {
338
      e_b = element.binding_energy_[i_shell];
11,130,323✔
339
    }
340

341
    // Create Compton electron
342
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
11,130,323✔
343
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
11,130,323✔
344
    int electron = ParticleType::electron().transport_index();
11,130,323✔
345
    if (E_electron >= settings::energy_cutoff[electron]) {
11,130,323✔
346
      double mu_electron = (alpha - alpha_out * p.mu()) /
11,025,739✔
347
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
22,051,478✔
348
                                     2.0 * alpha * alpha_out * p.mu());
11,025,739✔
349
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
11,025,739✔
350
      p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
11,025,739✔
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) {
11,130,323!
357
      element.atomic_relaxation(element.subshell_map_[i_shell], p);
11,130,323✔
358
    }
359

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

368
  // Photoelectric effect
369
  double prob_after = prob + micro.photoelectric;
5,174,168✔
370

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

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

382
      // Check threshold of reaction
383
      if (xs_lower(i_shell) == 0)
24,284,966✔
384
        continue;
10,266,637✔
385

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

390
      if (prob > cutoff) {
14,018,329✔
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_
5,086,904✔
394
                                  ? shell.binding_energy
5,086,904!
395
                                  : element.binding_energy_[i_shell];
×
396

397
        // Determine energy of secondary electron
398
        double E_electron = p.E() - binding_energy;
5,086,904✔
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());
7,630,547✔
406
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
7,630,547✔
407
            double rel_vel =
408
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
5,086,904✔
409
              (E_electron + MASS_ELECTRON_EV);
5,086,904✔
410
            mu =
5,086,904✔
411
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
5,086,904✔
412
            break;
5,086,904✔
413
          }
414
        }
2,543,643✔
415

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

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

425
        // Allow electrons to fill orbital and produce auger electrons
426
        // and fluorescent photons
427
        element.atomic_relaxation(i_shell, p);
5,086,904✔
428
        p.event() = TallyEvent::ABSORB;
5,086,904✔
429
        p.event_mt() = 533 + shell.index_subshell;
5,086,904✔
430
        p.wgt() = 0.0;
5,086,904✔
431
        p.E() = 0.0;
5,086,904✔
432
        return;
5,086,904✔
433
      }
434
    }
435
  }
10,173,808!
436
  prob = prob_after;
87,264✔
437

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

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

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

460
void sample_electron_reaction(Particle& p)
53,369,085✔
461
{
462
  // TODO: create reaction types
463

464
  if (settings::electron_treatment == ElectronTreatment::TTB) {
53,369,085✔
465
    double E_lost;
466
    thick_target_bremsstrahlung(p, &E_lost);
53,065,430✔
467
  }
468

469
  p.E() = 0.0;
53,369,085✔
470
  p.wgt() = 0.0;
53,369,085✔
471
  p.event() = TallyEvent::ABSORB;
53,369,085✔
472
}
53,369,085✔
473

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

478
  if (settings::electron_treatment == ElectronTreatment::TTB) {
87,264✔
479
    double E_lost;
480
    thick_target_bremsstrahlung(p, &E_lost);
85,999✔
481
  }
482

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

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

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

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

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

504
  double prob = 0.0;
873,243,261✔
505
  for (int i = 0; i < n; ++i) {
1,860,585,168!
506
    // Get atom density
507
    int i_nuclide = mat->nuclide_[i];
1,860,585,168✔
508
    double atom_density = mat->atom_density(i, p.density_mult());
1,860,585,168✔
509

510
    // Increment probability to compare to cutoff
511
    prob += atom_density * p.neutron_xs(i_nuclide).total;
1,860,585,168✔
512
    if (prob >= cutoff)
1,860,585,168✔
513
      return i_nuclide;
873,243,261✔
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)
17,254,311✔
522
{
523
  // Sample cumulative distribution function
524
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
17,254,311✔
525

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

529
  double prob = 0.0;
17,254,311✔
530
  for (int i = 0; i < mat->element_.size(); ++i) {
41,244,739!
531
    // Find atom density
532
    int i_element = mat->element_[i];
41,244,739✔
533
    double atom_density = mat->atom_density(i, p.density_mult());
41,244,739✔
534

535
    // Determine microscopic cross section
536
    double sigma = atom_density * p.photon_xs(i_element).total;
41,244,739✔
537

538
    // Increment probability to compare to cutoff
539
    prob += sigma;
41,244,739✔
540
    if (prob > cutoff) {
41,244,739✔
541
      // Save which nuclide particle had collision with for tally purpose
542
      p.event_nuclide() = mat->nuclide_[i];
17,254,311✔
543

544
      return i_element;
17,254,311✔
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)
114,590,119✔
554
{
555
  // Get pointer to nuclide
556
  const auto& nuc {data::nuclides[i_nuclide]};
114,590,119✔
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_) {
114,590,119✔
562
    return *nuc->fission_rx_[0];
114,562,355✔
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_) {
27,764!
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);
27,764✔
575
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
27,764✔
576
  double prob = 0.0;
27,764✔
577

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

583
    // Create fission bank sites if fission occurs
584
    if (prob > cutoff)
27,824✔
585
      return *rx;
27,764✔
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(
1,337,644✔
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);
1,337,644✔
598
  double cutoff = prn(p.current_seed()) * micro.photon_prod;
1,337,644✔
599
  double prob = 0.0;
1,337,644✔
600

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

608
    // if cross section is zero for this reaction, skip it
609
    if (xs == 0.0)
21,995,831✔
610
      continue;
7,191,415✔
611

612
    for (int j = 0; j < rx->products_.size(); ++j) {
69,577,497✔
613
      if (rx->products_[j].particle_.is_photon()) {
56,110,725✔
614
        // For fission, artificially increase the photon yield to account
615
        // for delayed photons
616
        double f = 1.0;
43,656,910✔
617
        if (settings::delayed_photon_scaling) {
43,656,910!
618
          if (is_fission(rx->mt_)) {
43,656,910✔
619
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
540,221!
620
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
540,221✔
621
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
540,221✔
622
              f = (energy_prompt + energy_delayed) / (energy_prompt);
540,221✔
623
            }
624
          }
625
        }
626

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

630
        *i_rx = i;
43,656,910✔
631
        *i_product = j;
43,656,910✔
632
        if (prob > cutoff)
43,656,910✔
633
          return;
1,337,644✔
634
      }
635
    }
636
  }
637
}
638

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

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

649
    // Score implicit absorption estimate of keff
650
    if (settings::run_mode == RunMode::EIGENVALUE) {
499,950!
651
      p.keff_tally_absorption() += wgt_absorb *
499,950✔
652
                                   p.neutron_xs(i_nuclide).nu_fission /
499,950✔
653
                                   p.neutron_xs(i_nuclide).absorption;
499,950✔
654
    }
655
  } else {
656
    // See if disappearance reaction happens
657
    if (p.neutron_xs(i_nuclide).absorption >
872,739,791✔
658
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
872,739,791✔
659
      // Score absorption estimate of keff
660
      if (settings::run_mode == RunMode::EIGENVALUE) {
21,838,307✔
661
        p.keff_tally_absorption() += p.wgt() *
34,486,064✔
662
                                     p.neutron_xs(i_nuclide).nu_fission /
17,243,032✔
663
                                     p.neutron_xs(i_nuclide).absorption;
17,243,032✔
664
      }
665

666
      p.wgt() = 0.0;
21,838,307✔
667
      p.event() = TallyEvent::ABSORB;
21,838,307✔
668
      if (!p.fission()) {
21,838,307✔
669
        p.event_mt() = N_DISAPPEAR;
13,301,055✔
670
      }
671
    }
672
  }
673
}
873,239,741✔
674

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

680
  // Get pointer to nuclide and grid index/interpolation factor
681
  const auto& nuc {data::nuclides[i_nuclide]};
851,246,125✔
682
  const auto& micro {p.neutron_xs(i_nuclide)};
851,246,125✔
683
  int i_temp = micro.index_temp;
851,246,125✔
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);
851,246,125✔
688
  bool sampled = false;
851,246,125✔
689

690
  // Calculate elastic cross section if it wasn't precalculated
691
  if (micro.elastic == CACHE_INVALID) {
851,246,125✔
692
    nuc->calculate_elastic_xs(p);
702,236,592✔
693
  }
694

695
  double prob = micro.elastic - micro.thermal;
851,246,125✔
696
  if (prob > cutoff) {
851,246,125✔
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];
728,461,780✔
702

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

706
    p.event_mt() = ELASTIC;
728,461,780✔
707
    sampled = true;
728,461,780✔
708
  }
709

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

715
    sab_scatter(i_nuclide, micro.index_sab, p);
105,302,963✔
716

717
    p.event_mt() = ELASTIC;
105,302,963✔
718
    sampled = true;
105,302,963✔
719
  }
720

721
  if (!sampled) {
851,246,125✔
722
    // =======================================================================
723
    // INELASTIC SCATTERING
724

725
    int n = nuc->index_inelastic_scatter_.size();
17,481,382✔
726
    int i = 0;
17,481,382✔
727
    for (int j = 0; j < n && prob < cutoff; ++j) {
335,422,560✔
728
      i = nuc->index_inelastic_scatter_[j];
317,941,178✔
729

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

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

740
  // Set event component
741
  p.event() = TallyEvent::SCATTER;
851,246,125✔
742

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

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

760
  double vel = std::sqrt(p.E());
728,461,780✔
761
  double awr = nuc->awr_;
728,461,780✔
762

763
  // Neutron velocity in LAB
764
  Direction v_n = vel * p.u();
728,461,780✔
765

766
  // Sample velocity of target nucleus
767
  Direction v_t {};
728,461,780✔
768
  if (!p.neutron_xs(i_nuclide).use_ptable) {
728,461,780✔
769
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
1,401,293,814✔
770
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
700,646,907✔
771
  }
772

773
  // Velocity of center-of-mass
774
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
728,461,780✔
775

776
  // Transform to CM frame
777
  v_n -= v_cm;
728,461,780✔
778

779
  // Find speed of neutron in CM
780
  vel = v_n.norm();
728,461,780✔
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];
728,461,780✔
786
  auto d_ = dynamic_cast<UncorrelatedAngleEnergy*>(d.get());
728,461,780!
787
  if (!d_->angle().empty()) {
728,461,780!
788
    mu_cm = d_->angle().sample(p.E(), p.current_seed());
728,461,780✔
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;
728,461,780✔
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());
728,461,780✔
800

801
  // Transform back to LAB frame
802
  v_n += v_cm;
728,461,780✔
803

804
  p.E() = v_n.dot(v_n);
728,461,780✔
805
  vel = std::sqrt(p.E());
728,461,780✔
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;
728,461,780✔
810

811
  // Set energy and direction of particle in LAB frame
812
  p.u() = v_n / vel;
728,461,780✔
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)
728,461,780!
818
    p.mu() = std::copysign(1.0, p.mu());
×
819
}
728,461,780✔
820

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

827
  // Sample energy and angle
828
  double E_out;
829
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
210,605,926✔
830
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
105,302,963✔
831

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

837
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
700,646,907✔
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_) {
700,646,907✔
843

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

847
    // upper resonance scattering energy bound (target is at rest above this E)
848
    if (E > settings::res_scat_energy_max) {
84,557✔
849
      return {};
40,755✔
850

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

856
    // otherwise, use free gas model
857
  } else {
858
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
700,562,350✔
859
      return {};
336,211,584✔
860
    } else {
861
      sampling_method = ResScatMethod::cxs;
364,350,766✔
862
    }
863
  }
864

865
  // use appropriate target velocity sampling method
866
  switch (sampling_method) {
364,394,568!
867
  case ResScatMethod::cxs:
364,375,758✔
868

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

872
  case ResScatMethod::dbrc:
18,810✔
873
  case ResScatMethod::rvs: {
874
    double E_red = std::sqrt(nuc.awr_ * E / kT);
18,810✔
875
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
18,810✔
876
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
18,810✔
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()) {
18,810!
882
      i_E_low = 0;
×
883
    } else if (E_low > nuc.energy_0K_.back()) {
18,810!
884
      i_E_low = nuc.energy_0K_.size() - 2;
×
885
    } else {
886
      i_E_low =
18,810✔
887
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
18,810✔
888
    }
889

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

901
    if (i_E_up == i_E_low) {
18,810✔
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);
18,810✔
905
    }
906

907
    if (sampling_method == ResScatMethod::dbrc) {
15,532!
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) {
15,532!
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;
15,532✔
947
      if (E_low > nuc.energy_0K_.front()) {
15,532!
948
        double m = (nuc.xs_cdf_[i_E_low + 1] - nuc.xs_cdf_[i_E_low]) /
15,532✔
949
                   (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
15,532✔
950
        cdf_low = nuc.xs_cdf_[i_E_low] + m * (E_low - nuc.energy_0K_[i_E_low]);
15,532✔
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]) /
15,532✔
955
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
15,532✔
956
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
15,532✔
957

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

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

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

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

988
  UNREACHABLE();
×
989
}
990

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

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

1004
    if (prn(seed) < alpha) {
428,162,357✔
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);
103,297,370✔
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));
324,864,987✔
1017
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
324,864,987✔
1018
    }
1019

1020
    // Determine beta * vt
1021
    double beta_vt = std::sqrt(beta_vt_sq);
428,162,357✔
1022

1023
    // Sample cosine of angle between neutron and target velocity
1024
    mu = uniform_distribution(-1., 1., seed);
428,162,357✔
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) /
428,162,357✔
1029
      (beta_vn + beta_vt);
428,162,357✔
1030

1031
    // Perform rejection sampling on vt and mu
1032
    if (prn(seed) < accept_prob)
428,162,357✔
1033
      break;
364,379,036✔
1034
  }
63,783,321✔
1035

1036
  // Determine speed of target nucleus
1037
  double vt = std::sqrt(beta_vt_sq * kT / awr);
364,379,036✔
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);
364,379,036✔
1042
}
1043

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

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

1057
  if (prn(seed) < beta) {
30,003,214✔
1058
    // ====================================================================
1059
    // DELAYED NEUTRON SAMPLED
1060

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

1069
      // Check if this group is sampled
1070
      prob += yield;
686,092✔
1071
      if (xi < prob)
686,092✔
1072
        break;
174,724✔
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_);
187,926✔
1079

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

1083
    // Sample time of emission based on decay constant of precursor
1084
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
187,926✔
1085
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
187,926✔
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;
29,815,288✔
1093
  }
1094

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

1101
    // resample if energy is greater than maximum neutron energy
1102
    int neutron = ParticleType::neutron().transport_index();
30,003,214✔
1103
    if (site->E < data::energy_max[neutron])
30,003,214!
1104
      break;
30,003,214✔
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);
30,003,214✔
1118
}
30,003,214✔
1119

1120
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
17,481,382✔
1121
{
1122
  // copy energy of neutron
1123
  double E_in = p.E();
17,481,382✔
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());
17,481,382✔
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_) {
17,481,382✔
1133
    double E_cm = E;
17,427,388✔
1134

1135
    // determine outgoing energy in lab
1136
    double A = nuc.awr_;
17,427,388✔
1137
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
17,427,388✔
1138
                 ((A + 1.0) * (A + 1.0));
17,427,388✔
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);
17,427,388✔
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)
17,481,382!
1148
    mu = std::copysign(1.0, mu);
×
1149

1150
  // Set outgoing energy and scattering angle
1151
  p.E() = E;
17,481,382✔
1152
  p.mu() = mu;
17,481,382✔
1153

1154
  // change direction of particle
1155
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
17,481,382✔
1156

1157
  // evaluate yield
1158
  double yield = (*rx.products_[0].yield_)(E_in);
17,481,382✔
1159
  if (std::floor(yield) == yield && yield > 0) {
17,481,382!
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) {
17,583,434✔
1162
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
102,106✔
1163
    }
1164
  } else {
17,481,328✔
1165
    // Otherwise, change weight of particle based on yield
1166
    p.wgt() *= yield;
54✔
1167
  }
1168
}
17,481,382✔
1169

1170
void sample_secondary_photons(Particle& p, int i_nuclide)
8,809,548✔
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;
8,809,548✔
1175
  double photon_wgt = p.wgt();
8,809,548✔
1176
  int y = 1;
8,809,548✔
1177

1178
  if (settings::use_decay_photons) {
8,809,548✔
1179
    // For decay photons, sample a single photon and modify the weight
1180
    if (y_t <= 0.0)
72,006✔
1181
      return;
17,281✔
1182
    photon_wgt *= y_t;
54,725✔
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);
8,737,542✔
1187
    if (prn(p.current_seed()) <= y_t - y)
8,737,542✔
1188
      ++y;
574,860✔
1189
  }
1190

1191
  // Sample each secondary photon
1192
  for (int i = 0; i < y; ++i) {
10,129,911✔
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);
1,337,644✔
1197

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

1204
    // Sample the new direction
1205
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,337,644✔
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;
1,337,644✔
1213
    if (settings::run_mode == RunMode::EIGENVALUE && !is_fission(rx->mt_)) {
1,337,644✔
1214
      wgt *= simulation::keff;
348,128✔
1215
    }
1216

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

1220
    // Tag secondary particle with parent nuclide
1221
    if (created_photon && settings::use_decay_photons) {
1,337,644✔
1222
      p.secondary_bank().back().parent_nuclide =
52,844✔
1223
        rx->products_[i_product].parent_nuclide_;
52,844✔
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