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

openmc-dev / openmc / 15901185519

26 Jun 2025 11:57AM UTC coverage: 85.193% (-0.06%) from 85.252%
15901185519

Pull #3413

github

web-flow
Merge 3e6f15158 into 5c1021446
Pull Request #3413: More interpolation types in Tabular.

72 of 129 new or added lines in 3 files covered. (55.81%)

39 existing lines in 3 files now uncovered.

52649 of 61800 relevant lines covered (85.19%)

36544178.92 hits per line

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

71.21
/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)
11,938✔
24
{
25
  auto params = get_node_array<double>(node, "parameters");
11,938✔
26
  std::size_t n = params.size() / 2;
11,938✔
27

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

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

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

40
  this->init_alias();
64,634✔
41
}
64,634✔
42

43
void DiscreteIndex::init_alias()
64,634✔
44
{
45
  normalize();
64,634✔
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;
64,634✔
51
  vector<size_t> small;
64,634✔
52

53
  size_t n = prob_.size();
64,634✔
54

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

58
  // Fill large and small vectors based on 1/n
59
  for (size_t i = 0; i < n; i++) {
696,083✔
60
    prob_[i] *= n;
631,449✔
61
    if (prob_[i] > 1.0) {
631,449✔
62
      large.push_back(i);
90,464✔
63
    } else {
64
      small.push_back(i);
540,985✔
65
    }
66
  }
67

68
  while (!large.empty() && !small.empty()) {
557,593✔
69
    int j = small.back();
492,959✔
70
    int k = large.back();
492,959✔
71

72
    // Remove last element of small
73
    small.pop_back();
492,959✔
74

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

79
    // Move large index to small vector, if it is no longer large
80
    if (prob_[k] < 1.0) {
492,959✔
81
      small.push_back(k);
87,309✔
82
      large.pop_back();
87,309✔
83
    }
84
  }
85
}
64,634✔
86

87
size_t DiscreteIndex::sample(uint64_t* seed) const
55,735,692✔
88
{
89
  // Alias sampling of discrete distribution
90
  size_t n = prob_.size();
55,735,692✔
91
  if (n > 1) {
55,735,692✔
92
    size_t u = prn(seed) * n;
12,645,394✔
93
    if (prn(seed) < prob_[u]) {
12,645,394✔
94
      return u;
7,244,979✔
95
    } else {
96
      return alias_[u];
5,400,415✔
97
    }
98
  } else {
99
    return 0;
43,090,298✔
100
  }
101
}
102

103
void DiscreteIndex::normalize()
64,634✔
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);
64,634✔
109
  for (auto& p_i : prob_) {
696,083✔
110
    p_i /= integral_;
631,449✔
111
  }
112
}
64,634✔
113

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

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

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

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

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

130
  x_.assign(x, x + n);
45,721✔
131
}
45,721✔
132

133
double Discrete::sample(uint64_t* seed) const
54,252,922✔
134
{
135
  return x_[di_.sample(seed)];
54,252,922✔
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
9,248,154✔
215
{
216
  return watt_spectrum(a_, b_, seed);
9,248,154✔
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);
×
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)
2,702✔
244
{
245
  if (check_for_node(node, "interpolation")) {
2,702✔
246
    std::string temp = get_node_value(node, "interpolation");
2,702✔
247
    if (temp == "histogram") {
2,702✔
248
      interp_ = Interpolation::histogram;
2,638✔
249
    } else if (temp == "linear-linear") {
64✔
250
      interp_ = Interpolation::lin_lin;
64✔
NEW
251
    } else if (temp == "log-linear") {
×
NEW
252
      interp_ = Interpolation::log_lin;
×
NEW
253
    } else if (temp == "linear-log") {
×
NEW
254
      interp_ = Interpolation::lin_log;
×
NEW
255
    } else if (temp == "log-log") {
×
NEW
256
      interp_ = Interpolation::log_log;
×
257
    } else {
UNCOV
258
      openmc::fatal_error(
×
UNCOV
259
        "Unsupported interpolation type for distribution: " + temp);
×
260
    }
261
  } else {
2,702✔
UNCOV
262
    interp_ = Interpolation::histogram;
×
263
  }
264

265
  // Read and initialize tabular distribution. If number of parameters is odd,
266
  // add an extra zero for the 'p' array.
267
  auto params = get_node_array<double>(node, "parameters");
2,702✔
268
  if (params.size() % 2 != 0) {
2,702✔
UNCOV
269
    params.push_back(0.0);
×
270
  }
271
  std::size_t n = params.size() / 2;
2,702✔
272
  const double* x = params.data();
2,702✔
273
  const double* p = x + n;
2,702✔
274
  init(x, p, n);
2,702✔
275
}
2,702✔
276

277
Tabular::Tabular(const double* x, const double* p, int n, Interpolation interp,
42,251,260✔
278
  const double* c)
42,251,260✔
279
  : interp_ {interp}
42,251,260✔
280
{
281
  init(x, p, n, c);
42,251,260✔
282
}
42,251,260✔
283

284
void Tabular::init(
42,253,962✔
285
  const double* x, const double* p, std::size_t n, const double* c)
286
{
287
  // Copy x/p arrays into vectors
288
  std::copy(x, x + n, std::back_inserter(x_));
42,253,962✔
289
  std::copy(p, p + n, std::back_inserter(p_));
42,253,962✔
290

291
  // Calculate cumulative distribution function
292
  if (c) {
42,253,962✔
293
    std::copy(c, c + n, std::back_inserter(c_));
42,251,260✔
294
  } else {
295
    c_.resize(n);
2,702✔
296
    c_[0] = 0.0;
2,702✔
297
    for (int i = 1; i < n; ++i) {
35,496✔
298
      if (interp_ == Interpolation::histogram) {
32,794✔
299
        c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]);
32,666✔
300
      } else if (interp_ == Interpolation::lin_lin) {
128✔
301
        c_[i] = c_[i - 1] + 0.5 * (p_[i - 1] + p_[i]) * (x_[i] - x_[i - 1]);
128✔
NEW
302
      } else if (interp_ == Interpolation::lin_log) {
×
NEW
303
        double m = (p_[i] - p_[i - 1]) / std::log(x_[i] / x_[i - 1]);
×
NEW
304
        c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]) +
×
NEW
305
                m * (x_[i] * (std::log(x_[i] / x_[i - 1]) - 1.0) + x_[i - 1]);
×
NEW
306
      } else if (interp_ == Interpolation::log_lin) {
×
NEW
307
        double m = std::log(p_[i] / p_[i - 1]) / (x_[i] - x_[i - 1]);
×
NEW
308
        c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]) *
×
NEW
309
                              exprel(m * (x_[i] - x_[i - 1]));
×
NEW
310
      } else if (interp_ == Interpolation::log_log) {
×
NEW
311
        double m = std::log((x_[i] * p_[i]) / (x_[i - 1] * p_[i - 1])) /
×
NEW
UNCOV
312
                   std::log(x_[i] / x_[i - 1]);
×
NEW
UNCOV
313
        c_[i] = c_[i - 1] + x_[i - 1] * p_[i - 1] *
×
NEW
UNCOV
314
                              std::log(x_[i] / x_[i - 1]) *
×
NEW
UNCOV
315
                              exprel(m * std::log(x_[i] / x_[i - 1]));
×
316
      } else {
NEW
UNCOV
317
        UNREACHABLE();
×
318
      }
319
    }
320
  }
321

322
  // Normalize density and distribution functions. Note that we save the
323
  // integral of the distribution so that if it is used as part of another
324
  // distribution (e.g., Mixture), we know its relative strength.
325
  integral_ = c_[n - 1];
42,253,962✔
326
  for (int i = 0; i < n; ++i) {
597,561,200✔
327
    p_[i] = p_[i] / integral_;
555,307,238✔
328
    c_[i] = c_[i] / integral_;
555,307,238✔
329
  }
330
}
42,253,962✔
331

332
double Tabular::sample(uint64_t* seed) const
563,273,948✔
333
{
334
  // Sample value of CDF
335
  double c = prn(seed);
563,273,948✔
336

337
  // Find first CDF bin which is above the sampled value
338
  double c_i = c_[0];
563,273,948✔
339
  int i;
340
  std::size_t n = c_.size();
563,273,948✔
341
  for (i = 0; i < n - 1; ++i) {
1,963,739,347✔
342
    if (c <= c_[i + 1])
1,963,739,347✔
343
      break;
563,273,948✔
344
    c_i = c_[i + 1];
1,400,465,399✔
345
  }
346

347
  // Determine bounding PDF values
348
  double x_i = x_[i];
563,273,948✔
349
  double p_i = p_[i];
563,273,948✔
350

351
  if (interp_ == Interpolation::histogram) {
563,273,948✔
352
    // Histogram interpolation
353
    if (p_i > 0.0) {
3,409,835✔
354
      return x_i + (c - c_i) / p_i;
3,409,835✔
355
    } else {
UNCOV
356
      return x_i;
×
357
    }
358
  } else if (interp_ == Interpolation::lin_lin) {
559,864,113✔
359
    // Linear-linear interpolation
360
    double x_i1 = x_[i + 1];
559,864,113✔
361
    double p_i1 = p_[i + 1];
559,864,113✔
362

363
    double m = (p_i1 - p_i) / (x_i1 - x_i);
559,864,113✔
364
    if (m == 0.0) {
559,864,113✔
365
      return x_i + (c - c_i) / p_i;
307,252,989✔
366
    } else {
367
      return x_i +
368
             (std::sqrt(std::max(0.0, p_i * p_i + 2 * m * (c - c_i))) - p_i) /
252,611,124✔
369
               m;
252,611,124✔
370
    }
NEW
371
  } else if (interp_ == Interpolation::lin_log) {
×
372
    // Linear-Log interpolation
NEW
373
    double x_i1 = x_[i + 1];
×
NEW
374
    double p_i1 = p_[i + 1];
×
375

NEW
376
    double m = (p_i1 - p_i) / std::log(x_i1 / x_i);
×
NEW
377
    double a = p_i / m - 1;
×
NEW
378
    if (m > 0.0) {
×
NEW
379
      return x_i * ((c - c_i) / (m * x_i) + a) /
×
NEW
380
             lambert_w0(((c - c_i) / (m * x_i) + a) * std::exp(a));
×
NEW
381
    } else if (m < 0.0) {
×
NEW
382
      return x_i * ((c - c_i) / (m * x_i) + a) /
×
NEW
UNCOV
383
             lambert_wm1(((c - c_i) / (m * x_i) + a) * std::exp(a));
×
384
    } else {
NEW
UNCOV
385
      return x_i + (c - c_i) / p_i;
×
386
    }
NEW
UNCOV
387
  } else if (interp_ == Interpolation::log_lin) {
×
388
    // Log-linear interpolation
NEW
UNCOV
389
    double x_i1 = x_[i + 1];
×
NEW
390
    double p_i1 = p_[i + 1];
×
391

NEW
392
    double m = std::log(p_i1 / p_i) / (x_i1 - x_i);
×
NEW
UNCOV
393
    double f = (c - c_i) / p_i;
×
NEW
394
    return x_i + f * log1prel(m * f);
×
NEW
395
  } else if (interp_ == Interpolation::log_log) {
×
396
    // Log-Log interpolation
NEW
397
    double x_i1 = x_[i + 1];
×
NEW
398
    double p_i1 = p_[i + 1];
×
399

NEW
UNCOV
400
    double m = std::log((x_i1 * p_i1) / (x_i * p_i)) / std::log(x_i1 / x_i);
×
NEW
UNCOV
401
    double f = (c - c_i) / (p_i * x_i);
×
NEW
UNCOV
402
    return x_i * std::exp(f * log1prel(m * f));
×
403
  } else {
NEW
UNCOV
404
    UNREACHABLE();
×
405
  }
406
}
407

408
//==============================================================================
409
// Equiprobable implementation
410
//==============================================================================
411

412
double Equiprobable::sample(uint64_t* seed) const
×
413
{
414
  std::size_t n = x_.size();
×
415

UNCOV
416
  double r = prn(seed);
×
UNCOV
417
  int i = std::floor((n - 1) * r);
×
418

UNCOV
419
  double xl = x_[i];
×
UNCOV
420
  double xr = x_[i + i];
×
UNCOV
421
  return xl + ((n - 1) * r - i) * (xr - xl);
×
422
}
423

424
//==============================================================================
425
// Mixture implementation
426
//==============================================================================
427

428
Mixture::Mixture(pugi::xml_node node)
48✔
429
{
430
  double cumsum = 0.0;
48✔
431
  for (pugi::xml_node pair : node.children("pair")) {
192✔
432
    // Check that required data exists
433
    if (!pair.attribute("probability"))
144✔
UNCOV
434
      fatal_error("Mixture pair element does not have probability.");
×
435
    if (!pair.child("dist"))
144✔
UNCOV
436
      fatal_error("Mixture pair element does not have a distribution.");
×
437

438
    // cummulative sum of probabilities
439
    double p = std::stod(pair.attribute("probability").value());
144✔
440

441
    // Save cummulative probability and distribution
442
    auto dist = distribution_from_xml(pair.child("dist"));
144✔
443
    cumsum += p * dist->integral();
144✔
444

445
    distribution_.push_back(std::make_pair(cumsum, std::move(dist)));
144✔
446
  }
144✔
447

448
  // Save integral of distribution
449
  integral_ = cumsum;
48✔
450

451
  // Normalize cummulative probabilities to 1
452
  for (auto& pair : distribution_) {
192✔
453
    pair.first /= cumsum;
144✔
454
  }
455
}
48✔
456

457
double Mixture::sample(uint64_t* seed) const
3,564✔
458
{
459
  // Sample value of CDF
460
  const double p = prn(seed);
3,564✔
461

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

466
  // This should not happen. Catch it
467
  assert(it != distribution_.cend());
2,916✔
468

469
  // Sample the chosen distribution
470
  return it->second->sample(seed);
7,128✔
471
}
472

473
//==============================================================================
474
// Helper function
475
//==============================================================================
476

477
UPtrDist distribution_from_xml(pugi::xml_node node)
15,125✔
478
{
479
  if (!check_for_node(node, "type"))
15,125✔
UNCOV
480
    openmc::fatal_error("Distribution type must be specified.");
×
481

482
  // Determine type of distribution
483
  std::string type = get_node_value(node, "type", true, true);
15,125✔
484

485
  // Allocate extension of Distribution
486
  UPtrDist dist;
15,125✔
487
  if (type == "uniform") {
15,125✔
488
    dist = UPtrDist {new Uniform(node)};
256✔
489
  } else if (type == "powerlaw") {
14,869✔
490
    dist = UPtrDist {new PowerLaw(node)};
32✔
491
  } else if (type == "maxwell") {
14,837✔
492
    dist = UPtrDist {new Maxwell(node)};
64✔
493
  } else if (type == "watt") {
14,773✔
494
    dist = UPtrDist {new Watt(node)};
96✔
495
  } else if (type == "normal") {
14,677✔
UNCOV
496
    dist = UPtrDist {new Normal(node)};
×
497
  } else if (type == "discrete") {
14,677✔
498
    dist = UPtrDist {new Discrete(node)};
11,927✔
499
  } else if (type == "tabular") {
2,750✔
500
    dist = UPtrDist {new Tabular(node)};
2,702✔
501
  } else if (type == "mixture") {
48✔
502
    dist = UPtrDist {new Mixture(node)};
48✔
UNCOV
503
  } else if (type == "muir") {
×
UNCOV
504
    openmc::fatal_error(
×
505
      "'muir' distributions are now specified using the openmc.stats.muir() "
506
      "function in Python. Please regenerate your XML files.");
507
  } else {
UNCOV
508
    openmc::fatal_error("Invalid distribution type: " + type);
×
509
  }
510
  return dist;
30,250✔
511
}
15,125✔
512

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

© 2026 Coveralls, Inc