-
Notifications
You must be signed in to change notification settings - Fork 658
Expand file tree
/
Copy pathsource.py
More file actions
1319 lines (1089 loc) · 43.4 KB
/
Copy pathsource.py
File metadata and controls
1319 lines (1089 loc) · 43.4 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.abc import Iterable, Sequence
from numbers import Real
from pathlib import Path
import warnings
from typing import Any
import lxml.etree as ET
import numpy as np
import h5py
import pandas as pd
import openmc
import openmc.checkvalue as cv
from openmc.checkvalue import PathLike
from openmc.stats.multivariate import UnitSphere, Spatial
from openmc.stats.univariate import Univariate
from ._xml import get_elem_list, get_text
from .mesh import MeshBase, StructuredMesh, UnstructuredMesh
from .particle_type import ParticleType
from .statepoint import _VERSION_STATEPOINT
from .utility_funcs import input_path
class SourceBase(ABC):
"""Base class for external sources
Parameters
----------
strength : float
Strength of the source
constraints : dict
Constraints on sampled source particles. Valid keys include 'domains',
'time_bounds', 'energy_bounds', 'fissionable', and 'rejection_strategy'.
For 'domains', the corresponding value is an iterable of
:class:`openmc.Cell`, :class:`openmc.Material`, or
:class:`openmc.Universe` for which sampled sites must be within. For
'time_bounds' and 'energy_bounds', the corresponding value is a sequence
of floats giving the lower and upper bounds on time in [s] or energy in
[eV] that the sampled particle must be within. For 'fissionable', the
value is a bool indicating that only sites in fissionable material
should be accepted. The 'rejection_strategy' indicates what should
happen when a source particle is rejected: either 'resample' (pick a new
particle) or 'kill' (accept and terminate).
Attributes
----------
type : {'independent', 'file', 'compiled', 'mesh'}
Indicator of source type.
strength : float
Strength of the source
constraints : dict
Constraints on sampled source particles. Valid keys include
'domain_type', 'domain_ids', 'time_bounds', 'energy_bounds',
'fissionable', and 'rejection_strategy'.
"""
def __init__(
self,
strength: float | None = 1.0,
constraints: dict[str, Any] | None = None
):
self.strength = strength
self.constraints = constraints
@property
def strength(self):
return self._strength
@strength.setter
def strength(self, strength):
cv.check_type('source strength', strength, Real, none_ok=True)
if strength is not None:
cv.check_greater_than('source strength', strength, 0.0, True)
self._strength = strength
@property
def constraints(self) -> dict[str, Any]:
return self._constraints
@constraints.setter
def constraints(self, constraints: dict[str, Any] | None):
self._constraints = {}
if constraints is None:
return
for key, value in constraints.items():
if key == 'domains':
cv.check_type('domains', value, Iterable,
(openmc.Cell, openmc.Material, openmc.Universe))
if isinstance(value[0], openmc.Cell):
self._constraints['domain_type'] = 'cell'
elif isinstance(value[0], openmc.Material):
self._constraints['domain_type'] = 'material'
elif isinstance(value[0], openmc.Universe):
self._constraints['domain_type'] = 'universe'
self._constraints['domain_ids'] = [d.id for d in value]
elif key == 'time_bounds':
cv.check_type('time bounds', value, Iterable, Real)
self._constraints['time_bounds'] = tuple(value)
elif key == 'energy_bounds':
cv.check_type('energy bounds', value, Iterable, Real)
self._constraints['energy_bounds'] = tuple(value)
elif key == 'fissionable':
cv.check_type('fissionable', value, bool)
self._constraints['fissionable'] = value
elif key == 'rejection_strategy':
cv.check_value('rejection strategy',
value, ('resample', 'kill'))
self._constraints['rejection_strategy'] = value
else:
raise ValueError(
f'Unknown key in constraints dictionary: {key}')
@abstractmethod
def populate_xml_element(self, element):
"""Add necessary source information to an XML element
Returns
-------
element : lxml.etree._Element
XML element containing source data
"""
def to_xml_element(self) -> ET.Element:
"""Return XML representation of the source
Returns
-------
element : xml.etree.ElementTree.Element
XML element containing source data
"""
element = ET.Element("source")
element.set("type", self.type)
if self.strength is not None:
element.set("strength", str(self.strength))
self.populate_xml_element(element)
constraints = self.constraints
if constraints:
constraints_elem = ET.SubElement(element, "constraints")
if "domain_ids" in constraints:
dt_elem = ET.SubElement(constraints_elem, "domain_type")
dt_elem.text = constraints["domain_type"]
id_elem = ET.SubElement(constraints_elem, "domain_ids")
id_elem.text = ' '.join(str(uid)
for uid in constraints["domain_ids"])
if "time_bounds" in constraints:
dt_elem = ET.SubElement(constraints_elem, "time_bounds")
dt_elem.text = ' '.join(str(t)
for t in constraints["time_bounds"])
if "energy_bounds" in constraints:
dt_elem = ET.SubElement(constraints_elem, "energy_bounds")
dt_elem.text = ' '.join(str(E)
for E in constraints["energy_bounds"])
if "fissionable" in constraints:
dt_elem = ET.SubElement(constraints_elem, "fissionable")
dt_elem.text = str(constraints["fissionable"]).lower()
if "rejection_strategy" in constraints:
dt_elem = ET.SubElement(constraints_elem, "rejection_strategy")
dt_elem.text = constraints["rejection_strategy"]
return element
@classmethod
def from_xml_element(cls, elem: ET.Element, meshes=None) -> SourceBase:
"""Generate source from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
meshes : dict
Dictionary with mesh IDs as keys and openmc.MeshBase instances as
values
Returns
-------
openmc.SourceBase
Source generated from XML element
"""
source_type = get_text(elem, 'type')
if source_type is None:
# attempt to determine source type based on attributes
# for backward compatibility
if get_text(elem, 'file') is not None:
return FileSource.from_xml_element(elem)
elif get_text(elem, 'library') is not None:
return CompiledSource.from_xml_element(elem)
else:
return IndependentSource.from_xml_element(elem)
else:
if source_type == 'independent':
return IndependentSource.from_xml_element(elem, meshes)
elif source_type == 'compiled':
return CompiledSource.from_xml_element(elem)
elif source_type == 'file':
return FileSource.from_xml_element(elem)
elif source_type == 'mesh':
return MeshSource.from_xml_element(elem, meshes)
else:
raise ValueError(
f'Source type {source_type} is not recognized')
@staticmethod
def _get_constraints(elem: ET.Element) -> dict[str, Any]:
# Find element containing constraints
constraints_elem = elem.find("constraints")
elem = constraints_elem if constraints_elem is not None else elem
constraints = {}
domain_type = get_text(elem, "domain_type")
if domain_type is not None:
domain_ids = get_elem_list(elem, "domain_ids", int)
# Instantiate some throw-away domains that are used by the
# constructor to assign IDs
with warnings.catch_warnings():
warnings.simplefilter('ignore', openmc.IDWarning)
if domain_type == 'cell':
domains = [openmc.Cell(uid) for uid in domain_ids]
elif domain_type == 'material':
domains = [openmc.Material(uid) for uid in domain_ids]
elif domain_type == 'universe':
domains = [openmc.Universe(uid) for uid in domain_ids]
constraints['domains'] = domains
time_bounds = get_elem_list(elem, "time_bounds", float)
if time_bounds is not None:
constraints['time_bounds'] = time_bounds
energy_bounds = get_elem_list(elem, "energy_bounds", float)
if energy_bounds is not None:
constraints['energy_bounds'] = energy_bounds
fissionable = get_text(elem, "fissionable")
if fissionable is not None:
constraints['fissionable'] = fissionable in ('true', '1')
rejection_strategy = get_text(elem, "rejection_strategy")
if rejection_strategy is not None:
constraints['rejection_strategy'] = rejection_strategy
return constraints
class IndependentSource(SourceBase):
"""Distribution of phase space coordinates for source sites.
.. versionadded:: 0.14.0
Parameters
----------
space : openmc.stats.Spatial
Spatial distribution of source sites
angle : openmc.stats.UnitSphere
Angular distribution of source sites
energy : openmc.stats.Univariate
Energy distribution of source sites
time : openmc.stats.Univariate
time distribution of source sites
strength : float
Strength of the source
particle : str or int or openmc.ParticleType
Source particle type (name, PDG number, or type)
domains : iterable of openmc.Cell, openmc.Material, or openmc.Universe
Domains to reject based on, i.e., if a sampled spatial location is not
within one of these domains, it will be rejected.
.. deprecated:: 0.15.0
Use the `constraints` argument instead.
constraints : dict
Constraints on sampled source particles. Valid keys include 'domains',
'time_bounds', 'energy_bounds', 'fissionable', and 'rejection_strategy'.
For 'domains', the corresponding value is an iterable of
:class:`openmc.Cell`, :class:`openmc.Material`, or
:class:`openmc.Universe` for which sampled sites must be within. For
'time_bounds' and 'energy_bounds', the corresponding value is a sequence
of floats giving the lower and upper bounds on time in [s] or energy in
[eV] that the sampled particle must be within. For 'fissionable', the
value is a bool indicating that only sites in fissionable material
should be accepted. The 'rejection_strategy' indicates what should
happen when a source particle is rejected: either 'resample' (pick a new
particle) or 'kill' (accept and terminate).
Attributes
----------
space : openmc.stats.Spatial or None
Spatial distribution of source sites
angle : openmc.stats.UnitSphere or None
Angular distribution of source sites
energy : openmc.stats.Univariate or None
Energy distribution of source sites
time : openmc.stats.Univariate or None
time distribution of source sites
strength : float
Strength of the source
type : str
Indicator of source type: 'independent'
.. versionadded:: 0.14.0
particle : str or int or openmc.ParticleType
Source particle type (alias, PDG number, or GNDS nuclide name)
constraints : dict
Constraints on sampled source particles. Valid keys include
'domain_type', 'domain_ids', 'time_bounds', 'energy_bounds',
'fissionable', and 'rejection_strategy'.
"""
def __init__(
self,
space: openmc.stats.Spatial | None = None,
angle: openmc.stats.UnitSphere | None = None,
energy: openmc.stats.Univariate | None = None,
time: openmc.stats.Univariate | None = None,
strength: float = 1.0,
particle: str | int | ParticleType = 'neutron',
domains: Sequence[openmc.Cell | openmc.Material |
openmc.Universe] | None = None,
constraints: dict[str, Any] | None = None
):
if domains is not None:
warnings.warn("The 'domains' arguments has been replaced by the "
"'constraints' argument.", FutureWarning)
constraints = {'domains': domains}
super().__init__(strength=strength, constraints=constraints)
self._space = None
self._angle = None
self._energy = None
self._time = None
if space is not None:
self.space = space
if angle is not None:
self.angle = angle
if energy is not None:
self.energy = energy
if time is not None:
self.time = time
self.particle = particle
@property
def type(self) -> str:
return 'independent'
def __getattr__(self, name):
cls_names = {'file': 'FileSource', 'library': 'CompiledSource',
'parameters': 'CompiledSource'}
if name in cls_names:
raise AttributeError(
f'The "{name}" attribute has been deprecated on the '
f'IndependentSource class. Please use the {cls_names[name]} class.')
else:
super().__getattribute__(name)
def __setattr__(self, name, value):
if name in ('file', 'library', 'parameters'):
# Ensure proper AttributeError is thrown
getattr(self, name)
else:
super().__setattr__(name, value)
@property
def space(self):
return self._space
@space.setter
def space(self, space):
cv.check_type('spatial distribution', space, Spatial)
self._space = space
@property
def angle(self):
return self._angle
@angle.setter
def angle(self, angle):
cv.check_type('angular distribution', angle, UnitSphere)
self._angle = angle
@property
def energy(self):
return self._energy
@energy.setter
def energy(self, energy):
cv.check_type('energy distribution', energy, Univariate)
self._energy = energy
@property
def time(self):
return self._time
@time.setter
def time(self, time):
cv.check_type('time distribution', time, Univariate)
self._time = time
@property
def particle(self) -> ParticleType:
return self._particle
@particle.setter
def particle(self, particle):
self._particle = ParticleType(particle)
def populate_xml_element(self, element):
"""Add necessary source information to an XML element
Returns
-------
element : lxml.etree._Element
XML element containing source data
"""
element.set("particle", str(self.particle))
if self.space is not None:
element.append(self.space.to_xml_element())
if self.angle is not None:
element.append(self.angle.to_xml_element())
if self.energy is not None:
element.append(self.energy.to_xml_element('energy'))
if self.time is not None:
element.append(self.time.to_xml_element('time'))
@classmethod
def from_xml_element(cls, elem: ET.Element, meshes=None) -> SourceBase:
"""Generate source from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
meshes : dict
Dictionary with mesh IDs as keys and openmc.MeshBase instaces as
values
Returns
-------
openmc.Source
Source generated from XML element
"""
constraints = cls._get_constraints(elem)
source = cls(constraints=constraints)
strength = get_text(elem, 'strength')
if strength is not None:
source.strength = float(strength)
particle = get_text(elem, 'particle')
if particle is not None:
source.particle = particle
space = elem.find('space')
if space is not None:
source.space = Spatial.from_xml_element(space, meshes)
angle = elem.find('angle')
if angle is not None:
source.angle = UnitSphere.from_xml_element(angle)
energy = elem.find('energy')
if energy is not None:
source.energy = Univariate.from_xml_element(energy)
time = elem.find('time')
if time is not None:
source.time = Univariate.from_xml_element(time)
return source
class MeshSource(SourceBase):
"""A source with a spatial distribution over mesh elements
This class represents a mesh-based source in which random positions are
uniformly sampled within mesh elements and each element can have independent
angle, energy, and time distributions. The element sampled is chosen based
on the relative strengths of the sources applied to the elements. The
strength of the mesh source as a whole is the sum of all source strengths
applied to the elements.
.. versionadded:: 0.15.0
Parameters
----------
mesh : openmc.MeshBase
The mesh over which source sites will be generated.
sources : sequence of openmc.SourceBase
Sources for each element in the mesh. Sources must be specified as
either a 1-D array in the order of the mesh indices or a
multidimensional array whose shape matches the mesh shape. If spatial
distributions are set on any of the source objects, they will be ignored
during source site sampling.
constraints : dict
Constraints on sampled source particles. Valid keys include 'domains',
'time_bounds', 'energy_bounds', 'fissionable', and 'rejection_strategy'.
For 'domains', the corresponding value is an iterable of
:class:`openmc.Cell`, :class:`openmc.Material`, or
:class:`openmc.Universe` for which sampled sites must be within. For
'time_bounds' and 'energy_bounds', the corresponding value is a sequence
of floats giving the lower and upper bounds on time in [s] or energy in
[eV] that the sampled particle must be within. For 'fissionable', the
value is a bool indicating that only sites in fissionable material
should be accepted. The 'rejection_strategy' indicates what should
happen when a source particle is rejected: either 'resample' (pick a new
particle) or 'kill' (accept and terminate).
Attributes
----------
mesh : openmc.MeshBase
The mesh over which source sites will be generated.
sources : numpy.ndarray of openmc.SourceBase
Sources to apply to each element
strength : float
Strength of the source
type : str
Indicator of source type: 'mesh'
constraints : dict
Constraints on sampled source particles. Valid keys include
'domain_type', 'domain_ids', 'time_bounds', 'energy_bounds',
'fissionable', and 'rejection_strategy'.
"""
def __init__(
self,
mesh: MeshBase,
sources: Sequence[SourceBase],
constraints: dict[str, Any] | None = None,
):
super().__init__(strength=None, constraints=constraints)
self.mesh = mesh
self.sources = sources
@property
def type(self) -> str:
return "mesh"
@property
def mesh(self) -> MeshBase:
return self._mesh
@property
def strength(self) -> float:
return sum(s.strength for s in self.sources)
@property
def sources(self) -> np.ndarray:
return self._sources
@mesh.setter
def mesh(self, m):
cv.check_type('source mesh', m, MeshBase)
self._mesh = m
@sources.setter
def sources(self, s):
cv.check_iterable_type('mesh sources', s, SourceBase, max_depth=3)
s = np.asarray(s)
if isinstance(self.mesh, StructuredMesh):
if s.size != self.mesh.n_elements:
raise ValueError(
f'The length of the source array ({s.size}) does not match '
f'the number of mesh elements ({self.mesh.n_elements}).')
# If user gave a multidimensional array, flatten in the order
# of the mesh indices
if s.ndim > 1:
s = s.ravel(order='F')
elif isinstance(self.mesh, UnstructuredMesh):
if s.ndim > 1:
raise ValueError(
'Sources must be a 1-D array for unstructured mesh')
self._sources = s
for src in self._sources:
if isinstance(src, IndependentSource) and src.space is not None:
warnings.warn('Some sources on the mesh have spatial '
'distributions that will be ignored at runtime.')
break
@strength.setter
def strength(self, val):
if val is not None:
cv.check_type('mesh source strength', val, Real)
self.set_total_strength(val)
def set_total_strength(self, strength: float):
"""Scales the element source strengths based on a desired total strength.
Parameters
----------
strength : float
Total source strength
"""
current_strength = self.strength if self.strength != 0.0 else 1.0
for s in self.sources:
s.strength *= strength / current_strength
def normalize_source_strengths(self):
"""Update all element source strengths such that they sum to 1.0."""
self.set_total_strength(1.0)
def populate_xml_element(self, elem: ET.Element):
"""Add necessary source information to an XML element
Returns
-------
element : lxml.etree._Element
XML element containing source data
"""
elem.set("mesh", str(self.mesh.id))
# write in the order of mesh indices
for s in self.sources:
elem.append(s.to_xml_element())
@classmethod
def from_xml_element(cls, elem: ET.Element, meshes) -> openmc.MeshSource:
"""
Generate MeshSource from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
meshes : dict
A dictionary with mesh IDs as keys and openmc.MeshBase instances as
values
Returns
-------
openmc.MeshSource
MeshSource generated from the XML element
"""
mesh_id = int(get_text(elem, 'mesh'))
mesh = meshes[mesh_id]
sources = [SourceBase.from_xml_element(
e) for e in elem.iterchildren('source')]
constraints = cls._get_constraints(elem)
return cls(mesh, sources, constraints=constraints)
def Source(*args, **kwargs):
"""
A function for backward compatibility of sources. Will be removed in the
future. Please update to IndependentSource.
"""
warnings.warn(
"This class is deprecated in favor of 'IndependentSource'", FutureWarning)
return openmc.IndependentSource(*args, **kwargs)
class CompiledSource(SourceBase):
"""A source based on a compiled shared library
.. versionadded:: 0.14.0
Parameters
----------
library : path-like
Path to a compiled shared library
parameters : str
Parameters to be provided to the compiled shared library function
strength : float
Strength of the source
constraints : dict
Constraints on sampled source particles. Valid keys include 'domains',
'time_bounds', 'energy_bounds', 'fissionable', and 'rejection_strategy'.
For 'domains', the corresponding value is an iterable of
:class:`openmc.Cell`, :class:`openmc.Material`, or
:class:`openmc.Universe` for which sampled sites must be within. For
'time_bounds' and 'energy_bounds', the corresponding value is a sequence
of floats giving the lower and upper bounds on time in [s] or energy in
[eV] that the sampled particle must be within. For 'fissionable', the
value is a bool indicating that only sites in fissionable material
should be accepted. The 'rejection_strategy' indicates what should
happen when a source particle is rejected: either 'resample' (pick a new
particle) or 'kill' (accept and terminate).
Attributes
----------
library : pathlib.Path
Path to a compiled shared library
parameters : str
Parameters to be provided to the compiled shared library function
strength : float
Strength of the source
type : str
Indicator of source type: 'compiled'
constraints : dict
Constraints on sampled source particles. Valid keys include
'domain_type', 'domain_ids', 'time_bounds', 'energy_bounds',
'fissionable', and 'rejection_strategy'.
"""
def __init__(
self,
library: PathLike,
parameters: str | None = None,
strength: float = 1.0,
constraints: dict[str, Any] | None = None
) -> None:
super().__init__(strength=strength, constraints=constraints)
self.library = library
self._parameters = None
if parameters is not None:
self.parameters = parameters
@property
def type(self) -> str:
return "compiled"
@property
def library(self) -> Path:
return self._library
@library.setter
def library(self, library_name: PathLike):
cv.check_type('library', library_name, PathLike)
self._library = input_path(library_name)
@property
def parameters(self) -> str:
return self._parameters
@parameters.setter
def parameters(self, parameters_path):
cv.check_type('parameters', parameters_path, str)
self._parameters = parameters_path
def populate_xml_element(self, element):
"""Add necessary compiled source information to an XML element
Returns
-------
element : lxml.etree._Element
XML element containing source data
"""
element.set("library", str(self.library))
if self.parameters is not None:
element.set("parameters", self.parameters)
@classmethod
def from_xml_element(cls, elem: ET.Element) -> openmc.CompiledSource:
"""Generate a compiled source from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
meshes : dict
Dictionary with mesh IDs as keys and openmc.MeshBase instances as
values
Returns
-------
openmc.CompiledSource
Source generated from XML element
"""
kwargs = {'constraints': cls._get_constraints(elem)}
kwargs['library'] = get_text(elem, 'library')
source = cls(**kwargs)
strength = get_text(elem, 'strength')
if strength is not None:
source.strength = float(strength)
parameters = get_text(elem, 'parameters')
if parameters is not None:
source.parameters = parameters
return source
class FileSource(SourceBase):
"""A source based on particles stored in a file
.. versionadded:: 0.14.0
Parameters
----------
path : path-like
Path to the source file from which sites should be sampled
strength : float
Strength of the source (default is 1.0)
constraints : dict
Constraints on sampled source particles. Valid keys include 'domains',
'time_bounds', 'energy_bounds', 'fissionable', and 'rejection_strategy'.
For 'domains', the corresponding value is an iterable of
:class:`openmc.Cell`, :class:`openmc.Material`, or
:class:`openmc.Universe` for which sampled sites must be within. For
'time_bounds' and 'energy_bounds', the corresponding value is a sequence
of floats giving the lower and upper bounds on time in [s] or energy in
[eV] that the sampled particle must be within. For 'fissionable', the
value is a bool indicating that only sites in fissionable material
should be accepted. The 'rejection_strategy' indicates what should
happen when a source particle is rejected: either 'resample' (pick a new
particle) or 'kill' (accept and terminate).
Attributes
----------
path : Pathlike
Source file from which sites should be sampled
strength : float
Strength of the source
type : str
Indicator of source type: 'file'
constraints : dict
Constraints on sampled source particles. Valid keys include
'domain_type', 'domain_ids', 'time_bounds', 'energy_bounds',
'fissionable', and 'rejection_strategy'.
"""
def __init__(
self,
path: PathLike,
strength: float = 1.0,
constraints: dict[str, Any] | None = None
):
super().__init__(strength=strength, constraints=constraints)
self.path = path
@property
def type(self) -> str:
return "file"
@property
def path(self) -> PathLike:
return self._path
@path.setter
def path(self, p: PathLike):
cv.check_type('source file', p, PathLike)
self._path = input_path(p)
def populate_xml_element(self, element):
"""Add necessary file source information to an XML element
Returns
-------
element : lxml.etree._Element
XML element containing source data
"""
if self.path is not None:
element.set("file", str(self.path))
@classmethod
def from_xml_element(cls, elem: ET.Element) -> openmc.FileSource:
"""Generate file source from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
meshes : dict
Dictionary with mesh IDs as keys and openmc.MeshBase instances as
values
Returns
-------
openmc.FileSource
Source generated from XML element
"""
kwargs = {'constraints': cls._get_constraints(elem)}
kwargs['path'] = get_text(elem, 'file')
strength = get_text(elem, 'strength')
if strength is not None:
kwargs['strength'] = float(strength)
return cls(**kwargs)
class SourceParticle:
"""Source particle
This class can be used to create source particles that can be written to a
file and used by OpenMC
Parameters
----------
r : iterable of float
Position of particle in Cartesian coordinates
u : iterable of float
Directional cosines
E : float
Energy of particle in [eV]
time : float
Time of particle in [s]
wgt : float
Weight of the particle
delayed_group : int
Delayed group particle was created in (neutrons only)
surf_id : int
Surface ID where particle is at, if any.
particle : ParticleType or str or int
Type of the particle (type, name, or PDG number)
"""
def __init__(
self,
r: Iterable[float] = (0., 0., 0.),
u: Iterable[float] = (0., 0., 1.),
E: float = 1.0e6,
time: float = 0.0,
wgt: float = 1.0,
delayed_group: int = 0,
surf_id: int = 0,
particle: ParticleType | str | int = ParticleType.NEUTRON
):
self.r = tuple(r)
self.u = tuple(u)
self.E = float(E)
self.time = float(time)
self.wgt = float(wgt)
self.delayed_group = delayed_group
self.surf_id = surf_id
self.particle = particle
@property
def particle(self) -> ParticleType:
return self._particle
@particle.setter
def particle(self, particle):
self._particle = ParticleType(particle)
def __repr__(self):
return f'<SourceParticle: {str(self.particle)} at E={self.E:.6e} eV>'
def to_tuple(self) -> tuple:
"""Return source particle attributes as a tuple
Returns
-------
tuple
Source particle attributes
"""
return (self.r, self.u, self.E, self.time, self.wgt,
self.delayed_group, self.surf_id, self.particle.pdg_number)
def write_source_file(
source_particles: Iterable[SourceParticle],
filename: PathLike, **kwargs
):
"""Write a source file using a collection of source particles
Parameters
----------
source_particles : iterable of SourceParticle
Source particles to write to file
filename : str or path-like
Path to source file to write
**kwargs
Keyword arguments to pass to :class:`h5py.File`
See Also
--------
openmc.SourceParticle
"""
cv.check_iterable_type(
"source particles", source_particles, SourceParticle)
pl = ParticleList(source_particles)
pl.export_to_hdf5(filename, **kwargs)
class ParticleList(list):
"""A collection of SourceParticle objects.