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

openmc-dev / openmc / 43314235397

12 Nov 2026 09:50PM UTC coverage: 82.188% (+0.7%) from 81.44%
43314235397

Pull #3877

github

web-flow
Merge 85d867c33 into 013cfbb99
Pull Request #3877: Add VTKHDF output support for all structured mesh types

19751 of 27809 branches covered (71.02%)

Branch coverage included in aggregate %.

84 of 85 new or added lines in 1 file covered. (98.82%)

2101 existing lines in 43 files now uncovered.

62828 of 72667 relevant lines covered (86.46%)

39889466.57 hits per line

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

85.46
/src/photon.cpp
1
#include "openmc/photon.h"
2

3
#include "openmc/array.h"
4
#include "openmc/bremsstrahlung.h"
5
#include "openmc/constants.h"
6
#include "openmc/distribution_multi.h"
7
#include "openmc/hdf5_interface.h"
8
#include "openmc/message_passing.h"
9
#include "openmc/nuclide.h"
10
#include "openmc/particle.h"
11
#include "openmc/physics.h"
12
#include "openmc/random_dist.h"
13
#include "openmc/random_lcg.h"
14
#include "openmc/search.h"
15
#include "openmc/settings.h"
16

17
#include "openmc/tensor.h"
18

19
#include <cmath>
20
#include <fmt/core.h>
21
#include <limits>
22
#include <stdexcept>
23
#include <tuple> // for tie
24

25
namespace openmc {
26

27
constexpr int PhotonInteraction::MAX_STACK_SIZE;
28

29
//==============================================================================
30
// Global variables
31
//==============================================================================
32

33
namespace data {
34

35
tensor::Tensor<double> compton_profile_pz;
36

37
std::unordered_map<std::string, int> element_map;
38
vector<unique_ptr<PhotonInteraction>> elements;
39

40
} // namespace data
41

42
//==============================================================================
43
// PhotonInteraction implementation
44
//==============================================================================
45

46
PhotonInteraction::PhotonInteraction(hid_t group)
1,069 ✔
47
{
48
  // Set index of element in global vector
49
  index_ = data::elements.size();
1,069 ✔
50

51
  // Get name of nuclide from group, removing leading '/'
52
  name_ = object_name(group).substr(1);
1,069 ✔
53
  data::element_map[name_] = index_;
1,069 ✔
54

55
  // Get atomic number
56
  read_attribute(group, "Z", Z_);
1,069 ✔
57

58
  // Determine number of energies and read energy grid
59
  read_dataset(group, "energy", energy_);
1,069 ✔
60

61
  // Read coherent scattering
62
  hid_t rgroup = open_group(group, "coherent");
1,069 ✔
63
  read_dataset(rgroup, "xs", coherent_);
1,069 ✔
64

65
  hid_t dset = open_dataset(rgroup, "integrated_scattering_factor");
1,069 ✔
66
  coherent_int_form_factor_ = Tabulated1D {dset};
1,069 ✔
67
  close_dataset(dset);
1,069 ✔
68

69
  if (object_exists(group, "anomalous_real")) {
1,069 !
70
    dset = open_dataset(rgroup, "anomalous_real");
×
71
    coherent_anomalous_real_ = Tabulated1D {dset};
×
72
    close_dataset(dset);
×
73
  }
74

75
  if (object_exists(group, "anomalous_imag")) {
1,069 !
76
    dset = open_dataset(rgroup, "anomalous_imag");
×
77
    coherent_anomalous_imag_ = Tabulated1D {dset};
×
78
    close_dataset(dset);
×
79
  }
80
  close_group(rgroup);
1,069 ✔
81

82
  // Read incoherent scattering
83
  rgroup = open_group(group, "incoherent");
1,069 ✔
84
  read_dataset(rgroup, "xs", incoherent_);
1,069 ✔
85
  dset = open_dataset(rgroup, "scattering_factor");
1,069 ✔
86
  incoherent_form_factor_ = Tabulated1D {dset};
1,069 ✔
87
  close_dataset(dset);
1,069 ✔
88
  close_group(rgroup);
1,069 ✔
89

90
  // Read pair production
91
  if (object_exists(group, "pair_production_electron")) {
1,069 !
92
    rgroup = open_group(group, "pair_production_electron");
1,069 ✔
93
    read_dataset(rgroup, "xs", pair_production_electron_);
1,069 ✔
94
    close_group(rgroup);
1,069 ✔
95
  } else {
96
    pair_production_electron_ = tensor::zeros_like(energy_);
×
97
  }
98

99
  // Read pair production
100
  if (object_exists(group, "pair_production_nuclear")) {
1,069 !
101
    rgroup = open_group(group, "pair_production_nuclear");
1,069 ✔
102
    read_dataset(rgroup, "xs", pair_production_nuclear_);
1,069 ✔
103
    close_group(rgroup);
1,069 ✔
104
  } else {
105
    pair_production_nuclear_ = tensor::zeros_like(energy_);
×
106
  }
107

108
  // Read photoelectric
109
  rgroup = open_group(group, "photoelectric");
1,069 ✔
110
  read_dataset(rgroup, "xs", photoelectric_total_);
1,069 ✔
111
  close_group(rgroup);
1,069 ✔
112

113
  // Read heating
114
  if (object_exists(group, "heating")) {
1,069 !
115
    rgroup = open_group(group, "heating");
1,069 ✔
116
    read_dataset(rgroup, "xs", heating_);
1,069 ✔
117
    close_group(rgroup);
1,069 ✔
118
  } else {
119
    heating_ = tensor::zeros_like(energy_);
×
120
  }
121

122
  // Read subshell photoionization cross section and atomic relaxation data
123
  rgroup = open_group(group, "subshells");
1,069 ✔
124
  vector<std::string> designators;
1,069 ✔
125
  read_attribute(rgroup, "designators", designators);
1,069 ✔
126
  auto n_shell = designators.size();
1,069 !
127
  if (n_shell == 0) {
1,069 !
128
    throw std::runtime_error {
×
129
      "Photoatomic data for " + name_ + " does not have subshell data."};
×
130
  }
131

132
  shells_.resize(n_shell);
1,069 ✔
133
  cross_sections_ = tensor::zeros<double>({energy_.size(), n_shell});
1,069 ✔
134

135
  // Create mapping from designator to index
136
  std::unordered_map<int, int> shell_map;
1,069 ✔
137
  for (int i = 0; i < n_shell; ++i) {
8,988 ✔
138
    const auto& designator {designators[i]};
7,919 ✔
139

140
    int j = 1;
7,919 ✔
141
    for (const auto& subshell : SUBSHELLS) {
54,438 !
142
      if (designator == subshell) {
54,438 ✔
143
        shell_map[j] = i;
7,919 ✔
144
        shells_[i].index_subshell = j;
7,919 ✔
145
        break;
7,919 ✔
146
      }
147
      ++j;
46,519 ✔
148
    }
149
  }
150
  shell_map[0] = -1;
1,069 ✔
151

152
  for (int i = 0; i < n_shell; ++i) {
8,988 ✔
153
    const auto& designator {designators[i]};
7,919 ✔
154
    auto& shell {shells_[i]};
7,919 ✔
155

156
    // TODO: Move to ElectronSubshell constructor
157

158
    hid_t tgroup = open_group(rgroup, designator.c_str());
7,919 ✔
159

160
    // Read binding energy if atomic relaxation data is present
161
    if (attribute_exists(tgroup, "binding_energy")) {
7,919 !
162
      has_atomic_relaxation_ = true;
7,919 ✔
163
      read_attribute(tgroup, "binding_energy", shell.binding_energy);
7,919 ✔
164
    }
165

166
    // Read subshell cross section
167
    tensor::Tensor<double> xs;
7,919 ✔
168
    dset = open_dataset(tgroup, "xs");
7,919 ✔
169
    read_attribute(dset, "threshold_idx", shell.threshold);
7,919 ✔
170
    close_dataset(dset);
7,919 ✔
171
    read_dataset(tgroup, "xs", xs);
7,919 ✔
172

173
    auto cross_section =
7,919 ✔
174
      cross_sections_.slice(tensor::range(static_cast<size_t>(shell.threshold),
7,919 ✔
175
                              cross_sections_.shape(0)),
176
        i);
15,838 !
177
    cross_section = tensor::where(xs > 0, tensor::log(xs), 0);
23,757 ✔
178

179
    if (settings::atomic_relaxation && object_exists(tgroup, "transitions")) {
7,919 ✔
180
      // Determine dimensions of transitions
181
      dset = open_dataset(tgroup, "transitions");
4,658 ✔
182
      auto dims = object_shape(dset);
4,658 ✔
183
      close_dataset(dset);
4,658 ✔
184

185
      int n_transition = dims[0];
4,658 !
186
      if (n_transition > 0) {
4,658 !
187
        tensor::Tensor<double> matrix;
4,658 ✔
188
        read_dataset(tgroup, "transitions", matrix);
4,658 ✔
189

190
        // Transition probability normalization
191
        double norm =
4,658 ✔
192
          tensor::Tensor<double>(matrix.slice(tensor::all, 3)).sum();
9,316 ✔
193

194
        shell.transitions.resize(n_transition);
4,658 ✔
195
        for (int j = 0; j < n_transition; ++j) {
228,032 ✔
196
          auto& transition = shell.transitions[j];
223,374 ✔
197
          transition.primary_subshell = shell_map.at(matrix(j, 0));
223,374 ✔
198
          transition.secondary_subshell = shell_map.at(matrix(j, 1));
223,374 ✔
199
          transition.energy = matrix(j, 2);
223,374 ✔
200
          transition.probability = matrix(j, 3) / norm;
223,374 ✔
201
        }
202
      }
4,658 ✔
203
    }
4,658 ✔
204
    close_group(tgroup);
7,919 ✔
205
  }
15,838 ✔
206
  close_group(rgroup);
1,069 ✔
207

208
  // Check the maximum size of the atomic relaxation stack
209
  auto max_size = this->calc_max_stack_size();
1,069 ✔
210
  if (max_size > MAX_STACK_SIZE && mpi::master) {
1,069 !
211
    warning(fmt::format("The subshell vacancy stack in atomic relaxation can "
×
212
                        "grow up to {}, but the stack size limit is set to {}.",
213
      max_size, MAX_STACK_SIZE));
214
  }
215

216
  // Determine number of electron shells
217
  rgroup = open_group(group, "compton_profiles");
1,069 ✔
218

219
  // Read electron shell PDF and binding energies
220
  read_dataset(rgroup, "num_electrons", electron_pdf_);
1,069 ✔
221
  electron_pdf_ /= electron_pdf_.sum();
1,069 ✔
222
  read_dataset(rgroup, "binding_energy", binding_energy_);
1,069 ✔
223

224
  // Read Compton profiles
225
  read_dataset(rgroup, "J", profile_pdf_);
1,069 ✔
226

227
  // Get Compton profile momentum grid
228
  if (data::compton_profile_pz.size() == 0) {
1,069 ✔
229
    read_dataset(rgroup, "pz", data::compton_profile_pz);
411 ✔
230
  }
231
  close_group(rgroup);
1,069 ✔
232

233
  // Map Compton subshell data to atomic relaxation data by finding the
234
  // subshell with the equivalent binding energy
235
  if (settings::atomic_relaxation && has_atomic_relaxation_) {
1,069 !
236
    auto is_close = [](double a, double b) {
15,015 ✔
237
      return std::abs(a - b) / a < FP_REL_PRECISION;
13,964 ✔
238
    };
239
    subshell_map_ = tensor::Tensor<int>(binding_energy_.shape(), -1);
2,102 ✔
240
    for (int i = 0; i < binding_energy_.size(); ++i) {
7,443 ✔
241
      double E_b = binding_energy_[i];
6,392 !
242
      if (i < n_shell && is_close(E_b, shells_[i].binding_energy)) {
6,392 !
243
        subshell_map_[i] = i;
5,183 ✔
244
      } else {
245
        for (int j = 0; j < n_shell; ++j) {
7,572 !
246
          if (is_close(E_b, shells_[j].binding_energy)) {
7,572 ✔
247
            subshell_map_[i] = j;
1,209 ✔
248
            break;
1,209 ✔
249
          }
250
        }
251
      }
252
    }
253
  }
254

255
  // Create Compton profile CDF
256
  auto n_profile = data::compton_profile_pz.size();
1,069 !
257
  auto n_shell_compton = profile_pdf_.shape(0);
1,069 !
258
  if (n_profile < 2) {
1,069 !
259
    throw std::runtime_error {
×
260
      "At least two points are required in a Compton profile."};
×
261
  }
262
  profile_cdf_ = tensor::Tensor<double>({n_shell_compton, n_profile});
1,069 ✔
263
  profile_tail_slope_ = tensor::Tensor<double>({n_shell_compton});
1,069 ✔
264
  profile_negative_mass_ = tensor::Tensor<double>({n_shell_compton});
1,069 ✔
265
  if (n_shell_compton > SUBSHELLS.size()) {
1,069 !
266
    throw std::runtime_error {"Photoatomic data for element " + name_ +
×
267
                              " has more Compton profiles than supported "
268
                              "electron subshells."};
×
269
  }
270
  for (int i = 0; i < n_shell_compton; ++i) {
7,677 ✔
271
    double c = 0.0;
6,608 ✔
272
    profile_cdf_(i, 0) = 0.0;
6,608 ✔
273
    for (int j = 0; j < n_profile - 1; ++j) {
204,848 ✔
274
      c += 0.5 *
198,240 ✔
275
           (data::compton_profile_pz(j + 1) - data::compton_profile_pz(j)) *
198,240 ✔
276
           (profile_pdf_(i, j) + profile_pdf_(i, j + 1));
198,240 ✔
277
      profile_cdf_(i, j + 1) = c;
198,240 ✔
278
    }
279

280
    // Extrapolate the profile beyond the tabulated grid linearly on a
281
    // log-linear scale. The normalization includes the extrapolated tail.
282
    double pz_last = data::compton_profile_pz(n_profile - 1);
6,608 !
283
    double pz_prev = data::compton_profile_pz(n_profile - 2);
6,608 ✔
284
    double profile_last = profile_pdf_(i, n_profile - 1);
6,608 ✔
285
    double profile_prev = profile_pdf_(i, n_profile - 2);
6,608 ✔
286
    if (!(pz_last > pz_prev) || !(profile_last > 0.0) ||
6,608 !
287
        !(profile_prev > 0.0)) {
288
      throw std::runtime_error {"The final two points of the Compton profile "
×
289
                                "for element " +
×
290
                                name_ + " are not valid for extrapolation."};
×
291
    }
292
    double slope = std::log(profile_last / profile_prev) / (pz_last - pz_prev);
6,608 ✔
293
    if (!std::isfinite(slope) || slope >= 0.0) {
6,608 !
294
      throw std::runtime_error {"The final two values of the Compton profile "
×
295
                                "for element " +
×
296
                                name_ + " do not form a decreasing tail."};
×
297
    }
298
    profile_tail_slope_(i) = slope;
6,608 !
299
    double norm = 2.0 * (c - profile_last / slope);
6,608 ✔
300
    if (!std::isfinite(norm) || norm <= 0.0) {
6,608 !
301
      throw std::runtime_error {"The Compton profile for element " + name_ +
×
302
                                " has an invalid normalization."};
×
303
    }
304
    for (int j = 0; j < n_profile; ++j) {
211,456 ✔
305
      profile_pdf_(i, j) /= norm;
204,848 ✔
306
      profile_cdf_(i, j) /= norm;
204,848 ✔
307
    }
308
  }
309
  for (int i = 0; i < n_shell_compton; ++i) {
7,677 ✔
310
    profile_negative_mass_(i) = this->compton_profile_cdf(i, FINE_STRUCTURE);
6,608 ✔
311
  }
312

313
  // Calculate total pair production
314
  pair_production_total_ = pair_production_nuclear_ + pair_production_electron_;
1,069 ✔
315

316
  if (settings::electron_treatment == ElectronTreatment::TTB) {
1,069 ✔
317
    // Read bremsstrahlung scaled DCS
318
    rgroup = open_group(group, "bremsstrahlung");
862 ✔
319
    read_dataset(rgroup, "dcs", dcs_);
862 ✔
320
    auto n_e = dcs_.shape(0);
862 !
321
    auto n_k = dcs_.shape(1);
862 !
322

323
    // Get energy grids used for bremsstrahlung DCS and for stopping powers
324
    tensor::Tensor<double> electron_energy;
862 ✔
325
    read_dataset(rgroup, "electron_energy", electron_energy);
862 ✔
326
    if (data::ttb_k_grid.size() == 0) {
862 ✔
327
      read_dataset(rgroup, "photon_energy", data::ttb_k_grid);
316 ✔
328
    }
329

330
    // Get data used for density effect correction
331
    read_dataset(rgroup, "num_electrons", n_electrons_);
862 ✔
332
    read_dataset(rgroup, "ionization_energy", ionization_energy_);
862 ✔
333
    read_attribute(rgroup, "I", I_);
862 ✔
334
    close_group(rgroup);
862 ✔
335

336
    // Truncate the bremsstrahlung data at the cutoff energy
337
    int photon = ParticleType::photon().transport_index();
862 ✔
338
    const auto& E {electron_energy};
862 ✔
339
    double cutoff = settings::energy_cutoff[photon];
862 ✔
340
    if (cutoff > E(0)) {
862 ✔
341
      size_t i_grid = lower_bound_index(
7 ✔
342
        E.cbegin(), E.cend(), settings::energy_cutoff[photon]);
7 ✔
343

344
      // calculate interpolation factor
345
      double f = (std::log(cutoff) - std::log(E(i_grid))) /
7 ✔
346
                 (std::log(E(i_grid + 1)) - std::log(E(i_grid)));
7 ✔
347

348
      // Interpolate bremsstrahlung DCS at the cutoff energy and truncate
349
      tensor::Tensor<double> dcs({n_e - i_grid, n_k});
7 ✔
350
      for (int i = 0; i < n_k; ++i) {
217 ✔
351
        double y = std::exp(
630 ✔
352
          std::log(dcs_(i_grid, i)) +
210 ✔
353
          f * (std::log(dcs_(i_grid + 1, i)) - std::log(dcs_(i_grid, i))));
210 ✔
354
        tensor::View<double> col_i = dcs.slice(tensor::all, i);
210 ✔
355
        col_i(0) = y;
210 ✔
356
        for (int j = i_grid + 1; j < n_e; ++j) {
39,030 ✔
357
          col_i(j - i_grid) = dcs_(j, i);
38,820 ✔
358
        }
359
      }
210 ✔
360
      dcs_ = dcs;
7 ✔
361

362
      tensor::Tensor<double> frst({static_cast<size_t>(1)});
7 ✔
363
      frst(0) = cutoff;
7 ✔
364
      tensor::Tensor<double> rest(electron_energy.slice(
7 ✔
365
        tensor::range(i_grid + 1, electron_energy.size())));
7 ✔
366
      electron_energy = tensor::concatenate(frst, rest);
14 ✔
367
    }
21 ✔
368

369
    // Set incident particle energy grid
370
    if (data::ttb_e_grid.size() == 0) {
862 ✔
371
      data::ttb_e_grid = electron_energy;
316 ✔
372
    }
373

374
    // Calculate the radiative stopping power
375
    stopping_power_radiative_ =
862 ✔
376
      tensor::Tensor<double>({data::ttb_e_grid.size()});
862 ✔
377
    for (int i = 0; i < data::ttb_e_grid.size(); ++i) {
173,163 ✔
378
      // Integrate over reduced photon energy
379
      double c = 0.0;
380
      for (int j = 0; j < data::ttb_k_grid.size() - 1; ++j) {
5,169,030 ✔
381
        c += 0.5 * (dcs_(i, j + 1) + dcs_(i, j)) *
4,996,729 ✔
382
             (data::ttb_k_grid(j + 1) - data::ttb_k_grid(j));
4,996,729 ✔
383
      }
384
      double e = data::ttb_e_grid(i);
172,301 ✔
385

386
      // Square of the ratio of the speed of light to the velocity of the
387
      // charged particle
388
      double beta_sq = e * (e + 2.0 * MASS_ELECTRON_EV) /
172,301 ✔
389
                       ((e + MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV));
172,301 ✔
390

391
      stopping_power_radiative_(i) = Z_ * Z_ / beta_sq * e * c;
172,301 ✔
392
    }
393
  }
862 ✔
394

395
  // Take logarithm of energies and cross sections since they are log-log
396
  // interpolated. Note that cross section libraries converted from ACE files
397
  // represent zero as exp(-500) to avoid log-log interpolation errors. For
398
  // values below exp(-499) we store the log as -900, for which exp(-900)
399
  // evaluates to zero.
400
  double limit = std::exp(-499.0);
1,069 ✔
401
  energy_ = tensor::log(energy_);
1,069 ✔
402
  coherent_ = tensor::where(coherent_ > limit, tensor::log(coherent_), -900.0);
3,207 ✔
403
  incoherent_ =
1,069 ✔
404
    tensor::where(incoherent_ > limit, tensor::log(incoherent_), -900.0);
3,207 ✔
405
  photoelectric_total_ = tensor::where(
2,138 ✔
406
    photoelectric_total_ > limit, tensor::log(photoelectric_total_), -900.0);
3,207 ✔
407
  pair_production_total_ = tensor::where(pair_production_total_ > limit,
3,207 ✔
408
    tensor::log(pair_production_total_), -900.0);
2,138 ✔
409
  heating_ = tensor::where(heating_ > limit, tensor::log(heating_), -900.0);
4,276 ✔
410
}
1,069 ✔
411

412
PhotonInteraction::~PhotonInteraction()
1,069 ✔
413
{
414
  data::element_map.erase(name_);
1,069 ✔
415
}
22,449 ✔
416

417
int PhotonInteraction::calc_max_stack_size() const
1,069 ✔
418
{
419
  // Table to store solutions to sub-problems
420
  std::unordered_map<int, int> visited;
1,069 ✔
421

422
  // Find the maximum possible size of the stack used to store holes created
423
  // during atomic relaxation, checking over every subshell the initial hole
424
  // could be in
425
  int max_size = 0;
1,069 ✔
426
  for (int i_shell = 0; i_shell < shells_.size(); ++i_shell) {
8,988 ✔
427
    max_size = std::max(max_size, this->calc_helper(visited, i_shell));
8,988 ✔
428
  }
429
  return max_size;
1,069 ✔
430
}
1,069 ✔
431

432
int PhotonInteraction::calc_helper(
431,885 ✔
433
  std::unordered_map<int, int>& visited, int i_shell) const
434
{
435
  // No transitions for this subshell, so this is the only shell in the stack
436
  const auto& shell {shells_[i_shell]};
431,885 ✔
437
  if (shell.transitions.empty()) {
431,885 ✔
438
    return 1;
439
  }
440

441
  // Check the table to see if the maximum stack size has already been
442
  // calculated for this shell
443
  auto it = visited.find(i_shell);
271,912 ✔
444
  if (it != visited.end()) {
271,912 ✔
445
    return it->second;
267,254 ✔
446
  }
447

448
  int max_size = 0;
4,658 ✔
449
  for (const auto& transition : shell.transitions) {
228,032 ✔
450
    // If this is a non-radiative transition two vacancies are created and
451
    // the stack grows by one; if this is a radiative transition only one
452
    // vacancy is created and the stack size stays the same
453
    int size = 0;
223,374 ✔
454
    if (transition.secondary_subshell != -1) {
223,374 ✔
455
      size = this->calc_helper(visited, transition.secondary_subshell) + 1;
200,592 ✔
456
    }
457
    size =
446,748 ✔
458
      std::max(size, this->calc_helper(visited, transition.primary_subshell));
223,374 ✔
459
    max_size = std::max(max_size, size);
230,835 ✔
460
  }
461
  visited[i_shell] = max_size;
4,658 ✔
462
  return max_size;
4,658 ✔
463
}
464

465
void PhotonInteraction::compton_scatter(double alpha, bool doppler,
17,287,917 ✔
466
  double* alpha_out, double* mu, int* i_shell, uint64_t* seed) const
467
{
468
  double form_factor_xmax = 0.0;
17,287,917 ✔
469
  while (true) {
17,608,403 ✔
470
    // Sample Klein-Nishina distribution for trial energy and angle
471
    std::tie(*alpha_out, *mu) = klein_nishina(alpha, seed);
17,608,403 ✔
472

473
    // Note that the parameter used here does not correspond exactly to the
474
    // momentum transfer q in ENDF-102 Eq. (27.2). Rather, this is the
475
    // parameter as defined by Hubbell, where the actual data comes from
476
    double x =
17,608,403 ✔
477
      MASS_ELECTRON_EV / PLANCK_C * alpha * std::sqrt(0.5 * (1.0 - *mu));
17,608,403 ✔
478

479
    // Calculate S(x, Z) and S(x_max, Z)
480
    double form_factor_x = incoherent_form_factor_(x);
17,608,403 ✔
481
    if (form_factor_xmax == 0.0) {
17,608,403 ✔
482
      form_factor_xmax =
17,287,917 ✔
483
        incoherent_form_factor_(MASS_ELECTRON_EV / PLANCK_C * alpha);
17,287,917 ✔
484
    }
485

486
    // Perform rejection on form factor
487
    if (prn(seed) < form_factor_x / form_factor_xmax) {
17,608,403 ✔
488
      if (doppler) {
17,287,917 !
489
        double E_out;
17,287,917 ✔
490
        this->compton_doppler(alpha, *mu, &E_out, i_shell, seed);
17,287,917 ✔
491
        *alpha_out = E_out / MASS_ELECTRON_EV;
17,287,917 ✔
492
      } else {
493
        *i_shell = -1;
×
494
      }
495
      break;
17,287,917 ✔
496
    }
497
  }
498
}
17,287,917 ✔
499

500
double PhotonInteraction::compton_profile_cdf(int i_shell, double pz) const
31,051,740 ✔
501
{
502
  if (pz <= 0.0)
31,051,740 !
503
    return 0.0;
504

505
  auto n = data::compton_profile_pz.size();
31,051,740 ✔
506
  double pz_last = data::compton_profile_pz(n - 1);
31,051,740 ✔
507
  double c;
31,051,740 ✔
508
  if (pz >= pz_last) {
31,051,740 ✔
509
    c = profile_cdf_(i_shell, n - 1) + detail::compton_profile_tail_integral(pz,
10,259,595 ✔
510
                                         pz_last, profile_pdf_(i_shell, n - 1),
10,259,595 ✔
511
                                         profile_tail_slope_(i_shell));
10,259,595 ✔
512
  } else {
513
    int i = lower_bound_index(
20,792,145 ✔
514
      data::compton_profile_pz.cbegin(), data::compton_profile_pz.cend(), pz);
20,792,145 ✔
515
    double pz_l = data::compton_profile_pz(i);
20,792,145 ✔
516
    double pz_r = data::compton_profile_pz(i + 1);
20,792,145 ✔
517
    double p_l = profile_pdf_(i_shell, i);
20,792,145 ✔
518
    double p_r = profile_pdf_(i_shell, i + 1);
20,792,145 ✔
519
    double c_l = profile_cdf_(i_shell, i);
20,792,145 ✔
520
    double slope = (p_r - p_l) / (pz_r - pz_l);
20,792,145 ✔
521
    double delta = pz - pz_l;
20,792,145 ✔
522
    c = c_l + p_l * delta + 0.5 * slope * delta * delta;
20,792,145 ✔
523
  }
524
  return std::min(0.5, c);
59,867,862 ✔
525
}
526

527
double PhotonInteraction::invert_compton_profile_cdf(
28,290,059 ✔
528
  int i_shell, double c) const
529
{
530
  auto n = data::compton_profile_pz.size();
28,290,059 ✔
531
  double integral = c;
28,290,059 ✔
532
  double c_last = profile_cdf_(i_shell, n - 1);
28,290,059 ✔
533
  if (integral >= c_last) {
28,290,059 ✔
534
    // Invert the log-linear extrapolated tail using Kaltiaisenaho Eq. (3.123).
535
    return detail::invert_compton_profile_tail(integral - c_last,
2,212 ✔
536
      data::compton_profile_pz(n - 1), profile_pdf_(i_shell, n - 1),
2,212 ✔
537
      profile_tail_slope_(i_shell));
2,212 ✔
538
  }
539

540
  // Invert the piecewise-linear tabulated profile (Kaltiaisenaho Eq. 3.126).
541
  // The rationalized quadratic root used below is equivalent to that equation
542
  // but remains well-conditioned when the profile slope is small.
543
  tensor::View<const double> cdf_shell = profile_cdf_.slice(i_shell);
28,287,847 ✔
544
  int i = lower_bound_index(cdf_shell.cbegin(), cdf_shell.cend(), integral);
28,287,847 ✔
545
  double pz_l = data::compton_profile_pz(i);
28,287,847 ✔
546
  double pz_r = data::compton_profile_pz(i + 1);
28,287,847 ✔
547
  double p_l = profile_pdf_(i_shell, i);
28,287,847 ✔
548
  double p_r = profile_pdf_(i_shell, i + 1);
28,287,847 ✔
549
  double c_l = profile_cdf_(i_shell, i);
28,287,847 ✔
550
  if (p_l == p_r) {
28,287,847 ✔
551
    return pz_l + (integral - c_l) / p_l;
2,315,997 ✔
552
  }
553

554
  double slope = (p_r - p_l) / (pz_r - pz_l);
25,971,850 ✔
555
  double delta_c = integral - c_l;
25,971,850 ✔
556
  double discriminant = p_l * p_l + 2.0 * slope * delta_c;
25,971,850 ✔
557
  double denominator = p_l + std::sqrt(std::max(0.0, discriminant));
51,943,700 !
558
  return pz_l + 2.0 * delta_c / denominator;
25,971,850 ✔
559
}
28,290,059 ✔
560

561
PhotonInteraction::ShellKinematics PhotonInteraction::compton_shell_kinematics(
31,049,683 ✔
562
  double alpha, double mu, double E, int i_shell) const
563
{
564
  ShellKinematics kinematics {};
31,049,683 ✔
565
  double E_b = binding_energy_(i_shell);
31,049,683 ✔
566
  if (E <= E_b)
31,049,683 ✔
567
    return kinematics;
568

569
  // Kaltiaisenaho Eq. (3.73): substitute E' = E - E_b in the RIA
570
  // kinematic relation to obtain the upper bound on the allowed pz interval.
571
  kinematics.pz_max = -FINE_STRUCTURE * (E_b - (E - E_b) * alpha * (1.0 - mu)) /
62,090,264 ✔
572
                      std::sqrt(2.0 * E * (E - E_b) * (1.0 - mu) + E_b * E_b);
31,045,132 ✔
573
  if (kinematics.pz_max <= -FINE_STRUCTURE)
31,045,132 !
574
    return kinematics;
575

576
  // Eq. (3.118), using profile_negative_mass_ = K_i(1/alpha): the
577
  // kinematically accessible mass is the integral from -1/alpha to pz_max.
578
  double c_negative = profile_negative_mass_(i_shell);
31,045,132 ✔
579
  kinematics.c_limit =
62,090,264 ✔
580
    this->compton_profile_cdf(i_shell, std::abs(kinematics.pz_max));
31,045,132 ✔
581
  kinematics.profile_mass =
31,045,132 ✔
582
    c_negative + std::copysign(kinematics.c_limit, kinematics.pz_max);
31,045,132 ✔
583
  return kinematics;
31,045,132 ✔
584
}
585

586
bool PhotonInteraction::sample_compton_momentum(double alpha, double mu,
28,290,059 ✔
587
  double E, int i_shell, const ShellKinematics& kinematics, double* E_out,
588
  uint64_t* seed) const
589
{
590
  double c_negative = profile_negative_mass_(i_shell);
28,290,059 ✔
591
  double pz;
28,290,059 ✔
592
  // Inverse-transform sampling of the signed pz distribution, following
593
  // Kaltiaisenaho Eqs. (3.120)-(3.126). The tabulated profile is symmetric,
594
  // so its negative branch is obtained by reflecting the half-profile CDF.
595
  if (kinematics.pz_max < 0.0) {
28,290,059 ✔
596
    double c = kinematics.c_limit + prn(seed) * kinematics.profile_mass;
57,393 ✔
597
    pz = -this->invert_compton_profile_cdf(i_shell, c);
57,393 ✔
598
  } else {
599
    double c = prn(seed) * kinematics.profile_mass;
28,232,666 ✔
600
    if (c < c_negative) {
28,232,666 ✔
601
      pz = -this->invert_compton_profile_cdf(i_shell, c_negative - c);
14,226,914 ✔
602
    } else {
603
      pz = this->invert_compton_profile_cdf(i_shell, c - c_negative);
14,005,752 ✔
604
    }
605
  }
606

607
  double energy_ratio = detail::compton_energy_ratio(alpha, mu, pz);
28,290,059 ✔
608
  double max_energy_ratio = 1.0 - binding_energy_(i_shell) / E;
28,290,059 !
609
  if (!std::isfinite(energy_ratio) || energy_ratio <= 0.0)
28,290,059 !
610
    return false;
611

612
  double energy_tolerance = 16.0 * std::numeric_limits<double>::epsilon() *
28,290,059 ✔
613
                            std::max(1.0, max_energy_ratio);
28,290,059 !
614
  if (energy_ratio > max_energy_ratio + energy_tolerance)
28,290,059 !
615
    return false;
616

617
  energy_ratio = std::min(energy_ratio, max_energy_ratio);
28,290,059 !
618
  *E_out = energy_ratio * E;
28,290,059 ✔
619

620
  // Kaltiaisenaho Eq. (3.127): account for the E'/E factor in the
621
  // approximate RIA DDCS after solving the scattered-photon energy.
622
  return prn(seed) <= energy_ratio;
28,290,059 ✔
623
}
624

625
bool PhotonInteraction::compton_doppler_conditional(double alpha, double mu,
1,803,488 ✔
626
  double E, double* E_out, int* i_shell, uint64_t* seed) const
627
{
628
  array<ShellKinematics, SUBSHELLS.size()> shell_data;
1,803,488 ✔
629
  array<double, SUBSHELLS.size()> shell_cdf;
1,803,488 ✔
630
  double shell_pmf_norm = 0.0;
1,803,488 ✔
631

632
  // Form the shell PMF in Eq. (3.116), f_i times the accessible profile mass.
633
  // This is algebraically equivalent to repeated shell rejection in Eq.
634
  // (3.119).
635
  for (int i = 0; i < electron_pdf_.size(); ++i) {
11,236,429 ✔
636
    shell_data[i] = this->compton_shell_kinematics(alpha, mu, E, i);
9,432,941 ✔
637
    shell_pmf_norm += electron_pdf_(i) * shell_data[i].profile_mass;
9,432,941 ✔
638
    shell_cdf[i] = shell_pmf_norm;
9,432,941 ✔
639
  }
640
  if (shell_pmf_norm == 0.0)
1,803,488 !
641
    return false;
642

643
  // The conditional shell PMF avoids repeated rejection when the accessible
644
  // profile mass is small. Retain a bound to protect against degenerate
645
  // momentum/energy sampling and roundoff.
646
  constexpr int MAX_SAMPLES = 100000;
647
  for (int attempt = 0; attempt < MAX_SAMPLES; ++attempt) {
6,984,307 !
648
    double rn = prn(seed) * shell_pmf_norm;
6,984,307 ✔
649
    int shell;
6,984,307 ✔
650
    for (shell = 0; shell < electron_pdf_.size(); ++shell) {
22,426,245 !
651
      if (rn < shell_cdf[shell])
22,426,245 ✔
652
        break;
653
    }
654
    *i_shell = shell;
6,984,307 ✔
655

656
    if (this->sample_compton_momentum(
6,984,307 ✔
657
          alpha, mu, E, shell, shell_data[shell], E_out, seed))
6,984,307 ✔
658
      return true;
659
  }
660
  return false;
661
}
662

663
void PhotonInteraction::compton_doppler(
17,287,917 ✔
664
  double alpha, double mu, double* E_out, int* i_shell, uint64_t* seed) const
665
{
666
  // Implements the approximate RIA Doppler-broadening algorithm in Sec. 3.4.8
667
  // of T. Kaltiaisenaho, "Implementing a photon physics model in Serpent 2"
668
  // (2016), https://aaltodoc.aalto.fi/handle/123456789/21004.
669
  // First use Kaltiaisenaho's shell-rejection procedure (Eqs. 3.116-3.119),
670
  // which usually accepts quickly. If it does not, sample its equivalent
671
  // conditional shell PMF to bound work for near-forward scattering.
672
  constexpr int N_FAST_SAMPLES = 2;
17,287,917 ✔
673

674
  double E = alpha * MASS_ELECTRON_EV;
17,287,917 ✔
675
  int shell = 0;
17,287,917 ✔
676
  for (int attempt = 0; attempt < N_FAST_SAMPLES; ++attempt) {
23,420,230 ✔
677
    // Propose shell i according to occupancy f_i (first step of Eq. 3.119).
678
    double rn = prn(seed);
21,616,742 ✔
679
    double c = 0.0;
680
    for (shell = 0; shell < electron_pdf_.size(); ++shell) {
62,651,080 !
681
      c += electron_pdf_(shell);
62,651,080 ✔
682
      if (rn < c)
62,651,080 ✔
683
        break;
684
    }
685

686
    auto kinematics = this->compton_shell_kinematics(alpha, mu, E, shell);
21,616,742 ✔
687
    if (kinematics.profile_mass <= 0.0)
21,616,742 ✔
688
      continue;
310,990 ✔
689

690
    // Accept with the accessible Compton-profile mass (Eq. 3.119).
691
    if (prn(seed) >= kinematics.profile_mass)
21,615,888 ✔
692
      continue;
310,136 ✔
693

694
    if (this->sample_compton_momentum(
21,305,752 ✔
695
          alpha, mu, E, shell, kinematics, E_out, seed)) {
696
      *i_shell = shell;
15,484,429 ✔
697
      return;
15,484,429 ✔
698
    }
699
  }
700

701
  *i_shell = shell;
1,803,488 ✔
702
  if (this->compton_doppler_conditional(alpha, mu, E, E_out, i_shell, seed))
1,803,488 !
703
    return;
704

705
  // No shell/momentum sample was accepted within the iteration budget.
706
  // Fall back to the free-electron Compton energy for the last sampled
707
  // shell rather than looping indefinitely.
708
  *E_out = alpha / (1.0 + alpha * (1.0 - mu)) * MASS_ELECTRON_EV;
×
709
}
710

711
void PhotonInteraction::calculate_xs(Particle& p) const
122,978,115 ✔
712
{
713
  // Perform binary search on the element energy grid in order to determine
714
  // which points to interpolate between
715
  int n_grid = energy_.size();
122,978,115 ✔
716
  double log_E = std::log(p.E());
122,978,115 ✔
717
  int i_grid;
122,978,115 ✔
718
  if (log_E <= energy_[0]) {
122,978,115 !
719
    i_grid = 0;
720
  } else if (log_E > energy_(n_grid - 1)) {
122,978,115 !
721
    i_grid = n_grid - 2;
×
722
  } else {
723
    // We use upper_bound_index here because sometimes photons are created with
724
    // energies that exactly match a grid point
725
    i_grid = upper_bound_index(energy_.cbegin(), energy_.cend(), log_E);
122,978,115 ✔
726
  }
727

728
  // check for case where two energy points are the same
729
  if (energy_(i_grid) == energy_(i_grid + 1))
122,978,115 !
730
    ++i_grid;
×
731

732
  // calculate interpolation factor
733
  double f =
122,978,115 ✔
734
    (log_E - energy_(i_grid)) / (energy_(i_grid + 1) - energy_(i_grid));
122,978,115 ✔
735

736
  auto& xs {p.photon_xs(index_)};
122,978,115 ✔
737
  xs.index_grid = i_grid;
122,978,115 ✔
738
  xs.interp_factor = f;
122,978,115 ✔
739

740
  // Calculate microscopic coherent cross section
741
  xs.coherent = std::exp(
245,956,230 ✔
742
    coherent_(i_grid) + f * (coherent_(i_grid + 1) - coherent_(i_grid)));
122,978,115 ✔
743

744
  // Calculate microscopic incoherent cross section
745
  xs.incoherent = std::exp(
245,956,230 ✔
746
    incoherent_(i_grid) + f * (incoherent_(i_grid + 1) - incoherent_(i_grid)));
122,978,115 ✔
747

748
  // Calculate microscopic photoelectric cross section
749
  xs.photoelectric = 0.0;
122,978,115 ✔
750
  tensor::View<const double> xs_lower = cross_sections_.slice(i_grid);
122,978,115 ✔
751
  tensor::View<const double> xs_upper = cross_sections_.slice(i_grid + 1);
122,978,115 ✔
752

753
  for (int i = 0; i < xs_upper.size(); ++i)
1,805,558,364 ✔
754
    if (xs_lower(i) != 0)
779,801,067 ✔
755
      xs.photoelectric +=
772,036,639 ✔
756
        std::exp(xs_lower(i) + f * (xs_upper(i) - xs_lower(i)));
772,036,639 ✔
757

758
  // Calculate microscopic pair production cross section
759
  xs.pair_production = std::exp(
245,956,230 ✔
760
    pair_production_total_(i_grid) +
122,978,115 ✔
761
    f * (pair_production_total_(i_grid + 1) - pair_production_total_(i_grid)));
122,978,115 ✔
762

763
  // Calculate microscopic total cross section
764
  xs.total =
122,978,115 ✔
765
    xs.coherent + xs.incoherent + xs.photoelectric + xs.pair_production;
122,978,115 ✔
766
  xs.last_E = p.E();
122,978,115 ✔
767
}
245,956,230 ✔
768

769
double PhotonInteraction::rayleigh_scatter(double alpha, uint64_t* seed) const
1,142,603 ✔
770
{
771
  double mu;
1,291,120 ✔
772
  while (true) {
1,439,637 ✔
773
    // Determine maximum value of x^2
774
    double x2_max = std::pow(MASS_ELECTRON_EV / PLANCK_C * alpha, 2);
1,291,120 ✔
775

776
    // Determine F(x^2_max, Z)
777
    double F_max = coherent_int_form_factor_(x2_max);
1,291,120 ✔
778

779
    // Sample cumulative distribution
780
    double F = prn(seed) * F_max;
1,291,120 ✔
781

782
    // Determine x^2 corresponding to F
783
    const auto& x {coherent_int_form_factor_.x()};
1,291,120 ✔
784
    const auto& y {coherent_int_form_factor_.y()};
1,291,120 ✔
785
    int i = lower_bound_index(y.cbegin(), y.cend(), F);
1,291,120 ✔
786
    double r = (F - y[i]) / (y[i + 1] - y[i]);
1,291,120 ✔
787
    double x2 = x[i] + r * (x[i + 1] - x[i]);
1,291,120 ✔
788

789
    // Calculate mu
790
    mu = 1.0 - 2.0 * x2 / x2_max;
1,291,120 ✔
791

792
    if (prn(seed) < 0.5 * (1.0 + mu * mu))
1,291,120 ✔
793
      break;
794
  }
148,517 ✔
795
  return mu;
1,142,603 ✔
796
}
797

798
void PhotonInteraction::pair_production(double alpha, double* E_electron,
136,094 ✔
799
  double* E_positron, double* mu_electron, double* mu_positron,
800
  uint64_t* seed) const
801
{
802
  constexpr double r[] {122.81, 73.167, 69.228, 67.301, 64.696, 61.228, 57.524,
136,094 ✔
803
    54.033, 50.787, 47.851, 46.373, 45.401, 44.503, 43.815, 43.074, 42.321,
804
    41.586, 40.953, 40.524, 40.256, 39.756, 39.144, 38.462, 37.778, 37.174,
805
    36.663, 35.986, 35.317, 34.688, 34.197, 33.786, 33.422, 33.068, 32.740,
806
    32.438, 32.143, 31.884, 31.622, 31.438, 31.142, 30.950, 30.758, 30.561,
807
    30.285, 30.097, 29.832, 29.581, 29.411, 29.247, 29.085, 28.930, 28.721,
808
    28.580, 28.442, 28.312, 28.139, 27.973, 27.819, 27.675, 27.496, 27.285,
809
    27.093, 26.911, 26.705, 26.516, 26.304, 26.108, 25.929, 25.730, 25.577,
810
    25.403, 25.245, 25.100, 24.941, 24.790, 24.655, 24.506, 24.391, 24.262,
811
    24.145, 24.039, 23.922, 23.813, 23.712, 23.621, 23.523, 23.430, 23.331,
812
    23.238, 23.139, 23.048, 22.967, 22.833, 22.694, 22.624, 22.545, 22.446,
813
    22.358, 22.264};
814

815
  // The reduced screening radius r is the ratio of the screening radius to
816
  // the Compton wavelength of the electron, where the screening radius is
817
  // obtained under the assumption that the Coulomb field of the nucleus is
818
  // exponentially screened by atomic electrons. This allows us to use a
819
  // simplified atomic form factor and analytical approximations of the
820
  // screening functions in the pair production DCS instead of computing the
821
  // screening functions numerically. The reduced screening radii above for
822
  // Z = 1-99 come from F. Salvat, J. M. Fernández-Varea, and J. Sempau,
823
  // "PENELOPE-2011: A Code System for Monte Carlo Simulation of Electron and
824
  // Photon Transport," OECD-NEA, Issy-les-Moulineaux, France (2011).
825

826
  // Compute the high-energy Coulomb correction
827
  double a = Z_ / FINE_STRUCTURE;
136,094 ✔
828
  double c =
136,094 ✔
829
    a * a *
136,094 ✔
830
    (1.0 / (1.0 + a * a) + 0.202059 +
136,094 ✔
831
      a * a *
136,094 ✔
832
        (-0.03693 +
136,094 ✔
833
          a * a *
136,094 ✔
834
            (0.00835 +
136,094 ✔
835
              a * a *
136,094 ✔
836
                (-0.00201 +
136,094 ✔
837
                  a * a * (0.00049 + a * a * (-0.00012 + a * a * 0.00003))))));
136,094 ✔
838

839
  // The analytical approximation of the DCS underestimates the cross section
840
  // at low energies. The correction factor f compensates for this.
841
  double q = std::sqrt(2.0 / alpha);
136,094 ✔
842
  double f = q * (-0.1774 - 12.10 * a + 11.18 * a * a) +
136,094 ✔
843
             q * q * (8.523 + 73.26 * a - 44.41 * a * a) +
136,094 ✔
844
             q * q * q * (-13.52 - 121.1 * a + 96.41 * a * a) +
136,094 ✔
845
             q * q * q * q * (8.946 + 62.05 * a - 63.41 * a * a);
136,094 ✔
846

847
  // Calculate phi_1(1/2) and phi_2(1/2). The unnormalized PDF for the reduced
848
  // energy is given by p = 2*(1/2 - e)^2*phi_1(e) + phi_2(e), where phi_1 and
849
  // phi_2 are non-negative and maximum at e = 1/2.
850
  double b = 2.0 * r[Z_] / alpha;
136,094 ✔
851
  double t1 = 2.0 * std::log(1.0 + b * b);
136,094 ✔
852
  double t2 = b * std::atan(1.0 / b);
136,094 ✔
853
  double t3 = b * b * (4.0 - 4.0 * t2 - 3.0 * std::log(1.0 + 1.0 / (b * b)));
136,094 ✔
854
  double t4 = 4.0 * std::log(r[Z_]) - 4.0 * c + f;
136,094 ✔
855
  double phi1_max = 7.0 / 3.0 - t1 - 6.0 * t2 - t3 + t4;
136,094 ✔
856
  double phi2_max = 11.0 / 6.0 - t1 - 3.0 * t2 + 0.5 * t3 + t4;
136,094 ✔
857

858
  // To aid sampling, the unnormalized PDF can be expressed as
859
  // p = u_1*U_1(e)*pi_1(e) + u_2*U_2(e)*pi_2(e), where pi_1 and pi_2 are
860
  // normalized PDFs on the interval (e_min, e_max) from which values of e can
861
  // be sampled using the inverse transform method, and
862
  // U_1 = phi_1(e)/phi_1(1/2) and U_2 = phi_2(e)/phi_2(1/2) are valid
863
  // rejection functions. The reduced energy can now be sampled using a
864
  // combination of the composition and rejection methods.
865
  double u1 = 2.0 / 3.0 * std::pow(0.5 - 1.0 / alpha, 2) * phi1_max;
136,094 ✔
866
  double u2 = phi2_max;
136,094 ✔
867
  double e;
172,991 ✔
868
  while (true) {
172,991 ✔
869
    double rn = prn(seed);
172,991 ✔
870

871
    // Sample the index i in (1, 2) using the point probabilities
872
    // p(1) = u_1/(u_1 + u_2) and p(2) = u_2/(u_1 + u_2)
873
    int i;
172,991 ✔
874
    if (prn(seed) < u1 / (u1 + u2)) {
172,991 ✔
875
      i = 1;
15,113 ✔
876

877
      // Sample e from pi_1 using the inverse transform method
878
      e = rn >= 0.5
15,113 ✔
879
            ? 0.5 + (0.5 - 1.0 / alpha) * std::pow(2.0 * rn - 1.0, 1.0 / 3.0)
15,113 ✔
880
            : 0.5 - (0.5 - 1.0 / alpha) * std::pow(1.0 - 2.0 * rn, 1.0 / 3.0);
7,742 ✔
881
    } else {
882
      i = 2;
157,878 ✔
883

884
      // Sample e from pi_2 using the inverse transform method
885
      e = 1.0 / alpha + (0.5 - 1.0 / alpha) * 2.0 * rn;
157,878 ✔
886
    }
887

888
    // Calculate phi_i(e) and deliver e if rn <= U_i(e)
889
    b = r[Z_] / (2.0 * alpha * e * (1.0 - e));
172,991 ✔
890
    t1 = 2.0 * std::log(1.0 + b * b);
172,991 ✔
891
    t2 = b * std::atan(1.0 / b);
172,991 ✔
892
    t3 = b * b * (4.0 - 4.0 * t2 - 3.0 * std::log(1.0 + 1.0 / (b * b)));
172,991 ✔
893
    if (i == 1) {
172,991 ✔
894
      double phi1 = 7.0 / 3.0 - t1 - 6.0 * t2 - t3 + t4;
15,113 ✔
895
      if (prn(seed) <= phi1 / phi1_max)
15,113 ✔
896
        break;
897
    } else {
898
      double phi2 = 11.0 / 6.0 - t1 - 3.0 * t2 + 0.5 * t3 + t4;
157,878 ✔
899
      if (prn(seed) <= phi2 / phi2_max)
157,878 ✔
900
        break;
901
    }
902
  }
903

904
  // Compute the kinetic energy of the electron and the positron
905
  *E_electron = (alpha * e - 1.0) * MASS_ELECTRON_EV;
136,094 ✔
906
  *E_positron = (alpha * (1.0 - e) - 1.0) * MASS_ELECTRON_EV;
136,094 ✔
907

908
  // Sample the scattering angle of the electron. The cosine of the polar
909
  // angle of the direction relative to the incident photon is sampled from
910
  // p(mu) = C/(1 - beta*mu)^2 using the inverse transform method.
911
  double beta =
136,094 ✔
912
    std::sqrt(*E_electron * (*E_electron + 2.0 * MASS_ELECTRON_EV)) /
136,094 ✔
913
    (*E_electron + MASS_ELECTRON_EV);
136,094 ✔
914
  double rn = uniform_distribution(-1., 1., seed);
136,094 ✔
915
  *mu_electron = (rn + beta) / (rn * beta + 1.0);
136,094 ✔
916

917
  // Sample the scattering angle of the positron
918
  beta = std::sqrt(*E_positron * (*E_positron + 2.0 * MASS_ELECTRON_EV)) /
136,094 ✔
919
         (*E_positron + MASS_ELECTRON_EV);
136,094 ✔
920
  rn = uniform_distribution(-1., 1., seed);
136,094 ✔
921
  *mu_positron = (rn + beta) / (rn * beta + 1.0);
136,094 ✔
922
}
136,094 ✔
923

924
void PhotonInteraction::atomic_relaxation(int i_shell, Particle& p) const
22,415,929 ✔
925
{
926
  // Return if no atomic relaxation data is present or if the binding energy is
927
  // larger than the incident particle energy
928
  if (!has_atomic_relaxation_ || shells_[i_shell].binding_energy > p.E())
22,415,929 !
929
    return;
×
930

931
  // Stack for unprocessed holes left by transitioning electrons
932
  int n_holes = 0;
22,415,929 ✔
933
  array<int, MAX_STACK_SIZE> holes;
22,415,929 ✔
934

935
  // Push the initial hole onto the stack
936
  holes[n_holes++] = i_shell;
22,415,929 ✔
937

938
  // Cascades from vacancies below the photon cutoff cannot produce transported
939
  // photons, either directly or through Auger-electron bremsstrahlung.
940
  double E_cutoff =
22,415,929 ✔
941
    settings::energy_cutoff[ParticleType::photon().transport_index()];
22,415,929 ✔
942

943
  while (n_holes > 0) {
61,378,206 ✔
944
    // Pop the next hole off the stack
945
    int i_hole = holes[--n_holes];
38,962,277 ✔
946
    const auto& shell {shells_[i_hole]};
38,962,277 ✔
947
    if (shell.binding_energy < E_cutoff)
38,962,277 ✔
948
      continue;
32,156,888 ✔
949

950
    // If no transitions, assume fluorescent photon from captured free electron
951
    if (shell.transitions.empty()) {
8,972,989 !
UNCOV
952
      Direction u = isotropic_direction(p.current_seed());
×
UNCOV
953
      double E = shell.binding_energy;
×
UNCOV
954
      p.create_secondary(p.wgt(), u, E, ParticleType::photon());
×
UNCOV
955
      continue;
×
UNCOV
956
    }
×
957

958
    // Sample transition
959
    double c = -prn(p.current_seed());
8,972,989 ✔
960
    int i_trans;
8,972,989 ✔
961
    for (i_trans = 0; i_trans < shell.transitions.size(); ++i_trans) {
327,930,787 !
962
      c += shell.transitions[i_trans].probability;
327,930,787 ✔
963
      if (c > 0)
327,930,787 ✔
964
        break;
965
    }
966
    const auto& transition = shell.transitions[i_trans];
8,972,989 ✔
967

968
    // Push the hole created by the electron transitioning to the photoelectron
969
    // hole onto the stack
970
    holes[n_holes++] = transition.primary_subshell;
8,972,989 ✔
971

972
    // Push the hole left by an emitted Auger electron onto the stack
973
    bool auger = transition.secondary_subshell != -1;
8,972,989 ✔
974
    if (auger)
8,972,989 ✔
975
      holes[n_holes++] = transition.secondary_subshell;
7,573,359 ✔
976

977
    if (transition.energy < E_cutoff)
8,972,989 ✔
978
      continue;
2,167,600 ✔
979

980
    // Sample angle isotropically
981
    Direction u = isotropic_direction(p.current_seed());
6,805,389 ✔
982

983
    if (auger) {
6,805,389 ✔
984
      // Non-radiative transition -- process Auger/Coster-Kronig electron at the
985
      // photon collision site
986
      process_charged_secondary(
5,407,193 ✔
987
        p, u, transition.energy, ParticleType::electron());
5,407,193 ✔
988
    } else {
989
      // Radiative transition -- create fluorescent photon
990
      p.create_secondary(p.wgt(), u, transition.energy, ParticleType::photon());
1,398,196 ✔
991
    }
992
  }
993
}
994

995
//==============================================================================
996
// Non-member functions
997
//==============================================================================
998

999
double detail::compton_profile_tail_integral(
10,259,616 ✔
1000
  double pz, double pz_last, double profile_last, double slope)
1001
{
1002
  return profile_last * std::expm1(slope * (pz - pz_last)) / slope;
10,259,616 ✔
1003
}
1004

1005
double detail::invert_compton_profile_tail(
2,219 ✔
1006
  double integral, double pz_last, double profile_last, double slope)
1007
{
1008
  return pz_last + std::log1p(slope * integral / profile_last) / slope;
2,219 ✔
1009
}
1010

1011
double detail::compton_energy_ratio(double alpha, double mu, double pz)
28,290,080 ✔
1012
{
1013
  if (pz == 0.0)
28,290,080 ✔
1014
    return 1.0 / (1.0 + alpha * (1.0 - mu));
7 ✔
1015

1016
  double momentum = pz / FINE_STRUCTURE;
28,290,073 ✔
1017
  double momentum_sq = momentum * momentum;
28,290,073 ✔
1018
  double f = 1.0 + alpha * (1.0 - mu);
28,290,073 ✔
1019
  double a = momentum_sq - f * f;
28,290,073 ✔
1020
  double b = 2.0 * (f - momentum_sq * mu);
28,290,073 ✔
1021
  double c = momentum_sq - 1.0;
28,290,073 ✔
1022
  double discriminant = b * b - 4.0 * a * c;
28,290,073 ✔
1023
  double discriminant_tolerance = 16.0 *
28,290,073 ✔
1024
                                  std::numeric_limits<double>::epsilon() *
1025
                                  (b * b + std::abs(4.0 * a * c));
28,290,073 !
1026
  if (discriminant < -discriminant_tolerance)
28,290,073 !
1027
    return std::numeric_limits<double>::quiet_NaN();
1028
  discriminant = std::max(0.0, discriminant);
28,290,073 ✔
1029

1030
  double root1;
28,290,073 ✔
1031
  double root2;
28,290,073 ✔
1032
  if (std::abs(a) < 1.0e-14 * (std::abs(b) + std::abs(c))) {
28,290,073 !
UNCOV
1033
    if (b == 0.0)
×
1034
      return std::numeric_limits<double>::quiet_NaN();
UNCOV
1035
    root1 = -c / b;
×
UNCOV
1036
    root2 = root1;
×
1037
  } else {
1038
    double sqrt_discriminant = std::sqrt(discriminant);
28,290,073 ✔
1039
    double q = -0.5 * (b + std::copysign(sqrt_discriminant, b));
28,290,073 ✔
1040
    root1 = q / a;
28,290,073 ✔
1041
    root2 = q == 0.0 ? (-b + sqrt_discriminant) / (2.0 * a) : c / q;
28,290,073 !
1042
  }
1043

1044
  double root_min = std::numeric_limits<double>::infinity();
28,290,073 ✔
1045
  double root_max = -std::numeric_limits<double>::infinity();
28,290,073 ✔
1046
  if (std::isfinite(root1) && root1 > 0.0) {
28,290,073 !
1047
    root_min = root1;
28,290,073 ✔
1048
    root_max = root1;
28,290,073 ✔
1049
  }
1050
  if (std::isfinite(root2) && root2 > 0.0) {
28,290,073 !
1051
    root_min = std::min(root_min, root2);
28,289,765 ✔
1052
    root_max = std::max(root_max, root2);
28,289,765 !
1053
  }
1054
  if (!std::isfinite(root_min))
28,290,073 !
1055
    return std::numeric_limits<double>::quiet_NaN();
1056

1057
  double energy_ratio = pz < 0.0 ? root_min : root_max;
28,290,073 ✔
1058
  double free_electron_ratio = 1.0 / f;
28,290,073 ✔
1059
  double tolerance = 16.0 * std::numeric_limits<double>::epsilon() *
28,290,073 ✔
1060
                     std::max(1.0, free_electron_ratio);
28,290,073 !
1061
  if ((pz < 0.0 && energy_ratio > free_electron_ratio + tolerance) ||
28,290,073 !
1062
      (pz > 0.0 && energy_ratio < free_electron_ratio - tolerance)) {
14,005,759 !
1063
    return std::numeric_limits<double>::quiet_NaN();
1064
  }
1065
  return energy_ratio;
28,290,073 ✔
1066
}
1067

1068
std::pair<double, double> klein_nishina(double alpha, uint64_t* seed)
17,608,403 ✔
1069
{
1070
  double alpha_out, mu;
17,608,403 ✔
1071
  double beta = 1.0 + 2.0 * alpha;
17,608,403 ✔
1072
  if (alpha < 3.0) {
17,608,403 ✔
1073
    // Kahn's rejection method
1074
    double t = beta / (beta + 8.0);
16,013,593 ✔
1075
    double x;
26,816,192 ✔
1076
    while (true) {
26,816,192 ✔
1077
      if (prn(seed) < t) {
26,816,192 ✔
1078
        // Left branch of flow chart
1079
        double r = uniform_distribution(0.0, 2.0, seed);
4,956,140 ✔
1080
        x = 1.0 + alpha * r;
4,956,140 ✔
1081
        if (prn(seed) < 4.0 / x * (1.0 - 1.0 / x)) {
4,956,140 ✔
1082
          mu = 1 - r;
3,178,552 ✔
1083
          break;
3,178,552 ✔
1084
        }
1085
      } else {
1086
        // Right branch of flow chart
1087
        x = beta / (1.0 + 2.0 * alpha * prn(seed));
21,860,052 ✔
1088
        mu = 1.0 + (1.0 - x) / alpha;
21,860,052 ✔
1089
        if (prn(seed) < 0.5 * (mu * mu + 1.0 / x))
21,860,052 ✔
1090
          break;
1091
      }
1092
    }
1093
    alpha_out = alpha / x;
16,013,593 ✔
1094

1095
  } else {
1096
    // Koblinger's direct method
1097
    double gamma = 1.0 - std::pow(beta, -2);
1,594,810 ✔
1098
    double s =
1,594,810 ✔
1099
      prn(seed) * (4.0 / alpha + 0.5 * gamma +
1,594,810 ✔
1100
                    (1.0 - (1.0 + beta) / (alpha * alpha)) * std::log(beta));
1,594,810 ✔
1101
    if (s <= 2.0 / alpha) {
1,594,810 ✔
1102
      // For first term, x = 1 + 2ar
1103
      // Therefore, a' = a/(1 + 2ar)
1104
      alpha_out = alpha / (1.0 + 2.0 * alpha * prn(seed));
248,332 ✔
1105
    } else if (s <= 4.0 / alpha) {
1,346,478 ✔
1106
      // For third term, x = beta/(1 + 2ar)
1107
      // Therefore, a' = a(1 + 2ar)/beta
1108
      alpha_out = alpha * (1.0 + 2.0 * alpha * prn(seed)) / beta;
248,878 ✔
1109
    } else if (s <= 4.0 / alpha + 0.5 * gamma) {
1,097,600 ✔
1110
      // For fourth term, x = 1/sqrt(1 - gamma*r)
1111
      // Therefore, a' = a*sqrt(1 - gamma*r)
1112
      alpha_out = alpha * std::sqrt(1.0 - gamma * prn(seed));
299,789 ✔
1113
    } else {
1114
      // For third term, x = beta^r
1115
      // Therefore, a' = a/beta^r
1116
      alpha_out = alpha / std::pow(beta, prn(seed));
797,811 ✔
1117
    }
1118

1119
    // Calculate cosine of scattering angle based on basic relation
1120
    mu = 1.0 + 1.0 / alpha - 1.0 / alpha_out;
1,594,810 ✔
1121
  }
1122
  return {alpha_out, mu};
17,608,403 ✔
1123
}
1124

1125
void free_memory_photon()
6,100 ✔
1126
{
1127
  data::elements.clear();
6,100 ✔
1128
  data::compton_profile_pz.resize({0});
6,100 ✔
1129
  data::ttb_e_grid.resize({0});
6,100 ✔
1130
  data::ttb_k_grid.resize({0});
6,100 ✔
1131
}
6,100 ✔
1132

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