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

openmc-dev / openmc / 18537555145

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

Pull #3417

github

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

16802 of 23354 branches covered (71.94%)

Branch coverage included in aggregate %.

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

483 existing lines in 53 files now uncovered.

54134 of 63171 relevant lines covered (85.69%)

43199115.04 hits per line

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

82.61
/src/distribution.cpp
1
#include "openmc/distribution.h"
2

3
#include <algorithm> // for copy
4
#include <array>
5
#include <cmath>     // for sqrt, floor, max
6
#include <iterator>  // for back_inserter
7
#include <numeric>   // for accumulate
8
#include <stdexcept> // for runtime_error
9
#include <string>    // for string, stod
10

11
#include "openmc/error.h"
12
#include "openmc/math_functions.h"
13
#include "openmc/random_dist.h"
14
#include "openmc/random_lcg.h"
15
#include "openmc/xml_interface.h"
16

17
namespace openmc {
18

19
//==============================================================================
20
// DiscreteIndex implementation
21
//==============================================================================
22

23
DiscreteIndex::DiscreteIndex(pugi::xml_node node)
25,864✔
24
{
25
  auto params = get_node_array<double>(node, "parameters");
25,864✔
26
  std::size_t n = params.size() / 2;
25,864✔
27

28
  assign({params.data() + n, n});
25,864✔
29
}
25,864✔
30

31
DiscreteIndex::DiscreteIndex(span<const double> p)
46,940✔
32
{
33
  assign(p);
46,940✔
34
}
46,940✔
35

36
void DiscreteIndex::assign(span<const double> p)
80,981✔
37
{
38
  prob_.assign(p.begin(), p.end());
80,981✔
39

40
  this->init_alias();
80,981✔
41
}
80,981✔
42

43
void DiscreteIndex::init_alias()
80,981✔
44
{
45
  normalize();
80,981✔
46

47
  // The initialization and sampling method is based on Vose
48
  // (DOI: 10.1109/32.92917)
49
  // Vectors for large and small probabilities based on 1/n
50
  vector<size_t> large;
80,981✔
51
  vector<size_t> small;
80,981✔
52

53
  size_t n = prob_.size();
80,981✔
54

55
  // Set and allocate memory
56
  alias_.assign(n, 0);
80,981✔
57

58
  // Fill large and small vectors based on 1/n
59
  for (size_t i = 0; i < n; i++) {
1,544,811✔
60
    prob_[i] *= n;
1,463,830✔
61
    if (prob_[i] > 1.0) {
1,463,830✔
62
      large.push_back(i);
218,761✔
63
    } else {
64
      small.push_back(i);
1,245,069✔
65
    }
66
  }
67

68
  while (!large.empty() && !small.empty()) {
1,389,893✔
69
    int j = small.back();
1,308,912✔
70
    int k = large.back();
1,308,912✔
71

72
    // Remove last element of small
73
    small.pop_back();
1,308,912✔
74

75
    // Update probability and alias based on Vose's algorithm
76
    prob_[k] += prob_[j] - 1.0;
1,308,912✔
77
    alias_[j] = k;
1,308,912✔
78

79
    // Move large index to small vector, if it is no longer large
80
    if (prob_[k] < 1.0) {
1,308,912✔
81
      small.push_back(k);
211,005✔
82
      large.pop_back();
211,005✔
83
    }
84
  }
85
}
80,981✔
86

87
size_t DiscreteIndex::sample(uint64_t* seed) const
64,412,619✔
88
{
89
  // Alias sampling of discrete distribution
90
  size_t n = prob_.size();
64,412,619✔
91
  if (n > 1) {
64,412,619✔
92
    size_t u = prn(seed) * n;
14,321,912✔
93
    if (prn(seed) < prob_[u]) {
14,321,912✔
94
      return u;
8,894,255✔
95
    } else {
96
      return alias_[u];
5,427,657✔
97
    }
98
  } else {
99
    return 0;
50,090,707✔
100
  }
101
}
102

103
void DiscreteIndex::normalize()
80,981✔
104
{
105
  // Renormalize density function so that it sums to unity. Note that we save
106
  // the integral of the distribution so that if it is used as part of another
107
  // distribution (e.g., Mixture), we know its relative strength.
108
  integral_ = std::accumulate(prob_.begin(), prob_.end(), 0.0);
80,981✔
109
  for (auto& p_i : prob_) {
1,544,811✔
110
    p_i /= integral_;
1,463,830✔
111
  }
112
}
80,981✔
113

114
//==============================================================================
115
// Discrete implementation
116
//==============================================================================
117

118
Discrete::Discrete(pugi::xml_node node) : di_(node)
25,864✔
119
{
120
  auto params = get_node_array<double>(node, "parameters");
25,864✔
121

122
  std::size_t n = params.size() / 2;
25,864✔
123

124
  x_.assign(params.begin(), params.begin() + n);
25,864✔
125
}
25,864✔
126

127
Discrete::Discrete(const double* x, const double* p, size_t n) : di_({p, n})
46,940✔
128
{
129

130
  x_.assign(x, x + n);
46,940✔
131
}
46,940✔
132

133
double Discrete::sample(uint64_t* seed) const
61,255,441✔
134
{
135
  return x_[di_.sample(seed)];
61,255,441✔
136
}
137

138
//==============================================================================
139
// Uniform implementation
140
//==============================================================================
141

142
Uniform::Uniform(pugi::xml_node node)
256✔
143
{
144
  auto params = get_node_array<double>(node, "parameters");
256✔
145
  if (params.size() != 2) {
256!
146
    fatal_error("Uniform distribution must have two "
×
147
                "parameters specified.");
148
  }
149

150
  a_ = params.at(0);
256✔
151
  b_ = params.at(1);
256✔
152
}
256✔
153

154
double Uniform::sample(uint64_t* seed) const
285,116✔
155
{
156
  return a_ + prn(seed) * (b_ - a_);
285,116✔
157
}
158

159
//==============================================================================
160
// PowerLaw implementation
161
//==============================================================================
162

163
PowerLaw::PowerLaw(pugi::xml_node node)
32✔
164
{
165
  auto params = get_node_array<double>(node, "parameters");
32✔
166
  if (params.size() != 3) {
32!
167
    fatal_error("PowerLaw distribution must have three "
×
168
                "parameters specified.");
169
  }
170

171
  const double a = params.at(0);
32✔
172
  const double b = params.at(1);
32✔
173
  const double n = params.at(2);
32✔
174

175
  offset_ = std::pow(a, n + 1);
32✔
176
  span_ = std::pow(b, n + 1) - offset_;
32✔
177
  ninv_ = 1 / (n + 1);
32✔
178
}
32✔
179

180
double PowerLaw::sample(uint64_t* seed) const
2,222✔
181
{
182
  return std::pow(offset_ + prn(seed) * span_, ninv_);
2,222✔
183
}
184

185
//==============================================================================
186
// Maxwell implementation
187
//==============================================================================
188

189
Maxwell::Maxwell(pugi::xml_node node)
64✔
190
{
191
  theta_ = std::stod(get_node_value(node, "parameters"));
64✔
192
}
64✔
193

194
double Maxwell::sample(uint64_t* seed) const
3,883✔
195
{
196
  return maxwell_spectrum(theta_, seed);
3,883✔
197
}
198

199
//==============================================================================
200
// Watt implementation
201
//==============================================================================
202

203
Watt::Watt(pugi::xml_node node)
96✔
204
{
205
  auto params = get_node_array<double>(node, "parameters");
96✔
206
  if (params.size() != 2)
96!
207
    openmc::fatal_error("Watt energy distribution must have two "
×
208
                        "parameters specified.");
209

210
  a_ = params.at(0);
96✔
211
  b_ = params.at(1);
96✔
212
}
96✔
213

214
double Watt::sample(uint64_t* seed) const
11,421,433✔
215
{
216
  return watt_spectrum(a_, b_, seed);
11,421,433✔
217
}
218

219
//==============================================================================
220
// Normal implementation
221
//==============================================================================
222
Normal::Normal(pugi::xml_node node)
×
223
{
224
  auto params = get_node_array<double>(node, "parameters");
×
225
  if (params.size() != 2) {
×
226
    openmc::fatal_error("Normal energy distribution must have two "
×
227
                        "parameters specified.");
228
  }
229

230
  mean_value_ = params.at(0);
×
231
  std_dev_ = params.at(1);
×
UNCOV
232
}
×
233

234
double Normal::sample(uint64_t* seed) const
×
235
{
236
  return normal_variate(mean_value_, std_dev_, seed);
×
237
}
238

239
//==============================================================================
240
// Tabular implementation
241
//==============================================================================
242

243
Tabular::Tabular(pugi::xml_node node)
7,285✔
244
{
245
  if (check_for_node(node, "interpolation")) {
7,285!
246
    std::string temp = get_node_value(node, "interpolation");
7,285✔
247
    if (temp == "histogram") {
7,285✔
248
      interp_ = Interpolation::histogram;
7,221✔
249
    } else if (temp == "linear-linear") {
64!
250
      interp_ = Interpolation::lin_lin;
64✔
251
    } else {
252
      openmc::fatal_error(
×
253
        "Unsupported interpolation type for distribution: " + temp);
×
254
    }
255
  } else {
7,285✔
256
    interp_ = Interpolation::histogram;
×
257
  }
258

259
  // Read and initialize tabular distribution. If number of parameters is odd,
260
  // add an extra zero for the 'p' array.
261
  auto params = get_node_array<double>(node, "parameters");
7,285✔
262
  if (params.size() % 2 != 0) {
7,285!
263
    params.push_back(0.0);
×
264
  }
265
  std::size_t n = params.size() / 2;
7,285✔
266
  const double* x = params.data();
7,285✔
267
  const double* p = x + n;
7,285✔
268
  init(x, p, n);
7,285✔
269
}
7,285✔
270

271
Tabular::Tabular(const double* x, const double* p, int n, Interpolation interp,
50,802,628✔
272
  const double* c)
50,802,628✔
273
  : interp_ {interp}
50,802,628✔
274
{
275
  init(x, p, n, c);
50,802,628✔
276
}
50,802,628✔
277

278
void Tabular::init(
50,809,913✔
279
  const double* x, const double* p, std::size_t n, const double* c)
280
{
281
  // Copy x/p arrays into vectors
282
  std::copy(x, x + n, std::back_inserter(x_));
50,809,913✔
283
  std::copy(p, p + n, std::back_inserter(p_));
50,809,913✔
284

285
  // Check interpolation parameter
286
  if (interp_ != Interpolation::histogram &&
50,809,913✔
287
      interp_ != Interpolation::lin_lin) {
42,708,810!
288
    openmc::fatal_error("Only histogram and linear-linear interpolation "
×
289
                        "for tabular distribution is supported.");
290
  }
291

292
  // Calculate cumulative distribution function
293
  if (c) {
50,809,913✔
294
    std::copy(c, c + n, std::back_inserter(c_));
50,802,628✔
295
  } else {
296
    c_.resize(n);
7,285✔
297
    c_[0] = 0.0;
7,285✔
298
    for (int i = 1; i < n; ++i) {
90,492✔
299
      if (interp_ == Interpolation::histogram) {
83,207✔
300
        c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]);
83,079✔
301
      } else if (interp_ == Interpolation::lin_lin) {
128!
302
        c_[i] = c_[i - 1] + 0.5 * (p_[i - 1] + p_[i]) * (x_[i] - x_[i - 1]);
128✔
303
      }
304
    }
305
  }
306

307
  // Normalize density and distribution functions. Note that we save the
308
  // integral of the distribution so that if it is used as part of another
309
  // distribution (e.g., Mixture), we know its relative strength.
310
  integral_ = c_[n - 1];
50,809,913✔
311
  for (int i = 0; i < n; ++i) {
736,828,554✔
312
    p_[i] = p_[i] / integral_;
686,018,641✔
313
    c_[i] = c_[i] / integral_;
686,018,641✔
314
  }
315
}
50,809,913✔
316

317
double Tabular::sample(uint64_t* seed) const
612,207,433✔
318
{
319
  // Sample value of CDF
320
  double c = prn(seed);
612,207,433✔
321

322
  // Find first CDF bin which is above the sampled value
323
  double c_i = c_[0];
612,207,433✔
324
  int i;
325
  std::size_t n = c_.size();
612,207,433✔
326
  for (i = 0; i < n - 1; ++i) {
2,147,483,647!
327
    if (c <= c_[i + 1])
2,147,483,647✔
328
      break;
612,207,433✔
329
    c_i = c_[i + 1];
1,625,724,873✔
330
  }
331

332
  // Determine bounding PDF values
333
  double x_i = x_[i];
612,207,433✔
334
  double p_i = p_[i];
612,207,433✔
335

336
  if (interp_ == Interpolation::histogram) {
612,207,433✔
337
    // Histogram interpolation
338
    if (p_i > 0.0) {
3,421,748!
339
      return x_i + (c - c_i) / p_i;
3,421,748✔
340
    } else {
341
      return x_i;
×
342
    }
343
  } else {
344
    // Linear-linear interpolation
345
    double x_i1 = x_[i + 1];
608,785,685✔
346
    double p_i1 = p_[i + 1];
608,785,685✔
347

348
    double m = (p_i1 - p_i) / (x_i1 - x_i);
608,785,685✔
349
    if (m == 0.0) {
608,785,685✔
350
      return x_i + (c - c_i) / p_i;
316,491,886✔
351
    } else {
352
      return x_i +
353
             (std::sqrt(std::max(0.0, p_i * p_i + 2 * m * (c - c_i))) - p_i) /
292,293,799✔
354
               m;
292,293,799✔
355
    }
356
  }
357
}
358

359
//==============================================================================
360
// Equiprobable implementation
361
//==============================================================================
362

363
double Equiprobable::sample(uint64_t* seed) const
×
364
{
365
  std::size_t n = x_.size();
×
366

367
  double r = prn(seed);
×
368
  int i = std::floor((n - 1) * r);
×
369

370
  double xl = x_[i];
×
371
  double xr = x_[i + i];
×
372
  return xl + ((n - 1) * r - i) * (xr - xl);
×
373
}
374

375
//==============================================================================
376
// Mixture implementation
377
//==============================================================================
378

379
Mixture::Mixture(pugi::xml_node node)
48✔
380
{
381
  double cumsum = 0.0;
48✔
382
  for (pugi::xml_node pair : node.children("pair")) {
192✔
383
    // Check that required data exists
384
    if (!pair.attribute("probability"))
144!
385
      fatal_error("Mixture pair element does not have probability.");
×
386
    if (!pair.child("dist"))
144!
387
      fatal_error("Mixture pair element does not have a distribution.");
×
388

389
    // cummulative sum of probabilities
390
    double p = std::stod(pair.attribute("probability").value());
144✔
391

392
    // Save cummulative probability and distribution
393
    auto dist = distribution_from_xml(pair.child("dist"));
144✔
394
    cumsum += p * dist->integral();
144✔
395

396
    distribution_.push_back(std::make_pair(cumsum, std::move(dist)));
144✔
397
  }
144✔
398

399
  // Save integral of distribution
400
  integral_ = cumsum;
48✔
401

402
  // Normalize cummulative probabilities to 1
403
  for (auto& pair : distribution_) {
192✔
404
    pair.first /= cumsum;
144✔
405
  }
406
}
48✔
407

408
double Mixture::sample(uint64_t* seed) const
3,564✔
409
{
410
  // Sample value of CDF
411
  const double p = prn(seed);
3,564✔
412

413
  // find matching distribution
414
  const auto it = std::lower_bound(distribution_.cbegin(), distribution_.cend(),
3,564✔
415
    p, [](const DistPair& pair, double p) { return pair.first < p; });
7,128✔
416

417
  // This should not happen. Catch it
418
  assert(it != distribution_.cend());
2,916!
419

420
  // Sample the chosen distribution
421
  return it->second->sample(seed);
7,128✔
422
}
423

424
//==============================================================================
425
// Helper function
426
//==============================================================================
427

428
UPtrDist distribution_from_xml(pugi::xml_node node)
33,634✔
429
{
430
  if (!check_for_node(node, "type"))
33,634!
431
    openmc::fatal_error("Distribution type must be specified.");
×
432

433
  // Determine type of distribution
434
  std::string type = get_node_value(node, "type", true, true);
33,634✔
435

436
  // Allocate extension of Distribution
437
  UPtrDist dist;
33,634✔
438
  if (type == "uniform") {
33,634✔
439
    dist = UPtrDist {new Uniform(node)};
256✔
440
  } else if (type == "powerlaw") {
33,378✔
441
    dist = UPtrDist {new PowerLaw(node)};
32✔
442
  } else if (type == "maxwell") {
33,346✔
443
    dist = UPtrDist {new Maxwell(node)};
64✔
444
  } else if (type == "watt") {
33,282✔
445
    dist = UPtrDist {new Watt(node)};
96✔
446
  } else if (type == "normal") {
33,186!
447
    dist = UPtrDist {new Normal(node)};
×
448
  } else if (type == "discrete") {
33,186✔
449
    dist = UPtrDist {new Discrete(node)};
25,853✔
450
  } else if (type == "tabular") {
7,333✔
451
    dist = UPtrDist {new Tabular(node)};
7,285✔
452
  } else if (type == "mixture") {
48!
453
    dist = UPtrDist {new Mixture(node)};
48✔
454
  } else if (type == "muir") {
×
455
    openmc::fatal_error(
×
456
      "'muir' distributions are now specified using the openmc.stats.muir() "
457
      "function in Python. Please regenerate your XML files.");
458
  } else {
459
    openmc::fatal_error("Invalid distribution type: " + type);
×
460
  }
461
  return dist;
67,268✔
462
}
33,634✔
463

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