Repository navigation
Expand file tree
/
Copy pathdistribution.cpp
More file actions
423 lines (355 loc) · 11.3 KB
/
Copy pathdistribution.cpp
File metadata and controls
423 lines (355 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#include "openmc/distribution.h"
#include <algorithm> // for copy
#include <cmath> // for sqrt, floor, max
#include <iterator> // for back_inserter
#include <numeric> // for accumulate
#include <stdexcept> // for runtime_error
#include <string> // for string, stod
#include <gsl/gsl-lite.hpp>
#include "openmc/error.h"
#include "openmc/math_functions.h"
#include "openmc/random_dist.h"
#include "openmc/random_lcg.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// Discrete implementation
//==============================================================================
Discrete::Discrete(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
std::size_t n = params.size();
std::copy(params.begin(), params.begin() + n / 2, std::back_inserter(x_));
std::copy(params.begin() + n / 2, params.end(), std::back_inserter(p_));
normalize();
}
Discrete::Discrete(const double* x, const double* p, int n)
: x_ {x, x + n}, p_ {p, p + n}
{
normalize();
// Vectors for large and small probabilities based on 1/n
vector<int> large;
vector<int> small;
// Set and allocate memory
prob_ = p_;
alias_.reserve(n);
// Fill large and small vectors based on 1/n
for (int i = 0; i < n; i++) {
prob_[i] *= n;
if (prob_[i] > 1.0) {
large.push_back(i);
} else {
small.push_back(i);
}
}
while (!large.empty() && !small.empty()) {
int j = small.back();
int k = large.back();
// Update probability and alias based on Vose's algorithm
prob_[k] += prob_[j] - 1;
alias_[j] = k;
// Remove last vector element and or move large index to small vector
if (prob_[k] < 1) {
small.push_back(k);
large.pop_back();
} else {
small.pop_back();
}
}
}
double Discrete::sample(uint64_t* seed) const
{
int n = prob_.size();
if (n > 1) {
int u = prn(seed) * n;
if (prn(seed) < prob_[u]) {
return x_[u];
} else {
return x_[alias_[u]];
}
// double xi = prn(seed);
// double c = 0.0;
// for (int i = 0; i < n; ++i) {
// c += p_[i];
// if (xi < c)
// return x_[i];
// }
// throw std::runtime_error {"Error when sampling probability mass function."};
} else {
return x_[0];
}
}
void Discrete::normalize()
{
// Renormalize density function so that it sums to unity
double norm = std::accumulate(p_.begin(), p_.end(), 0.0);
for (auto& p_i : p_) {
p_i /= norm;
}
}
//==============================================================================
// Uniform implementation
//==============================================================================
Uniform::Uniform(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2) {
fatal_error("Uniform distribution must have two "
"parameters specified.");
}
a_ = params.at(0);
b_ = params.at(1);
}
double Uniform::sample(uint64_t* seed) const
{
return a_ + prn(seed) * (b_ - a_);
}
//==============================================================================
// PowerLaw implementation
//==============================================================================
PowerLaw::PowerLaw(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 3) {
fatal_error("PowerLaw distribution must have three "
"parameters specified.");
}
const double a = params.at(0);
const double b = params.at(1);
const double n = params.at(2);
offset_ = std::pow(a, n + 1);
span_ = std::pow(b, n + 1) - offset_;
ninv_ = 1 / (n + 1);
}
double PowerLaw::sample(uint64_t* seed) const
{
return std::pow(offset_ + prn(seed) * span_, ninv_);
}
//==============================================================================
// Maxwell implementation
//==============================================================================
Maxwell::Maxwell(pugi::xml_node node)
{
theta_ = std::stod(get_node_value(node, "parameters"));
}
double Maxwell::sample(uint64_t* seed) const
{
return maxwell_spectrum(theta_, seed);
}
//==============================================================================
// Watt implementation
//==============================================================================
Watt::Watt(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2)
openmc::fatal_error("Watt energy distribution must have two "
"parameters specified.");
a_ = params.at(0);
b_ = params.at(1);
}
double Watt::sample(uint64_t* seed) const
{
return watt_spectrum(a_, b_, seed);
}
//==============================================================================
// Normal implementation
//==============================================================================
Normal::Normal(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2) {
openmc::fatal_error("Normal energy distribution must have two "
"parameters specified.");
}
mean_value_ = params.at(0);
std_dev_ = params.at(1);
}
double Normal::sample(uint64_t* seed) const
{
return normal_variate(mean_value_, std_dev_, seed);
}
//==============================================================================
// Tabular implementation
//==============================================================================
Tabular::Tabular(pugi::xml_node node)
{
if (check_for_node(node, "interpolation")) {
std::string temp = get_node_value(node, "interpolation");
if (temp == "histogram") {
interp_ = Interpolation::histogram;
} else if (temp == "linear-linear") {
interp_ = Interpolation::lin_lin;
} else {
openmc::fatal_error(
"Unknown interpolation type for distribution: " + temp);
}
} else {
interp_ = Interpolation::histogram;
}
// Read and initialize tabular distribution
auto params = get_node_array<double>(node, "parameters");
std::size_t n = params.size() / 2;
const double* x = params.data();
const double* p = x + n;
init(x, p, n);
}
Tabular::Tabular(const double* x, const double* p, int n, Interpolation interp,
const double* c)
: interp_ {interp}
{
init(x, p, n, c);
}
void Tabular::init(
const double* x, const double* p, std::size_t n, const double* c)
{
// Copy x/p arrays into vectors
std::copy(x, x + n, std::back_inserter(x_));
std::copy(p, p + n, std::back_inserter(p_));
// Check interpolation parameter
if (interp_ != Interpolation::histogram &&
interp_ != Interpolation::lin_lin) {
openmc::fatal_error("Only histogram and linear-linear interpolation "
"for tabular distribution is supported.");
}
// Calculate cumulative distribution function
if (c) {
std::copy(c, c + n, std::back_inserter(c_));
} else {
c_.resize(n);
c_[0] = 0.0;
for (int i = 1; i < n; ++i) {
if (interp_ == Interpolation::histogram) {
c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]);
} else if (interp_ == Interpolation::lin_lin) {
c_[i] = c_[i - 1] + 0.5 * (p_[i - 1] + p_[i]) * (x_[i] - x_[i - 1]);
}
}
}
// Normalize density and distribution functions
for (int i = 0; i < n; ++i) {
p_[i] = p_[i] / c_[n - 1];
c_[i] = c_[i] / c_[n - 1];
}
}
double Tabular::sample(uint64_t* seed) const
{
// Sample value of CDF
double c = prn(seed);
// Find first CDF bin which is above the sampled value
double c_i = c_[0];
int i;
std::size_t n = c_.size();
for (i = 0; i < n - 1; ++i) {
if (c <= c_[i + 1])
break;
c_i = c_[i + 1];
}
// Determine bounding PDF values
double x_i = x_[i];
double p_i = p_[i];
if (interp_ == Interpolation::histogram) {
// Histogram interpolation
if (p_i > 0.0) {
return x_i + (c - c_i) / p_i;
} else {
return x_i;
}
} else {
// Linear-linear interpolation
double x_i1 = x_[i + 1];
double p_i1 = p_[i + 1];
double m = (p_i1 - p_i) / (x_i1 - x_i);
if (m == 0.0) {
return x_i + (c - c_i) / p_i;
} else {
return x_i +
(std::sqrt(std::max(0.0, p_i * p_i + 2 * m * (c - c_i))) - p_i) /
m;
}
}
}
//==============================================================================
// Equiprobable implementation
//==============================================================================
double Equiprobable::sample(uint64_t* seed) const
{
std::size_t n = x_.size();
double r = prn(seed);
int i = std::floor((n - 1) * r);
double xl = x_[i];
double xr = x_[i + i];
return xl + ((n - 1) * r - i) * (xr - xl);
}
//==============================================================================
// Mixture implementation
//==============================================================================
Mixture::Mixture(pugi::xml_node node)
{
double cumsum = 0.0;
for (pugi::xml_node pair : node.children("pair")) {
// Check that required data exists
if (!pair.attribute("probability"))
fatal_error("Mixture pair element does not have probability.");
if (!pair.child("dist"))
fatal_error("Mixture pair element does not have a distribution.");
// cummulative sum of probybilities
cumsum += std::stod(pair.attribute("probability").value());
// Save cummulative probybility and distrubution
distribution_.push_back(
std::make_pair(cumsum, distribution_from_xml(pair.child("dist"))));
}
// Normalize cummulative probabilities to 1
for (auto& pair : distribution_) {
pair.first /= cumsum;
}
}
double Mixture::sample(uint64_t* seed) const
{
// Sample value of CDF
const double p = prn(seed);
// find matching distribution
const auto it = std::lower_bound(distribution_.cbegin(), distribution_.cend(),
p, [](const DistPair& pair, double p) { return pair.first < p; });
// This should not happen. Catch it
Ensures(it != distribution_.cend());
// Sample the chosen distribution
return it->second->sample(seed);
}
//==============================================================================
// Helper function
//==============================================================================
UPtrDist distribution_from_xml(pugi::xml_node node)
{
if (!check_for_node(node, "type"))
openmc::fatal_error("Distribution type must be specified.");
// Determine type of distribution
std::string type = get_node_value(node, "type", true, true);
// Allocate extension of Distribution
UPtrDist dist;
if (type == "uniform") {
dist = UPtrDist {new Uniform(node)};
} else if (type == "powerlaw") {
dist = UPtrDist {new PowerLaw(node)};
} else if (type == "maxwell") {
dist = UPtrDist {new Maxwell(node)};
} else if (type == "watt") {
dist = UPtrDist {new Watt(node)};
} else if (type == "normal") {
dist = UPtrDist {new Normal(node)};
} else if (type == "discrete") {
dist = UPtrDist {new Discrete(node)};
} else if (type == "tabular") {
dist = UPtrDist {new Tabular(node)};
} else if (type == "mixture") {
dist = UPtrDist {new Mixture(node)};
} else if (type == "muir") {
openmc::fatal_error(
"'muir' distributions are now specified using the openmc.stats.muir() "
"function in Python. Please regenerate your XML files.");
} else {
openmc::fatal_error("Invalid distribution type: " + type);
}
return dist;
}
} // namespace openmc