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

openmc-dev / openmc / 30728565910

02 Aug 2026 02:16AM UTC coverage: 81.423% (-0.03%) from 81.45%
30728565910

Pull #4040

github

web-flow
Merge 23a1e43d7 into 03b036aa6
Pull Request #4040: Inline photon-induced electron and positron treatment

18512 of 26815 branches covered (69.04%)

Branch coverage included in aggregate %.

31 of 32 new or added lines in 3 files covered. (96.88%)

17 existing lines in 3 files now uncovered.

60221 of 69881 relevant lines covered (86.18%)

49939664.5 hits per line

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

82.7
/src/physics.cpp
1
#include "openmc/physics.h"
2

3
#include "openmc/bank.h"
4
#include "openmc/bremsstrahlung.h"
5
#include "openmc/chain.h"
6
#include "openmc/constants.h"
7
#include "openmc/distribution_multi.h"
8
#include "openmc/eigenvalue.h"
9
#include "openmc/endf.h"
10
#include "openmc/error.h"
11
#include "openmc/ifp.h"
12
#include "openmc/material.h"
13
#include "openmc/math_functions.h"
14
#include "openmc/message_passing.h"
15
#include "openmc/ncrystal_interface.h"
16
#include "openmc/nuclide.h"
17
#include "openmc/photon.h"
18
#include "openmc/physics_common.h"
19
#include "openmc/random_dist.h"
20
#include "openmc/random_lcg.h"
21
#include "openmc/reaction.h"
22
#include "openmc/search.h"
23
#include "openmc/secondary_uncorrelated.h"
24
#include "openmc/settings.h"
25
#include "openmc/simulation.h"
26
#include "openmc/string_utils.h"
27
#include "openmc/tallies/tally.h"
28
#include "openmc/thermal.h"
29
#include "openmc/weight_windows.h"
30

31
#include <fmt/core.h>
32

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

37
namespace openmc {
38

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

43
void collision(Particle& p)
1,587,036,601✔
44
{
45
  // Add to collision counter for particle
46
  ++(p.n_collision());
1,587,036,601✔
47
  p.secondary_bank_index() = p.local_secondary_bank().size();
1,587,036,601!
48

49
  // Sample reaction for the material the particle is in
50
  switch (p.type().pdg_number()) {
1,587,036,601!
51
  case PDG_NEUTRON:
1,552,587,179✔
52
    sample_neutron_reaction(p);
1,552,587,179✔
53
    break;
1,552,587,179✔
54
  case PDG_PHOTON:
34,339,422✔
55
    sample_photon_reaction(p);
34,339,422✔
56
    break;
34,339,422✔
57
  case PDG_ELECTRON:
110,000✔
58
    sample_electron_reaction(p);
110,000✔
59
    break;
110,000✔
UNCOV
60
  case PDG_POSITRON:
×
UNCOV
61
    sample_positron_reaction(p);
×
UNCOV
62
    break;
×
63
  default:
×
64
    fatal_error("Unsupported particle PDG for collision sampling.");
×
65
  }
66

67
  if (settings::weight_windows_on) {
1,587,036,601✔
68
    auto [ww_found, ww] = search_weight_window(p);
417,639,735✔
69
    if (!ww_found && p.type() == ParticleType::neutron()) {
417,639,735✔
70
      // if the weight window is not valid, apply russian roulette for neutrons
71
      // (regardless of weight window collision checkpoint setting)
72
      apply_russian_roulette(p);
66,274✔
73
    } else if (settings::weight_window_checkpoint_collision) {
417,573,461!
74
      // if collision checkpointing is on, apply weight window
75
      apply_weight_window(p, ww);
417,573,461✔
76
    }
77
  }
78

79
  // Kill particle if energy falls below cutoff
80
  int type = p.type().transport_index();
1,587,036,601!
81
  if (type != C_NONE && p.E() < settings::energy_cutoff[type]) {
1,587,036,601!
82
    p.wgt() = 0.0;
8,100,603✔
83
  }
84

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

105
void sample_neutron_reaction(Particle& p)
1,552,587,179✔
106
{
107
  // Sample a nuclide within the material
108
  int i_nuclide = sample_nuclide(p);
1,552,587,179✔
109

110
  // Save which nuclide particle had collision with
111
  p.event_nuclide() = i_nuclide;
1,552,587,179✔
112

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

118
  const auto& nuc {data::nuclides[i_nuclide]};
1,552,587,179✔
119

120
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
1,552,587,179✔
121
    auto& rx = sample_fission(i_nuclide, p);
170,029,310✔
122
    if (settings::run_mode == RunMode::EIGENVALUE) {
170,029,310✔
123
      create_fission_sites(p, i_nuclide, rx);
145,002,265✔
124
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
25,027,045✔
125
               settings::create_fission_neutrons) {
126
      create_fission_sites(p, i_nuclide, rx);
580,997✔
127

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

141
  // Create secondary photons
142
  if (settings::photon_transport) {
1,552,587,179✔
143
    sample_secondary_photons(p, i_nuclide);
77,865,359✔
144
  }
145

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

149
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
1,552,587,179✔
150
    absorption(p, i_nuclide);
1,552,474,077✔
151
  }
152
  if (!p.alive())
1,552,587,179✔
153
    return;
154

155
  // Sample a scattering reaction and determine the secondary energy of the
156
  // exiting neutron
157
  const auto& ncrystal_mat = model::materials[p.material()]->ncrystal_mat();
1,518,124,411✔
158
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
1,518,124,411!
159
    ncrystal_mat.scatter(p);
158,829✔
160
  } else {
161
    scatter(p, i_nuclide);
1,517,965,582✔
162
  }
163

164
  // Advance URR seed stream 'N' times after energy changes
165
  if (p.E() != p.E_last()) {
1,518,124,411✔
166
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
1,517,805,180✔
167
  }
168

169
  // Play russian roulette if there are no weight windows
170
  if (!settings::weight_windows_on)
1,518,124,411✔
171
    apply_russian_roulette(p);
1,129,310,220✔
172
}
173

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

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

185
  // Sample the number of neutrons produced
186
  int nu = static_cast<int>(nu_t);
145,583,262✔
187
  if (prn(p.current_seed()) <= (nu_t - nu))
145,583,262✔
188
    ++nu;
24,146,642✔
189

190
  // If no neutrons were produced then don't continue
191
  if (nu == 0)
145,583,262✔
192
    return;
115,592,862✔
193

194
  // Initialize the counter of delayed neutrons encountered for each delayed
195
  // group.
196
  double nu_d[MAX_DELAYED_GROUPS] = {0.};
29,990,400✔
197

198
  // Clear out particle's nu fission bank
199
  p.nu_bank().clear();
29,990,400✔
200

201
  p.fission() = true;
29,990,400✔
202

203
  // Determine whether to place fission sites into the shared fission bank
204
  // or the secondary particle bank.
205
  bool use_fission_bank = (settings::run_mode == RunMode::EIGENVALUE);
29,990,400✔
206

207
  // Counter for the number of fission sites successfully stored to the shared
208
  // fission bank or the secondary particle bank
209
  int n_sites_stored;
29,990,400✔
210

211
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
69,014,266✔
212
    // Initialize fission site object with particle data
213
    SourceSite site;
39,023,866✔
214
    site.r = p.r();
39,023,866✔
215
    site.particle = ParticleType::neutron();
39,023,866✔
216
    site.time = p.time();
39,023,866✔
217
    site.wgt = 1. / weight;
39,023,866✔
218
    site.surf_id = 0;
39,023,866✔
219

220
    // Sample delayed group and angle/energy for fission reaction
221
    sample_fission_neutron(i_nuclide, rx, &site, p);
39,023,866✔
222

223
    // Reject site if it exceeds time cutoff
224
    if (site.delayed_group > 0) {
39,023,866✔
225
      double t_cutoff = settings::time_cutoff[site.particle.transport_index()];
257,138!
226
      if (site.time > t_cutoff) {
257,138!
227
        continue;
×
228
      }
229
    }
230

231
    // Set parent and progeny IDs
232
    site.parent_id = p.current_work();
39,023,866✔
233
    site.progeny_id = p.n_progeny()++;
39,023,866✔
234

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

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

249
        // Break out of loop as no more sites can be added to fission bank
250
        break;
×
251
      }
252
      // Iterated Fission Probability (IFP) method
253
      if (settings::ifp_on) {
38,809,081✔
254
        ifp(p, idx);
1,352,626✔
255
      }
256
    } else {
257
      site.wgt_born = p.wgt_born();
214,785✔
258
      site.wgt_ww_born = p.wgt_ww_born();
214,785✔
259
      site.n_split = p.n_split();
214,785✔
260
      p.local_secondary_bank().push_back(site);
214,785✔
261
      p.n_secondaries()++;
214,785✔
262
    }
263

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

269
    // Write fission particles to nuBank
270
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
39,023,866✔
271
    nu_bank_entry.wgt = site.wgt;
39,023,866✔
272
    nu_bank_entry.E = site.E;
39,023,866✔
273
    nu_bank_entry.delayed_group = site.delayed_group;
39,023,866✔
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,990,400!
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,990,400✔
286

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

295
void sample_photon_reaction(Particle& p)
34,339,422✔
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();
34,339,422✔
301
  if (p.E() < settings::energy_cutoff[photon]) {
34,339,422✔
302
    p.E() = 0.0;
55✔
303
    p.wgt() = 0.0;
55✔
304
    return;
55✔
305
  }
306

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

312
  // Calculate photon energy over electron rest mass equivalent
313
  double alpha = p.E() / MASS_ELECTRON_EV;
34,339,367✔
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;
34,339,367✔
318
  double cutoff = prn(p.current_seed()) * micro.total;
34,339,367✔
319

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

330
  // Incoherent (Compton) scattering
331
  prob += micro.incoherent;
32,672,258✔
332
  if (prob > cutoff) {
32,672,258✔
333
    double alpha_out;
24,582,633✔
334
    int i_shell;
24,582,633✔
335
    element.compton_scatter(
24,582,633✔
336
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
24,582,633✔
337

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

347
    // Create Compton electron
348
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
24,582,633✔
349
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
24,582,633✔
350
    int electron = ParticleType::electron().transport_index();
24,582,633✔
351
    if (E_electron >= settings::energy_cutoff[electron]) {
24,582,633!
352
      double mu_electron = (alpha - alpha_out * p.mu()) /
24,582,633✔
353
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
24,582,633✔
354
                                     2.0 * alpha * alpha_out * p.mu());
24,582,633✔
355
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
24,582,633✔
356
      process_charged_secondary(p, u, E_electron, ParticleType::electron());
24,582,633✔
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 && element.has_atomic_relaxation_ &&
24,425,575!
363
        i_shell >= 0 && element.subshell_map_[i_shell] >= 0) {
49,008,208!
364
      element.atomic_relaxation(element.subshell_map_[i_shell], p);
24,425,575✔
365
    }
366

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

375
  // Photoelectric effect
376
  double prob_after = prob + micro.photoelectric;
8,089,625✔
377

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

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

390
      // Check threshold of reaction
391
      if (xs_lower(i_shell) == 0)
27,649,286✔
392
        continue;
10,383,904✔
393

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

398
      if (prob > cutoff) {
17,265,382✔
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_
7,892,120✔
402
                                  ? shell.binding_energy
7,892,120!
403
                                  : element.binding_energy_[i_shell];
×
404

405
        // Determine energy of secondary electron
406
        double E_electron = p.E() - binding_energy;
7,892,120✔
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;
11,844,588✔
412
        while (true) {
11,844,588✔
413
          double r = prn(p.current_seed());
11,844,588✔
414
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
11,844,588✔
415
            double rel_vel =
7,892,120✔
416
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
7,892,120✔
417
              (E_electron + MASS_ELECTRON_EV);
7,892,120✔
418
            mu =
7,892,120✔
419
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
7,892,120✔
420
            break;
7,892,120✔
421
          }
422
        }
423

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

430
        // Process secondary electron at the photon collision site.
431
        process_charged_secondary(p, u, E_electron, ParticleType::electron());
7,892,120✔
432

433
        // Allow electrons to fill orbital and produce auger electrons
434
        // and fluorescent photons
435
        if (settings::atomic_relaxation) {
7,892,120✔
436
          element.atomic_relaxation(i_shell, p);
7,672,120✔
437
        }
438
        p.event() = TallyEvent::ABSORB;
7,892,120✔
439
        p.event_mt() = 533 + shell.index_subshell;
7,892,120✔
440
        p.wgt() = 0.0;
7,892,120✔
441
        p.E() = 0.0;
7,892,120✔
442
        return;
7,892,120✔
443
      }
444
    }
445
  }
15,784,240✔
446
  prob = prob_after;
197,505✔
447

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

456
    // Process secondary electron at the photon collision site.
457
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
197,505✔
458
    process_charged_secondary(p, u, E_electron, ParticleType::electron());
197,505✔
459

460
    // Process secondary positron at the photon collision site.
461
    u = rotate_angle(p.u(), mu_positron, nullptr, p.current_seed());
197,505✔
462
    process_charged_secondary(p, u, E_positron, ParticleType::positron());
197,505✔
463
    p.event() = TallyEvent::ABSORB;
197,505✔
464
    p.event_mt() = PAIR_PROD;
197,505✔
465
    p.wgt() = 0.0;
197,505✔
466
    p.E() = 0.0;
197,505✔
467
  }
468
}
469

470
void process_charged_secondary(
87,546,346✔
471
  Particle& p, Direction u, double E, ParticleType type)
472
{
473
  int idx = type.transport_index();
87,546,346✔
474
  if (idx == C_NONE || E < settings::energy_cutoff[idx])
87,546,346!
475
    return;
476

477
  if (settings::electron_treatment == ElectronTreatment::TTB) {
87,546,346✔
478
    thick_target_bremsstrahlung(p, type, u, E);
87,050,884✔
479
  }
480

481
  if (type == ParticleType::positron()) {
87,546,346✔
482
    Direction photon_u = isotropic_direction(p.current_seed());
197,505✔
483
    p.create_secondary(
197,505✔
484
      p.wgt(), photon_u, MASS_ELECTRON_EV, ParticleType::photon());
197,505✔
485
    p.create_secondary(
197,505✔
486
      p.wgt(), -photon_u, MASS_ELECTRON_EV, ParticleType::photon());
197,505✔
487

488
    // The annihilation photons are now emitted during the parent photon
489
    // collision. Offset the pair-production Q value in the energy balance so
490
    // heating matches the prior explicit positron slowing-down sequence.
491
    p.bank_second_E() -= 2 * MASS_ELECTRON_EV;
197,505✔
492
  }
493
}
494

495
void sample_electron_reaction(Particle& p)
110,000✔
496
{
497
  // TODO: create reaction types
498

499
  if (settings::electron_treatment == ElectronTreatment::TTB) {
110,000!
500
    thick_target_bremsstrahlung(p);
110,000✔
501
  }
502

503
  p.E() = 0.0;
110,000✔
504
  p.wgt() = 0.0;
110,000✔
505
  p.event() = TallyEvent::ABSORB;
110,000✔
506
}
110,000✔
507

UNCOV
508
void sample_positron_reaction(Particle& p)
×
509
{
510
  // TODO: create reaction types
511

UNCOV
512
  if (settings::electron_treatment == ElectronTreatment::TTB) {
×
NEW
513
    thick_target_bremsstrahlung(p);
×
514
  }
515

516
  // Sample angle isotropically
UNCOV
517
  Direction u = isotropic_direction(p.current_seed());
×
518

519
  // Create annihilation photon pair traveling in opposite directions
UNCOV
520
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon());
×
UNCOV
521
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon());
×
522

UNCOV
523
  p.E() = 0.0;
×
UNCOV
524
  p.wgt() = 0.0;
×
UNCOV
525
  p.event() = TallyEvent::ABSORB;
×
UNCOV
526
}
×
527

528
int sample_nuclide(Particle& p)
1,552,587,179✔
529
{
530
  // Sample cumulative distribution function
531
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
1,552,587,179✔
532

533
  // Get pointers to nuclide/density arrays
534
  const auto& mat {model::materials[p.material()]};
1,552,587,179✔
535
  int n = mat->nuclide_.size();
1,552,587,179✔
536

537
  double prob = 0.0;
1,552,587,179✔
538
  for (int i = 0; i < n; ++i) {
2,147,483,647!
539
    // Get atom density
540
    int i_nuclide = mat->nuclide_[i];
2,147,483,647✔
541
    double atom_density = mat->atom_density(i, p.density_mult());
2,147,483,647✔
542

543
    // Increment probability to compare to cutoff
544
    prob += atom_density * p.neutron_xs(i_nuclide).total;
2,147,483,647✔
545
    if (prob >= cutoff)
2,147,483,647✔
546
      return i_nuclide;
1,552,587,179✔
547
  }
548

549
  // If we reach here, no nuclide was sampled
550
  p.write_restart();
×
551
  throw std::runtime_error {"Did not sample any nuclide during collision."};
×
552
}
553

554
int sample_element(Particle& p)
34,339,367✔
555
{
556
  // Sample cumulative distribution function
557
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
34,339,367✔
558

559
  // Get pointers to elements, densities
560
  const auto& mat {model::materials[p.material()]};
34,339,367✔
561

562
  double prob = 0.0;
34,339,367✔
563
  for (int i = 0; i < mat->element_.size(); ++i) {
138,553,125!
564
    // Find atom density
565
    int i_element = mat->element_[i];
138,553,125✔
566
    double atom_density = mat->atom_density(i, p.density_mult());
138,553,125✔
567

568
    // Determine microscopic cross section
569
    double sigma = atom_density * p.photon_xs(i_element).total;
138,553,125✔
570

571
    // Increment probability to compare to cutoff
572
    prob += sigma;
138,553,125✔
573
    if (prob > cutoff) {
138,553,125✔
574
      // Save which nuclide particle had collision with for tally purpose
575
      p.event_nuclide() = mat->nuclide_[i];
34,339,367✔
576

577
      return i_element;
34,339,367✔
578
    }
579
  }
580

581
  // If we made it here, no element was sampled
582
  p.write_restart();
×
583
  fatal_error("Did not sample any element during collision.");
×
584
}
585

586
Reaction& sample_fission(int i_nuclide, Particle& p)
170,029,310✔
587
{
588
  // Get pointer to nuclide
589
  const auto& nuc {data::nuclides[i_nuclide]};
170,029,310✔
590

591
  // If we're in the URR, by default use the first fission reaction. We also
592
  // default to the first reaction if we know that there are no partial fission
593
  // reactions
594
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
170,029,310✔
595
    return *nuc->fission_rx_[0];
169,971,143✔
596
  }
597

598
  // Check to see if we are in a windowed multipole range.  WMP only supports
599
  // the first fission reaction.
600
  if (nuc->multipole_) {
58,167✔
601
    if (p.E() >= nuc->multipole_->E_min_ && p.E() <= nuc->multipole_->E_max_) {
2,849!
602
      return *nuc->fission_rx_[0];
1,991✔
603
    }
604
  }
605

606
  // Get grid index and interpolation factor and sample fission cdf
607
  const auto& micro = p.neutron_xs(i_nuclide);
56,176✔
608
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
56,176✔
609
  double prob = 0.0;
56,176✔
610

611
  // Loop through each partial fission reaction type
612
  for (auto& rx : nuc->fission_rx_) {
56,247!
613
    // add to cumulative probability
614
    prob += rx->xs(micro);
56,247✔
615

616
    // Create fission bank sites if fission occurs
617
    if (prob > cutoff)
56,247✔
618
      return *rx;
56,176✔
619
  }
620

621
  // If we reached here, no reaction was sampled
622
  throw std::runtime_error {
×
623
    "No fission reaction was sampled for " + nuc->name_};
×
624
}
625

626
void sample_photon_product(
2,936,868✔
627
  int i_nuclide, Particle& p, int* i_rx, int* i_product)
628
{
629
  // Get grid index and interpolation factor and sample photon production cdf
630
  const auto& micro = p.neutron_xs(i_nuclide);
2,936,868✔
631
  double cutoff = prn(p.current_seed()) * micro.photon_prod;
2,936,868✔
632
  double prob = 0.0;
2,936,868✔
633

634
  // Loop through each reaction type
635
  const auto& nuc {data::nuclides[i_nuclide]};
2,936,868✔
636
  for (int i = 0; i < nuc->reactions_.size(); ++i) {
54,189,135!
637
    // Evaluate neutron cross section
638
    const auto& rx = nuc->reactions_[i];
54,189,135✔
639
    double xs = rx->xs(micro);
54,189,135✔
640

641
    // if cross section is zero for this reaction, skip it
642
    if (xs == 0.0)
54,189,135✔
643
      continue;
33,772,475✔
644

645
    for (int j = 0; j < rx->products_.size(); ++j) {
148,910,608✔
646
      if (rx->products_[j].particle_.is_photon()) {
131,430,816✔
647
        // For fission, artificially increase the photon yield to account
648
        // for delayed photons
649
        double f = 1.0;
115,952,287✔
650
        if (settings::delayed_photon_scaling) {
115,952,287!
651
          if (is_fission(rx->mt_)) {
115,952,287✔
652
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
540,826!
653
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
540,826✔
654
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
540,826✔
655
              f = (energy_prompt + energy_delayed) / (energy_prompt);
540,826✔
656
            }
657
          }
658
        }
659

660
        // add to cumulative probability
661
        prob += f * (*rx->products_[j].yield_)(p.E()) * xs;
115,952,287✔
662

663
        *i_rx = i;
115,952,287✔
664
        *i_product = j;
115,952,287✔
665
        if (prob > cutoff)
115,952,287✔
666
          return;
667
      }
668
    }
669
  }
670
}
671

672
void absorption(Particle& p, int i_nuclide)
1,552,474,077✔
673
{
674
  if (settings::survival_biasing) {
1,552,474,077✔
675
    // Determine weight absorbed in survival biasing
676
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
41,632,481✔
677
                              p.neutron_xs(i_nuclide).total;
41,632,481✔
678

679
    // Adjust weight of particle by probability of absorption
680
    p.wgt() -= wgt_absorb;
41,632,481✔
681

682
    // Score implicit absorption estimate of keff
683
    if (settings::run_mode == RunMode::EIGENVALUE) {
41,632,481✔
684
      p.keff_tally_absorption() += wgt_absorb *
499,950✔
685
                                   p.neutron_xs(i_nuclide).nu_fission /
499,950✔
686
                                   p.neutron_xs(i_nuclide).absorption;
499,950✔
687
    }
688
  } else {
689
    // See if disappearance reaction happens
690
    if (p.neutron_xs(i_nuclide).absorption >
1,510,841,596✔
691
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
1,510,841,596✔
692
      // Score absorption estimate of keff
693
      if (settings::run_mode == RunMode::EIGENVALUE) {
34,461,250✔
694
        p.keff_tally_absorption() += p.wgt() *
24,297,964✔
695
                                     p.neutron_xs(i_nuclide).nu_fission /
24,297,964✔
696
                                     p.neutron_xs(i_nuclide).absorption;
24,297,964✔
697
      }
698

699
      p.wgt() = 0.0;
34,461,250✔
700
      p.event() = TallyEvent::ABSORB;
34,461,250✔
701
      if (!p.fission()) {
34,461,250✔
702
        p.event_mt() = N_DISAPPEAR;
22,098,389✔
703
      }
704
    }
705
  }
706
}
1,552,474,077✔
707

708
void scatter(Particle& p, int i_nuclide)
1,517,965,582✔
709
{
710
  // copy incoming direction
711
  Direction u_old {p.u()};
1,517,965,582✔
712

713
  // Get pointer to nuclide and grid index/interpolation factor
714
  const auto& nuc {data::nuclides[i_nuclide]};
1,517,965,582✔
715
  const auto& micro {p.neutron_xs(i_nuclide)};
1,517,965,582✔
716
  int i_temp = micro.index_temp;
1,517,965,582✔
717

718
  // For tallying purposes, this routine might be called directly. In that
719
  // case, we need to sample a reaction via the cutoff variable
720
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
1,517,965,582✔
721
  bool sampled = false;
1,517,965,582✔
722

723
  // Calculate elastic cross section if it wasn't precalculated
724
  if (micro.elastic == CACHE_INVALID) {
1,517,965,582✔
725
    nuc->calculate_elastic_xs(p);
1,262,143,948✔
726
  }
727

728
  double prob = micro.elastic - micro.thermal;
1,517,965,582✔
729
  if (prob > cutoff) {
1,517,965,582✔
730
    // =======================================================================
731
    // NON-S(A,B) ELASTIC SCATTERING
732

733
    // Determine temperature
734
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
1,365,810,012✔
735

736
    // Perform collision physics for elastic scattering
737
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
1,365,810,012✔
738

739
    p.event_mt() = ELASTIC;
1,365,810,012✔
740
    sampled = true;
1,365,810,012✔
741
  }
742

743
  prob = micro.elastic;
1,517,965,582✔
744
  if (prob > cutoff && !sampled) {
1,517,965,582✔
745
    // =======================================================================
746
    // S(A,B) SCATTERING
747

748
    sab_scatter(i_nuclide, micro.index_sab, p);
127,577,858✔
749

750
    p.event_mt() = ELASTIC;
127,577,858✔
751
    sampled = true;
127,577,858✔
752
  }
753

754
  if (!sampled) {
1,517,965,582✔
755
    // =======================================================================
756
    // INELASTIC SCATTERING
757

758
    int n = nuc->index_inelastic_scatter_.size();
24,577,712✔
759
    int i = 0;
24,577,712✔
760
    for (int j = 0; j < n && prob < cutoff; ++j) {
455,685,587✔
761
      i = nuc->index_inelastic_scatter_[j];
431,107,875✔
762

763
      // add to cumulative probability
764
      prob += nuc->reactions_[i]->xs(micro);
431,107,875✔
765
    }
766

767
    // Perform collision physics for inelastic scattering
768
    const auto& rx {nuc->reactions_[i]};
24,577,712✔
769
    inelastic_scatter(*nuc, *rx, p);
24,577,712✔
770
    p.event_mt() = rx->mt_;
24,577,712✔
771
  }
772

773
  // Set event component
774
  p.event() = TallyEvent::SCATTER;
1,517,965,582✔
775

776
  // Sample new outgoing angle for isotropic-in-lab scattering
777
  const auto& mat {model::materials[p.material()]};
1,517,965,582!
778
  if (!mat->p0_.empty()) {
1,517,965,582!
779
    int i_nuc_mat = mat->mat_nuclide_index_[i_nuclide];
326,370✔
780
    if (mat->p0_[i_nuc_mat]) {
326,370!
781
      // Sample isotropic-in-lab outgoing direction
782
      p.u() = isotropic_direction(p.current_seed());
326,370✔
783
      p.mu() = u_old.dot(p.u());
326,370✔
784
    }
785
  }
786
}
1,517,965,582✔
787

788
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
1,365,810,012✔
789
{
790
  // get pointer to nuclide
791
  const auto& nuc {data::nuclides[i_nuclide]};
1,365,810,012✔
792

793
  double vel = std::sqrt(p.E());
1,365,810,012✔
794
  double awr = nuc->awr_;
1,365,810,012✔
795

796
  // Neutron velocity in LAB
797
  Direction v_n = vel * p.u();
1,365,810,012✔
798

799
  // Sample velocity of target nucleus
800
  Direction v_t {};
1,365,810,012✔
801
  if (!p.neutron_xs(i_nuclide).use_ptable) {
1,365,810,012✔
802
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
1,318,162,440✔
803
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
1,318,162,440✔
804
  }
805

806
  // Velocity of center-of-mass
807
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
1,365,810,012✔
808

809
  // Transform to CM frame
810
  v_n -= v_cm;
1,365,810,012✔
811

812
  // Find speed of neutron in CM
813
  vel = v_n.norm();
1,365,810,012✔
814

815
  // Sample scattering angle, checking if angle distribution is present (assume
816
  // isotropic otherwise)
817
  double mu_cm;
1,365,810,012✔
818
  auto& d = rx.products_[0].distribution_[0];
1,365,810,012!
819
  auto d_ = dynamic_cast<UncorrelatedAngleEnergy*>(d.get());
1,365,810,012!
820
  if (!d_->angle().empty()) {
1,365,810,012!
821
    mu_cm = d_->angle().sample(p.E(), p.current_seed());
1,365,810,012✔
822
  } else {
823
    mu_cm = uniform_distribution(-1., 1., p.current_seed());
×
824
  }
825

826
  // Determine direction cosines in CM
827
  Direction u_cm = v_n / vel;
1,365,810,012✔
828

829
  // Rotate neutron velocity vector to new angle -- note that the speed of the
830
  // neutron in CM does not change in elastic scattering. However, the speed
831
  // will change when we convert back to LAB
832
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
1,365,810,012✔
833

834
  // Transform back to LAB frame
835
  v_n += v_cm;
1,365,810,012✔
836

837
  p.E() = v_n.dot(v_n);
1,365,810,012✔
838
  vel = std::sqrt(p.E());
1,365,810,012✔
839

840
  // compute cosine of scattering angle in LAB frame by taking dot product of
841
  // neutron's pre- and post-collision angle
842
  p.mu() = p.u().dot(v_n) / vel;
1,365,810,012✔
843

844
  // Set energy and direction of particle in LAB frame
845
  p.u() = v_n / vel;
1,365,810,012!
846

847
  // Because of floating-point roundoff, it may be possible for mu_lab to be
848
  // outside of the range [-1,1). In these cases, we just set mu_lab to exactly
849
  // -1 or 1
850
  if (std::abs(p.mu()) > 1.0)
1,365,810,012!
851
    p.mu() = std::copysign(1.0, p.mu());
×
852
}
1,365,810,012✔
853

854
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
127,577,858✔
855
{
856
  // Determine temperature index
857
  const auto& micro {p.neutron_xs(i_nuclide)};
127,577,858✔
858
  int i_temp = micro.index_temp_sab;
127,577,858✔
859

860
  // Sample energy and angle
861
  double E_out;
127,577,858✔
862
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
127,577,858✔
863
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
127,577,858✔
864

865
  // Set energy to outgoing, change direction of particle
866
  p.E() = E_out;
127,577,858✔
867
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
127,577,858✔
868
}
127,577,858✔
869

870
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
1,318,162,440✔
871
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
872
{
873
  // check if nuclide is a resonant scatterer
874
  ResScatMethod sampling_method;
1,318,162,440✔
875
  if (nuc.resonant_) {
1,318,162,440✔
876

877
    // sampling method to use
878
    sampling_method = settings::res_scat_method;
84,557✔
879

880
    // upper resonance scattering energy bound (target is at rest above this E)
881
    if (E > settings::res_scat_energy_max) {
84,557✔
882
      return {};
40,755✔
883

884
      // lower resonance scattering energy bound (should be no resonances below)
885
    } else if (E < settings::res_scat_energy_min) {
43,802✔
886
      sampling_method = ResScatMethod::cxs;
887
    }
888

889
    // otherwise, use free gas model
890
  } else {
891
    if (E >= settings::free_gas_threshold * kT && nuc.awr_ > 1.0) {
1,318,077,883✔
892
      return {};
489,542,190✔
893
    } else {
894
      sampling_method = ResScatMethod::cxs;
895
    }
896
  }
897

898
  // use appropriate target velocity sampling method
899
  switch (sampling_method) {
18,810!
900
  case ResScatMethod::cxs:
828,560,685✔
901

902
    // sample target velocity with the constant cross section (cxs) approx.
903
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
828,560,685✔
904

905
  case ResScatMethod::dbrc:
18,810✔
906
  case ResScatMethod::rvs: {
18,810✔
907
    double E_red = std::sqrt(nuc.awr_ * E / kT);
18,810✔
908
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
37,620!
909
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
18,810✔
910

911
    // find lower and upper energy bound indices
912
    // lower index
913
    int i_E_low;
18,810✔
914
    if (E_low < nuc.energy_0K_.front()) {
18,810!
915
      i_E_low = 0;
916
    } else if (E_low > nuc.energy_0K_.back()) {
18,810!
917
      i_E_low = nuc.energy_0K_.size() - 2;
×
918
    } else {
919
      i_E_low =
18,810✔
920
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
18,810✔
921
    }
922

923
    // upper index
924
    int i_E_up;
18,810✔
925
    if (E_up < nuc.energy_0K_.front()) {
18,810!
926
      i_E_up = 0;
927
    } else if (E_up > nuc.energy_0K_.back()) {
18,810!
928
      i_E_up = nuc.energy_0K_.size() - 2;
×
929
    } else {
930
      i_E_up =
18,810✔
931
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_up);
18,810✔
932
    }
933

934
    if (i_E_up == i_E_low) {
18,810✔
935
      // Handle degenerate case -- if the upper/lower bounds occur for the same
936
      // index, then using cxs is probably a good approximation
937
      return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
18,810✔
938
    }
939

940
    if (sampling_method == ResScatMethod::dbrc) {
15,532!
941
      // interpolate xs since we're not exactly at the energy indices
942
      double xs_low = nuc.elastic_0K_[i_E_low];
×
943
      double m = (nuc.elastic_0K_[i_E_low + 1] - xs_low) /
×
944
                 (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
×
945
      xs_low += m * (E_low - nuc.energy_0K_[i_E_low]);
×
946
      double xs_up = nuc.elastic_0K_[i_E_up];
×
947
      m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) /
×
948
          (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
×
949
      xs_up += m * (E_up - nuc.energy_0K_[i_E_up]);
×
950

951
      // get max 0K xs value over range of practical relative energies
952
      double xs_max = *std::max_element(
×
953
        &nuc.elastic_0K_[i_E_low + 1], &nuc.elastic_0K_[i_E_up + 1]);
×
954
      xs_max = std::max({xs_low, xs_max, xs_up});
×
955

956
      while (true) {
×
957
        double E_rel;
×
958
        Direction v_target;
×
959
        while (true) {
×
960
          // sample target velocity with the constant cross section (cxs)
961
          // approx.
962
          v_target = sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
×
963
          Direction v_rel = v_neut - v_target;
×
964
          E_rel = v_rel.dot(v_rel);
×
965
          if (E_rel < E_up)
×
966
            break;
967
        }
968

969
        // perform Doppler broadening rejection correction (dbrc)
970
        double xs_0K = nuc.elastic_xs_0K(E_rel);
×
971
        double R = xs_0K / xs_max;
×
972
        if (prn(seed) < R)
×
973
          return v_target;
×
974
      }
975

976
    } else if (sampling_method == ResScatMethod::rvs) {
15,532✔
977
      // interpolate xs CDF since we're not exactly at the energy indices
978
      // cdf value at lower bound attainable energy
979
      double cdf_low = 0.0;
15,532✔
980
      if (E_low > nuc.energy_0K_.front()) {
15,532!
981
        double m = (nuc.xs_cdf_[i_E_low + 1] - nuc.xs_cdf_[i_E_low]) /
15,532✔
982
                   (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
15,532✔
983
        cdf_low = nuc.xs_cdf_[i_E_low] + m * (E_low - nuc.energy_0K_[i_E_low]);
15,532✔
984
      }
985

986
      // cdf value at upper bound attainable energy
987
      double m = (nuc.xs_cdf_[i_E_up + 1] - nuc.xs_cdf_[i_E_up]) /
15,532✔
988
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
15,532✔
989
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
15,532✔
990

991
      while (true) {
325,908✔
992
        // directly sample Maxwellian
993
        double E_t = -kT * std::log(prn(seed));
170,720✔
994

995
        // sample a relative energy using the xs cdf
996
        double cdf_rel = cdf_low + prn(seed) * (cdf_up - cdf_low);
170,720✔
997
        int i_E_rel = lower_bound_index(nuc.xs_cdf_.begin() + i_E_low,
170,720✔
998
          nuc.xs_cdf_.begin() + i_E_up + 2, cdf_rel);
170,720✔
999
        double E_rel = nuc.energy_0K_[i_E_low + i_E_rel];
170,720✔
1000
        double m = (nuc.xs_cdf_[i_E_low + i_E_rel + 1] -
170,720✔
1001
                     nuc.xs_cdf_[i_E_low + i_E_rel]) /
170,720✔
1002
                   (nuc.energy_0K_[i_E_low + i_E_rel + 1] -
170,720✔
1003
                     nuc.energy_0K_[i_E_low + i_E_rel]);
170,720✔
1004
        E_rel += (cdf_rel - nuc.xs_cdf_[i_E_low + i_E_rel]) / m;
170,720✔
1005

1006
        // perform rejection sampling on cosine between
1007
        // neutron and target velocities
1008
        double mu = (E_t + nuc.awr_ * (E - E_rel)) /
170,720✔
1009
                    (2.0 * std::sqrt(nuc.awr_ * E * E_t));
170,720✔
1010

1011
        if (std::abs(mu) < 1.0) {
170,720✔
1012
          // set and accept target velocity
1013
          E_t /= nuc.awr_;
15,532✔
1014
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
15,532✔
1015
        }
1016
      }
155,188✔
1017
    }
1018
  } // case RVS, DBRC
1019
  } // switch (sampling_method)
1020

1021
  UNREACHABLE();
×
1022
}
1023

1024
Direction sample_cxs_target_velocity(
828,563,963✔
1025
  double awr, double E, Direction u, double kT, uint64_t* seed)
1026
{
1027
  double beta_vn = std::sqrt(awr * E / kT);
828,563,963✔
1028
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
828,563,963✔
1029

1030
  double beta_vt_sq;
1,012,565,959✔
1031
  double mu;
1,012,565,959✔
1032
  while (true) {
1,012,565,959✔
1033
    // Sample two random numbers
1034
    double r1 = prn(seed);
1,012,565,959✔
1035
    double r2 = prn(seed);
1,012,565,959✔
1036

1037
    if (prn(seed) < alpha) {
1,012,565,959✔
1038
      // With probability alpha, we sample the distribution p(y) =
1039
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
1040
      // Carlo sampler
1041

1042
      beta_vt_sq = -std::log(r1 * r2);
292,851,490✔
1043

1044
    } else {
1045
      // With probability 1-alpha, we sample the distribution p(y) = y^2 *
1046
      // e^(-y^2). This can be done with sampling scheme C61 from the Monte
1047
      // Carlo sampler
1048

1049
      double c = std::cos(PI / 2.0 * prn(seed));
719,714,469✔
1050
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
719,714,469✔
1051
    }
1052

1053
    // Determine beta * vt
1054
    double beta_vt = std::sqrt(beta_vt_sq);
1,012,565,959✔
1055

1056
    // Sample cosine of angle between neutron and target velocity
1057
    mu = uniform_distribution(-1., 1., seed);
1,012,565,959✔
1058

1059
    // Determine rejection probability
1060
    double accept_prob =
1,012,565,959✔
1061
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
1,012,565,959✔
1062
      (beta_vn + beta_vt);
1,012,565,959✔
1063

1064
    // Perform rejection sampling on vt and mu
1065
    if (prn(seed) < accept_prob)
1,012,565,959✔
1066
      break;
1067
  }
1068

1069
  // Determine speed of target nucleus
1070
  double vt = std::sqrt(beta_vt_sq * kT / awr);
828,563,963✔
1071

1072
  // Determine velocity vector of target nucleus based on neutron's velocity
1073
  // and the sampled angle between them
1074
  return vt * rotate_angle(u, mu, nullptr, seed);
828,563,963✔
1075
}
1076

1077
void sample_fission_neutron(
39,023,866✔
1078
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1079
{
1080
  // Get attributes of particle
1081
  double E_in = p.E();
39,023,866✔
1082
  uint64_t* seed = p.current_seed();
39,023,866✔
1083

1084
  // Determine total nu, delayed nu, and delayed neutron fraction
1085
  const auto& nuc {data::nuclides[i_nuclide]};
39,023,866✔
1086
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
39,023,866✔
1087
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
39,023,866✔
1088
  double beta = nu_d / nu_t;
39,023,866✔
1089

1090
  if (prn(seed) < beta) {
39,023,866✔
1091
    // ====================================================================
1092
    // DELAYED NEUTRON SAMPLED
1093

1094
    // sampled delayed precursor group
1095
    double xi = prn(seed) * nu_d;
257,138✔
1096
    double prob = 0.0;
257,138✔
1097
    int group;
257,138✔
1098
    for (group = 1; group < nuc->n_precursor_; ++group) {
958,034✔
1099
      // determine delayed neutron precursor yield for group j
1100
      double yield = (*rx.products_[group].yield_)(E_in);
939,583✔
1101

1102
      // Check if this group is sampled
1103
      prob += yield;
939,583✔
1104
      if (xi < prob)
939,583✔
1105
        break;
1106
    }
1107

1108
    // if the sum of the probabilities is slightly less than one and the
1109
    // random number is greater, j will be greater than nuc %
1110
    // n_precursor -- check for this condition
1111
    group = std::min(group, nuc->n_precursor_);
257,138!
1112

1113
    // set the delayed group for the particle born from fission
1114
    site->delayed_group = group;
257,138✔
1115

1116
    // Sample time of emission based on decay constant of precursor
1117
    double decay_rate = rx.products_[site->delayed_group].decay_rate_;
257,138✔
1118
    site->time -= std::log(prn(p.current_seed())) / decay_rate;
257,138✔
1119

1120
  } else {
1121
    // ====================================================================
1122
    // PROMPT NEUTRON SAMPLED
1123

1124
    // set the delayed group for the particle born from fission to 0
1125
    site->delayed_group = 0;
38,766,728✔
1126
  }
1127

1128
  // sample from prompt neutron energy distribution
1129
  int n_sample = 0;
1130
  double mu;
39,023,866✔
1131
  while (true) {
39,023,866✔
1132
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
39,023,866✔
1133

1134
    // resample if energy is greater than maximum neutron energy
1135
    int neutron = ParticleType::neutron().transport_index();
39,023,866✔
1136
    if (site->E < data::energy_max[neutron])
39,023,866!
1137
      break;
1138

1139
    // check for large number of resamples
1140
    ++n_sample;
×
1141
    if (n_sample == MAX_SAMPLE) {
×
1142
      // particle_write_restart(p)
1143
      fatal_error("Resampled energy distribution maximum number of times "
×
1144
                  "for nuclide " +
×
1145
                  nuc->name_);
×
1146
    }
1147
  }
1148

1149
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1150
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
39,023,866✔
1151
}
39,023,866✔
1152

1153
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
24,577,712✔
1154
{
1155
  // copy energy of neutron
1156
  double E_in = p.E();
24,577,712✔
1157

1158
  // sample outgoing energy and scattering cosine
1159
  double E;
24,577,712✔
1160
  double mu;
24,577,712✔
1161
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
24,577,712✔
1162

1163
  // if scattering system is in center-of-mass, transfer cosine of scattering
1164
  // angle and outgoing energy from CM to LAB
1165
  if (rx.scatter_in_cm_) {
24,577,712✔
1166
    double E_cm = E;
24,483,842✔
1167

1168
    // determine outgoing energy in lab
1169
    double A = nuc.awr_;
24,483,842✔
1170
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
24,483,842✔
1171
                 ((A + 1.0) * (A + 1.0));
24,483,842✔
1172

1173
    // determine outgoing angle in lab
1174
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
24,483,842✔
1175
  }
1176

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

1183
  // Set outgoing energy and scattering angle
1184
  p.E() = E;
24,577,712✔
1185
  p.mu() = mu;
24,577,712✔
1186

1187
  // change direction of particle
1188
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
24,577,712✔
1189

1190
  // evaluate yield
1191
  double yield = (*rx.products_[0].yield_)(E_in);
24,577,712✔
1192
  if (std::floor(yield) == yield && yield > 0) {
24,577,712!
1193
    // If yield is integral, create exactly that many secondary particles
1194
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
24,712,189✔
1195
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron());
134,531✔
1196
    }
1197
  } else {
1198
    // Otherwise, change weight of particle based on yield
1199
    p.wgt() *= yield;
54✔
1200
  }
1201
}
24,577,712✔
1202

1203
void sample_secondary_photons(Particle& p, int i_nuclide)
77,865,359✔
1204
{
1205
  // Sample the number of photons produced
1206
  double y_t =
77,865,359✔
1207
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
77,865,359✔
1208
  double photon_wgt = p.wgt();
77,865,359✔
1209
  int y = 1;
77,865,359✔
1210

1211
  if (settings::use_decay_photons) {
77,865,359✔
1212
    // For decay photons, sample a single photon and modify the weight
1213
    if (y_t <= 0.0)
72,006✔
1214
      return;
1215
    photon_wgt *= y_t;
54,725✔
1216
  } else {
1217
    // For prompt photons, sample an integral number of photons with weight
1218
    // equal to the neutron's weight
1219
    y = static_cast<int>(y_t);
77,793,353✔
1220
    if (prn(p.current_seed()) <= y_t - y)
77,793,353✔
1221
      ++y;
2,118,952✔
1222
  }
1223

1224
  // Sample each secondary photon
1225
  for (int i = 0; i < y; ++i) {
80,784,946✔
1226
    // Sample the reaction and product
1227
    int i_rx;
2,936,868✔
1228
    int i_product;
2,936,868✔
1229
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
2,936,868✔
1230

1231
    // Sample the outgoing energy and angle
1232
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
2,936,868✔
1233
    double E;
2,936,868✔
1234
    double mu;
2,936,868✔
1235
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
2,936,868✔
1236

1237
    // Sample the new direction
1238
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
2,936,868✔
1239

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

1250
    // Create the secondary photon
1251
    bool created_photon = p.create_secondary(wgt, u, E, ParticleType::photon());
2,936,868✔
1252

1253
    // Pre-add photon energy to pht_storage so pht_secondary_particles()
1254
    // subtraction results in net zero
1255
    if (created_photon && !model::active_pulse_height_tallies.empty()) {
2,936,868✔
1256
      auto it = std::find(model::pulse_height_cells.begin(),
528✔
1257
        model::pulse_height_cells.end(), p.lowest_coord().cell());
528!
1258
      if (it != model::pulse_height_cells.end()) {
528!
1259
        int index = std::distance(model::pulse_height_cells.begin(), it);
528✔
1260
        p.pht_storage()[index] += E;
528✔
1261
      }
1262
    }
1263

1264
    // Tag secondary particle with parent nuclide
1265
    if (created_photon && settings::use_decay_photons) {
2,936,868✔
1266
      p.local_secondary_bank().back().parent_nuclide =
52,844✔
1267
        rx->products_[i_product].parent_nuclide_;
52,844✔
1268
    }
1269
  }
1270
}
1271

1272
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc