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

openmc-dev / openmc / 18537555145

15 Oct 2025 05:37PM UTC coverage: 81.983% (-3.2%) from 85.194%
18537555145

Pull #3417

github

web-flow
Merge 3615a1fcc into e9077b137
Pull Request #3417: Addition of a collision tracking feature

16802 of 23354 branches covered (71.94%)

Branch coverage included in aggregate %.

480 of 522 new or added lines in 13 files covered. (91.95%)

483 existing lines in 53 files now uncovered.

54134 of 63171 relevant lines covered (85.69%)

43199115.04 hits per line

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

83.01
/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)
774,761,696✔
44
{
45
  // Add to collision counter for particle
46
  ++(p.n_collision());
774,761,696✔
47

48
  // Sample reaction for the material the particle is in
49
  switch (p.type()) {
774,761,696!
50
  case ParticleType::neutron:
706,647,449✔
51
    sample_neutron_reaction(p);
706,647,449✔
52
    break;
706,647,449✔
53
  case ParticleType::photon:
16,209,222✔
54
    sample_photon_reaction(p);
16,209,222✔
55
    break;
16,209,222✔
56
  case ParticleType::electron:
51,819,333✔
57
    sample_electron_reaction(p);
51,819,333✔
58
    break;
51,819,333✔
59
  case ParticleType::positron:
85,692✔
60
    sample_positron_reaction(p);
85,692✔
61
    break;
85,692✔
62
  }
63

64
  if (settings::weight_window_checkpoint_collision)
774,761,696!
65
    apply_weight_windows(p);
774,761,696✔
66

67
  // Kill particle if energy falls below cutoff
68
  int type = static_cast<int>(p.type());
774,761,696✔
69
  if (p.E() < settings::energy_cutoff[type]) {
774,761,696✔
70
    p.wgt() = 0.0;
5,005,232✔
71
  }
72

73
  // Display information about collision
74
  if (settings::verbosity >= 10 || p.trace()) {
774,761,696!
75
    std::string msg;
66✔
76
    if (p.event() == TallyEvent::KILL) {
66!
77
      msg = fmt::format("    Killed. Energy = {} eV.", p.E());
×
78
    } else if (p.type() == ParticleType::neutron) {
66!
79
      msg = fmt::format("    {} with {}. Energy = {} eV.",
186✔
80
        reaction_name(p.event_mt()), data::nuclides[p.event_nuclide()]->name_,
132✔
81
        p.E());
66✔
82
    } else if (p.type() == ParticleType::photon) {
×
83
      msg = fmt::format("    {} with {}. Energy = {} eV.",
×
84
        reaction_name(p.event_mt()),
×
85
        to_element(data::nuclides[p.event_nuclide()]->name_), p.E());
×
86
    } else {
87
      msg = fmt::format("    Disappeared. Energy = {} eV.", p.E());
×
88
    }
89
    write_message(msg, 1);
66✔
90
  }
66✔
91
}
774,761,696✔
92

93
void sample_neutron_reaction(Particle& p)
706,647,449✔
94
{
95
  // Sample a nuclide within the material
96
  int i_nuclide = sample_nuclide(p);
706,647,449✔
97

98
  // Save which nuclide particle had collision with
99
  p.event_nuclide() = i_nuclide;
706,647,449✔
100

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

106
  const auto& nuc {data::nuclides[i_nuclide]};
706,647,449✔
107

108
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
706,647,449✔
109
    auto& rx = sample_fission(i_nuclide, p);
96,047,650✔
110
    if (settings::run_mode == RunMode::EIGENVALUE) {
96,047,650✔
111
      create_fission_sites(p, i_nuclide, rx);
90,960,711✔
112
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
5,086,939✔
113
               settings::create_fission_neutrons) {
114
      create_fission_sites(p, i_nuclide, rx);
5,073,035✔
115

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

128
  // Create secondary photons
129
  if (settings::photon_transport) {
706,647,449✔
130
    sample_secondary_photons(p, i_nuclide);
8,809,548✔
131
  }
132

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

136
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
706,647,449✔
137
    absorption(p, i_nuclide);
706,643,919✔
138
  }
139
  if (!p.alive())
706,647,449✔
140
    return;
18,252,245✔
141

142
  // Sample a scattering reaction and determine the secondary energy of the
143
  // exiting neutron
144
  const auto& ncrystal_mat = model::materials[p.material()]->ncrystal_mat();
688,395,204✔
145
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
688,395,204!
146
    ncrystal_mat.scatter(p);
158,829✔
147
  } else {
148
    scatter(p, i_nuclide);
688,236,375✔
149
  }
150

151
  // Advance URR seed stream 'N' times after energy changes
152
  if (p.E() != p.E_last()) {
688,395,204✔
153
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
688,075,973✔
154
  }
155

156
  // Play russian roulette if survival biasing is turned on
157
  if (settings::survival_biasing) {
688,395,204✔
158
    // if survival normalization is on, use normalized weight cutoff and
159
    // normalized weight survive
160
    if (settings::survival_normalization) {
499,950!
161
      if (p.wgt() < settings::weight_cutoff * p.wgt_born()) {
×
162
        russian_roulette(p, settings::weight_survive * p.wgt_born());
×
163
      }
164
    } else if (p.wgt() < settings::weight_cutoff) {
499,950✔
165
      russian_roulette(p, settings::weight_survive);
56,991✔
166
    }
167
  }
168
}
169

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

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

181
  // Sample the number of neutrons produced
182
  int nu = static_cast<int>(nu_t);
96,033,746✔
183
  if (prn(p.current_seed()) <= (nu_t - nu))
96,033,746✔
184
    ++nu;
15,864,510✔
185

186
  // If no neutrons were produced then don't continue
187
  if (nu == 0)
96,033,746✔
188
    return;
76,265,299✔
189

190
  // Initialize the counter of delayed neutrons encountered for each delayed
191
  // group.
192
  double nu_d[MAX_DELAYED_GROUPS] = {0.};
19,768,447✔
193

194
  // Clear out particle's nu fission bank
195
  p.nu_bank().clear();
19,768,447✔
196

197
  p.fission() = true;
19,768,447✔
198

199
  // Determine whether to place fission sites into the shared fission bank
200
  // or the secondary particle bank.
201
  bool use_fission_bank = (settings::run_mode == RunMode::EIGENVALUE);
19,768,447✔
202

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

207
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
44,915,567✔
208
    // Initialize fission site object with particle data
209
    SourceSite site;
25,147,120✔
210
    site.r = p.r();
25,147,120✔
211
    site.particle = ParticleType::neutron;
25,147,120✔
212
    site.time = p.time();
25,147,120✔
213
    site.wgt = 1. / weight;
25,147,120✔
214
    site.surf_id = 0;
25,147,120✔
215

216
    // Sample delayed group and angle/energy for fission reaction
217
    sample_fission_neutron(i_nuclide, rx, &site, p);
25,147,120✔
218

219
    // Reject site if it exceeds time cutoff
220
    if (site.delayed_group > 0) {
25,147,120✔
221
      double t_cutoff = settings::time_cutoff[static_cast<int>(site.particle)];
157,710✔
222
      if (site.time > t_cutoff) {
157,710!
223
        continue;
×
224
      }
225
    }
226

227
    // Set parent and progeny IDs
228
    site.parent_id = p.id();
25,147,120✔
229
    site.progeny_id = p.n_progeny()++;
25,147,120✔
230

231
    // Store fission site in bank
232
    if (use_fission_bank) {
25,147,120✔
233
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
24,808,389✔
234
      if (idx == -1) {
24,808,389!
235
        warning(
×
236
          "The shared fission bank is full. Additional fission sites created "
237
          "in this generation will not be banked. Results may be "
238
          "non-deterministic.");
239

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

245
        // Break out of loop as no more sites can be added to fission bank
246
        break;
×
247
      }
248
      // Iterated Fission Probability (IFP) method
249
      if (settings::ifp_on) {
24,808,389✔
250
        ifp(p, idx);
1,352,626✔
251
      }
252
    } else {
253
      p.secondary_bank().push_back(site);
338,731✔
254
    }
255

256
    // Increment the number of neutrons born delayed
257
    if (site.delayed_group > 0) {
25,147,120✔
258
      nu_d[site.delayed_group - 1]++;
157,710✔
259
    }
260

261
    // Write fission particles to nuBank
262
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
25,147,120✔
263
    nu_bank_entry.wgt = site.wgt;
25,147,120✔
264
    nu_bank_entry.E = site.E;
25,147,120✔
265
    nu_bank_entry.delayed_group = site.delayed_group;
25,147,120✔
266
  }
267

268
  // If shared fission bank was full, and no fissions could be added,
269
  // set the particle fission flag to false.
270
  if (n_sites_stored == 0) {
19,768,447!
271
    p.fission() = false;
×
272
    return;
×
273
  }
274

275
  // Set nu to the number of fission sites successfully stored. If the fission
276
  // bank was not found to be full then these values are already equivalent.
277
  nu = n_sites_stored;
19,768,447✔
278

279
  // Store the total weight banked for analog fission tallies
280
  p.n_bank() = nu;
19,768,447✔
281
  p.wgt_bank() = nu / weight;
19,768,447✔
282
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
177,916,023✔
283
    p.n_delayed_bank(d) = nu_d[d];
158,147,576✔
284
  }
285
}
286

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

299
  // Sample element within material
300
  int i_element = sample_element(p);
16,209,222✔
301
  const auto& micro {p.photon_xs(i_element)};
16,209,222✔
302
  const auto& element {*data::elements[i_element]};
16,209,222✔
303

304
  // Calculate photon energy over electron rest mass equivalent
305
  double alpha = p.E() / MASS_ELECTRON_EV;
16,209,222✔
306

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

312
  // Coherent (Rayleigh) scattering
313
  prob += micro.coherent;
16,209,222✔
314
  if (prob > cutoff) {
16,209,222✔
315
    p.mu() = element.rayleigh_scatter(alpha, p.current_seed());
894,386✔
316
    p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
894,386✔
317
    p.event() = TallyEvent::SCATTER;
894,386✔
318
    p.event_mt() = COHERENT;
894,386✔
319
    return;
894,386✔
320
  }
321

322
  // Incoherent (Compton) scattering
323
  prob += micro.incoherent;
15,314,836✔
324
  if (prob > cutoff) {
15,314,836✔
325
    double alpha_out;
326
    int i_shell;
327
    element.compton_scatter(
20,641,054✔
328
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
10,320,527✔
329

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

339
    // Create Compton electron
340
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
10,320,527✔
341
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
10,320,527✔
342
    int electron = static_cast<int>(ParticleType::electron);
10,320,527✔
343
    if (E_electron >= settings::energy_cutoff[electron]) {
10,320,527✔
344
      double mu_electron = (alpha - alpha_out * p.mu()) /
10,223,329✔
345
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
20,446,658✔
346
                                     2.0 * alpha * alpha_out * p.mu());
10,223,329✔
347
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
10,223,329✔
348
      p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron);
10,223,329✔
349
    }
350

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

358
    phi += PI;
10,320,527✔
359
    p.E() = alpha_out * MASS_ELECTRON_EV;
10,320,527✔
360
    p.u() = rotate_angle(p.u(), p.mu(), &phi, p.current_seed());
10,320,527✔
361
    p.event() = TallyEvent::SCATTER;
10,320,527✔
362
    p.event_mt() = INCOHERENT;
10,320,527✔
363
    return;
10,320,527✔
364
  }
365

366
  // Photoelectric effect
367
  double prob_after = prob + micro.photoelectric;
4,994,309✔
368

369
  if (prob_after > cutoff) {
4,994,309✔
370
    // Get grid index, interpolation factor, and bounding subshell
371
    // cross sections
372
    int i_grid = micro.index_grid;
4,908,617✔
373
    double f = micro.interp_factor;
4,908,617✔
374
    const auto& xs_lower = xt::row(element.cross_sections_, i_grid);
4,908,617✔
375
    const auto& xs_upper = xt::row(element.cross_sections_, i_grid + 1);
4,908,617✔
376

377
    for (int i_shell = 0; i_shell < element.shells_.size(); ++i_shell) {
24,083,620!
378
      const auto& shell {element.shells_[i_shell]};
24,083,620✔
379

380
      // Check threshold of reaction
381
      if (xs_lower(i_shell) == 0)
24,083,620✔
382
        continue;
10,261,522✔
383

384
      //  Evaluation subshell photoionization cross section
385
      prob += std::exp(
13,822,098✔
386
        xs_lower(i_shell) + f * (xs_upper(i_shell) - xs_lower(i_shell)));
13,822,098✔
387

388
      if (prob > cutoff) {
13,822,098✔
389
        // Determine binding energy based on whether atomic relaxation data is
390
        // present (if not, use value from Compton profile data)
391
        double binding_energy = element.has_atomic_relaxation_
4,908,617✔
392
                                  ? shell.binding_energy
4,908,617!
393
                                  : element.binding_energy_[i_shell];
×
394

395
        // Determine energy of secondary electron
396
        double E_electron = p.E() - binding_energy;
4,908,617✔
397

398
        // Sample mu using non-relativistic Sauter distribution.
399
        // See Eqns 3.19 and 3.20 in "Implementing a photon physics
400
        // model in Serpent 2" by Toni Kaltiaisenaho
401
        double mu;
402
        while (true) {
403
          double r = prn(p.current_seed());
7,362,439✔
404
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
7,362,439✔
405
            double rel_vel =
406
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
4,908,617✔
407
              (E_electron + MASS_ELECTRON_EV);
4,908,617✔
408
            mu =
4,908,617✔
409
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
4,908,617✔
410
            break;
4,908,617✔
411
          }
412
        }
2,453,822✔
413

414
        double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
4,908,617✔
415
        Direction u;
4,908,617✔
416
        u.x = mu;
4,908,617✔
417
        u.y = std::sqrt(1.0 - mu * mu) * std::cos(phi);
4,908,617✔
418
        u.z = std::sqrt(1.0 - mu * mu) * std::sin(phi);
4,908,617✔
419

420
        // Create secondary electron
421
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron);
4,908,617✔
422

423
        // Allow electrons to fill orbital and produce auger electrons
424
        // and fluorescent photons
425
        element.atomic_relaxation(i_shell, p);
4,908,617✔
426
        p.event() = TallyEvent::ABSORB;
4,908,617✔
427
        p.event_mt() = 533 + shell.index_subshell;
4,908,617✔
428
        p.wgt() = 0.0;
4,908,617✔
429
        p.E() = 0.0;
4,908,617✔
430
        return;
4,908,617✔
431
      }
432
    }
433
  }
9,817,234!
434
  prob = prob_after;
85,692✔
435

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

444
    // Create secondary electron
445
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
85,692✔
446
    p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron);
85,692✔
447

448
    // Create secondary positron
449
    u = rotate_angle(p.u(), mu_positron, nullptr, p.current_seed());
85,692✔
450
    p.create_secondary(p.wgt(), u, E_positron, ParticleType::positron);
85,692✔
451

452
    p.event() = TallyEvent::ABSORB;
85,692✔
453
    p.event_mt() = PAIR_PROD;
85,692✔
454
    p.wgt() = 0.0;
85,692✔
455
    p.E() = 0.0;
85,692✔
456
  }
457
}
458

459
void sample_electron_reaction(Particle& p)
51,819,333✔
460
{
461
  // TODO: create reaction types
462

463
  if (settings::electron_treatment == ElectronTreatment::TTB) {
51,819,333✔
464
    double E_lost;
465
    thick_target_bremsstrahlung(p, &E_lost);
51,816,671✔
466
  }
467

468
  p.E() = 0.0;
51,819,333✔
469
  p.wgt() = 0.0;
51,819,333✔
470
  p.event() = TallyEvent::ABSORB;
51,819,333✔
471
}
51,819,333✔
472

473
void sample_positron_reaction(Particle& p)
85,692✔
474
{
475
  // TODO: create reaction types
476

477
  if (settings::electron_treatment == ElectronTreatment::TTB) {
85,692✔
478
    double E_lost;
479
    thick_target_bremsstrahlung(p, &E_lost);
85,681✔
480
  }
481

482
  // Sample angle isotropically
483
  Direction u = isotropic_direction(p.current_seed());
85,692✔
484

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

489
  p.E() = 0.0;
85,692✔
490
  p.wgt() = 0.0;
85,692✔
491
  p.event() = TallyEvent::ABSORB;
85,692✔
492
}
85,692✔
493

494
int sample_nuclide(Particle& p)
706,647,449✔
495
{
496
  // Sample cumulative distribution function
497
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
706,647,449✔
498

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

503
  double prob = 0.0;
706,647,449✔
504
  for (int i = 0; i < n; ++i) {
1,562,333,169!
505
    // Get atom density
506
    int i_nuclide = mat->nuclide_[i];
1,562,333,169✔
507
    double atom_density = mat->atom_density(i, p.density_mult());
1,562,333,169✔
508

509
    // Increment probability to compare to cutoff
510
    prob += atom_density * p.neutron_xs(i_nuclide).total;
1,562,333,169✔
511
    if (prob >= cutoff)
1,562,333,169✔
512
      return i_nuclide;
706,647,449✔
513
  }
514

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

520
int sample_element(Particle& p)
16,209,222✔
521
{
522
  // Sample cumulative distribution function
523
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
16,209,222✔
524

525
  // Get pointers to elements, densities
526
  const auto& mat {model::materials[p.material()]};
16,209,222✔
527

528
  double prob = 0.0;
16,209,222✔
529
  for (int i = 0; i < mat->element_.size(); ++i) {
39,356,609!
530
    // Find atom density
531
    int i_element = mat->element_[i];
39,356,609✔
532
    double atom_density = mat->atom_density(i, p.density_mult());
39,356,609✔
533

534
    // Determine microscopic cross section
535
    double sigma = atom_density * p.photon_xs(i_element).total;
39,356,609✔
536

537
    // Increment probability to compare to cutoff
538
    prob += sigma;
39,356,609✔
539
    if (prob > cutoff) {
39,356,609✔
540
      // Save which nuclide particle had collision with for tally purpose
541
      p.event_nuclide() = mat->nuclide_[i];
16,209,222✔
542

543
      return i_element;
16,209,222✔
544
    }
545
  }
546

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

552
Reaction& sample_fission(int i_nuclide, Particle& p)
96,047,650✔
553
{
554
  // Get pointer to nuclide
555
  const auto& nuc {data::nuclides[i_nuclide]};
96,047,650✔
556

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

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

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

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

582
    // Create fission bank sites if fission occurs
583
    if (prob > cutoff)
25,956✔
584
      return *rx;
25,905✔
585
  }
586

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

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

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

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

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

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

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

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

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

648
    // Score implicit absorption estimate of keff
649
    if (settings::run_mode == RunMode::EIGENVALUE) {
499,950!
650
      p.keff_tally_absorption() += wgt_absorb *
499,950✔
651
                                   p.neutron_xs(i_nuclide).nu_fission /
499,950✔
652
                                   p.neutron_xs(i_nuclide).absorption;
499,950✔
653
    }
654
  } else {
655
    // See if disappearance reaction happens
656
    if (p.neutron_xs(i_nuclide).absorption >
706,143,969✔
657
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
706,143,969✔
658
      // Score absorption estimate of keff
659
      if (settings::run_mode == RunMode::EIGENVALUE) {
18,252,245✔
660
        p.keff_tally_absorption() += p.wgt() *
31,009,454✔
661
                                     p.neutron_xs(i_nuclide).nu_fission /
15,504,727✔
662
                                     p.neutron_xs(i_nuclide).absorption;
15,504,727✔
663
      }
664

665
      p.wgt() = 0.0;
18,252,245✔
666
      p.event() = TallyEvent::ABSORB;
18,252,245✔
667
      if (!p.fission()) {
18,252,245✔
668
        p.event_mt() = N_DISAPPEAR;
10,422,280✔
669
      }
670
    }
671
  }
672
}
706,643,919✔
673

674
void scatter(Particle& p, int i_nuclide)
688,236,375✔
675
{
676
  // copy incoming direction
677
  Direction u_old {p.u()};
688,236,375✔
678

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

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

689
  // Calculate elastic cross section if it wasn't precalculated
690
  if (micro.elastic == CACHE_INVALID) {
688,236,375✔
691
    nuc->calculate_elastic_xs(p);
577,293,177✔
692
  }
693

694
  double prob = micro.elastic - micro.thermal;
688,236,375✔
695
  if (prob > cutoff) {
688,236,375✔
696
    // =======================================================================
697
    // NON-S(A,B) ELASTIC SCATTERING
698

699
    // Determine temperature
700
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
596,774,814✔
701

702
    // Perform collision physics for elastic scattering
703
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
596,774,814✔
704

705
    p.event_mt() = ELASTIC;
596,774,814✔
706
    sampled = true;
596,774,814✔
707
  }
708

709
  prob = micro.elastic;
688,236,375✔
710
  if (prob > cutoff && !sampled) {
688,236,375✔
711
    // =======================================================================
712
    // S(A,B) SCATTERING
713

714
    sab_scatter(i_nuclide, micro.index_sab, p);
75,539,461✔
715

716
    p.event_mt() = ELASTIC;
75,539,461✔
717
    sampled = true;
75,539,461✔
718
  }
719

720
  if (!sampled) {
688,236,375✔
721
    // =======================================================================
722
    // INELASTIC SCATTERING
723

724
    int n = nuc->index_inelastic_scatter_.size();
15,922,100✔
725
    int i = 0;
15,922,100✔
726
    for (int j = 0; j < n && prob < cutoff; ++j) {
269,080,440✔
727
      i = nuc->index_inelastic_scatter_[j];
253,158,340✔
728

729
      // add to cumulative probability
730
      prob += nuc->reactions_[i]->xs(micro);
253,158,340✔
731
    }
732

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

739
  // Set event component
740
  p.event() = TallyEvent::SCATTER;
688,236,375✔
741

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

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

759
  double vel = std::sqrt(p.E());
596,774,814✔
760
  double awr = nuc->awr_;
596,774,814✔
761

762
  // Neutron velocity in LAB
763
  Direction v_n = vel * p.u();
596,774,814✔
764

765
  // Sample velocity of target nucleus
766
  Direction v_t {};
596,774,814✔
767
  if (!p.neutron_xs(i_nuclide).use_ptable) {
596,774,814✔
768
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
1,154,530,724✔
769
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
577,265,362✔
770
  }
771

772
  // Velocity of center-of-mass
773
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
596,774,814✔
774

775
  // Transform to CM frame
776
  v_n -= v_cm;
596,774,814✔
777

778
  // Find speed of neutron in CM
779
  vel = v_n.norm();
596,774,814✔
780

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

792
  // Determine direction cosines in CM
793
  Direction u_cm = v_n / vel;
596,774,814✔
794

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

800
  // Transform back to LAB frame
801
  v_n += v_cm;
596,774,814✔
802

803
  p.E() = v_n.dot(v_n);
596,774,814✔
804
  vel = std::sqrt(p.E());
596,774,814✔
805

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

810
  // Set energy and direction of particle in LAB frame
811
  p.u() = v_n / vel;
596,774,814✔
812

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

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

826
  // Sample energy and angle
827
  double E_out;
828
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
151,078,922✔
829
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
75,539,461✔
830

831
  // Set energy to outgoing, change direction of particle
832
  p.E() = E_out;
75,539,461✔
833
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
75,539,461✔
834
}
75,539,461✔
835

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

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

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

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

855
    // otherwise, use free gas model
856
  } else {
857
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
577,180,805✔
858
      return {};
235,678,112✔
859
    } else {
860
      sampling_method = ResScatMethod::cxs;
341,502,693✔
861
    }
862
  }
863

864
  // use appropriate target velocity sampling method
865
  switch (sampling_method) {
341,546,495!
866
  case ResScatMethod::cxs:
341,527,685✔
867

868
    // sample target velocity with the constant cross section (cxs) approx.
869
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
341,527,685✔
870

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

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

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

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

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

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

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

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

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

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

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

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

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

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

987
  UNREACHABLE();
×
988
}
989

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

996
  double beta_vt_sq;
997
  double mu;
998
  while (true) {
999
    // Sample two random numbers
1000
    double r1 = prn(seed);
404,524,074✔
1001
    double r2 = prn(seed);
404,524,074✔
1002

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

1008
      beta_vt_sq = -std::log(r1 * r2);
102,353,651✔
1009

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

1015
      double c = std::cos(PI / 2.0 * prn(seed));
302,170,423✔
1016
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
302,170,423✔
1017
    }
1018

1019
    // Determine beta * vt
1020
    double beta_vt = std::sqrt(beta_vt_sq);
404,524,074✔
1021

1022
    // Sample cosine of angle between neutron and target velocity
1023
    mu = uniform_distribution(-1., 1., seed);
404,524,074✔
1024

1025
    // Determine rejection probability
1026
    double accept_prob =
1027
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
404,524,074✔
1028
      (beta_vn + beta_vt);
404,524,074✔
1029

1030
    // Perform rejection sampling on vt and mu
1031
    if (prn(seed) < accept_prob)
404,524,074✔
1032
      break;
341,530,963✔
1033
  }
62,993,111✔
1034

1035
  // Determine speed of target nucleus
1036
  double vt = std::sqrt(beta_vt_sq * kT / awr);
341,530,963✔
1037

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

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

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

1056
  if (prn(seed) < beta) {
25,147,120✔
1057
    // ====================================================================
1058
    // DELAYED NEUTRON SAMPLED
1059

1060
    // sampled delayed precursor group
1061
    double xi = prn(seed) * nu_d;
157,710✔
1062
    double prob = 0.0;
157,710✔
1063
    int group;
1064
    for (group = 1; group < nuc->n_precursor_; ++group) {
589,482✔
1065
      // determine delayed neutron precursor yield for group j
1066
      double yield = (*rx.products_[group].yield_)(E_in);
578,421✔
1067

1068
      // Check if this group is sampled
1069
      prob += yield;
578,421✔
1070
      if (xi < prob)
578,421✔
1071
        break;
146,649✔
1072
    }
1073

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

1079
    // set the delayed group for the particle born from fission
1080
    site->delayed_group = group;
157,710✔
1081

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

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

1090
    // set the delayed group for the particle born from fission to 0
1091
    site->delayed_group = 0;
24,989,410✔
1092
  }
1093

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

1100
    // resample if energy is greater than maximum neutron energy
1101
    constexpr int neutron = static_cast<int>(ParticleType::neutron);
25,147,120✔
1102
    if (site->E < data::energy_max[neutron])
25,147,120!
1103
      break;
25,147,120✔
1104

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

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

1119
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
15,922,100✔
1120
{
1121
  // copy energy of neutron
1122
  double E_in = p.E();
15,922,100✔
1123

1124
  // sample outgoing energy and scattering cosine
1125
  double E;
1126
  double mu;
1127
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
15,922,100✔
1128

1129
  // if scattering system is in center-of-mass, transfer cosine of scattering
1130
  // angle and outgoing energy from CM to LAB
1131
  if (rx.scatter_in_cm_) {
15,922,100✔
1132
    double E_cm = E;
15,872,183✔
1133

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

1139
    // determine outgoing angle in lab
1140
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
15,872,183✔
1141
  }
1142

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

1149
  // Set outgoing energy and scattering angle
1150
  p.E() = E;
15,922,100✔
1151
  p.mu() = mu;
15,922,100✔
1152

1153
  // change direction of particle
1154
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
15,922,100✔
1155

1156
  // evaluate yield
1157
  double yield = (*rx.products_[0].yield_)(E_in);
15,922,100✔
1158
  if (std::floor(yield) == yield && yield > 0) {
15,922,100!
1159
    // If yield is integral, create exactly that many secondary particles
1160
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
15,994,314✔
1161
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron);
72,290✔
1162
    }
1163
  } else {
15,922,024✔
1164
    // Otherwise, change weight of particle based on yield
1165
    p.wgt() *= yield;
76✔
1166
  }
1167
}
15,922,100✔
1168

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

1177
  if (settings::use_decay_photons) {
8,809,548✔
1178
    // For decay photons, sample a single photon and modify the weight
1179
    if (y_t <= 0.0)
72,006✔
1180
      return;
17,281✔
1181
    photon_wgt *= y_t;
54,725✔
1182
  } else {
1183
    // For prompt photons, sample an integral number of photons with weight
1184
    // equal to the neutron's weight
1185
    y = static_cast<int>(y_t);
8,737,542✔
1186
    if (prn(p.current_seed()) <= y_t - y)
8,737,542✔
1187
      ++y;
574,860✔
1188
  }
1189

1190
  // Sample each secondary photon
1191
  for (int i = 0; i < y; ++i) {
10,129,911✔
1192
    // Sample the reaction and product
1193
    int i_rx;
1194
    int i_product;
1195
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
1,337,644✔
1196

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

1203
    // Sample the new direction
1204
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,337,644✔
1205

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

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

1219
    // Tag secondary particle with parent nuclide
1220
    if (created_photon && settings::use_decay_photons) {
1,337,644✔
1221
      p.secondary_bank().back().parent_nuclide =
52,844✔
1222
        rx->products_[i_product].parent_nuclide_;
52,844✔
1223
    }
1224
  }
1225
}
1226

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

© 2025 Coveralls, Inc