-
Notifications
You must be signed in to change notification settings - Fork 658
Expand file tree
/
Copy pathunivariate.py
More file actions
2621 lines (2139 loc) · 83.1 KB
/
Copy pathunivariate.py
File metadata and controls
2621 lines (2139 loc) · 83.1 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import Iterable, Sequence
from functools import cache
from math import sqrt, pi, exp, log
from numbers import Real
from pathlib import Path
from warnings import warn
import lxml.etree as ET
import numpy as np
from scipy.integrate import trapezoid
from scipy.special import exprel, hyp1f1, lambertw
import scipy
import openmc.checkvalue as cv
from openmc.data import atomic_mass, NEUTRON_MASS
import openmc.data
from .._xml import get_elem_list, get_text
from ..mixin import EqualityMixin
_INTERPOLATION_SCHEMES = {
'histogram',
'linear-linear',
'linear-log',
'log-linear',
'log-log'
}
def exprel2(x):
"""Evaluate 2*(exp(x)-1-x)/x^2 without loss of precision near 0"""
return hyp1f1(1, 3, x)
def log1prel(x):
"""Evaluate log(1+x)/x without loss of precision near 0"""
return np.where(np.abs(x) < 1e-16, 1.0, np.log1p(x) / x)
class Univariate(EqualityMixin, ABC):
"""Probability distribution of a single random variable.
The Univariate class is an abstract class that can be derived to implement a
specific probability distribution.
Parameters
----------
bias : Iterable of float, optional
Distribution or discrete probabilities for biased sampling or discrete
probabilities for biased sampling.
"""
def __init__(self, bias: Univariate | Sequence[float] | None = None):
self.bias = bias
@property
def bias(self):
return self._bias
@bias.setter
def bias(self, bias):
check_bias_support(self, bias)
self._bias = bias
def _append_bias_to_xml(self, element: ET.Element) -> None:
"""Append bias distribution element to XML if present."""
if self.bias is not None:
if self.bias.bias is not None:
raise RuntimeError('Biasing distributions should not have their own bias.')
bias_elem = self.bias.to_xml_element("bias")
element.append(bias_elem)
@classmethod
def _read_bias_from_xml(cls, elem: ET.Element):
"""Read bias distribution from XML element if present."""
bias_elem = elem.find('bias')
if bias_elem is not None:
return Univariate.from_xml_element(bias_elem)
return None
def _append_array_bias_to_xml(self, element: ET.Element) -> None:
"""Append array-based bias probabilities to XML."""
if self.bias is not None:
bias_elem = ET.SubElement(element, "bias")
bias_elem.text = ' '.join(map(str, self.bias))
@classmethod
def _read_array_bias_from_xml(cls, elem: ET.Element):
"""Read array-based bias probabilities from XML."""
bias_elem = elem.find('bias')
if bias_elem is not None:
return get_elem_list(elem, "bias", float)
return None
@abstractmethod
def to_xml_element(self, element_name):
return ''
@abstractmethod
def __len__(self):
return 0
@classmethod
@abstractmethod
def from_xml_element(cls, elem):
distribution = get_text(elem, 'type')
if distribution == 'discrete':
return Discrete.from_xml_element(elem)
elif distribution == 'uniform':
return Uniform.from_xml_element(elem)
elif distribution == 'powerlaw':
return PowerLaw.from_xml_element(elem)
elif distribution == 'maxwell':
return Maxwell.from_xml_element(elem)
elif distribution == 'watt':
return Watt.from_xml_element(elem)
elif distribution == 'normal':
return Normal.from_xml_element(elem)
elif distribution == 'muir':
# Support older files where Muir had its own class
return muir(*get_elem_list(elem, "parameters", float))
elif distribution == 'tabular':
return Tabular.from_xml_element(elem)
elif distribution == 'legendre':
return Legendre.from_xml_element(elem)
elif distribution == 'mixture':
return Mixture.from_xml_element(elem)
elif distribution == 'decay_spectrum':
return DecaySpectrum.from_xml_element(elem)
@abstractmethod
def _sample_unbiased(self, n_samples: int = 1, seed: int | None = None):
"""Sample without bias handling.
Parameters
----------
n_samples : int
Number of sampled values to generate
seed : int or None
Initial random number seed.
Returns
-------
numpy.ndarray
The array of sampled values
"""
pass
def sample(self, n_samples: int = 1, seed: int | None = None):
"""Sample the univariate distribution, handling biasing automatically.
Parameters
----------
n_samples : int
Number of sampled values to generate
seed : int or None
Initial random number seed.
Returns
-------
tuple of numpy.ndarray
A tuple of (samples, weights)
"""
if self.bias is None:
x = self._sample_unbiased(n_samples, seed)
return x, np.ones_like(x)
else:
if self.bias.bias is not None:
raise RuntimeError('Biasing distributions should not have their own bias.')
x, _ = self.bias.sample(n_samples=n_samples, seed=seed)
weight = self.evaluate(x) / self.bias.evaluate(x)
return x, weight
def integral(self):
"""Return integral of distribution
.. versionadded:: 0.13.1
Returns
-------
float
Integral of distribution
"""
return 1.0
@abstractmethod
def evaluate(self, x: float | Sequence[float]):
"""Evaluate the probability density at the provided value.
Parameters
----------
x : float or sequence of float
Location to evaluate p(x)
Returns
-------
float or numpy.ndarray
Value of p(x)
"""
pass
@property
@abstractmethod
def support(self):
"""Return the support of the probability distribution.
Returns
-------
set or tuple of float or dict
Returns the set of unique points assigned probability mass in a
discrete distribution, the sampling interval for a continuous
distribution, or a dictionary storing the discrete and continuous
parts of the support of a mixed random variable
"""
pass
def _intensity_clip(intensity: Sequence[float], tolerance: float = 1e-6) -> np.ndarray:
"""Clip low-importance points from an array of intensities.
Given an array of intensities, this function returns an array of indices for
points that contribute non-negligibly to the total sum of intensities.
Parameters
----------
intensity : sequence of float
Intensities in arbitrary units.
tolerance : float
Maximum fraction of intensities that will be discarded.
Returns
-------
Array of indices
"""
# Get indices of intensities from largest to smallest
index_sort = np.argsort(intensity)[::-1]
# Get intensities from largest to smallest
sorted_intensity = np.asarray(intensity)[index_sort]
# Determine cumulative sum of probabilities
cumsum = np.cumsum(sorted_intensity)
cumsum /= cumsum[-1]
# Find index that satisfies cutoff
index_cutoff = np.searchsorted(cumsum, 1.0 - tolerance)
# Now get indices up to cutoff
new_indices = index_sort[:index_cutoff + 1]
# Put back in the order of the original array and return
new_indices.sort()
return new_indices
class Discrete(Univariate):
"""Distribution characterized by a probability mass function.
The Discrete distribution assigns probability values to discrete values of a
random variable, rather than expressing the distribution as a continuous
random variable.
Parameters
----------
x : Iterable of float
Values of the random variable
p : Iterable of float
Discrete probability for each value
bias : Iterable of float, optional
Alternative discrete probabilities for biased sampling. Defaults to
None for unbiased sampling.
Attributes
----------
x : numpy.ndarray
Values of the random variable
p : numpy.ndarray
Discrete probability for each value
support : set
Values of the random variable over which the distribution is
nonzero-valued
bias : numpy.ndarray or None
Discrete probabilities for biased sampling
"""
def __init__(self, x, p, bias=None):
self.x = x
self.p = p
super().__init__(bias)
def __len__(self):
return len(self.x)
@property
def x(self):
return self._x
@x.setter
def x(self, x):
if isinstance(x, Real):
x = [x]
cv.check_type('discrete values', x, Iterable, Real)
self._x = np.array(x, dtype=float)
@property
def p(self):
return self._p
@p.setter
def p(self, p):
if isinstance(p, Real):
p = [p]
cv.check_type('discrete probabilities', p, Iterable, Real)
for pk in p:
cv.check_greater_than('discrete probability', pk, 0.0, True)
self._p = np.array(p, dtype=float)
@property
def support(self):
return set(np.unique(self._x))
@Univariate.bias.setter
def bias(self, bias):
if bias is None:
self._bias = bias
else:
if isinstance(bias, Real):
bias = [bias]
cv.check_type('discrete bias probabilities', bias, Iterable, Real)
for bk in bias:
cv.check_greater_than('discrete probability', bk, 0.0, True)
if len(bias) != len(self.x):
raise RuntimeError("Discrete distribution has unequal number of "
"biased and unbiased probability entries.")
self._bias = np.array(bias, dtype=float)
def cdf(self):
return np.insert(np.cumsum(self.p), 0, 0.0)
def sample(self, n_samples=1, seed=None):
if self.bias is None:
samples = self._sample_unbiased(n_samples, seed)
return samples, np.ones_like(samples)
else:
rng = np.random.RandomState(seed)
p = self.p / self.p.sum()
b = self.bias / self.bias.sum()
indices = rng.choice(self.x.size, n_samples, p=b)
biased_sample = self.x[indices]
wgt = p[indices] / b[indices]
return biased_sample, wgt
def _sample_unbiased(self, n_samples=1, seed=None):
rng = np.random.RandomState(seed)
p = self.p / self.p.sum()
return rng.choice(self.x, n_samples, p=p)
def normalize(self):
"""Normalize the probabilities stored on the distribution"""
norm = sum(self.p)
self.p = [val / norm for val in self.p]
def evaluate(self, x):
raise NotImplementedError
def to_xml_element(self, element_name):
"""Return XML representation of the discrete distribution
Parameters
----------
element_name : str
XML element name
Returns
-------
element : lxml.etree._Element
XML element containing discrete distribution data
"""
element = ET.Element(element_name)
element.set("type", "discrete")
params = ET.SubElement(element, "parameters")
params.text = ' '.join(map(str, self.x)) + ' ' + ' '.join(map(str, self.p))
self._append_array_bias_to_xml(element)
return element
@classmethod
def from_xml_element(cls, elem: ET.Element):
"""Generate discrete distribution from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
Returns
-------
openmc.stats.Discrete
Discrete distribution generated from XML element
"""
params = get_elem_list(elem, "parameters", float)
x = params[:len(params)//2]
p = params[len(params)//2:]
bias_dist = cls._read_array_bias_from_xml(elem)
return cls(x, p, bias=bias_dist)
@classmethod
def merge(
cls,
dists: Sequence[Discrete],
probs: Sequence[float]
):
"""Merge multiple discrete distributions into a single distribution
.. versionadded:: 0.13.1
Parameters
----------
dists : iterable of openmc.stats.Discrete
Discrete distributions to combine
probs : iterable of float
Probability of each distribution
Returns
-------
openmc.stats.Discrete
Combined discrete distribution
"""
if len(dists) != len(probs):
raise ValueError("Number of distributions and probabilities must match.")
biasing = False
for d in dists:
if d.bias is not None:
# If we find that at least one distribution is biased, all
# distributions which are not biased will be assigned their
# default probability vector as a "bias" so that biased
# sampling can occur on the merged distribution.
biasing = True
break
# Combine distributions accounting for duplicate x values
x_merged = set()
p_merged = defaultdict(float)
new_bias = None
if biasing:
b_merged = defaultdict(float)
# Generate any missing bias distributions
dists = dists.copy()
for i, d in enumerate(dists):
if d.bias is None:
dists[i] = Discrete(d.x, d.p, bias=d.p)
for dist, p_dist in zip(dists, probs):
for x, p, b in zip(dist.x, dist.p, dist.bias):
x_merged.add(x)
p_merged[x] += p*p_dist
b_merged[x] += b*p_dist
# Create values and bias probabilities as arrays
x_arr = np.array(sorted(x_merged))
new_bias = np.array([b_merged[x] for x in x_arr])
else:
for dist, p_dist in zip(dists, probs):
for x, p in zip(dist.x, dist.p):
x_merged.add(x)
p_merged[x] += p*p_dist
# Create values as array
x_arr = np.array(sorted(x_merged))
# Create probabilities as array
p_arr = np.array([p_merged[x] for x in x_arr])
return cls(x_arr, p_arr, new_bias)
def integral(self):
"""Return integral of distribution
.. versionadded:: 0.13.1
Returns
-------
float
Integral of discrete distribution
"""
return np.sum(self.p)
def mean(self) -> float:
"""Return mean of the discrete distribution
The mean is the weighted average of the discrete values.
.. versionadded:: 0.15.3
Returns
-------
float
Mean of discrete distribution
"""
return np.sum(self.x * self.p) / np.sum(self.p)
def clip(self, tolerance: float = 1e-6, inplace: bool = False) -> Discrete:
r"""Remove low-importance points from discrete distribution.
Given a probability mass function :math:`p(x)` with :math:`\{x_1, x_2,
x_3, \dots\}` the possible values of the random variable with
corresponding probabilities :math:`\{p_1, p_2, p_3, \dots\}`, this
function will remove any low-importance points such that :math:`\sum_i
x_i p_i` is preserved to within some threshold.
For biased distributions, clipping should be performed before the bias
probabilities are added.
.. versionadded:: 0.14.0
Parameters
----------
tolerance : float
Maximum fraction of :math:`\sum_i x_i p_i` that will be discarded.
inplace : bool
Whether to modify the current object in-place or return a new one.
Returns
-------
Discrete distribution with low-importance points removed
"""
if self.bias is not None:
raise RuntimeError("Biased discrete distributions should be clipped "
"before applying bias.")
cv.check_less_than("tolerance", tolerance, 1.0, equality=True)
cv.check_greater_than("tolerance", tolerance, 0.0, equality=True)
# Compute intensities
intensity = self.p * self.x
# Get indices for intensities above threshold
indices = _intensity_clip(intensity, tolerance=tolerance)
# Create new discrete distribution
if inplace:
self.x = self.x[indices]
self.p = self.p[indices]
return self
else:
new_x = self.x[indices]
new_p = self.p[indices]
return type(self)(new_x, new_p)
def delta_function(value: float, intensity: float = 1.0) -> Discrete:
"""Return a discrete distribution with a single point.
.. versionadded:: 0.15.1
Parameters
----------
value : float
Value of the random variable.
intensity : float, optional
When used for an energy distribution, this can be used to assign an
intensity.
Returns
-------
Discrete distribution with a single point
"""
return Discrete([value], [intensity])
class Uniform(Univariate):
"""Distribution with constant probability over a finite interval [a,b]
Parameters
----------
a : float, optional
Lower bound of the sampling interval. Defaults to zero.
b : float, optional
Upper bound of the sampling interval. Defaults to unity.
bias : openmc.stats.Univariate, optional
Distribution for biased sampling.
Attributes
----------
a : float
Lower bound of the sampling interval
b : float
Upper bound of the sampling interval
support : tuple of float
A 2-tuple (lower, upper) defining the interval over which the
distribution is nonzero-valued
bias : openmc.stats.Univariate or None
Distribution for biased sampling
"""
def __init__(self, a: float = 0.0, b: float = 1.0,
bias: Univariate | None = None):
self.a = a
self.b = b
super().__init__(bias)
def __len__(self):
return 2
@property
def a(self):
return self._a
@a.setter
def a(self, a):
cv.check_type('Uniform a', a, Real)
self._a = a
@property
def b(self):
return self._b
@b.setter
def b(self, b):
cv.check_type('Uniform b', b, Real)
self._b = b
@property
def support(self):
return (self._a, self._b)
def to_tabular(self):
if self.bias is not None:
raise RuntimeError("to_tabular() is not permitted for biased distributions.")
prob = 1./(self.b - self.a)
t = Tabular([self.a, self.b], [prob, prob], 'histogram')
t.c = [0., 1.]
return t
def _sample_unbiased(self, n_samples=1, seed=None):
rng = np.random.RandomState(seed)
return rng.uniform(self.a, self.b, n_samples)
def evaluate(self, x):
return np.where((self.a <= x) & (x <= self.b), 1/(self.b - self.a), 0.0)
def mean(self) -> float:
"""Return mean of the uniform distribution
.. versionadded:: 0.15.3
Returns
-------
float
Mean of uniform distribution
"""
return 0.5 * (self.a + self.b)
def to_xml_element(self, element_name: str):
"""Return XML representation of the uniform distribution
Parameters
----------
element_name : str
XML element name
Returns
-------
element : lxml.etree._Element
XML element containing uniform distribution data
"""
element = ET.Element(element_name)
element.set("type", "uniform")
element.set("parameters", f'{self.a} {self.b}')
self._append_bias_to_xml(element)
return element
@classmethod
def from_xml_element(cls, elem: ET.Element):
"""Generate uniform distribution from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
Returns
-------
openmc.stats.Uniform
Uniform distribution generated from XML element
"""
params = get_elem_list(elem, "parameters", float)
bias_dist = cls._read_bias_from_xml(elem)
return cls(*params, bias=bias_dist)
class PowerLaw(Univariate):
"""Distribution with power law probability over a finite interval [a,b]
The power law distribution has density function :math:`p(x) dx = c x^n dx`.
.. versionadded:: 0.13.0
Parameters
----------
a : float, optional
Lower bound of the sampling interval. Defaults to zero.
b : float, optional
Upper bound of the sampling interval. Defaults to unity.
n : float, optional
Power law exponent. Defaults to zero, which is equivalent to a uniform
distribution.
bias : openmc.stats.Univariate, optional
Distribution for biased sampling.
Attributes
----------
a : float
Lower bound of the sampling interval
b : float
Upper bound of the sampling interval
n : float
Power law exponent
support : tuple of float
A 2-tuple (lower, upper) defining the interval over which the
distribution is nonzero-valued
bias : openmc.stats.Univariate or None
Distribution for biased sampling
"""
def __init__(self, a: float = 0.0, b: float = 1.0, n: float = 0.,
bias: Univariate | None = None):
if a >= b:
raise ValueError(
"Lower bound of sampling interval must be less than upper bound.")
self.a = a
self.b = b
self.n = n
super().__init__(bias)
def __len__(self):
return 3
@property
def a(self):
return self._a
@a.setter
def a(self, a):
cv.check_type('interval lower bound', a, Real)
if a < 0:
raise ValueError(
"PowerLaw sampling is restricted to positive-valued intervals.")
self._a = a
@property
def b(self):
return self._b
@b.setter
def b(self, b):
cv.check_type('interval upper bound', b, Real)
if b < 0:
raise ValueError(
"PowerLaw sampling is restricted to positive-valued intervals.")
self._b = b
@property
def n(self):
return self._n
@n.setter
def n(self, n):
cv.check_type('power law exponent', n, Real)
self._n = n
@property
def support(self):
return (self._a, self._b)
def _sample_unbiased(self, n_samples=1, seed=None):
rng = np.random.RandomState(seed)
xi = rng.random(n_samples)
pwr = self.n + 1
offset = self.a**pwr
span = self.b**pwr - offset
return np.power(offset + xi * span, 1/pwr)
def evaluate(self, x):
c = (self.n + 1)/(self.b**(self.n + 1) - self.a**(self.n + 1))
return np.where((self.a <= x) & (x <= self.b), c * np.abs(x)**self.n, 0.0)
def to_xml_element(self, element_name: str):
"""Return XML representation of the power law distribution
Parameters
----------
element_name : str
XML element name
Returns
-------
element : lxml.etree._Element
XML element containing distribution data
"""
element = ET.Element(element_name)
element.set("type", "powerlaw")
element.set("parameters", f'{self.a} {self.b} {self.n}')
self._append_bias_to_xml(element)
return element
@classmethod
def from_xml_element(cls, elem: ET.Element):
"""Generate power law distribution from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
Returns
-------
openmc.stats.PowerLaw
Distribution generated from XML element
"""
params = get_elem_list(elem, "parameters", float)
bias_dist = cls._read_bias_from_xml(elem)
return cls(*map(float, params), bias=bias_dist)
class Maxwell(Univariate):
r"""Maxwellian distribution in energy.
The Maxwellian distribution in energy is characterized by a single parameter
:math:`\theta` and has a density function :math:`p(E) dE = c \sqrt{E}
e^{-E/\theta} dE`.
Parameters
----------
theta : float
Effective temperature for distribution in eV
bias : openmc.stats.Univariate, optional
Distribution for biased sampling.
Attributes
----------
theta : float
Effective temperature for distribution in eV
support : tuple of float
A 2-tuple (lower, upper) defining the interval over which the
distribution is nonzero-valued
bias : openmc.stats.Univariate or None
Distribution for biased sampling
"""
def __init__(self, theta, bias: Univariate | None = None):
self.theta = theta
super().__init__(bias)
def __len__(self):
return 1
@property
def theta(self):
return self._theta
@theta.setter
def theta(self, theta):
cv.check_type('Maxwell temperature', theta, Real)
cv.check_greater_than('Maxwell temperature', theta, 0.0)
self._theta = theta
@property
def support(self):
return (0.0, np.inf)
def _sample_unbiased(self, n_samples=1, seed=None):
rng = np.random.RandomState(seed)
return self.sample_maxwell(self.theta, n_samples, rng=rng)
@staticmethod
def sample_maxwell(t, n_samples: int, rng=None):
if rng is None:
rng = np.random.default_rng()
return rng.gamma(1.5, t, n_samples)
def evaluate(self, E):
return scipy.stats.gamma.pdf(E, 1.5, scale=self.theta)
def to_xml_element(self, element_name: str):
"""Return XML representation of the Maxwellian distribution
Parameters
----------
element_name : str
XML element name
Returns
-------
element : lxml.etree._Element
XML element containing Maxwellian distribution data
"""
element = ET.Element(element_name)
element.set("type", "maxwell")
element.set("parameters", str(self.theta))
self._append_bias_to_xml(element)
return element
@classmethod
def from_xml_element(cls, elem: ET.Element):
"""Generate Maxwellian distribution from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
Returns
-------
openmc.stats.Maxwell
Maxwellian distribution generated from XML element
"""
theta = float(get_text(elem, 'parameters'))
bias_dist = cls._read_bias_from_xml(elem)
return cls(theta, bias=bias_dist)
class Watt(Univariate):
r"""Watt fission energy spectrum.
The Watt fission energy spectrum is characterized by two parameters
:math:`a` and :math:`b` and has density function :math:`p(E) dE = c e^{-E/a}
\sinh \sqrt{b \, E} dE`.
Parameters
----------
a : float
First parameter of distribution in units of eV
b : float
Second parameter of distribution in units of 1/eV
bias : openmc.stats.Univariate, optional
Distribution for biased sampling.
Attributes
----------
a : float
First parameter of distribution in units of eV
b : float
Second parameter of distribution in units of 1/eV
support : tuple of float
A 2-tuple (lower, upper) defining the interval over which the
distribution is nonzero-valued
bias : openmc.stats.Univariate or None
Distribution for biased sampling
"""
def __init__(self, a=0.988e6, b=2.249e-6, bias: Univariate | None = None):
self.a = a
self.b = b
super().__init__(bias)
def __len__(self):
return 2
@property
def a(self):
return self._a
@a.setter
def a(self, a):
cv.check_type('Watt a', a, Real)
cv.check_greater_than('Watt a', a, 0.0)
self._a = a
@property
def b(self):
return self._b
@b.setter
def b(self, b):
cv.check_type('Watt b', b, Real)
cv.check_greater_than('Watt b', b, 0.0)
self._b = b