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

openmc-dev / openmc / 13952790711

19 Mar 2025 05:22PM UTC coverage: 85.123% (+0.3%) from 84.851%
13952790711

Pull #3279

github

web-flow
Merge b9073ecb5 into e23760b02
Pull Request #3279: Hexagonal mesh model

51566 of 60578 relevant lines covered (85.12%)

36894230.49 hits per line

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

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

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

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

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

40
  this->init_alias();
63,113✔
41
}
63,113✔
42

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

53
  size_t n = prob_.size();
63,113✔
54

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

58
  // Fill large and small vectors based on 1/n
59
  for (size_t i = 0; i < n; i++) {
660,413✔
60
    prob_[i] *= n;
597,300✔
61
    if (prob_[i] > 1.0) {
597,300✔
62
      large.push_back(i);
85,381✔
63
    } else {
64
      small.push_back(i);
511,919✔
65
    }
66
  }
67

68
  while (!large.empty() && !small.empty()) {
525,455✔
69
    int j = small.back();
462,342✔
70
    int k = large.back();
462,342✔
71

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

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

79
    // Move large index to small vector, if it is no longer large
80
    if (prob_[k] < 1.0) {
462,342✔
81
      small.push_back(k);
82,424✔
82
      large.pop_back();
82,424✔
83
    }
84
  }
85
}
63,113✔
86

87
size_t DiscreteIndex::sample(uint64_t* seed) const
55,402,418✔
88
{
89
  // Alias sampling of discrete distribution
90
  size_t n = prob_.size();
55,402,418✔
91
  if (n > 1) {
55,402,418✔
92
    size_t u = prn(seed) * n;
12,544,634✔
93
    if (prn(seed) < prob_[u]) {
12,544,634✔
94
      return u;
7,144,462✔
95
    } else {
96
      return alias_[u];
5,400,172✔
97
    }
98
  } else {
99
    return 0;
42,857,784✔
100
  }
101
}
102

103
void DiscreteIndex::normalize()
63,113✔
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);
63,113✔
109
  for (auto& p_i : prob_) {
660,413✔
110
    p_i /= integral_;
597,300✔
111
  }
112
}
63,113✔
113

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

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

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

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

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

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

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

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

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

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

154
double Uniform::sample(uint64_t* seed) const
285,006✔
155
{
156
  return a_ + prn(seed) * (b_ - a_);
285,006✔
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,161,434✔
215
{
216
  return watt_spectrum(a_, b_, seed);
9,161,434✔
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,535✔
244
{
245
  if (check_for_node(node, "interpolation")) {
2,535✔
246
    std::string temp = get_node_value(node, "interpolation");
2,535✔
247
    if (temp == "histogram") {
2,535✔
248
      interp_ = Interpolation::histogram;
2,471✔
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 {
2,535✔
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");
2,535✔
262
  if (params.size() % 2 != 0) {
2,535✔
263
    params.push_back(0.0);
×
264
  }
265
  std::size_t n = params.size() / 2;
2,535✔
266
  const double* x = params.data();
2,535✔
267
  const double* p = x + n;
2,535✔
268
  init(x, p, n);
2,535✔
269
}
2,535✔
270

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

278
void Tabular::init(
40,198,726✔
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_));
40,198,726✔
283
  std::copy(p, p + n, std::back_inserter(p_));
40,198,726✔
284

285
  // Check interpolation parameter
286
  if (interp_ != Interpolation::histogram &&
40,198,726✔
287
      interp_ != Interpolation::lin_lin) {
33,707,353✔
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) {
40,198,726✔
294
    std::copy(c, c + n, std::back_inserter(c_));
40,196,191✔
295
  } else {
296
    c_.resize(n);
2,535✔
297
    c_[0] = 0.0;
2,535✔
298
    for (int i = 1; i < n; ++i) {
33,492✔
299
      if (interp_ == Interpolation::histogram) {
30,957✔
300
        c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]);
30,829✔
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];
40,198,726✔
311
  for (int i = 0; i < n; ++i) {
570,695,434✔
312
    p_[i] = p_[i] / integral_;
530,496,708✔
313
    c_[i] = c_[i] / integral_;
530,496,708✔
314
  }
315
}
40,198,726✔
316

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

322
  // Find first CDF bin which is above the sampled value
323
  double c_i = c_[0];
533,949,447✔
324
  int i;
325
  std::size_t n = c_.size();
533,949,447✔
326
  for (i = 0; i < n - 1; ++i) {
1,853,247,730✔
327
    if (c <= c_[i + 1])
1,853,247,730✔
328
      break;
533,949,447✔
329
    c_i = c_[i + 1];
1,319,298,283✔
330
  }
331

332
  // Determine bounding PDF values
333
  double x_i = x_[i];
533,949,447✔
334
  double p_i = p_[i];
533,949,447✔
335

336
  if (interp_ == Interpolation::histogram) {
533,949,447✔
337
    // Histogram interpolation
338
    if (p_i > 0.0) {
3,423,882✔
339
      return x_i + (c - c_i) / p_i;
3,423,882✔
340
    } else {
341
      return x_i;
×
342
    }
343
  } else {
344
    // Linear-linear interpolation
345
    double x_i1 = x_[i + 1];
530,525,565✔
346
    double p_i1 = p_[i + 1];
530,525,565✔
347

348
    double m = (p_i1 - p_i) / (x_i1 - x_i);
530,525,565✔
349
    if (m == 0.0) {
530,525,565✔
350
      return x_i + (c - c_i) / p_i;
298,300,921✔
351
    } else {
352
      return x_i +
353
             (std::sqrt(std::max(0.0, p_i * p_i + 2 * m * (c - c_i))) - p_i) /
232,224,644✔
354
               m;
232,224,644✔
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)
14,298✔
429
{
430
  if (!check_for_node(node, "type"))
14,298✔
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);
14,298✔
435

436
  // Allocate extension of Distribution
437
  UPtrDist dist;
14,298✔
438
  if (type == "uniform") {
14,298✔
439
    dist = UPtrDist {new Uniform(node)};
245✔
440
  } else if (type == "powerlaw") {
14,053✔
441
    dist = UPtrDist {new PowerLaw(node)};
32✔
442
  } else if (type == "maxwell") {
14,021✔
443
    dist = UPtrDist {new Maxwell(node)};
64✔
444
  } else if (type == "watt") {
13,957✔
445
    dist = UPtrDist {new Watt(node)};
96✔
446
  } else if (type == "normal") {
13,861✔
447
    dist = UPtrDist {new Normal(node)};
×
448
  } else if (type == "discrete") {
13,861✔
449
    dist = UPtrDist {new Discrete(node)};
11,278✔
450
  } else if (type == "tabular") {
2,583✔
451
    dist = UPtrDist {new Tabular(node)};
2,535✔
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;
28,596✔
462
}
14,298✔
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

© 2026 Coveralls, Inc