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

openmc-dev / openmc / 13134187828

04 Feb 2025 11:13AM UTC coverage: 84.945% (+0.08%) from 84.869%
13134187828

Pull #3252

github

web-flow
Merge 6f397fdd5 into 59c398be8
Pull Request #3252: Adding vtkhdf option to write vtk data

80 of 92 new or added lines in 1 file covered. (86.96%)

1267 existing lines in 48 files now uncovered.

50221 of 59122 relevant lines covered (84.94%)

35221818.06 hits per line

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

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

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

29
#include <fmt/core.h>
30

31
#include <algorithm> // for max, min, max_element
32
#include <cmath>     // for sqrt, exp, log, abs, copysign
33
#include <xtensor/xview.hpp>
34

35
namespace openmc {
36

37
//==============================================================================
38
// Non-member functions
39
//==============================================================================
40

41
void collision(Particle& p)
820,067,322✔
42
{
43
  // Add to collision counter for particle
44
  ++(p.n_collision());
820,067,322✔
45

46
  // Sample reaction for the material the particle is in
47
  switch (p.type()) {
820,067,322✔
48
  case ParticleType::neutron:
752,526,138✔
49
    sample_neutron_reaction(p);
752,526,138✔
50
    break;
752,526,138✔
51
  case ParticleType::photon:
14,556,100✔
52
    sample_photon_reaction(p);
14,556,100✔
53
    break;
14,556,100✔
54
  case ParticleType::electron:
52,892,120✔
55
    sample_electron_reaction(p);
52,892,120✔
56
    break;
52,892,120✔
57
  case ParticleType::positron:
92,964✔
58
    sample_positron_reaction(p);
92,964✔
59
    break;
92,964✔
60
  }
61

62
  if (settings::weight_window_checkpoint_collision)
820,067,322✔
63
    apply_weight_windows(p);
820,067,322✔
64

65
  // Kill particle if energy falls below cutoff
66
  int type = static_cast<int>(p.type());
820,067,322✔
67
  if (p.E() < settings::energy_cutoff[type]) {
820,067,322✔
68
    p.wgt() = 0.0;
5,123,228✔
69
  }
70

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

91
void sample_neutron_reaction(Particle& p)
752,526,138✔
92
{
93
  // Sample a nuclide within the material
94
  int i_nuclide = sample_nuclide(p);
752,526,138✔
95

96
  // Save which nuclide particle had collision with
97
  p.event_nuclide() = i_nuclide;
752,526,138✔
98

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

104
  const auto& nuc {data::nuclides[i_nuclide]};
752,526,138✔
105

106
  if (nuc->fissionable_ && p.neutron_xs(i_nuclide).fission > 0.0) {
752,526,138✔
107
    auto& rx = sample_fission(i_nuclide, p);
122,164,553✔
108
    if (settings::run_mode == RunMode::EIGENVALUE) {
122,164,553✔
109
      create_fission_sites(p, i_nuclide, rx);
121,561,306✔
110
    } else if (settings::run_mode == RunMode::FIXED_SOURCE &&
603,247✔
111
               settings::create_fission_neutrons) {
112
      create_fission_sites(p, i_nuclide, rx);
588,079✔
113

114
      // Make sure particle population doesn't grow out of control for
115
      // subcritical multiplication problems.
116
      if (p.secondary_bank().size() >= 10000) {
588,079✔
117
        fatal_error(
×
118
          "The secondary particle bank appears to be growing without "
119
          "bound. You are likely running a subcritical multiplication problem "
120
          "with k-effective close to or greater than one.");
121
      }
122
    }
123
  }
124

125
  // Create secondary photons
126
  if (settings::photon_transport) {
752,526,138✔
127
    sample_secondary_photons(p, i_nuclide);
9,848,112✔
128
  }
129

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

133
  if (p.neutron_xs(i_nuclide).absorption > 0.0) {
752,526,138✔
134
    absorption(p, i_nuclide);
752,521,834✔
135
  }
136
  if (!p.alive())
752,526,138✔
137
    return;
19,501,616✔
138

139
  // Sample a scattering reaction and determine the secondary energy of the
140
  // exiting neutron
141
  const auto& ncrystal_mat = model::materials[p.material()]->ncrystal_mat();
733,024,522✔
142
  if (ncrystal_mat && p.E() < NCRYSTAL_MAX_ENERGY) {
733,024,522✔
143
    ncrystal_mat.scatter(p);
14,438✔
144
  } else {
145
    scatter(p, i_nuclide);
733,010,084✔
146
  }
147

148
  // Advance URR seed stream 'N' times after energy changes
149
  if (p.E() != p.E_last()) {
733,024,522✔
150
    advance_prn_seed(data::nuclides.size(), &p.seeds(STREAM_URR_PTABLE));
732,811,850✔
151
  }
152

153
  // Play russian roulette if survival biasing is turned on
154
  if (settings::survival_biasing) {
733,024,522✔
155
    if (p.wgt() < settings::weight_cutoff) {
557,892✔
156
      russian_roulette(p, settings::weight_survive);
63,984✔
157
    }
158
  }
159
}
160

161
void create_fission_sites(Particle& p, int i_nuclide, const Reaction& rx)
122,149,385✔
162
{
163
  // If uniform fission source weighting is turned on, we increase or decrease
164
  // the expected number of fission sites produced
165
  double weight = settings::ufs_on ? ufs_get_weight(p) : 1.0;
122,149,385✔
166

167
  // Determine the expected number of neutrons produced
168
  double nu_t = p.wgt() / simulation::keff * weight *
122,149,385✔
169
                p.neutron_xs(i_nuclide).nu_fission /
122,149,385✔
170
                p.neutron_xs(i_nuclide).total;
122,149,385✔
171

172
  // Sample the number of neutrons produced
173
  int nu = static_cast<int>(nu_t);
122,149,385✔
174
  if (prn(p.current_seed()) <= (nu_t - nu))
122,149,385✔
175
    ++nu;
17,707,416✔
176

177
  // If no neutrons were produced then don't continue
178
  if (nu == 0)
122,149,385✔
179
    return;
100,170,225✔
180

181
  // Initialize the counter of delayed neutrons encountered for each delayed
182
  // group.
183
  double nu_d[MAX_DELAYED_GROUPS] = {0.};
21,979,160✔
184

185
  // Clear out particle's nu fission bank
186
  p.nu_bank().clear();
21,979,160✔
187

188
  p.fission() = true;
21,979,160✔
189

190
  // Determine whether to place fission sites into the shared fission bank
191
  // or the secondary particle bank.
192
  bool use_fission_bank = (settings::run_mode == RunMode::EIGENVALUE);
21,979,160✔
193

194
  // Counter for the number of fission sites successfully stored to the shared
195
  // fission bank or the secondary particle bank
196
  int n_sites_stored;
197

198
  for (n_sites_stored = 0; n_sites_stored < nu; n_sites_stored++) {
49,568,554✔
199
    // Initialize fission site object with particle data
200
    SourceSite site;
27,589,394✔
201
    site.r = p.r();
27,589,394✔
202
    site.particle = ParticleType::neutron;
27,589,394✔
203
    site.time = p.time();
27,589,394✔
204
    site.wgt = 1. / weight;
27,589,394✔
205
    site.parent_id = p.id();
27,589,394✔
206
    site.progeny_id = p.n_progeny()++;
27,589,394✔
207
    site.surf_id = 0;
27,589,394✔
208

209
    // Sample delayed group and angle/energy for fission reaction
210
    sample_fission_neutron(i_nuclide, rx, &site, p);
27,589,394✔
211

212
    // Store fission site in bank
213
    if (use_fission_bank) {
27,589,394✔
214
      int64_t idx = simulation::fission_bank.thread_safe_append(site);
27,386,041✔
215
      if (idx == -1) {
27,386,041✔
216
        warning(
×
217
          "The shared fission bank is full. Additional fission sites created "
218
          "in this generation will not be banked. Results may be "
219
          "non-deterministic.");
220

221
        // Decrement number of particle progeny as storage was unsuccessful.
222
        // This step is needed so that the sum of all progeny is equal to the
223
        // size of the shared fission bank.
224
        p.n_progeny()--;
×
225

226
        // Break out of loop as no more sites can be added to fission bank
227
        break;
×
228
      }
229
    } else {
230
      p.secondary_bank().push_back(site);
203,353✔
231
    }
232

233
    // Set the delayed group on the particle as well
234
    p.delayed_group() = site.delayed_group;
27,589,394✔
235

236
    // Increment the number of neutrons born delayed
237
    if (p.delayed_group() > 0) {
27,589,394✔
238
      nu_d[p.delayed_group() - 1]++;
174,937✔
239
    }
240

241
    // Write fission particles to nuBank
242
    NuBank& nu_bank_entry = p.nu_bank().emplace_back();
27,589,394✔
243
    nu_bank_entry.wgt = site.wgt;
27,589,394✔
244
    nu_bank_entry.E = site.E;
27,589,394✔
245
    nu_bank_entry.delayed_group = site.delayed_group;
27,589,394✔
246
  }
247

248
  // If shared fission bank was full, and no fissions could be added,
249
  // set the particle fission flag to false.
250
  if (n_sites_stored == 0) {
21,979,160✔
UNCOV
251
    p.fission() = false;
×
252
    return;
×
253
  }
254

255
  // Set nu to the number of fission sites successfully stored. If the fission
256
  // bank was not found to be full then these values are already equivalent.
257
  nu = n_sites_stored;
21,979,160✔
258

259
  // Store the total weight banked for analog fission tallies
260
  p.n_bank() = nu;
21,979,160✔
261
  p.wgt_bank() = nu / weight;
21,979,160✔
262
  for (size_t d = 0; d < MAX_DELAYED_GROUPS; d++) {
197,812,440✔
263
    p.n_delayed_bank(d) = nu_d[d];
175,833,280✔
264
  }
265
}
266

267
void sample_photon_reaction(Particle& p)
14,556,100✔
268
{
269
  // Kill photon if below energy cutoff -- an extra check is made here because
270
  // photons with energy below the cutoff may have been produced by neutrons
271
  // reactions or atomic relaxation
272
  int photon = static_cast<int>(ParticleType::photon);
14,556,100✔
273
  if (p.E() < settings::energy_cutoff[photon]) {
14,556,100✔
UNCOV
274
    p.E() = 0.0;
×
275
    p.wgt() = 0.0;
×
276
    return;
×
277
  }
278

279
  // Sample element within material
280
  int i_element = sample_element(p);
14,556,100✔
281
  const auto& micro {p.photon_xs(i_element)};
14,556,100✔
282
  const auto& element {*data::elements[i_element]};
14,556,100✔
283

284
  // Calculate photon energy over electron rest mass equivalent
285
  double alpha = p.E() / MASS_ELECTRON_EV;
14,556,100✔
286

287
  // For tallying purposes, this routine might be called directly. In that
288
  // case, we need to sample a reaction via the cutoff variable
289
  double prob = 0.0;
14,556,100✔
290
  double cutoff = prn(p.current_seed()) * micro.total;
14,556,100✔
291

292
  // Coherent (Rayleigh) scattering
293
  prob += micro.coherent;
14,556,100✔
294
  if (prob > cutoff) {
14,556,100✔
295
    p.mu() = element.rayleigh_scatter(alpha, p.current_seed());
772,080✔
296
    p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
772,080✔
297
    p.event() = TallyEvent::SCATTER;
772,080✔
298
    p.event_mt() = COHERENT;
772,080✔
299
    return;
772,080✔
300
  }
301

302
  // Incoherent (Compton) scattering
303
  prob += micro.incoherent;
13,784,020✔
304
  if (prob > cutoff) {
13,784,020✔
305
    double alpha_out;
306
    int i_shell;
307
    element.compton_scatter(
17,345,416✔
308
      alpha, true, &alpha_out, &p.mu(), &i_shell, p.current_seed());
8,672,708✔
309

310
    // Determine binding energy of shell. The binding energy is 0.0 if
311
    // doppler broadening is not used.
312
    double e_b;
313
    if (i_shell == -1) {
8,672,708✔
UNCOV
314
      e_b = 0.0;
×
315
    } else {
316
      e_b = element.binding_energy_[i_shell];
8,672,708✔
317
    }
318

319
    // Create Compton electron
320
    double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
8,672,708✔
321
    double E_electron = (alpha - alpha_out) * MASS_ELECTRON_EV - e_b;
8,672,708✔
322
    int electron = static_cast<int>(ParticleType::electron);
8,672,708✔
323
    if (E_electron >= settings::energy_cutoff[electron]) {
8,672,708✔
324
      double mu_electron = (alpha - alpha_out * p.mu()) /
8,594,020✔
325
                           std::sqrt(alpha * alpha + alpha_out * alpha_out -
17,188,040✔
326
                                     2.0 * alpha * alpha_out * p.mu());
8,594,020✔
327
      Direction u = rotate_angle(p.u(), mu_electron, &phi, p.current_seed());
8,594,020✔
328
      p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron);
8,594,020✔
329
    }
330

331
    // TODO: Compton subshell data does not match atomic relaxation data
332
    // Allow electrons to fill orbital and produce auger electrons
333
    // and fluorescent photons
334
    if (i_shell >= 0) {
8,672,708✔
335
      element.atomic_relaxation(i_shell, p);
8,672,708✔
336
    }
337

338
    phi += PI;
8,672,708✔
339
    p.E() = alpha_out * MASS_ELECTRON_EV;
8,672,708✔
340
    p.u() = rotate_angle(p.u(), p.mu(), &phi, p.current_seed());
8,672,708✔
341
    p.event() = TallyEvent::SCATTER;
8,672,708✔
342
    p.event_mt() = INCOHERENT;
8,672,708✔
343
    return;
8,672,708✔
344
  }
345

346
  // Photoelectric effect
347
  double prob_after = prob + micro.photoelectric;
5,111,312✔
348

349
  if (prob_after > cutoff) {
5,111,312✔
350
    // Get grid index, interpolation factor, and bounding subshell
351
    // cross sections
352
    int i_grid = micro.index_grid;
5,018,348✔
353
    double f = micro.interp_factor;
5,018,348✔
354
    const auto& xs_lower = xt::row(element.cross_sections_, i_grid);
5,018,348✔
355
    const auto& xs_upper = xt::row(element.cross_sections_, i_grid + 1);
5,018,348✔
356

357
    for (int i_shell = 0; i_shell < element.shells_.size(); ++i_shell) {
25,735,976✔
358
      const auto& shell {element.shells_[i_shell]};
25,735,976✔
359

360
      // Check threshold of reaction
361
      if (xs_lower(i_shell) == 0)
25,735,976✔
362
        continue;
11,113,200✔
363

364
      //  Evaluation subshell photoionization cross section
365
      prob += std::exp(
14,622,776✔
366
        xs_lower(i_shell) + f * (xs_upper(i_shell) - xs_lower(i_shell)));
14,622,776✔
367

368
      if (prob > cutoff) {
14,622,776✔
369
        // Determine binding energy based on whether atomic relaxation data is
370
        // present (if not, use value from Compton profile data)
371
        double binding_energy = element.has_atomic_relaxation_
5,018,348✔
372
                                  ? shell.binding_energy
5,018,348✔
UNCOV
373
                                  : element.binding_energy_[i_shell];
×
374

375
        // Determine energy of secondary electron
376
        double E_electron = p.E() - binding_energy;
5,018,348✔
377

378
        // Sample mu using non-relativistic Sauter distribution.
379
        // See Eqns 3.19 and 3.20 in "Implementing a photon physics
380
        // model in Serpent 2" by Toni Kaltiaisenaho
381
        double mu;
382
        while (true) {
383
          double r = prn(p.current_seed());
7,538,876✔
384
          if (4.0 * (1.0 - r) * r >= prn(p.current_seed())) {
7,538,876✔
385
            double rel_vel =
386
              std::sqrt(E_electron * (E_electron + 2.0 * MASS_ELECTRON_EV)) /
5,018,348✔
387
              (E_electron + MASS_ELECTRON_EV);
5,018,348✔
388
            mu =
5,018,348✔
389
              (2.0 * r + rel_vel - 1.0) / (2.0 * rel_vel * r - rel_vel + 1.0);
5,018,348✔
390
            break;
5,018,348✔
391
          }
392
        }
2,520,528✔
393

394
        double phi = uniform_distribution(0., 2.0 * PI, p.current_seed());
5,018,348✔
395
        Direction u;
5,018,348✔
396
        u.x = mu;
5,018,348✔
397
        u.y = std::sqrt(1.0 - mu * mu) * std::cos(phi);
5,018,348✔
398
        u.z = std::sqrt(1.0 - mu * mu) * std::sin(phi);
5,018,348✔
399

400
        // Create secondary electron
401
        p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron);
5,018,348✔
402

403
        // Allow electrons to fill orbital and produce auger electrons
404
        // and fluorescent photons
405
        element.atomic_relaxation(i_shell, p);
5,018,348✔
406
        p.event() = TallyEvent::ABSORB;
5,018,348✔
407
        p.event_mt() = 533 + shell.index_subshell;
5,018,348✔
408
        p.wgt() = 0.0;
5,018,348✔
409
        p.E() = 0.0;
5,018,348✔
410
        return;
5,018,348✔
411
      }
412
    }
413
  }
10,036,696✔
414
  prob = prob_after;
92,964✔
415

416
  // Pair production
417
  prob += micro.pair_production;
92,964✔
418
  if (prob > cutoff) {
92,964✔
419
    double E_electron, E_positron;
420
    double mu_electron, mu_positron;
421
    element.pair_production(alpha, &E_electron, &E_positron, &mu_electron,
92,964✔
422
      &mu_positron, p.current_seed());
423

424
    // Create secondary electron
425
    Direction u = rotate_angle(p.u(), mu_electron, nullptr, p.current_seed());
92,964✔
426
    p.create_secondary(p.wgt(), u, E_electron, ParticleType::electron);
92,964✔
427

428
    // Create secondary positron
429
    u = rotate_angle(p.u(), mu_positron, nullptr, p.current_seed());
92,964✔
430
    p.create_secondary(p.wgt(), u, E_positron, ParticleType::positron);
92,964✔
431

432
    p.event() = TallyEvent::ABSORB;
92,964✔
433
    p.event_mt() = PAIR_PROD;
92,964✔
434
    p.wgt() = 0.0;
92,964✔
435
    p.E() = 0.0;
92,964✔
436
  }
437
}
438

439
void sample_electron_reaction(Particle& p)
52,892,120✔
440
{
441
  // TODO: create reaction types
442

443
  if (settings::electron_treatment == ElectronTreatment::TTB) {
52,892,120✔
444
    double E_lost;
445
    thick_target_bremsstrahlung(p, &E_lost);
52,892,120✔
446
  }
447

448
  p.E() = 0.0;
52,892,120✔
449
  p.wgt() = 0.0;
52,892,120✔
450
  p.event() = TallyEvent::ABSORB;
52,892,120✔
451
}
52,892,120✔
452

453
void sample_positron_reaction(Particle& p)
92,964✔
454
{
455
  // TODO: create reaction types
456

457
  if (settings::electron_treatment == ElectronTreatment::TTB) {
92,964✔
458
    double E_lost;
459
    thick_target_bremsstrahlung(p, &E_lost);
92,964✔
460
  }
461

462
  // Sample angle isotropically
463
  Direction u = isotropic_direction(p.current_seed());
92,964✔
464

465
  // Create annihilation photon pair traveling in opposite directions
466
  p.create_secondary(p.wgt(), u, MASS_ELECTRON_EV, ParticleType::photon);
92,964✔
467
  p.create_secondary(p.wgt(), -u, MASS_ELECTRON_EV, ParticleType::photon);
92,964✔
468

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

474
int sample_nuclide(Particle& p)
752,526,138✔
475
{
476
  // Sample cumulative distribution function
477
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
752,526,138✔
478

479
  // Get pointers to nuclide/density arrays
480
  const auto& mat {model::materials[p.material()]};
752,526,138✔
481
  int n = mat->nuclide_.size();
752,526,138✔
482

483
  double prob = 0.0;
752,526,138✔
484
  for (int i = 0; i < n; ++i) {
1,709,409,831✔
485
    // Get atom density
486
    int i_nuclide = mat->nuclide_[i];
1,709,409,831✔
487
    double atom_density = mat->atom_density_[i];
1,709,409,831✔
488

489
    // Increment probability to compare to cutoff
490
    prob += atom_density * p.neutron_xs(i_nuclide).total;
1,709,409,831✔
491
    if (prob >= cutoff)
1,709,409,831✔
492
      return i_nuclide;
752,526,138✔
493
  }
494

495
  // If we reach here, no nuclide was sampled
UNCOV
496
  p.write_restart();
×
497
  throw std::runtime_error {"Did not sample any nuclide during collision."};
×
498
}
499

500
int sample_element(Particle& p)
14,556,100✔
501
{
502
  // Sample cumulative distribution function
503
  double cutoff = prn(p.current_seed()) * p.macro_xs().total;
14,556,100✔
504

505
  // Get pointers to elements, densities
506
  const auto& mat {model::materials[p.material()]};
14,556,100✔
507

508
  double prob = 0.0;
14,556,100✔
509
  for (int i = 0; i < mat->element_.size(); ++i) {
37,475,088✔
510
    // Find atom density
511
    int i_element = mat->element_[i];
37,475,088✔
512
    double atom_density = mat->atom_density_[i];
37,475,088✔
513

514
    // Determine microscopic cross section
515
    double sigma = atom_density * p.photon_xs(i_element).total;
37,475,088✔
516

517
    // Increment probability to compare to cutoff
518
    prob += sigma;
37,475,088✔
519
    if (prob > cutoff) {
37,475,088✔
520
      // Save which nuclide particle had collision with for tally purpose
521
      p.event_nuclide() = mat->nuclide_[i];
14,556,100✔
522

523
      return i_element;
14,556,100✔
524
    }
525
  }
526

527
  // If we made it here, no element was sampled
UNCOV
528
  p.write_restart();
×
529
  fatal_error("Did not sample any element during collision.");
×
530
}
531

532
Reaction& sample_fission(int i_nuclide, Particle& p)
122,164,553✔
533
{
534
  // Get pointer to nuclide
535
  const auto& nuc {data::nuclides[i_nuclide]};
122,164,553✔
536

537
  // If we're in the URR, by default use the first fission reaction. We also
538
  // default to the first reaction if we know that there are no partial fission
539
  // reactions
540
  if (p.neutron_xs(i_nuclide).use_ptable || !nuc->has_partial_fission_) {
122,164,553✔
541
    return *nuc->fission_rx_[0];
122,137,132✔
542
  }
543

544
  // Check to see if we are in a windowed multipole range.  WMP only supports
545
  // the first fission reaction.
546
  if (nuc->multipole_) {
27,421✔
UNCOV
547
    if (p.E() >= nuc->multipole_->E_min_ && p.E() <= nuc->multipole_->E_max_) {
×
548
      return *nuc->fission_rx_[0];
×
549
    }
550
  }
551

552
  // Get grid index and interpolation factor and sample fission cdf
553
  const auto& micro = p.neutron_xs(i_nuclide);
27,421✔
554
  double cutoff = prn(p.current_seed()) * p.neutron_xs(i_nuclide).fission;
27,421✔
555
  double prob = 0.0;
27,421✔
556

557
  // Loop through each partial fission reaction type
558
  for (auto& rx : nuc->fission_rx_) {
27,435✔
559
    // add to cumulative probability
560
    prob += rx->xs(micro);
27,435✔
561

562
    // Create fission bank sites if fission occurs
563
    if (prob > cutoff)
27,435✔
564
      return *rx;
27,421✔
565
  }
566

567
  // If we reached here, no reaction was sampled
UNCOV
568
  throw std::runtime_error {
×
569
    "No fission reaction was sampled for " + nuc->name_};
×
570
}
571

572
void sample_photon_product(
1,403,340✔
573
  int i_nuclide, Particle& p, int* i_rx, int* i_product)
574
{
575
  // Get grid index and interpolation factor and sample photon production cdf
576
  const auto& micro = p.neutron_xs(i_nuclide);
1,403,340✔
577
  double cutoff = prn(p.current_seed()) * micro.photon_prod;
1,403,340✔
578
  double prob = 0.0;
1,403,340✔
579

580
  // Loop through each reaction type
581
  const auto& nuc {data::nuclides[i_nuclide]};
1,403,340✔
582
  for (int i = 0; i < nuc->reactions_.size(); ++i) {
23,211,156✔
583
    // Evaluate neutron cross section
584
    const auto& rx = nuc->reactions_[i];
23,211,156✔
585
    double xs = rx->xs(micro);
23,211,156✔
586

587
    // if cross section is zero for this reaction, skip it
588
    if (xs == 0.0)
23,211,156✔
589
      continue;
7,180,140✔
590

591
    for (int j = 0; j < rx->products_.size(); ++j) {
76,049,580✔
592
      if (rx->products_[j].particle_ == ParticleType::photon) {
61,421,904✔
593
        // For fission, artificially increase the photon yield to account
594
        // for delayed photons
595
        double f = 1.0;
47,915,244✔
596
        if (settings::delayed_photon_scaling) {
47,915,244✔
597
          if (is_fission(rx->mt_)) {
47,915,244✔
598
            if (nuc->prompt_photons_ && nuc->delayed_photons_) {
586,632✔
599
              double energy_prompt = (*nuc->prompt_photons_)(p.E());
586,632✔
600
              double energy_delayed = (*nuc->delayed_photons_)(p.E());
586,632✔
601
              f = (energy_prompt + energy_delayed) / (energy_prompt);
586,632✔
602
            }
603
          }
604
        }
605

606
        // add to cumulative probability
607
        prob += f * (*rx->products_[j].yield_)(p.E()) * xs;
47,915,244✔
608

609
        *i_rx = i;
47,915,244✔
610
        *i_product = j;
47,915,244✔
611
        if (prob > cutoff)
47,915,244✔
612
          return;
1,403,340✔
613
      }
614
    }
615
  }
616
}
617

618
void absorption(Particle& p, int i_nuclide)
752,521,834✔
619
{
620
  if (settings::survival_biasing) {
752,521,834✔
621
    // Determine weight absorbed in survival biasing
622
    const double wgt_absorb = p.wgt() * p.neutron_xs(i_nuclide).absorption /
557,892✔
623
                              p.neutron_xs(i_nuclide).total;
557,892✔
624

625
    // Adjust weight of particle by probability of absorption
626
    p.wgt() -= wgt_absorb;
557,892✔
627

628
    // Score implicit absorption estimate of keff
629
    if (settings::run_mode == RunMode::EIGENVALUE) {
557,892✔
630
      p.keff_tally_absorption() += wgt_absorb *
557,892✔
631
                                   p.neutron_xs(i_nuclide).nu_fission /
557,892✔
632
                                   p.neutron_xs(i_nuclide).absorption;
557,892✔
633
    }
634
  } else {
635
    // See if disappearance reaction happens
636
    if (p.neutron_xs(i_nuclide).absorption >
751,963,942✔
637
        prn(p.current_seed()) * p.neutron_xs(i_nuclide).total) {
751,963,942✔
638
      // Score absorption estimate of keff
639
      if (settings::run_mode == RunMode::EIGENVALUE) {
19,501,616✔
640
        p.keff_tally_absorption() += p.wgt() *
34,252,052✔
641
                                     p.neutron_xs(i_nuclide).nu_fission /
17,126,026✔
642
                                     p.neutron_xs(i_nuclide).absorption;
17,126,026✔
643
      }
644

645
      p.wgt() = 0.0;
19,501,616✔
646
      p.event() = TallyEvent::ABSORB;
19,501,616✔
647
      p.event_mt() = N_DISAPPEAR;
19,501,616✔
648
    }
649
  }
650
}
752,521,834✔
651

652
void scatter(Particle& p, int i_nuclide)
733,010,084✔
653
{
654
  // copy incoming direction
655
  Direction u_old {p.u()};
733,010,084✔
656

657
  // Get pointer to nuclide and grid index/interpolation factor
658
  const auto& nuc {data::nuclides[i_nuclide]};
733,010,084✔
659
  const auto& micro {p.neutron_xs(i_nuclide)};
733,010,084✔
660
  int i_temp = micro.index_temp;
733,010,084✔
661

662
  // For tallying purposes, this routine might be called directly. In that
663
  // case, we need to sample a reaction via the cutoff variable
664
  double cutoff = prn(p.current_seed()) * (micro.total - micro.absorption);
733,010,084✔
665
  bool sampled = false;
733,010,084✔
666

667
  // Calculate elastic cross section if it wasn't precalculated
668
  if (micro.elastic == CACHE_INVALID) {
733,010,084✔
669
    nuc->calculate_elastic_xs(p);
610,504,573✔
670
  }
671

672
  double prob = micro.elastic - micro.thermal;
733,010,084✔
673
  if (prob > cutoff) {
733,010,084✔
674
    // =======================================================================
675
    // NON-S(A,B) ELASTIC SCATTERING
676

677
    // Determine temperature
678
    double kT = nuc->multipole_ ? p.sqrtkT() * p.sqrtkT() : nuc->kTs_[i_temp];
637,872,384✔
679

680
    // Perform collision physics for elastic scattering
681
    elastic_scatter(i_nuclide, *nuc->reactions_[0], kT, p);
637,872,384✔
682

683
    p.event_mt() = ELASTIC;
637,872,384✔
684
    sampled = true;
637,872,384✔
685
  }
686

687
  prob = micro.elastic;
733,010,084✔
688
  if (prob > cutoff && !sampled) {
733,010,084✔
689
    // =======================================================================
690
    // S(A,B) SCATTERING
691

692
    sab_scatter(i_nuclide, micro.index_sab, p);
78,170,576✔
693

694
    p.event_mt() = ELASTIC;
78,170,576✔
695
    sampled = true;
78,170,576✔
696
  }
697

698
  if (!sampled) {
733,010,084✔
699
    // =======================================================================
700
    // INELASTIC SCATTERING
701

702
    int n = nuc->index_inelastic_scatter_.size();
16,967,124✔
703
    int i = 0;
16,967,124✔
704
    for (int j = 0; j < n && prob < cutoff; ++j) {
291,514,388✔
705
      i = nuc->index_inelastic_scatter_[j];
274,547,264✔
706

707
      // add to cumulative probability
708
      prob += nuc->reactions_[i]->xs(micro);
274,547,264✔
709
    }
710

711
    // Perform collision physics for inelastic scattering
712
    const auto& rx {nuc->reactions_[i]};
16,967,124✔
713
    inelastic_scatter(*nuc, *rx, p);
16,967,124✔
714
    p.event_mt() = rx->mt_;
16,967,124✔
715
  }
716

717
  // Set event component
718
  p.event() = TallyEvent::SCATTER;
733,010,084✔
719

720
  // Sample new outgoing angle for isotropic-in-lab scattering
721
  const auto& mat {model::materials[p.material()]};
733,010,084✔
722
  if (!mat->p0_.empty()) {
733,010,084✔
723
    int i_nuc_mat = mat->mat_nuclide_index_[i_nuclide];
339,852✔
724
    if (mat->p0_[i_nuc_mat]) {
339,852✔
725
      // Sample isotropic-in-lab outgoing direction
726
      p.u() = isotropic_direction(p.current_seed());
339,852✔
727
      p.mu() = u_old.dot(p.u());
339,852✔
728
    }
729
  }
730
}
733,010,084✔
731

732
void elastic_scatter(int i_nuclide, const Reaction& rx, double kT, Particle& p)
637,872,384✔
733
{
734
  // get pointer to nuclide
735
  const auto& nuc {data::nuclides[i_nuclide]};
637,872,384✔
736

737
  double vel = std::sqrt(p.E());
637,872,384✔
738
  double awr = nuc->awr_;
637,872,384✔
739

740
  // Neutron velocity in LAB
741
  Direction v_n = vel * p.u();
637,872,384✔
742

743
  // Sample velocity of target nucleus
744
  Direction v_t {};
637,872,384✔
745
  if (!p.neutron_xs(i_nuclide).use_ptable) {
637,872,384✔
746
    v_t = sample_target_velocity(*nuc, p.E(), p.u(), v_n,
1,222,088,716✔
747
      p.neutron_xs(i_nuclide).elastic, kT, p.current_seed());
611,044,358✔
748
  }
749

750
  // Velocity of center-of-mass
751
  Direction v_cm = (v_n + awr * v_t) / (awr + 1.0);
637,872,384✔
752

753
  // Transform to CM frame
754
  v_n -= v_cm;
637,872,384✔
755

756
  // Find speed of neutron in CM
757
  vel = v_n.norm();
637,872,384✔
758

759
  // Sample scattering angle, checking if angle distribution is present (assume
760
  // isotropic otherwise)
761
  double mu_cm;
762
  auto& d = rx.products_[0].distribution_[0];
637,872,384✔
763
  auto d_ = dynamic_cast<UncorrelatedAngleEnergy*>(d.get());
637,872,384✔
764
  if (!d_->angle().empty()) {
637,872,384✔
765
    mu_cm = d_->angle().sample(p.E(), p.current_seed());
637,872,384✔
766
  } else {
UNCOV
767
    mu_cm = uniform_distribution(-1., 1., p.current_seed());
×
768
  }
769

770
  // Determine direction cosines in CM
771
  Direction u_cm = v_n / vel;
637,872,384✔
772

773
  // Rotate neutron velocity vector to new angle -- note that the speed of the
774
  // neutron in CM does not change in elastic scattering. However, the speed
775
  // will change when we convert back to LAB
776
  v_n = vel * rotate_angle(u_cm, mu_cm, nullptr, p.current_seed());
637,872,384✔
777

778
  // Transform back to LAB frame
779
  v_n += v_cm;
637,872,384✔
780

781
  p.E() = v_n.dot(v_n);
637,872,384✔
782
  vel = std::sqrt(p.E());
637,872,384✔
783

784
  // compute cosine of scattering angle in LAB frame by taking dot product of
785
  // neutron's pre- and post-collision angle
786
  p.mu() = p.u().dot(v_n) / vel;
637,872,384✔
787

788
  // Set energy and direction of particle in LAB frame
789
  p.u() = v_n / vel;
637,872,384✔
790

791
  // Because of floating-point roundoff, it may be possible for mu_lab to be
792
  // outside of the range [-1,1). In these cases, we just set mu_lab to exactly
793
  // -1 or 1
794
  if (std::abs(p.mu()) > 1.0)
637,872,384✔
UNCOV
795
    p.mu() = std::copysign(1.0, p.mu());
×
796
}
637,872,384✔
797

798
void sab_scatter(int i_nuclide, int i_sab, Particle& p)
78,170,576✔
799
{
800
  // Determine temperature index
801
  const auto& micro {p.neutron_xs(i_nuclide)};
78,170,576✔
802
  int i_temp = micro.index_temp_sab;
78,170,576✔
803

804
  // Sample energy and angle
805
  double E_out;
806
  data::thermal_scatt[i_sab]->data_[i_temp].sample(
156,341,152✔
807
    micro, p.E(), &E_out, &p.mu(), p.current_seed());
78,170,576✔
808

809
  // Set energy to outgoing, change direction of particle
810
  p.E() = E_out;
78,170,576✔
811
  p.u() = rotate_angle(p.u(), p.mu(), nullptr, p.current_seed());
78,170,576✔
812
}
78,170,576✔
813

814
Direction sample_target_velocity(const Nuclide& nuc, double E, Direction u,
611,044,358✔
815
  Direction v_neut, double xs_eff, double kT, uint64_t* seed)
816
{
817
  // check if nuclide is a resonant scatterer
818
  ResScatMethod sampling_method;
819
  if (nuc.resonant_) {
611,044,358✔
820

821
    // sampling method to use
822
    sampling_method = settings::res_scat_method;
90,600✔
823

824
    // upper resonance scattering energy bound (target is at rest above this E)
825
    if (E > settings::res_scat_energy_max) {
90,600✔
826
      return {};
44,196✔
827

828
      // lower resonance scattering energy bound (should be no resonances below)
829
    } else if (E < settings::res_scat_energy_min) {
46,404✔
830
      sampling_method = ResScatMethod::cxs;
26,052✔
831
    }
832

833
    // otherwise, use free gas model
834
  } else {
835
    if (E >= FREE_GAS_THRESHOLD * kT && nuc.awr_ > 1.0) {
610,953,758✔
836
      return {};
257,134,305✔
837
    } else {
838
      sampling_method = ResScatMethod::cxs;
353,819,453✔
839
    }
840
  }
841

842
  // use appropriate target velocity sampling method
843
  switch (sampling_method) {
353,865,857✔
844
  case ResScatMethod::cxs:
353,845,505✔
845

846
    // sample target velocity with the constant cross section (cxs) approx.
847
    return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
353,845,505✔
848

849
  case ResScatMethod::dbrc:
20,352✔
850
  case ResScatMethod::rvs: {
851
    double E_red = std::sqrt(nuc.awr_ * E / kT);
20,352✔
852
    double E_low = std::pow(std::max(0.0, E_red - 4.0), 2) * kT / nuc.awr_;
20,352✔
853
    double E_up = (E_red + 4.0) * (E_red + 4.0) * kT / nuc.awr_;
20,352✔
854

855
    // find lower and upper energy bound indices
856
    // lower index
857
    int i_E_low;
858
    if (E_low < nuc.energy_0K_.front()) {
20,352✔
UNCOV
859
      i_E_low = 0;
×
860
    } else if (E_low > nuc.energy_0K_.back()) {
20,352✔
UNCOV
861
      i_E_low = nuc.energy_0K_.size() - 2;
×
862
    } else {
863
      i_E_low =
20,352✔
864
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_low);
20,352✔
865
    }
866

867
    // upper index
868
    int i_E_up;
869
    if (E_up < nuc.energy_0K_.front()) {
20,352✔
UNCOV
870
      i_E_up = 0;
×
871
    } else if (E_up > nuc.energy_0K_.back()) {
20,352✔
UNCOV
872
      i_E_up = nuc.energy_0K_.size() - 2;
×
873
    } else {
874
      i_E_up =
20,352✔
875
        lower_bound_index(nuc.energy_0K_.begin(), nuc.energy_0K_.end(), E_up);
20,352✔
876
    }
877

878
    if (i_E_up == i_E_low) {
20,352✔
879
      // Handle degenerate case -- if the upper/lower bounds occur for the same
880
      // index, then using cxs is probably a good approximation
881
      return sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
20,352✔
882
    }
883

884
    if (sampling_method == ResScatMethod::dbrc) {
16,860✔
885
      // interpolate xs since we're not exactly at the energy indices
UNCOV
886
      double xs_low = nuc.elastic_0K_[i_E_low];
×
887
      double m = (nuc.elastic_0K_[i_E_low + 1] - xs_low) /
×
888
                 (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
×
889
      xs_low += m * (E_low - nuc.energy_0K_[i_E_low]);
×
890
      double xs_up = nuc.elastic_0K_[i_E_up];
×
891
      m = (nuc.elastic_0K_[i_E_up + 1] - xs_up) /
×
892
          (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
×
893
      xs_up += m * (E_up - nuc.energy_0K_[i_E_up]);
×
894

895
      // get max 0K xs value over range of practical relative energies
UNCOV
896
      double xs_max = *std::max_element(
×
897
        &nuc.elastic_0K_[i_E_low + 1], &nuc.elastic_0K_[i_E_up + 1]);
×
898
      xs_max = std::max({xs_low, xs_max, xs_up});
×
899

900
      while (true) {
901
        double E_rel;
UNCOV
902
        Direction v_target;
×
903
        while (true) {
904
          // sample target velocity with the constant cross section (cxs)
905
          // approx.
UNCOV
906
          v_target = sample_cxs_target_velocity(nuc.awr_, E, u, kT, seed);
×
907
          Direction v_rel = v_neut - v_target;
×
908
          E_rel = v_rel.dot(v_rel);
×
909
          if (E_rel < E_up)
×
910
            break;
×
911
        }
912

913
        // perform Doppler broadening rejection correction (dbrc)
UNCOV
914
        double xs_0K = nuc.elastic_xs_0K(E_rel);
×
915
        double R = xs_0K / xs_max;
×
916
        if (prn(seed) < R)
×
917
          return v_target;
×
918
      }
919

920
    } else if (sampling_method == ResScatMethod::rvs) {
16,860✔
921
      // interpolate xs CDF since we're not exactly at the energy indices
922
      // cdf value at lower bound attainable energy
923
      double cdf_low = 0.0;
16,860✔
924
      if (E_low > nuc.energy_0K_.front()) {
16,860✔
925
        double m = (nuc.xs_cdf_[i_E_low + 1] - nuc.xs_cdf_[i_E_low]) /
16,860✔
926
                   (nuc.energy_0K_[i_E_low + 1] - nuc.energy_0K_[i_E_low]);
16,860✔
927
        cdf_low = nuc.xs_cdf_[i_E_low] + m * (E_low - nuc.energy_0K_[i_E_low]);
16,860✔
928
      }
929

930
      // cdf value at upper bound attainable energy
931
      double m = (nuc.xs_cdf_[i_E_up + 1] - nuc.xs_cdf_[i_E_up]) /
16,860✔
932
                 (nuc.energy_0K_[i_E_up + 1] - nuc.energy_0K_[i_E_up]);
16,860✔
933
      double cdf_up = nuc.xs_cdf_[i_E_up] + m * (E_up - nuc.energy_0K_[i_E_up]);
16,860✔
934

935
      while (true) {
936
        // directly sample Maxwellian
937
        double E_t = -kT * std::log(prn(seed));
177,324✔
938

939
        // sample a relative energy using the xs cdf
940
        double cdf_rel = cdf_low + prn(seed) * (cdf_up - cdf_low);
177,324✔
941
        int i_E_rel = lower_bound_index(nuc.xs_cdf_.begin() + i_E_low,
177,324✔
942
          nuc.xs_cdf_.begin() + i_E_up + 2, cdf_rel);
177,324✔
943
        double E_rel = nuc.energy_0K_[i_E_low + i_E_rel];
177,324✔
944
        double m = (nuc.xs_cdf_[i_E_low + i_E_rel + 1] -
177,324✔
945
                     nuc.xs_cdf_[i_E_low + i_E_rel]) /
177,324✔
946
                   (nuc.energy_0K_[i_E_low + i_E_rel + 1] -
177,324✔
947
                     nuc.energy_0K_[i_E_low + i_E_rel]);
177,324✔
948
        E_rel += (cdf_rel - nuc.xs_cdf_[i_E_low + i_E_rel]) / m;
177,324✔
949

950
        // perform rejection sampling on cosine between
951
        // neutron and target velocities
952
        double mu = (E_t + nuc.awr_ * (E - E_rel)) /
177,324✔
953
                    (2.0 * std::sqrt(nuc.awr_ * E * E_t));
177,324✔
954

955
        if (std::abs(mu) < 1.0) {
177,324✔
956
          // set and accept target velocity
957
          E_t /= nuc.awr_;
16,860✔
958
          return std::sqrt(E_t) * rotate_angle(u, mu, nullptr, seed);
16,860✔
959
        }
960
      }
160,464✔
961
    }
962
  } // case RVS, DBRC
963
  } // switch (sampling_method)
964

UNCOV
965
  UNREACHABLE();
×
966
}
967

968
Direction sample_cxs_target_velocity(
353,848,997✔
969
  double awr, double E, Direction u, double kT, uint64_t* seed)
970
{
971
  double beta_vn = std::sqrt(awr * E / kT);
353,848,997✔
972
  double alpha = 1.0 / (1.0 + std::sqrt(PI) * beta_vn / 2.0);
353,848,997✔
973

974
  double beta_vt_sq;
975
  double mu;
976
  while (true) {
977
    // Sample two random numbers
978
    double r1 = prn(seed);
419,665,068✔
979
    double r2 = prn(seed);
419,665,068✔
980

981
    if (prn(seed) < alpha) {
419,665,068✔
982
      // With probability alpha, we sample the distribution p(y) =
983
      // y*e^(-y). This can be done with sampling scheme C45 from the Monte
984
      // Carlo sampler
985

986
      beta_vt_sq = -std::log(r1 * r2);
107,018,770✔
987

988
    } else {
989
      // With probability 1-alpha, we sample the distribution p(y) = y^2 *
990
      // e^(-y^2). This can be done with sampling scheme C61 from the Monte
991
      // Carlo sampler
992

993
      double c = std::cos(PI / 2.0 * prn(seed));
312,646,298✔
994
      beta_vt_sq = -std::log(r1) - std::log(r2) * c * c;
312,646,298✔
995
    }
996

997
    // Determine beta * vt
998
    double beta_vt = std::sqrt(beta_vt_sq);
419,665,068✔
999

1000
    // Sample cosine of angle between neutron and target velocity
1001
    mu = uniform_distribution(-1., 1., seed);
419,665,068✔
1002

1003
    // Determine rejection probability
1004
    double accept_prob =
1005
      std::sqrt(beta_vn * beta_vn + beta_vt_sq - 2 * beta_vn * beta_vt * mu) /
419,665,068✔
1006
      (beta_vn + beta_vt);
419,665,068✔
1007

1008
    // Perform rejection sampling on vt and mu
1009
    if (prn(seed) < accept_prob)
419,665,068✔
1010
      break;
353,848,997✔
1011
  }
65,816,071✔
1012

1013
  // Determine speed of target nucleus
1014
  double vt = std::sqrt(beta_vt_sq * kT / awr);
353,848,997✔
1015

1016
  // Determine velocity vector of target nucleus based on neutron's velocity
1017
  // and the sampled angle between them
1018
  return vt * rotate_angle(u, mu, nullptr, seed);
353,848,997✔
1019
}
1020

1021
void sample_fission_neutron(
27,589,394✔
1022
  int i_nuclide, const Reaction& rx, SourceSite* site, Particle& p)
1023
{
1024
  // Get attributes of particle
1025
  double E_in = p.E();
27,589,394✔
1026
  uint64_t* seed = p.current_seed();
27,589,394✔
1027

1028
  // Determine total nu, delayed nu, and delayed neutron fraction
1029
  const auto& nuc {data::nuclides[i_nuclide]};
27,589,394✔
1030
  double nu_t = nuc->nu(E_in, Nuclide::EmissionMode::total);
27,589,394✔
1031
  double nu_d = nuc->nu(E_in, Nuclide::EmissionMode::delayed);
27,589,394✔
1032
  double beta = nu_d / nu_t;
27,589,394✔
1033

1034
  if (prn(seed) < beta) {
27,589,394✔
1035
    // ====================================================================
1036
    // DELAYED NEUTRON SAMPLED
1037

1038
    // sampled delayed precursor group
1039
    double xi = prn(seed) * nu_d;
174,937✔
1040
    double prob = 0.0;
174,937✔
1041
    int group;
1042
    for (group = 1; group < nuc->n_precursor_; ++group) {
656,429✔
1043
      // determine delayed neutron precursor yield for group j
1044
      double yield = (*rx.products_[group].yield_)(E_in);
642,719✔
1045

1046
      // Check if this group is sampled
1047
      prob += yield;
642,719✔
1048
      if (xi < prob)
642,719✔
1049
        break;
161,227✔
1050
    }
1051

1052
    // if the sum of the probabilities is slightly less than one and the
1053
    // random number is greater, j will be greater than nuc %
1054
    // n_precursor -- check for this condition
1055
    group = std::min(group, nuc->n_precursor_);
174,937✔
1056

1057
    // set the delayed group for the particle born from fission
1058
    site->delayed_group = group;
174,937✔
1059

1060
  } else {
1061
    // ====================================================================
1062
    // PROMPT NEUTRON SAMPLED
1063

1064
    // set the delayed group for the particle born from fission to 0
1065
    site->delayed_group = 0;
27,414,457✔
1066
  }
1067

1068
  // sample from prompt neutron energy distribution
1069
  int n_sample = 0;
27,589,394✔
1070
  double mu;
1071
  while (true) {
1072
    rx.products_[site->delayed_group].sample(E_in, site->E, mu, seed);
27,589,394✔
1073

1074
    // resample if energy is greater than maximum neutron energy
1075
    constexpr int neutron = static_cast<int>(ParticleType::neutron);
27,589,394✔
1076
    if (site->E < data::energy_max[neutron])
27,589,394✔
1077
      break;
27,589,394✔
1078

1079
    // check for large number of resamples
UNCOV
1080
    ++n_sample;
×
1081
    if (n_sample == MAX_SAMPLE) {
×
1082
      // particle_write_restart(p)
UNCOV
1083
      fatal_error("Resampled energy distribution maximum number of times "
×
1084
                  "for nuclide " +
×
1085
                  nuc->name_);
×
1086
    }
1087
  }
1088

1089
  // Sample azimuthal angle uniformly in [0, 2*pi) and assign angle
1090
  site->u = rotate_angle(p.u(), mu, nullptr, seed);
27,589,394✔
1091
}
27,589,394✔
1092

1093
void inelastic_scatter(const Nuclide& nuc, const Reaction& rx, Particle& p)
16,967,124✔
1094
{
1095
  // copy energy of neutron
1096
  double E_in = p.E();
16,967,124✔
1097

1098
  // sample outgoing energy and scattering cosine
1099
  double E;
1100
  double mu;
1101
  rx.products_[0].sample(E_in, E, mu, p.current_seed());
16,967,124✔
1102

1103
  // if scattering system is in center-of-mass, transfer cosine of scattering
1104
  // angle and outgoing energy from CM to LAB
1105
  if (rx.scatter_in_cm_) {
16,967,124✔
1106
    double E_cm = E;
16,930,128✔
1107

1108
    // determine outgoing energy in lab
1109
    double A = nuc.awr_;
16,930,128✔
1110
    E = E_cm + (E_in + 2.0 * mu * (A + 1.0) * std::sqrt(E_in * E_cm)) /
16,930,128✔
1111
                 ((A + 1.0) * (A + 1.0));
16,930,128✔
1112

1113
    // determine outgoing angle in lab
1114
    mu = mu * std::sqrt(E_cm / E) + 1.0 / (A + 1.0) * std::sqrt(E_in / E);
16,930,128✔
1115
  }
1116

1117
  // Because of floating-point roundoff, it may be possible for mu to be
1118
  // outside of the range [-1,1). In these cases, we just set mu to exactly -1
1119
  // or 1
1120
  if (std::abs(mu) > 1.0)
16,967,124✔
UNCOV
1121
    mu = std::copysign(1.0, mu);
×
1122

1123
  // Set outgoing energy and scattering angle
1124
  p.E() = E;
16,967,124✔
1125
  p.mu() = mu;
16,967,124✔
1126

1127
  // change direction of particle
1128
  p.u() = rotate_angle(p.u(), mu, nullptr, p.current_seed());
16,967,124✔
1129

1130
  // evaluate yield
1131
  double yield = (*rx.products_[0].yield_)(E_in);
16,967,124✔
1132
  if (std::floor(yield) == yield && yield > 0) {
16,967,124✔
1133
    // If yield is integral, create exactly that many secondary particles
1134
    for (int i = 0; i < static_cast<int>(std::round(yield)) - 1; ++i) {
17,032,403✔
1135
      p.create_secondary(p.wgt(), p.u(), p.E(), ParticleType::neutron);
65,357✔
1136
    }
1137
  } else {
16,967,046✔
1138
    // Otherwise, change weight of particle based on yield
1139
    p.wgt() *= yield;
78✔
1140
  }
1141
}
16,967,124✔
1142

1143
void sample_secondary_photons(Particle& p, int i_nuclide)
9,848,112✔
1144
{
1145
  // Sample the number of photons produced
1146
  double y_t =
1147
    p.neutron_xs(i_nuclide).photon_prod / p.neutron_xs(i_nuclide).total;
9,848,112✔
1148
  int y = static_cast<int>(y_t);
9,848,112✔
1149
  if (prn(p.current_seed()) <= y_t - y)
9,848,112✔
1150
    ++y;
630,816✔
1151

1152
  // Sample each secondary photon
1153
  for (int i = 0; i < y; ++i) {
11,251,452✔
1154
    // Sample the reaction and product
1155
    int i_rx;
1156
    int i_product;
1157
    sample_photon_product(i_nuclide, p, &i_rx, &i_product);
1,403,340✔
1158

1159
    // Sample the outgoing energy and angle
1160
    auto& rx = data::nuclides[i_nuclide]->reactions_[i_rx];
1,403,340✔
1161
    double E;
1162
    double mu;
1163
    rx->products_[i_product].sample(p.E(), E, mu, p.current_seed());
1,403,340✔
1164

1165
    // Sample the new direction
1166
    Direction u = rotate_angle(p.u(), mu, nullptr, p.current_seed());
1,403,340✔
1167

1168
    // In a k-eigenvalue simulation, it's necessary to provide higher weight to
1169
    // secondary photons from non-fission reactions to properly balance energy
1170
    // release and deposition. See D. P. Griesheimer, S. J. Douglass, and M. H.
1171
    // Stedry, "Self-consistent energy normalization for quasistatic reactor
1172
    // calculations", Proc. PHYSOR, Cambridge, UK, Mar 29-Apr 2, 2020.
1173
    double wgt;
1174
    if (settings::run_mode == RunMode::EIGENVALUE && !is_fission(rx->mt_)) {
1,403,340✔
1175
      wgt = simulation::keff * p.wgt();
378,540✔
1176
    } else {
1177
      wgt = p.wgt();
1,024,800✔
1178
    }
1179

1180
    // Create the secondary photon
1181
    p.create_secondary(wgt, u, E, ParticleType::photon);
1,403,340✔
1182
  }
1183
}
9,848,112✔
1184

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

© 2025 Coveralls, Inc