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

openmc-dev / openmc / 21979737004

13 Feb 2026 08:19AM UTC coverage: 81.451% (-0.4%) from 81.851%
21979737004

Pull #3801

github

web-flow
Merge a4595d510 into bcb939520
Pull Request #3801: avoid need to set particles and batches for dagmc models when calling convert_to_multigroup

16960 of 23616 branches covered (71.82%)

Branch coverage included in aggregate %.

0 of 1 new or added line in 1 file covered. (0.0%)

908 existing lines in 38 files now uncovered.

55950 of 65898 relevant lines covered (84.9%)

36199990.53 hits per line

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

72.28
/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/constants.h"
12
#include "openmc/error.h"
13
#include "openmc/math_functions.h"
14
#include "openmc/random_dist.h"
15
#include "openmc/random_lcg.h"
16
#include "openmc/xml_interface.h"
17

18
namespace openmc {
19

20
//==============================================================================
21
// Helper function for computing importance weights from biased sampling
22
//==============================================================================
23

24
vector<double> compute_importance_weights(
7 ✔
25
  const vector<double>& p, const vector<double>& b)
26
{
27
  std::size_t n = p.size();
7 ✔
28

29
  // Normalize original probabilities
30
  double sum_p = std::accumulate(p.begin(), p.end(), 0.0);
7 ✔
31
  vector<double> p_norm(n);
7 ✔
32
  for (std::size_t i = 0; i < n; ++i) {
28 ✔
33
    p_norm[i] = p[i] / sum_p;
21 ✔
34
  }
35

36
  // Normalize bias probabilities
37
  double sum_b = std::accumulate(b.begin(), b.end(), 0.0);
7 ✔
38
  vector<double> b_norm(n);
7 ✔
39
  for (std::size_t i = 0; i < n; ++i) {
28 ✔
40
    b_norm[i] = b[i] / sum_b;
21 ✔
41
  }
42

43
  // Compute importance weights
44
  vector<double> weights(n);
7 ✔
45
  for (std::size_t i = 0; i < n; ++i) {
28 ✔
46
    weights[i] = (b_norm[i] == 0.0) ? INFTY : p_norm[i] / b_norm[i];
21 !
47
  }
48
  return weights;
14 ✔
49
}
7 ✔
50

51
std::pair<double, double> Distribution::sample(uint64_t* seed) const
543,348,485 ✔
52
{
53
  if (bias_) {
543,348,485 ✔
54
    // Sample from the bias distribution and compute importance weight
55
    double val = bias_->sample_unbiased(seed);
455,019 ✔
56
    double wgt = this->evaluate(val) / bias_->evaluate(val);
455,019 ✔
57
    return {val, wgt};
455,019 ✔
58
  } else {
59
    // Unbiased sampling: return sampled value with weight 1.0
60
    double val = sample_unbiased(seed);
542,893,466 ✔
61
    return {val, 1.0};
542,893,466 ✔
62
  }
63
}
64

65
// PDF evaluation not supported for all distribution types
66
double Distribution::evaluate(double x) const
×
67
{
68
  throw std::runtime_error(
×
69
    "PDF evaluation not implemented for this distribution type.");
×
70
}
71

72
void Distribution::read_bias_from_xml(pugi::xml_node node)
5,449 ✔
73
{
74
  if (check_for_node(node, "bias")) {
5,449 ✔
75
    pugi::xml_node bias_node = node.child("bias");
49 ✔
76

77
    if (check_for_node(bias_node, "bias")) {
49 !
78
      openmc::fatal_error(
×
79
        "Distribution has a bias distribution with its own bias distribution. "
80
        "Please ensure bias distributions do not have their own bias.");
81
    }
82

83
    UPtrDist bias = distribution_from_xml(bias_node);
49 ✔
84
    this->set_bias(std::move(bias));
49 ✔
85
  }
49 ✔
86
}
5,449 ✔
87

88
//==============================================================================
89
// DiscreteIndex implementation
90
//==============================================================================
91

92
DiscreteIndex::DiscreteIndex(pugi::xml_node node)
×
93
{
94
  auto params = get_node_array<double>(node, "parameters");
×
95
  std::size_t n = params.size() / 2;
×
96

97
  assign({params.data() + n, n});
×
98
}
×
99

100
DiscreteIndex::DiscreteIndex(span<const double> p)
19,401 ✔
101
{
102
  assign(p);
19,401 ✔
103
}
19,401 ✔
104

105
void DiscreteIndex::assign(span<const double> p)
42,497 ✔
106
{
107
  prob_.assign(p.begin(), p.end());
42,497 ✔
108
  this->init_alias();
42,497 ✔
109
}
42,497 ✔
110

111
void DiscreteIndex::init_alias()
42,497 ✔
112
{
113
  normalize();
42,497 ✔
114

115
  // The initialization and sampling method is based on Vose
116
  // (DOI: 10.1109/32.92917)
117
  // Vectors for large and small probabilities based on 1/n
118
  vector<size_t> large;
42,497 ✔
119
  vector<size_t> small;
42,497 ✔
120

121
  size_t n = prob_.size();
42,497 ✔
122

123
  // Set and allocate memory
124
  alias_.assign(n, 0);
42,497 ✔
125

126
  // Fill large and small vectors based on 1/n
127
  for (size_t i = 0; i < n; i++) {
999,740 ✔
128
    prob_[i] *= n;
957,243 ✔
129
    if (prob_[i] > 1.0) {
957,243 ✔
130
      large.push_back(i);
144,470 ✔
131
    } else {
132
      small.push_back(i);
812,773 ✔
133
    }
134
  }
135

136
  while (!large.empty() && !small.empty()) {
931,591 ✔
137
    int j = small.back();
889,094 ✔
138
    int k = large.back();
889,094 ✔
139

140
    // Remove last element of small
141
    small.pop_back();
889,094 ✔
142

143
    // Update probability and alias based on Vose's algorithm
144
    prob_[k] += prob_[j] - 1.0;
889,094 ✔
145
    alias_[j] = k;
889,094 ✔
146

147
    // Move large index to small vector, if it is no longer large
148
    if (prob_[k] < 1.0) {
889,094 ✔
149
      small.push_back(k);
138,969 ✔
150
      large.pop_back();
138,969 ✔
151
    }
152
  }
153
}
42,497 ✔
154

155
size_t DiscreteIndex::sample(uint64_t* seed) const
43,556,579 ✔
156
{
157
  // Alias sampling of discrete distribution
158
  size_t n = prob_.size();
43,556,579 ✔
159
  if (n > 1) {
43,556,579 ✔
160
    size_t u = prn(seed) * n;
11,118,737 ✔
161
    if (prn(seed) < prob_[u]) {
11,118,737 ✔
162
      return u;
6,565,897 ✔
163
    } else {
164
      return alias_[u];
4,552,840 ✔
165
    }
166
  } else {
167
    return 0;
32,437,842 ✔
168
  }
169
}
170

171
void DiscreteIndex::normalize()
42,497 ✔
172
{
173
  // Renormalize density function so that it sums to unity. Note that we save
174
  // the integral of the distribution so that if it is used as part of another
175
  // distribution (e.g., Mixture), we know its relative strength.
176
  integral_ = std::accumulate(prob_.begin(), prob_.end(), 0.0);
42,497 ✔
177
  for (auto& p_i : prob_) {
999,740 ✔
178
    p_i /= integral_;
957,243 ✔
179
  }
180
}
42,497 ✔
181

182
//==============================================================================
183
// Discrete implementation
184
//==============================================================================
185

186
Discrete::Discrete(pugi::xml_node node)
17,696 ✔
187
{
188
  auto params = get_node_array<double>(node, "parameters");
17,696 ✔
189
  std::size_t n = params.size() / 2;
17,696 ✔
190

191
  // First half is x values, second half is probabilities
192
  x_.assign(params.begin(), params.begin() + n);
17,696 ✔
193
  const double* p = params.data() + n;
17,696 ✔
194

195
  // Check for bias
196
  if (check_for_node(node, "bias")) {
17,696 ✔
197
    // Get bias probabilities
198
    auto bias_params = get_node_array<double>(node, "bias");
7 ✔
199
    if (bias_params.size() != n) {
7 !
200
      openmc::fatal_error(
×
201
        "Size mismatch: Attempted to bias Discrete distribution with " +
×
202
        std::to_string(n) + " probability entries using a bias with " +
×
203
        std::to_string(bias_params.size()) +
×
204
        " entries. Please ensure distributions have the same size.");
205
    }
206

207
    // Compute importance weights
208
    vector<double> p_vec(p, p + n);
7 ✔
209
    weight_ = compute_importance_weights(p_vec, bias_params);
7 ✔
210

211
    // Initialize DiscreteIndex with bias probabilities for sampling
212
    di_.assign(bias_params);
7 ✔
213
  } else {
7 ✔
214
    // Unbiased case: weight_ stays empty
215
    di_.assign({p, n});
17,689 ✔
216
  }
217
}
17,696 ✔
218

219
Discrete::Discrete(const double* x, const double* p, size_t n) : di_({p, n})
19,401 ✔
220
{
221
  x_.assign(x, x + n);
19,401 ✔
222
}
19,401 ✔
223

224
std::pair<double, double> Discrete::sample(uint64_t* seed) const
39,636,082 ✔
225
{
226
  size_t idx = di_.sample(seed);
39,636,082 ✔
227
  double wgt = weight_.empty() ? 1.0 : weight_[idx];
39,636,082 ✔
228
  return {x_[idx], wgt};
39,636,082 ✔
229
}
230

231
double Discrete::sample_unbiased(uint64_t* seed) const
×
232
{
233
  size_t idx = di_.sample(seed);
×
234
  return x_[idx];
×
235
}
236

237
//==============================================================================
238
// Uniform implementation
239
//==============================================================================
240

241
Uniform::Uniform(pugi::xml_node node)
207 ✔
242
{
243
  auto params = get_node_array<double>(node, "parameters");
207 ✔
244
  if (params.size() != 2) {
207 !
245
    fatal_error("Uniform distribution must have two "
×
246
                "parameters specified.");
247
  }
248

249
  a_ = params.at(0);
207 ✔
250
  b_ = params.at(1);
207 ✔
251

252
  read_bias_from_xml(node);
207 ✔
253
}
207 ✔
254

255
double Uniform::sample_unbiased(uint64_t* seed) const
432,356 ✔
256
{
257
  return a_ + prn(seed) * (b_ - a_);
432,356 ✔
258
}
259

260
double Uniform::evaluate(double x) const
245,019 ✔
261
{
262
  if (x <= a()) {
245,019 !
263
    return 0.0;
×
264
  } else if (x >= b()) {
245,019 !
265
    return 0.0;
×
266
  } else {
267
    return 1 / (b() - a());
245,019 ✔
268
  }
269
}
270

271
//==============================================================================
272
// PowerLaw implementation
273
//==============================================================================
274

275
PowerLaw::PowerLaw(pugi::xml_node node)
48 ✔
276
{
277
  auto params = get_node_array<double>(node, "parameters");
48 ✔
278
  if (params.size() != 3) {
48 !
279
    fatal_error("PowerLaw distribution must have three "
×
280
                "parameters specified.");
281
  }
282

283
  const double a = params.at(0);
48 ✔
284
  const double b = params.at(1);
48 ✔
285
  const double n = params.at(2);
48 ✔
286

287
  offset_ = std::pow(a, n + 1);
48 ✔
288
  span_ = std::pow(b, n + 1) - offset_;
48 ✔
289
  ninv_ = 1 / (n + 1);
48 ✔
290

291
  read_bias_from_xml(node);
48 ✔
292
}
48 ✔
293

294
double PowerLaw::evaluate(double x) const
175,019 ✔
295
{
296
  if (x <= a()) {
175,019 !
297
    return 0.0;
×
298
  } else if (x >= b()) {
175,019 !
299
    return 0.0;
×
300
  } else {
301
    int pwr = n() + 1;
175,019 ✔
302
    double norm = pwr / span_;
175,019 ✔
303
    return norm * std::pow(std::fabs(x), n());
175,019 ✔
304
  }
305
}
306

307
double PowerLaw::sample_unbiased(uint64_t* seed) const
176,433 ✔
308
{
309
  return std::pow(offset_ + prn(seed) * span_, ninv_);
176,433 ✔
310
}
311

312
//==============================================================================
313
// Maxwell implementation
314
//==============================================================================
315

316
Maxwell::Maxwell(pugi::xml_node node)
61 ✔
317
{
318
  theta_ = std::stod(get_node_value(node, "parameters"));
61 ✔
319

320
  read_bias_from_xml(node);
61 ✔
321
}
61 ✔
322

323
double Maxwell::sample_unbiased(uint64_t* seed) const
142,464 ✔
324
{
325
  return maxwell_spectrum(theta_, seed);
142,464 ✔
326
}
327

328
double Maxwell::evaluate(double x) const
140,000 ✔
329
{
330
  double c = (2.0 / SQRT_PI) * std::pow(theta_, -1.5);
140,000 ✔
331
  return c * std::sqrt(x) * std::exp(-x / theta_);
140,000 ✔
332
}
333

334
//==============================================================================
335
// Watt implementation
336
//==============================================================================
337

338
Watt::Watt(pugi::xml_node node)
81 ✔
339
{
340
  auto params = get_node_array<double>(node, "parameters");
81 ✔
341
  if (params.size() != 2)
81 !
342
    openmc::fatal_error("Watt energy distribution must have two "
×
343
                        "parameters specified.");
344

345
  a_ = params.at(0);
81 ✔
346
  b_ = params.at(1);
81 ✔
347

348
  read_bias_from_xml(node);
81 ✔
349
}
81 ✔
350

351
double Watt::sample_unbiased(uint64_t* seed) const
9,054,016 ✔
352
{
353
  return watt_spectrum(a_, b_, seed);
9,054,016 ✔
354
}
355

356
double Watt::evaluate(double x) const
140,000 ✔
357
{
358
  double c =
359
    2.0 / (std::sqrt(PI * b_) * std::pow(a_, 1.5) * std::exp(a_ * b_ / 4.0));
140,000 ✔
360
  return c * std::exp(-x / a_) * std::sinh(std::sqrt(b_ * x));
140,000 ✔
361
}
362

363
//==============================================================================
364
// Normal implementation
365
//==============================================================================
366

367
Normal::Normal(double mean_value, double std_dev, double lower, double upper)
42 ✔
368
  : mean_value_ {mean_value}, std_dev_ {std_dev}, lower_ {lower}, upper_ {upper}
42 ✔
369
{
370
  compute_normalization();
42 ✔
371
}
42 ✔
372

373
Normal::Normal(pugi::xml_node node)
28 ✔
374
{
375
  auto params = get_node_array<double>(node, "parameters");
28 ✔
376
  if (params.size() != 2 && params.size() != 4) {
28 !
UNCOV
377
    openmc::fatal_error("Normal energy distribution must have two "
×
378
                        "parameters (mean, std_dev) or four parameters "
379
                        "(mean, std_dev, lower, upper) specified.");
380
  }
381

382
  mean_value_ = params.at(0);
28 ✔
383
  std_dev_ = params.at(1);
28 ✔
384

385
  // Optional truncation bounds
386
  if (params.size() == 4) {
28 ✔
387
    lower_ = params.at(2);
7 ✔
388
    upper_ = params.at(3);
7 ✔
389
  } else {
390
    lower_ = -INFTY;
21 ✔
391
    upper_ = INFTY;
21 ✔
392
  }
393

394
  compute_normalization();
28 ✔
395
  read_bias_from_xml(node);
28 ✔
396
}
28 ✔
397

398
void Normal::compute_normalization()
70 ✔
399
{
400
  // Validate bounds
401
  if (lower_ >= upper_) {
70 !
UNCOV
402
    openmc::fatal_error(
×
403
      "Normal distribution lower bound must be less than upper bound.");
404
  }
405

406
  // Check if truncation bounds are finite
407
  is_truncated_ = (lower_ > -INFTY || upper_ < INFTY);
70 ✔
408

409
  if (is_truncated_) {
70 ✔
410
    double alpha = (lower_ - mean_value_) / std_dev_;
35 ✔
411
    double beta = (upper_ - mean_value_) / std_dev_;
35 ✔
412
    double cdf_diff = standard_normal_cdf(beta) - standard_normal_cdf(alpha);
35 ✔
413

414
    if (cdf_diff <= 0.0) {
35 !
UNCOV
415
      openmc::fatal_error(
×
416
        "Normal distribution truncation bounds exclude entire distribution.");
417
    }
418
    norm_factor_ = 1.0 / cdf_diff;
35 ✔
419
  } else {
420
    norm_factor_ = 1.0;
35 ✔
421
  }
422
}
70 ✔
423

424
double Normal::sample_unbiased(uint64_t* seed) const
210,000 ✔
425
{
426
  if (!is_truncated_) {
210,000 ✔
427
    return normal_variate(mean_value_, std_dev_, seed);
140,000 ✔
428
  }
429

430
  // Rejection sampling for truncated normal
431
  double x;
432
  do {
433
    x = normal_variate(mean_value_, std_dev_, seed);
102,613 ✔
434
  } while (x < lower_ || x > upper_);
102,613 ✔
435
  return x;
70,000 ✔
436
}
437

438
double Normal::evaluate(double x) const
140,077 ✔
439
{
440
  // Return 0 outside truncation bounds
441
  if (x < lower_ || x > upper_) {
140,077 ✔
442
    return 0.0;
28 ✔
443
  }
444

445
  // Standard normal PDF value
446
  double pdf = (1.0 / (std::sqrt(2.0 * PI) * std_dev_)) *
140,049 ✔
447
               std::exp(-std::pow((x - mean_value_), 2.0) /
140,049 ✔
448
                        (2.0 * std::pow(std_dev_, 2.0)));
140,049 ✔
449

450
  // Apply normalization for truncation
451
  return pdf * norm_factor_;
140,049 ✔
452
}
453

454
//==============================================================================
455
// Tabular implementation
456
//==============================================================================
457

458
Tabular::Tabular(pugi::xml_node node)
5,024 ✔
459
{
460
  if (check_for_node(node, "interpolation")) {
5,024 !
461
    std::string temp = get_node_value(node, "interpolation");
5,024 ✔
462
    if (temp == "histogram") {
5,024 ✔
463
      interp_ = Interpolation::histogram;
4,970 ✔
464
    } else if (temp == "linear-linear") {
54 !
465
      interp_ = Interpolation::lin_lin;
54 ✔
466
    } else if (temp == "log-linear") {
×
UNCOV
467
      interp_ = Interpolation::log_lin;
×
UNCOV
468
    } else if (temp == "log-log") {
×
UNCOV
469
      interp_ = Interpolation::log_log;
×
470
    } else {
UNCOV
471
      openmc::fatal_error(
×
UNCOV
472
        "Unsupported interpolation type for distribution: " + temp);
×
473
    }
474
  } else {
5,024 ✔
UNCOV
475
    interp_ = Interpolation::histogram;
×
476
  }
477

478
  // Read and initialize tabular distribution. If number of parameters is odd,
479
  // add an extra zero for the 'p' array.
480
  auto params = get_node_array<double>(node, "parameters");
5,024 ✔
481
  if (params.size() % 2 != 0) {
5,024 !
UNCOV
482
    params.push_back(0.0);
×
483
  }
484
  std::size_t n = params.size() / 2;
5,024 ✔
485
  const double* x = params.data();
5,024 ✔
486
  const double* p = x + n;
5,024 ✔
487
  init(x, p, n);
5,024 ✔
488

489
  read_bias_from_xml(node);
5,024 ✔
490
}
5,024 ✔
491

492
Tabular::Tabular(const double* x, const double* p, int n, Interpolation interp,
30,819,227 ✔
493
  const double* c)
30,819,227 ✔
494
  : interp_ {interp}
30,819,227 ✔
495
{
496
  init(x, p, n, c);
30,819,227 ✔
497
}
30,819,227 ✔
498

499
void Tabular::init(
30,824,251 ✔
500
  const double* x, const double* p, std::size_t n, const double* c)
501
{
502
  // Copy x/p arrays into vectors
503
  std::copy(x, x + n, std::back_inserter(x_));
30,824,251 ✔
504
  std::copy(p, p + n, std::back_inserter(p_));
30,824,251 ✔
505

506
  // Calculate cumulative distribution function
507
  if (c) {
30,824,251 ✔
508
    std::copy(c, c + n, std::back_inserter(c_));
30,819,227 ✔
509
  } else {
510
    c_.resize(n);
5,024 ✔
511
    c_[0] = 0.0;
5,024 ✔
512
    for (int i = 1; i < n; ++i) {
62,096 ✔
513
      if (interp_ == Interpolation::histogram) {
57,072 ✔
514
        c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]);
56,950 ✔
515
      } else if (interp_ == Interpolation::lin_lin) {
122 !
516
        c_[i] = c_[i - 1] + 0.5 * (p_[i - 1] + p_[i]) * (x_[i] - x_[i - 1]);
122 ✔
UNCOV
517
      } else if (interp_ == Interpolation::log_lin) {
×
UNCOV
518
        double m = std::log(p_[i] / p_[i - 1]) / (x_[i] - x_[i - 1]);
×
UNCOV
519
        c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]) *
×
520
                              exprel(m * (x_[i] - x_[i - 1]));
×
UNCOV
521
      } else if (interp_ == Interpolation::log_log) {
×
522
        double m = std::log((x_[i] * p_[i]) / (x_[i - 1] * p_[i - 1])) /
×
523
                   std::log(x_[i] / x_[i - 1]);
×
UNCOV
524
        c_[i] = c_[i - 1] + x_[i - 1] * p_[i - 1] *
×
525
                              std::log(x_[i] / x_[i - 1]) *
×
526
                              exprel(m * std::log(x_[i] / x_[i - 1]));
×
527
      } else {
528
        UNREACHABLE();
×
529
      }
530
    }
531
  }
532

533
  // Normalize density and distribution functions. Note that we save the
534
  // integral of the distribution so that if it is used as part of another
535
  // distribution (e.g., Mixture), we know its relative strength.
536
  integral_ = c_[n - 1];
30,824,251 ✔
537
  for (int i = 0; i < n; ++i) {
442,511,356 ✔
538
    p_[i] = p_[i] / integral_;
411,687,105 ✔
539
    c_[i] = c_[i] / integral_;
411,687,105 ✔
540
  }
541
}
30,824,251 ✔
542

543
double Tabular::sample_unbiased(uint64_t* seed) const
533,333,216 ✔
544
{
545
  // Sample value of CDF
546
  double c = prn(seed);
533,333,216 ✔
547

548
  // Find first CDF bin which is above the sampled value
549
  double c_i = c_[0];
533,333,216 ✔
550
  int i;
551
  std::size_t n = c_.size();
533,333,216 ✔
552
  for (i = 0; i < n - 1; ++i) {
2,007,088,560 !
553
    if (c <= c_[i + 1])
2,007,088,560 ✔
554
      break;
533,333,216 ✔
555
    c_i = c_[i + 1];
1,473,755,344 ✔
556
  }
557

558
  // Determine bounding PDF values
559
  double x_i = x_[i];
533,333,216 ✔
560
  double p_i = p_[i];
533,333,216 ✔
561

562
  if (interp_ == Interpolation::histogram) {
533,333,216 ✔
563
    // Histogram interpolation
564
    if (p_i > 0.0) {
2,170,399 !
565
      return x_i + (c - c_i) / p_i;
2,170,399 ✔
566
    } else {
UNCOV
567
      return x_i;
×
568
    }
569
  } else if (interp_ == Interpolation::lin_lin) {
531,162,817 !
570
    // Linear-linear interpolation
571
    double x_i1 = x_[i + 1];
531,162,817 ✔
572
    double p_i1 = p_[i + 1];
531,162,817 ✔
573

574
    double m = (p_i1 - p_i) / (x_i1 - x_i);
531,162,817 ✔
575
    if (m == 0.0) {
531,162,817 ✔
576
      return x_i + (c - c_i) / p_i;
214,217,615 ✔
577
    } else {
578
      return x_i +
579
             (std::sqrt(std::max(0.0, p_i * p_i + 2 * m * (c - c_i))) - p_i) /
316,945,202 ✔
580
               m;
316,945,202 ✔
581
    }
582
  } else if (interp_ == Interpolation::log_lin) {
×
583
    // Log-linear interpolation
UNCOV
584
    double x_i1 = x_[i + 1];
×
585
    double p_i1 = p_[i + 1];
×
586

587
    double m = std::log(p_i1 / p_i) / (x_i1 - x_i);
×
588
    double f = (c - c_i) / p_i;
×
UNCOV
589
    return x_i + f * log1prel(m * f);
×
590
  } else if (interp_ == Interpolation::log_log) {
×
591
    // Log-Log interpolation
UNCOV
592
    double x_i1 = x_[i + 1];
×
593
    double p_i1 = p_[i + 1];
×
594

UNCOV
595
    double m = std::log((x_i1 * p_i1) / (x_i * p_i)) / std::log(x_i1 / x_i);
×
UNCOV
596
    double f = (c - c_i) / (p_i * x_i);
×
UNCOV
597
    return x_i * std::exp(f * log1prel(m * f));
×
598
  } else {
UNCOV
599
    UNREACHABLE();
×
600
  }
601
}
602

603
double Tabular::evaluate(double x) const
70,000 ✔
604
{
605
  int i;
606

607
  if (interp_ == Interpolation::histogram) {
70,000 !
UNCOV
608
    i = std::upper_bound(x_.begin(), x_.end(), x) - x_.begin() - 1;
×
609
    if (i < 0 || i >= static_cast<int>(p_.size())) {
×
UNCOV
610
      return 0.0;
×
611
    } else {
UNCOV
612
      return p_[i];
×
613
    }
614
  } else {
615
    i = std::lower_bound(x_.begin(), x_.end(), x) - x_.begin() - 1;
70,000 ✔
616

617
    if (i < 0 || i >= static_cast<int>(p_.size()) - 1) {
70,000 !
UNCOV
618
      return 0.0;
×
619
    } else {
620
      double x0 = x_[i];
70,000 ✔
621
      double x1 = x_[i + 1];
70,000 ✔
622
      double p0 = p_[i];
70,000 ✔
623
      double p1 = p_[i + 1];
70,000 ✔
624

625
      double t = (x - x0) / (x1 - x0);
70,000 ✔
626
      return (1 - t) * p0 + t * p1;
70,000 ✔
627
    }
628
  }
629
}
630

631
//==============================================================================
632
// Equiprobable implementation
633
//==============================================================================
634

635
double Equiprobable::sample_unbiased(uint64_t* seed) const
×
636
{
UNCOV
637
  std::size_t n = x_.size();
×
638

UNCOV
639
  double r = prn(seed);
×
UNCOV
640
  int i = std::floor((n - 1) * r);
×
641

UNCOV
642
  double xl = x_[i];
×
UNCOV
643
  double xr = x_[i + i];
×
644
  return xl + ((n - 1) * r - i) * (xr - xl);
×
645
}
646

UNCOV
647
double Equiprobable::evaluate(double x) const
×
648
{
UNCOV
649
  double x_min = *std::min_element(x_.begin(), x_.end());
×
UNCOV
650
  double x_max = *std::max_element(x_.begin(), x_.end());
×
651

UNCOV
652
  if (x < x_min || x > x_max) {
×
UNCOV
653
    return 0.0;
×
654
  } else {
UNCOV
655
    return 1.0 / (x_max - x_min);
×
656
  }
657
}
658

659
//==============================================================================
660
// Mixture implementation
661
//==============================================================================
662

663
Mixture::Mixture(pugi::xml_node node)
44 ✔
664
{
665
  vector<double> probabilities;
44 ✔
666

667
  // First pass: collect distributions and their probabilities
668
  for (pugi::xml_node pair : node.children("pair")) {
162 ✔
669
    // Check that required data exists
670
    if (!pair.attribute("probability"))
118 !
UNCOV
671
      fatal_error("Mixture pair element does not have probability.");
×
672
    if (!pair.child("dist"))
118 !
UNCOV
673
      fatal_error("Mixture pair element does not have a distribution.");
×
674

675
    // Get probability and distribution
676
    double p = std::stod(pair.attribute("probability").value());
118 ✔
677
    auto dist = distribution_from_xml(pair.child("dist"));
118 ✔
678

679
    // Weight probability by the distribution's integral
680
    double weighted_prob = p * dist->integral();
118 ✔
681
    probabilities.push_back(weighted_prob);
118 ✔
682
    distribution_.push_back(std::move(dist));
118 ✔
683
  }
118 ✔
684

685
  // Save sum of weighted probabilities
686
  integral_ = std::accumulate(probabilities.begin(), probabilities.end(), 0.0);
44 ✔
687

688
  std::size_t n = probabilities.size();
44 ✔
689

690
  // Check for bias
691
  if (check_for_node(node, "bias")) {
44 !
692
    // Get bias probabilities
UNCOV
693
    auto bias_params = get_node_array<double>(node, "bias");
×
UNCOV
694
    if (bias_params.size() != n) {
×
UNCOV
695
      openmc::fatal_error(
×
UNCOV
696
        "Size mismatch: Attempted to bias Mixture distribution with " +
×
UNCOV
697
        std::to_string(n) + " components using a bias with " +
×
UNCOV
698
        std::to_string(bias_params.size()) +
×
699
        " entries. Please ensure distributions have the same size.");
700
    }
701

702
    // Compute importance weights
UNCOV
703
    weight_ = compute_importance_weights(probabilities, bias_params);
×
704

705
    // Initialize DiscreteIndex with bias probabilities for sampling
UNCOV
706
    di_.assign(bias_params);
×
UNCOV
707
  } else {
×
708
    // Unbiased case: weight_ stays empty
709
    di_.assign(probabilities);
44 ✔
710
  }
711
}
44 ✔
712

713
std::pair<double, double> Mixture::sample(uint64_t* seed) const
142,268 ✔
714
{
715
  size_t idx = di_.sample(seed);
142,268 ✔
716

717
  // Sample the chosen distribution
718
  auto [val, sub_wgt] = distribution_[idx]->sample(seed);
142,268 ✔
719

720
  // Multiply by component selection weight
721
  double mix_wgt = weight_.empty() ? 1.0 : weight_[idx];
142,268 !
722
  return {val, mix_wgt * sub_wgt};
142,268 ✔
723
}
724

UNCOV
725
double Mixture::sample_unbiased(uint64_t* seed) const
×
726
{
UNCOV
727
  size_t idx = di_.sample(seed);
×
UNCOV
728
  return distribution_[idx]->sample(seed).first;
×
729
}
730

731
//==============================================================================
732
// Helper function
733
//==============================================================================
734

735
UPtrDist distribution_from_xml(pugi::xml_node node)
23,175 ✔
736
{
737
  if (!check_for_node(node, "type"))
23,175 !
UNCOV
738
    openmc::fatal_error("Distribution type must be specified.");
×
739

740
  // Determine type of distribution
741
  std::string type = get_node_value(node, "type", true, true);
23,175 ✔
742

743
  // Allocate extension of Distribution
744
  UPtrDist dist;
23,175 ✔
745
  if (type == "uniform") {
23,175 ✔
746
    dist = UPtrDist {new Uniform(node)};
207 ✔
747
  } else if (type == "powerlaw") {
22,968 ✔
748
    dist = UPtrDist {new PowerLaw(node)};
48 ✔
749
  } else if (type == "maxwell") {
22,920 ✔
750
    dist = UPtrDist {new Maxwell(node)};
61 ✔
751
  } else if (type == "watt") {
22,859 ✔
752
    dist = UPtrDist {new Watt(node)};
81 ✔
753
  } else if (type == "normal") {
22,778 ✔
754
    dist = UPtrDist {new Normal(node)};
21 ✔
755
  } else if (type == "discrete") {
22,757 ✔
756
    dist = UPtrDist {new Discrete(node)};
17,689 ✔
757
  } else if (type == "tabular") {
5,068 ✔
758
    dist = UPtrDist {new Tabular(node)};
5,024 ✔
759
  } else if (type == "mixture") {
44 !
760
    dist = UPtrDist {new Mixture(node)};
44 ✔
UNCOV
761
  } else if (type == "muir") {
×
UNCOV
762
    openmc::fatal_error(
×
763
      "'muir' distributions are now specified using the openmc.stats.muir() "
764
      "function in Python. Please regenerate your XML files.");
765
  } else {
UNCOV
766
    openmc::fatal_error("Invalid distribution type: " + type);
×
767
  }
768
  return dist;
46,350 ✔
769
}
23,175 ✔
770

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