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

openmc-dev / openmc / 25716836022

12 May 2026 06:09AM UTC coverage: 80.991% (-0.4%) from 81.388%
25716836022

Pull #3757

github

web-flow
Merge cd9aafd9c into d56cda254
Pull Request #3757: Implementation of point detectors

17778 of 25854 branches covered (68.76%)

Branch coverage included in aggregate %.

52 of 384 new or added lines in 25 files covered. (13.54%)

3 existing lines in 2 files now uncovered.

58806 of 68705 relevant lines covered (85.59%)

47042473.82 hits per line

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

84.27
/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/next_event_scoring.h"
28
#include "openmc/tallies/tally.h"
29
#include "openmc/tallies/tally_scoring.h"
30
#include "openmc/thermal.h"
31
#include "openmc/weight_windows.h"
32

33
#include <fmt/core.h>
34

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

39
namespace openmc {
40

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

45
void collision(Particle& p)
1,269,591,850✔
46
{
47
  // Add to collision counter for particle
48
  ++(p.n_collision());
1,269,591,850✔
49
  p.secondary_bank_index() = p.secondary_bank().size();
1,269,591,850!
50

51
  // Sample reaction for the material the particle is in
52
  switch (p.type().pdg_number()) {
1,269,591,850!
53
  case PDG_NEUTRON:
1,194,937,516✔
54
    sample_neutron_reaction(p);
1,194,937,516✔
55
    break;
1,194,937,516✔
56
  case PDG_PHOTON:
18,459,622✔
57
    sample_photon_reaction(p);
18,459,622✔
58
    break;
18,459,622✔
59
  case PDG_ELECTRON:
56,107,988✔
60
    sample_electron_reaction(p);
56,107,988✔
61
    break;
56,107,988✔
62
  case PDG_POSITRON:
86,724✔
63
    sample_positron_reaction(p);
86,724✔
64
    break;
86,724✔
65
  default:
×
66
    fatal_error("Unsupported particle PDG for collision sampling.");
×
67
  }
68

69
  if (settings::weight_windows_on) {
1,269,591,850✔
70
    auto [ww_found, ww] = search_weight_window(p);
83,961,081✔
71
    if (!ww_found && p.type() == ParticleType::neutron()) {
83,961,081✔
72
      // if the weight window is not valid, apply russian roulette for neutrons
73
      // (regardless of weight window collision checkpoint setting)
74
      apply_russian_roulette(p);
66,995✔
75
    } else if (settings::weight_window_checkpoint_collision) {
83,894,086!
76
      // if collision checkpointing is on, apply weight window
77
      apply_weight_window(p, ww);
83,894,086✔
78
    }
79
  }
80

81
  // Kill particle if energy falls below cutoff
82
  int type = p.type().transport_index();
1,269,591,850!
83
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
1,269,591,850!
84
    p.wgt() = 0.0;
5,525,158✔
85
  }
86

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

107
void sample_neutron_reaction(Particle& p)
1,194,937,516✔
108
{
109
  // Sample a nuclide within the material
110
  int i_nuclide = sample_nuclide(p);
1,194,937,516✔
111

112
  // Save which nuclide particle had collision with
113
  p.event_nuclide() = i_nuclide;
1,194,937,516✔
114

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

120
  const auto& nuc {data::nuclides[i_nuclide]};
1,194,937,516✔
121

122
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
1,194,937,516✔
123
    auto& rx = sample_fission(i_nuclide, p);
168,989,666✔
124
    if (settings::run_mode == RunMode::EIGENVALUE) {
168,989,666✔
125
      create_fission_sites(p, i_nuclide, rx);
143,985,544✔
126
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
25,004,122✔
127
               settings::create_fission_neutrons) {
128
      create_fission_sites(p, i_nuclide, rx);
558,074✔
129

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

142
  // Create secondary photons
143
  if (settings::photon_transport) {
1,194,937,516✔
144
    sample_secondary_photons(p, i_nuclide);
8,382,044✔
145
  }
146

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

150
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
1,194,937,516✔
151
    absorption(p, i_nuclide);
1,194,824,252✔
152
  }
153
  if (!p.alive())
1,194,937,516✔
154
    return;
155

156
  // Sample a scattering reaction and determine the secondary energy of the
157
  // exiting neutron
158
  const auto& ncrystal_mat = model::materials[p.material()]->ncrystal_mat();
1,165,002,062✔
159
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
1,165,002,062!
160
    if (!model::active_point_tallies.empty())
158,829!
NEW
161
      fatal_error("Next-Event estimator does not support ncrystal materials");
×
162
    ncrystal_mat.scatter(p);
158,829✔
163
  } else {
164
    scatter(p, i_nuclide);
1,164,843,233✔
165
  }
166

167
  // Advance URR seed stream 'N' times after energy changes
168
  if (p.E() != p.E_last()) {
1,165,002,062✔
169
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
1,164,682,831✔
170
  }
171

172
  // Play russian roulette if there are no weight windows
173
  if (!settings::weight_windows_on)
1,165,002,062✔
174
    apply_russian_roulette(p);
1,101,394,494✔
175
}
176

177
void create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx)
144,543,618✔
178
{
179
  // If uniform fission source weighting is turned on, we increase or decrease
180
  // the expected number of fission sites produced
181
  double weight = settings::ufs_on ? ufs_get_weight(p) : 1.0;
144,543,618✔
182

183
  // Determine the expected number of neutrons produced
184
  double nu_t = p.wgt() / simulation::keff * weight *
144,543,618✔
185
                p.neutron_xs(i_nuclide).nu_fission /
144,543,618✔
186
                p.neutron_xs(i_nuclide).total;
144,543,618✔
187

188
  // Sample the number of neutrons produced
189
  int nu = static_cast<int>(nu_t);
144,543,618✔
190
  if (prn(p.current_seed()) <= (nu_t - nu))
144,543,618✔
191
    ++nu;
24,096,910✔
192

193
  // If no neutrons were produced then don't continue
194
  if (nu == 0)
144,543,618✔
195
    return;
114,604,102✔
196

197
  // Initialize the counter of delayed neutrons encountered for each delayed
198
  // group.
199
  double nu_d[MAX_DELAYED_GROUPS] = {0.};
29,939,516✔
200

201
  // Clear out particle's nu fission bank
202
  p.nu_bank().clear();
29,939,516✔
203

204
  p.fission() = true;
29,939,516✔
205

206
  // Determine whether to place fission sites into the shared fission bank
207
  // or the secondary particle bank.
208
  bool use_fission_bank = (settings::run_mode == RunMode::EIGENVALUE);
29,939,516✔
209

210
  // Counter for the number of fission sites successfully stored to the shared
211
  // fission bank or the secondary particle bank
212
  int n_sites_stored;
29,939,516✔
213

214
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
68,946,282✔
215
    // Initialize fission site object with particle data
216
    SourceSite site;
39,006,766✔
217
    site.r = p.r();
39,006,766✔
218
    site.particle = ParticleType::neutron();
39,006,766✔
219
    site.time = p.time();
39,006,766✔
220
    site.wgt = 1. / weight;
39,006,766✔
221
    site.surf_id = 0;
39,006,766✔
222

223
    // Sample delayed group and angle/energy for fission reaction
224
    sample_fission_neutron(i_nuclide, rx, &site, p);
39,006,766✔
225

226
    // Reject site if it exceeds time cutoff
227
    if (site.delayed_group > 0) {
39,006,766✔
228
      double t_cutoff = settings::time_cutoff[site.particle.transport_index()];
256,922!
229
      if (site.time > t_cutoff) {
256,922!
230
        continue;
×
231
      }
232
    }
233

234
    // Set parent and progeny IDs
235
    site.parent_id = p.id();
39,006,766✔
236
    site.progeny_id = p.n_progeny()++;
39,006,766✔
237

238
    // Store fission site in bank
239
    if (use_fission_bank) {
39,006,766✔
240
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
38,803,247✔
241
      if (idx == -1) {
38,803,247!
242
        warning(
×
243
          "The shared fission bank is full. Additional fission sites created "
244
          "in this generation will not be banked. Results may be "
245
          "non-deterministic.");
246

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

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

264
    // Increment the number of neutrons born delayed
265
    if (site.delayed_group > 0) {
39,006,766✔
266
      nu_d[site.delayed_group - 1]++;
256,922✔
267
    }
268

269
    // Write fission particles to nuBank
270
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
39,006,766✔
271
    nu_bank_entry.wgt = site.wgt;
39,006,766✔
272
    nu_bank_entry.E = site.E;
39,006,766✔
273
    nu_bank_entry.delayed_group = site.delayed_group;
39,006,766✔
274
  }
275

276
  // If shared fission bank was full, and no fissions could be added,
277
  // set the particle fission flag to false.
278
  if (n_sites_stored == 0) {
29,939,516!
279
    p.fission() = false;
×
280
    return;
×
281
  }
282

283
  // Set nu to the number of fission sites successfully stored. If the fission
284
  // bank was not found to be full then these values are already equivalent.
285
  nu = n_sites_stored;
29,939,516✔
286

287
  // Store the total weight banked for analog fission tallies
288
  p.n_bank() = nu;
29,939,516✔
289
  p.wgt_bank() = nu / weight;
29,939,516✔
290
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
269,455,644✔
291
    p.n_delayed_bank(d) = nu_d[d];
239,516,128✔
292
  }
293
}
294

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

307
  // Sample element within material
308
  int i_element = sample_element(p);
18,458,819✔
309
  const auto& micro {p.photon_xs(i_element)};
18,458,819✔
310
  const auto& element {*data::elements[i_element]};
18,458,819✔
311

312
  // Calculate photon energy over electron rest mass equivalent
313
  double alpha = p.E() / MASS_ELECTRON_EV;
18,458,819✔
314

315
  // For tallying purposes, this routine might be called directly. In that
316
  // case, we need to sample a reaction via the cutoff variable
317
  double prob = 0.0;
18,458,819✔
318
  double cutoff = prn(p.current_seed()) * micro.total;
18,458,819✔
319

320
  // Coherent (Rayleigh) scattering
321
  prob += micro.coherent;
18,458,819✔
322
  if (prob > cutoff) {
18,458,819✔
323
    p.mu() = element.rayleigh_scatter(alpha, p.current_seed());
1,010,979✔
324
    p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
1,010,979✔
325
    p.event() = TallyEvent::SCATTER;
1,010,979✔
326
    p.event_mt() = COHERENT;
1,010,979✔
327
    return;
1,010,979✔
328
  }
329

330
  // Incoherent (Compton) scattering
331
  prob += micro.incoherent;
17,447,840✔
332
  if (prob > cutoff) {
17,447,840✔
333
    double alpha_out;
11,934,408✔
334
    int i_shell;
11,934,408✔
335
    element.compton_scatter(
11,934,408✔
336
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
11,934,408✔
337

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

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

359
    // Allow electrons to fill orbital and produce Auger electrons and
360
    // fluorescent photons. Since Compton subshell data does not match atomic
361
    // relaxation data, use the mapping between the data to find the subshell
362
    if (settings::atomic_relaxation && i_shell >= 0 &&
11,934,408!
363
        element.subshell_map_[i_shell] >= 0) {
11,802,705!
364
      element.atomic_relaxation(element.subshell_map_[i_shell], p);
11,802,705✔
365
    }
366

367
    phi += PI;
11,934,408✔
368
    p.E() = alpha_out * MASS_ELECTRON_EV;
11,934,408✔
369
    p.u() = rotate_angle(p.u(), p.mu(), &phi, p.current_seed());
11,934,408✔
370
    p.event() = TallyEvent::SCATTER;
11,934,408✔
371
    p.event_mt() = INCOHERENT;
11,934,408✔
372
    return;
11,934,408✔
373
  }
374

375
  // Photoelectric effect
376
  double prob_after = prob + micro.photoelectric;
5,513,432✔
377

378
  if (prob_after > cutoff) {
5,513,432✔
379
    // Get grid index, interpolation factor, and bounding subshell
380
    // cross sections
381
    int i_grid = micro.index_grid;
5,426,708✔
382
    double f = micro.interp_factor;
5,426,708✔
383
    tensor::View<const double> xs_lower = element.cross_sections_.slice(i_grid);
5,426,708✔
384
    tensor::View<const double> xs_upper =
5,426,708✔
385
      element.cross_sections_.slice(i_grid + 1);
5,426,708✔
386

387
    for (int i_shell = 0; i_shell < element.shells_.size(); ++i_shell) {
24,882,486!
388
      const auto& shell {element.shells_[i_shell]};
24,882,486✔
389

390
      // Check threshold of reaction
391
      if (xs_lower(i_shell) == 0)
24,882,486✔
392
        continue;
10,351,315✔
393

394
      //  Evaluation subshell photoionization cross section
395
      prob += std::exp(
14,531,171✔
396
        xs_lower(i_shell) + f * (xs_upper(i_shell) - xs_lower(i_shell)));
14,531,171✔
397

398
      if (prob > cutoff) {
14,531,171✔
399
        // Determine binding energy based on whether atomic relaxation data is
400
        // present (if not, use value from Compton profile data)
401
        double binding_energy = element.has_atomic_relaxation_
5,426,708✔
402
                                  ? shell.binding_energy
5,426,708!
403
                                  : element.binding_energy_[i_shell];
×
404

405
        // Determine energy of secondary electron
406
        double E_electron = p.E() - binding_energy;
5,426,708✔
407

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

424
        double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
5,426,708✔
425
        Direction u;
5,426,708✔
426
        u.x = mu;
5,426,708✔
427
        u.y = std::sqrt(1.0 - mu * mu) * std::cos(phi);
5,426,708✔
428
        u.z = std::sqrt(1.0 - mu * mu) * std::sin(phi);
5,426,708✔
429

430
        // Create secondary electron
431
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
5,426,708✔
432

433
        // Allow electrons to fill orbital and produce auger electrons
434
        // and fluorescent photons
435
        if (settings::atomic_relaxation) {
5,426,708✔
436
          element.atomic_relaxation(i_shell, p);
5,316,708✔
437
        }
438
        p.event() = TallyEvent::ABSORB;
5,426,708✔
439
        p.event_mt() = 533 + shell.index_subshell;
5,426,708✔
440
        p.wgt() = 0.0;
5,426,708✔
441
        p.E() = 0.0;
5,426,708✔
442
        return;
5,426,708✔
443
      }
444
    }
445
  }
10,853,416✔
446
  prob = prob_after;
86,724✔
447

448
  // Pair production
449
  prob += micro.pair_production;
86,724✔
450
  if (prob > cutoff) {
86,724!
451
    double E_electron, E_positron;
86,724✔
452
    double mu_electron, mu_positron;
86,724✔
453
    element.pair_production(alpha, &E_electron, &E_positron, &mu_electron,
86,724✔
454
      &mu_positron, p.current_seed());
455

456
    // Create secondary electron
457
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
86,724✔
458
    p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron());
86,724✔
459

460
    // Create secondary positron
461
    u = rotate_angle(p.u(), mu_positron, nullptr, p.current_seed());
86,724✔
462
    p.create_secondary(p.wgt(), u, E_positron, ParticleType::positron());
86,724✔
463
    p.event() = TallyEvent::ABSORB;
86,724✔
464
    p.event_mt() = PAIR_PROD;
86,724✔
465
    p.wgt() = 0.0;
86,724✔
466
    p.E() = 0.0;
86,724✔
467
  }
468
}
469

470
void sample_electron_reaction(Particle& p)
56,107,988✔
471
{
472
  // TODO: create reaction types
473

474
  if (settings::electron_treatment == ElectronTreatment::TTB) {
56,107,988✔
475
    double E_lost;
53,525,947✔
476
    thick_target_bremsstrahlung(p, &E_lost);
53,525,947✔
477
  }
478

479
  p.E() = 0.0;
56,107,988✔
480
  p.wgt() = 0.0;
56,107,988✔
481
  p.event() = TallyEvent::ABSORB;
56,107,988✔
482
}
56,107,988✔
483

484
void sample_positron_reaction(Particle& p)
86,724✔
485
{
486
  // TODO: create reaction types
487

488
  if (settings::electron_treatment == ElectronTreatment::TTB) {
86,724✔
489
    double E_lost;
86,471✔
490
    thick_target_bremsstrahlung(p, &E_lost);
86,471✔
491
  }
492

493
  // Sample angle isotropically
494
  Direction u = isotropic_direction(p.current_seed());
86,724✔
495

496
  // Create annihilation photon pair traveling in opposite directions
497
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon());
86,724✔
498
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon());
86,724✔
499

500
  p.E() = 0.0;
86,724✔
501
  p.wgt() = 0.0;
86,724✔
502
  p.event() = TallyEvent::ABSORB;
86,724✔
503
}
86,724✔
504

505
int sample_nuclide(Particle& p)
1,194,937,516✔
506
{
507
  // Sample cumulative distribution function
508
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,194,937,516✔
509

510
  // Get pointers to nuclide/density arrays
511
  const auto& mat {model::materials[p.material()]};
1,194,937,516✔
512
  int n = mat->nuclide_.size();
1,194,937,516✔
513

514
  double prob = 0.0;
1,194,937,516✔
515
  for (int i = 0; i < n; ++i) {
2,147,483,647!
516
    // Get atom density
517
    int i_nuclide = mat->nuclide_[i];
2,147,483,647✔
518
    double atom_density = mat->atom_density(i, p.density_mult());
2,147,483,647✔
519

520
    // Increment probability to compare to cutoff
521
    prob += atom_density * p.neutron_xs(i_nuclide).total;
2,147,483,647✔
522
    if (prob >= cutoff)
2,147,483,647✔
523
      return i_nuclide;
1,194,937,516✔
524
  }
525

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

531
int sample_element(Particle& p)
18,458,819✔
532
{
533
  // Sample cumulative distribution function
534
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
18,458,819✔
535

536
  // Get pointers to elements, densities
537
  const auto& mat {model::materials[p.material()]};
18,458,819✔
538

539
  double prob = 0.0;
18,458,819✔
540
  for (int i = 0; i < mat->element_.size(); ++i) {
42,672,420!
541
    // Find atom density
542
    int i_element = mat->element_[i];
42,672,420✔
543
    double atom_density = mat->atom_density(i, p.density_mult());
42,672,420✔
544

545
    // Determine microscopic cross section
546
    double sigma = atom_density * p.photon_xs(i_element).total;
42,672,420✔
547

548
    // Increment probability to compare to cutoff
549
    prob += sigma;
42,672,420✔
550
    if (prob > cutoff) {
42,672,420✔
551
      // Save which nuclide particle had collision with for tally purpose
552
      p.event_nuclide() = mat->nuclide_[i];
18,458,819✔
553

554
      return i_element;
18,458,819✔
555
    }
556
  }
557

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

563
Reaction& sample_fission(int i_nuclide, Particle& p)
168,989,666✔
564
{
565
  // Get pointer to nuclide
566
  const auto& nuc {data::nuclides[i_nuclide]};
168,989,666✔
567

568
  // If we're in the URR, by default use the first fission reaction. We also
569
  // default to the first reaction if we know that there are no partial fission
570
  // reactions
571
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
168,989,666✔
572
    return *nuc->fission_rx_[0];
168,932,082✔
573
  }
574

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

583
  // Get grid index and interpolation factor and sample fission cdf
584
  const auto& micro = p.neutron_xs(i_nuclide);
55,593✔
585
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
55,593✔
586
  double prob = 0.0;
55,593✔
587

588
  // Loop through each partial fission reaction type
589
  for (auto& rx : nuc->fission_rx_) {
55,660!
590
    // add to cumulative probability
591
    prob += rx->xs(micro);
55,660✔
592

593
    // Create fission bank sites if fission occurs
594
    if (prob > cutoff)
55,660✔
595
      return *rx;
55,593✔
596
  }
597

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

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

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

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

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

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

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

649
void absorption(Particle& p, int i_nuclide)
1,194,824,252✔
650
{
651
  if (settings::survival_biasing) {
1,194,824,252✔
652
    // Determine weight absorbed in survival biasing
653
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
5,744,970✔
654
                              p.neutron_xs(i_nuclide).total;
5,744,970✔
655

656
    // Adjust weight of particle by probability of absorption
657
    p.wgt() -= wgt_absorb;
5,744,970✔
658

659
    // Score implicit absorption estimate of keff
660
    if (settings::run_mode == RunMode::EIGENVALUE) {
5,744,970✔
661
      p.keff_tally_absorption() += wgt_absorb *
499,950✔
662
                                   p.neutron_xs(i_nuclide).nu_fission /
499,950✔
663
                                   p.neutron_xs(i_nuclide).absorption;
499,950✔
664
    }
665
  } else {
666
    // See if disappearance reaction happens
667
    if (p.neutron_xs(i_nuclide).absorption >
1,189,079,282✔
668
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
1,189,079,282✔
669
      // Score absorption estimate of keff
670
      if (settings::run_mode == RunMode::EIGENVALUE) {
29,934,497✔
671
        p.keff_tally_absorption() += p.wgt() *
24,248,111✔
672
                                     p.neutron_xs(i_nuclide).nu_fission /
24,248,111✔
673
                                     p.neutron_xs(i_nuclide).absorption;
24,248,111✔
674
      }
675

676
      p.wgt() = 0.0;
29,934,497✔
677
      p.event() = TallyEvent::ABSORB;
29,934,497✔
678
      if (!p.fission()) {
29,934,497✔
679
        p.event_mt() = N_DISAPPEAR;
17,592,013✔
680
      }
681
    }
682
  }
683
}
1,194,824,252✔
684

685
void scatter(Particle& p, int i_nuclide)
1,164,843,233✔
686
{
687
  // copy incoming direction
688
  Direction u_old {p.u()};
1,164,843,233✔
689

690
  // Get pointer to nuclide and grid index/interpolation factor
691
  const auto& nuc {data::nuclides[i_nuclide]};
1,164,843,233✔
692
  const auto& micro {p.neutron_xs(i_nuclide)};
1,164,843,233✔
693
  int i_temp = micro.index_temp;
1,164,843,233✔
694

695
  // For tallying purposes, this routine might be called directly. In that
696
  // case, we need to sample a reaction via the cutoff variable
697
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
1,164,843,233✔
698
  bool sampled = false;
1,164,843,233✔
699

700
  // Calculate elastic cross section if it wasn't precalculated
701
  if (micro.elastic == CACHE_INVALID) {
1,164,843,233✔
702
    nuc->calculate_elastic_xs(p);
912,002,252✔
703
  }
704

705
  double prob = micro.elastic - micro.thermal;
1,164,843,233✔
706
  if (prob > cutoff) {
1,164,843,233✔
707
    // =======================================================================
708
    // NON-S(A,B) ELASTIC SCATTERING
709

710
    // Determine temperature
711
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
1,013,528,829✔
712

713
    // Perform collision physics for elastic scattering
714
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
1,013,528,829✔
715

716
    p.event_mt() = ELASTIC;
1,013,528,829✔
717
    sampled = true;
1,013,528,829✔
718
  }
719

720
  prob = micro.elastic;
1,164,843,233✔
721
  if (prob > cutoff && !sampled) {
1,164,843,233✔
722
    // =======================================================================
723
    // S(A,B) SCATTERING
724

725
    sab_scatter(i_nuclide, micro.index_sab, p);
127,478,075✔
726

727
    p.event_mt() = ELASTIC;
127,478,075✔
728
    sampled = true;
127,478,075✔
729
  }
730

731
  if (!sampled) {
1,164,843,233✔
732
    // =======================================================================
733
    // INELASTIC SCATTERING
734

735
    int n = nuc->index_inelastic_scatter_.size();
23,836,329✔
736
    int i = 0;
23,836,329✔
737
    for (int j = 0; j < n && prob < cutoff; ++j) {
448,524,049✔
738
      i = nuc->index_inelastic_scatter_[j];
424,687,720✔
739

740
      // add to cumulative probability
741
      prob += nuc->reactions_[i]->xs(micro);
424,687,720✔
742
    }
743

744
    // Perform collision physics for inelastic scattering
745
    const auto& rx {nuc->reactions_[i]};
23,836,329✔
746
    inelastic_scatter(i_nuclide, *rx, p);
23,836,329✔
747
    p.event_mt() = rx->mt_;
23,836,329✔
748
  }
749

750
  // Set event component
751
  p.event() = TallyEvent::SCATTER;
1,164,843,233✔
752

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

765
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
1,013,528,829✔
766
{
767
  // get pointer to nuclide
768
  const auto& nuc {data::nuclides[i_nuclide]};
1,013,528,829✔
769

770
  double vel = std::sqrt(p.E());
1,013,528,829✔
771
  double awr = nuc->awr_;
1,013,528,829✔
772

773
  // Neutron velocity in LAB
774
  Direction v_n = vel * p.u();
1,013,528,829✔
775

776
  // Sample velocity of target nucleus
777
  Direction v_t {};
1,013,528,829✔
778
  if (!p.neutron_xs(i_nuclide).use_ptable) {
1,013,528,829✔
779
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
968,562,994✔
780
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
968,562,994✔
781
  }
782

783
  // Velocity of center-of-mass
784
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
1,013,528,829✔
785

786
  // Transform to CM frame
787
  v_n -= v_cm;
1,013,528,829✔
788

789
  // Find speed of neutron in CM
790
  vel = v_n.norm();
1,013,528,829✔
791

792
  if (!model::active_point_tallies.empty()) {
1,013,528,829!
NEW
793
    score_point_tally_elastic(p, i_nuclide, rx, 0, v_t);
×
794
  }
795

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

807
  // Determine direction cosines in CM
808
  Direction u_cm = v_n / vel;
1,013,528,829✔
809

810
  // Rotate neutron velocity vector to new angle -- note that the speed of the
811
  // neutron in CM does not change in elastic scattering. However, the speed
812
  // will change when we convert back to LAB
813
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
1,013,528,829✔
814

815
  // Transform back to LAB frame
816
  v_n += v_cm;
1,013,528,829✔
817

818
  p.E() = v_n.dot(v_n);
1,013,528,829✔
819
  vel = std::sqrt(p.E());
1,013,528,829✔
820

821
  // compute cosine of scattering angle in LAB frame by taking dot product of
822
  // neutron's pre- and post-collision angle
823
  p.mu() = p.u().dot(v_n) / vel;
1,013,528,829✔
824

825
  // Set energy and direction of particle in LAB frame
826
  p.u() = v_n / vel;
1,013,528,829!
827

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

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

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

845
  if (!model::active_point_tallies.empty()) {
127,478,075!
NEW
846
    score_point_tally_sab(p, i_nuclide, sab, micro);
×
847
  }
848

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

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

856
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
968,562,994✔
857
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
858
{
859
  // check if nuclide is a resonant scatterer
860
  ResScatMethod sampling_method;
968,562,994✔
861
  if (nuc.resonant_) {
968,562,994✔
862

863
    // sampling method to use
864
    sampling_method = settings::res_scat_method;
84,557✔
865

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

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

875
    // otherwise, use free gas model
876
  } else {
877
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
968,478,437✔
878
      return {};
461,662,332✔
879
    } else {
880
      sampling_method = ResScatMethod::cxs;
881
    }
882
  }
883

884
  // use appropriate target velocity sampling method
885
  switch (sampling_method) {
18,810!
886
  case ResScatMethod::cxs:
506,841,097✔
887

888
    // sample target velocity with the constant cross section (cxs) approx.
889
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
506,841,097✔
890

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1007
  UNREACHABLE();
×
1008
}
1009

1010
Direction sample_cxs_target_velocity(
506,844,375✔
1011
  double awr, double E, Direction u, double kT, uint64_t* seed)
1012
{
1013
  double beta_vn = std::sqrt(awr * E / kT);
506,844,375✔
1014
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
506,844,375✔
1015

1016
  double beta_vt_sq;
586,743,550✔
1017
  double mu;
586,743,550✔
1018
  while (true) {
586,743,550✔
1019
    // Sample two random numbers
1020
    double r1 = prn(seed);
586,743,550✔
1021
    double r2 = prn(seed);
586,743,550✔
1022

1023
    if (prn(seed) < alpha) {
586,743,550✔
1024
      // With probability alpha, we sample the distribution p(y) =
1025
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1026
      // Carlo sampler
1027

1028
      beta_vt_sq = -std::log(r1 * r2);
127,210,155✔
1029

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

1035
      double c = std::cos(PI / 2.0 * prn(seed));
459,533,395✔
1036
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
459,533,395✔
1037
    }
1038

1039
    // Determine beta * vt
1040
    double beta_vt = std::sqrt(beta_vt_sq);
586,743,550✔
1041

1042
    // Sample cosine of angle between neutron and target velocity
1043
    mu = uniform_distribution(-1., 1., seed);
586,743,550✔
1044

1045
    // Determine rejection probability
1046
    double accept_prob =
586,743,550✔
1047
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
586,743,550✔
1048
      (beta_vn + beta_vt);
586,743,550✔
1049

1050
    // Perform rejection sampling on vt and mu
1051
    if (prn(seed) < accept_prob)
586,743,550✔
1052
      break;
1053
  }
1054

1055
  // Determine speed of target nucleus
1056
  double vt = std::sqrt(beta_vt_sq * kT / awr);
506,844,375✔
1057

1058
  // Determine velocity vector of target nucleus based on neutron's velocity
1059
  // and the sampled angle between them
1060
  return vt * rotate_angle(u, mu, nullptr, seed);
506,844,375✔
1061
}
1062

1063
void sample_fission_neutron(
39,006,766✔
1064
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1065
{
1066
  // Get attributes of particle
1067
  double E_in = p.E();
39,006,766✔
1068
  uint64_t* seed = p.current_seed();
39,006,766✔
1069

1070
  // Determine total nu, delayed nu, and delayed neutron fraction
1071
  const auto& nuc {data::nuclides[i_nuclide]};
39,006,766✔
1072
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
39,006,766✔
1073
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
39,006,766✔
1074
  double beta = nu_d / nu_t;
39,006,766✔
1075

1076
  if (prn(seed) < beta) {
39,006,766✔
1077
    // ====================================================================
1078
    // DELAYED NEUTRON SAMPLED
1079

1080
    // sampled delayed precursor group
1081
    double xi = prn(seed) * nu_d;
256,922✔
1082
    double prob = 0.0;
256,922✔
1083
    int group;
256,922✔
1084
    for (group = 1; group < nuc->n_precursor_; ++group) {
957,897✔
1085
      // determine delayed neutron precursor yield for group j
1086
      double yield = (*rx.products_[group].yield_)(E_in);
939,282✔
1087

1088
      // Check if this group is sampled
1089
      prob += yield;
939,282✔
1090
      if (xi < prob)
939,282✔
1091
        break;
1092
    }
1093

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

1099
    // set the delayed group for the particle born from fission
1100
    site->delayed_group = group;
256,922✔
1101

1102
    // Sample time of emission based on decay constant of precursor
1103
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
256,922✔
1104
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
256,922✔
1105

1106
  } else {
1107
    // ====================================================================
1108
    // PROMPT NEUTRON SAMPLED
1109

1110
    // set the delayed group for the particle born from fission to 0
1111
    site->delayed_group = 0;
38,749,844✔
1112
  }
1113

1114
  if (!model::active_point_tallies.empty()) {
39,006,766!
NEW
1115
    score_point_tally_fission(p, i_nuclide, rx, site->delayed_group);
×
1116
  }
1117

1118
  // sample from prompt neutron energy distribution
1119
  int n_sample = 0;
1120
  double mu;
39,006,768✔
1121
  while (true) {
39,006,768✔
1122
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
39,006,768✔
1123

1124
    // resample if energy is greater than maximum neutron energy
1125
    int neutron = ParticleType::neutron().transport_index();
39,006,768✔
1126
    if (site->E < data::energy_max[neutron])
39,006,768✔
1127
      break;
1128

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

1139
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1140
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
39,006,766✔
1141
}
39,006,766✔
1142

1143
void inelastic_scatter(int i_nuclide, const Reaction& rx, Particle& p)
23,836,329✔
1144
{
1145
  // Get pointer to nuclide
1146
  const auto& nuc {data::nuclides[i_nuclide]};
23,836,329✔
1147

1148
  // copy energy of neutron
1149
  double E_in = p.E();
23,836,329✔
1150

1151
  // sample outgoing energy and scattering cosine
1152
  double E;
23,836,329✔
1153
  double mu;
23,836,329✔
1154
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
23,836,329✔
1155

1156
  double yield = (*rx.products_[0].yield_)(E_in);
23,836,329✔
1157

1158
  if (!model::active_point_tallies.empty()) {
23,836,329!
NEW
1159
    score_point_tally_inelastic(p, i_nuclide, rx, 0, yield);
×
1160
  }
1161

1162
  // if scattering system is in center-of-mass, transfer cosine of scattering
1163
  // angle and outgoing energy from CM to LAB
1164
  if (rx.scatter_in_cm_) {
23,836,329✔
1165
    double E_cm = E;
23,781,025✔
1166

1167
    // determine outgoing energy in lab
1168
    double A = nuc->awr_;
23,781,025✔
1169
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
23,781,025✔
1170
                 ((A + 1.0) * (A + 1.0));
23,781,025✔
1171

1172
    // determine outgoing angle in lab
1173
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
23,781,025✔
1174
  }
1175

1176
  // Because of floating-point roundoff, it may be possible for mu to be
1177
  // outside of the range [-1,1). In these cases, we just set mu to exactly -1
1178
  // or 1
1179
  if (std::abs(mu) > 1.0)
23,836,329!
1180
    mu = std::copysign(1.0, mu);
×
1181

1182
  // Set outgoing energy and scattering angle
1183
  p.E() = E;
23,836,329✔
1184
  p.mu() = mu;
23,836,329✔
1185

1186
  // change direction of particle
1187
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
23,836,329!
1188

1189
  if (std::floor(yield) == yield && yield > 0) {
23,836,329!
1190
    // If yield is integral, create exactly that many secondary particles
1191
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
23,966,406✔
1192
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
130,131✔
1193
    }
1194
  } else {
1195
    // Otherwise, change weight of particle based on yield
1196
    p.wgt() *= yield;
54✔
1197
  }
1198
}
23,836,329✔
1199

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

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

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

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

1234
    // Sample the new direction
1235
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,326,754✔
1236

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

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

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

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