Repository navigation
Expand file tree
/
Copy pathmodel.py
More file actions
3660 lines (3180 loc) · 152 KB
/
Copy pathmodel.py
File metadata and controls
3660 lines (3180 loc) · 152 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 collections.abc import Callable, Iterable, Sequence
import copy
from dataclasses import dataclass, field
from functools import cache
from pathlib import Path
import math
from numbers import Integral, Real
import random
import re
from tempfile import TemporaryDirectory
from typing import Any, Protocol
import warnings
import h5py
import lxml.etree as ET
import numpy as np
from scipy.optimize import curve_fit
from scipy import ndimage
import openmc
import openmc._xml as xml
from openmc.dummy_comm import DummyCommunicator
from openmc.executor import _process_CLI_arguments
from openmc.checkvalue import (check_type, check_value, check_greater_than,
check_length, PathLike)
from openmc.exceptions import InvalidIDError
from openmc.plots import add_plot_params, _BASIS_INDICES, _id_map_to_rgb
from openmc.utility_funcs import change_directory, set_xml_input_path
def classify_undefined_regions(cell_ids: np.ndarray) -> np.ndarray:
"""Find internal undefined pixels in a 2D cell-ID slice.
Internal undefined pixels are those enclosed by defined pixels (i.e., holes
in the defined-pixel mask), as opposed to undefined pixels connected to the
slice boundary, which may represent void outside the model. The
classification is based only on connectivity within the sampled pixel grid,
so it does not guarantee true geometric interior classification.
Parameters
----------
cell_ids : numpy.ndarray
Two-dimensional array of cell IDs for a slice, which can be obtained
from the :meth:`openmc.Model.slice_data` method.
Returns
-------
numpy.ndarray of bool
Boolean mask of undefined pixels not connected to the boundary of the
sampled slice, i.e., undefined interior holes in the sampled grid.
"""
_NOT_FOUND = -2
if cell_ids is None:
raise TypeError("cell_ids must be a 2D numpy array, got None")
undefined = (cell_ids == _NOT_FOUND)
# Internal undefined pixels are holes in the defined-pixel mask.
return ndimage.binary_fill_holes(~undefined) & undefined
# Protocol for a function that is passed to search_keff
class ModelModifier(Protocol):
def __call__(self, val: float, **kwargs: Any) -> None:
...
def _check_pixels(pixels: int | Sequence[int]) -> None:
if isinstance(pixels, Integral):
check_greater_than('pixels', pixels, 0)
else:
check_length('pixels', pixels, 2)
for p in pixels:
check_greater_than('pixels', p, 0)
class Model:
"""Model container.
This class can be used to store instances of :class:`openmc.Geometry`,
:class:`openmc.Materials`, :class:`openmc.Settings`,
:class:`openmc.Tallies`, and :class:`openmc.Plots`, thus making a complete
model. The :meth:`Model.export_to_xml` method will export XML files for all
attributes that have been set. If the :attr:`Model.materials` attribute is
not set, it will attempt to create a ``materials.xml`` file based on all
materials appearing in the geometry.
.. versionchanged:: 0.13.0
The model information can now be loaded in to OpenMC directly via
openmc.lib
Parameters
----------
geometry : openmc.Geometry, optional
Geometry information
materials : openmc.Materials, optional
Materials information
settings : openmc.Settings, optional
Settings information
tallies : openmc.Tallies, optional
Tallies information
plots : openmc.Plots, optional
Plot information
description : str, optional
A description of the model
Attributes
----------
geometry : openmc.Geometry
Geometry information
materials : openmc.Materials
Materials information
settings : openmc.Settings
Settings information
tallies : openmc.Tallies
Tallies information
plots : openmc.Plots
Plot information
description : str
A description of the model
"""
def __init__(
self,
geometry: openmc.Geometry | None = None,
materials: openmc.Materials | None = None,
settings: openmc.Settings | None = None,
tallies: openmc.Tallies | None = None,
plots: openmc.Plots | None = None,
description: str = '',
):
self.geometry = openmc.Geometry() if geometry is None else geometry
self.materials = openmc.Materials() if materials is None else materials
self.settings = openmc.Settings() if settings is None else settings
self.tallies = openmc.Tallies() if tallies is None else tallies
self.plots = openmc.Plots() if plots is None else plots
self.description = description
@property
def geometry(self) -> openmc.Geometry:
return self._geometry
@geometry.setter
def geometry(self, geometry):
check_type('geometry', geometry, openmc.Geometry)
self._geometry = geometry
@property
def materials(self) -> openmc.Materials:
return self._materials
@materials.setter
def materials(self, materials):
check_type('materials', materials, Iterable, openmc.Material)
if isinstance(materials, openmc.Materials):
self._materials = materials
else:
if not hasattr(self, '_materials'):
self._materials = openmc.Materials()
del self._materials[:]
for mat in materials:
self._materials.append(mat)
@property
def settings(self) -> openmc.Settings:
return self._settings
@settings.setter
def settings(self, settings):
check_type('settings', settings, openmc.Settings)
self._settings = settings
@property
def tallies(self) -> openmc.Tallies:
return self._tallies
@tallies.setter
def tallies(self, tallies):
check_type('tallies', tallies, Iterable, openmc.Tally)
if isinstance(tallies, openmc.Tallies):
self._tallies = tallies
else:
if not hasattr(self, '_tallies'):
self._tallies = openmc.Tallies()
del self._tallies[:]
for tally in tallies:
self._tallies.append(tally)
@property
def plots(self) -> openmc.Plots:
return self._plots
@plots.setter
def plots(self, plots):
check_type('plots', plots, Iterable, openmc.PlotBase)
if isinstance(plots, openmc.Plots):
self._plots = plots
else:
if not hasattr(self, '_plots'):
self._plots = openmc.Plots()
del self._plots[:]
for plot in plots:
self._plots.append(plot)
@property
def description(self) -> str:
return self._description
@description.setter
def description(self, description):
check_type('description', description, str)
self._description = description
@property
def bounding_box(self) -> openmc.BoundingBox:
return self.geometry.bounding_box
@property
def is_initialized(self) -> bool:
try:
import openmc.lib
return openmc.lib.is_initialized
except ImportError:
return False
@property
@cache
def _materials_by_id(self) -> dict:
"""Dictionary mapping material ID --> material"""
if self.materials:
mats = self.materials
else:
mats = self.geometry.get_all_materials().values()
return {mat.id: mat for mat in mats}
@property
@cache
def _cells_by_id(self) -> dict:
"""Dictionary mapping cell ID --> cell"""
cells = self.geometry.get_all_cells()
return {cell.id: cell for cell in cells.values()}
@property
@cache
def _cells_by_name(self) -> dict[int, openmc.Cell]:
# Get the names maps, but since names are not unique, store a set for
# each name key. In this way when the user requests a change by a name,
# the change will be applied to all of the same name.
result = {}
for cell in self.geometry.get_all_cells().values():
if cell.name not in result:
result[cell.name] = set()
result[cell.name].add(cell)
return result
@property
@cache
def _materials_by_name(self) -> dict[int, openmc.Material]:
if self.materials is None:
mats = self.geometry.get_all_materials().values()
else:
mats = self.materials
result = {}
for mat in mats:
if mat.name not in result:
result[mat.name] = set()
result[mat.name].add(mat)
return result
# TODO: This should really get incorporated in lower-level calls to
# get_all_materials, but right now it requires information from the Model object
def _get_all_materials(self) -> dict[int, openmc.Material]:
"""Get all materials including those in DAGMC universes
Returns
-------
dict
Dictionary mapping material ID to material instances
"""
# Get all materials from the Geometry object
materials = self.geometry.get_all_materials()
# Account for materials in DAGMC universes
for cell in self.geometry.get_all_cells().values():
if isinstance(cell.fill, openmc.DAGMCUniverse):
names = cell.fill.material_names
materials.update({
mat.id: mat for mat in self.materials if mat.name in names
})
return materials
def add_kinetics_parameters_tallies(self, num_groups: int | None = None):
"""Add tallies for calculating kinetics parameters using the IFP method.
This method adds tallies to the model for calculating two kinetics
parameters, the generation time and the effective delayed neutron
fraction (beta effective). After a model is run, these parameters can be
determined through the :meth:`openmc.StatePoint.ifp_results` method.
Parameters
----------
num_groups : int, optional
Number of precursor groups to filter the delayed neutron fraction.
If None, only the total effective delayed neutron fraction is
tallied.
"""
if not any('ifp-time-numerator' in t.scores for t in self.tallies):
gen_time_tally = openmc.Tally(name='IFP time numerator')
gen_time_tally.scores = ['ifp-time-numerator']
self.tallies.append(gen_time_tally)
if not any('ifp-beta-numerator' in t.scores for t in self.tallies):
beta_tally = openmc.Tally(name='IFP beta numerator')
beta_tally.scores = ['ifp-beta-numerator']
if num_groups is not None:
beta_tally.filters = [openmc.DelayedGroupFilter(list(range(1, num_groups + 1)))]
self.tallies.append(beta_tally)
if not any('ifp-denominator' in t.scores for t in self.tallies):
denom_tally = openmc.Tally(name='IFP denominator')
denom_tally.scores = ['ifp-denominator']
self.tallies.append(denom_tally)
# TODO: This should also be incorporated into lower-level calls in
# settings.py, but it requires information about the tallies currently
# on the active Model
def _assign_fw_cadis_tally_IDs(self):
# Verify that all tallies assigned as targets on WeightWindowGenerators
# exist within model.tallies. If this is the case, convert the .targets
# attribute of each WeightWindowGenerator to a sequence of tally IDs.
if len(self.settings.weight_window_generators) == 0:
return
# List of valid tally IDs
reference_tally_ids = np.asarray([tal.id for tal in self.tallies])
for wwg in self.settings.weight_window_generators:
# Only proceeds if the "targets" attribute is an openmc.Tallies,
# which means it hasn't been checked against model.tallies.
if isinstance(wwg.targets, openmc.Tallies):
id_vec = []
for tal in wwg.targets:
# check against model tallies for equivalence
id_next = None
for reference_tal in self.tallies:
if tal == reference_tal:
id_next = reference_tal.id
break
if id_next is None:
raise RuntimeError(
f'Local FW-CADIS target tally {tal.id} not found on model.tallies!')
else:
id_vec.append(id_next)
wwg.targets = id_vec
elif isinstance(wwg.targets, np.ndarray):
invalid = wwg.targets[~np.isin(wwg.targets, reference_tally_ids)]
if len(invalid) > 0:
raise RuntimeError(
f'Local FW-CADIS target tally IDs {invalid} not found on model.tallies!')
@classmethod
def from_xml(
cls,
geometry: PathLike = "geometry.xml",
materials: PathLike = "materials.xml",
settings: PathLike = "settings.xml",
tallies: PathLike = "tallies.xml",
plots: PathLike = "plots.xml",
) -> Model:
"""Create model from existing XML files
Parameters
----------
geometry : PathLike
Path to geometry.xml file
materials : PathLike
Path to materials.xml file
settings : PathLike
Path to settings.xml file
tallies : PathLike
Path to tallies.xml file
.. versionadded:: 0.13.0
plots : PathLike
Path to plots.xml file
.. versionadded:: 0.13.0
Returns
-------
openmc.model.Model
Model created from XML files
"""
materials = openmc.Materials.from_xml(materials)
geometry = openmc.Geometry.from_xml(geometry, materials)
settings = openmc.Settings.from_xml(settings)
tallies = openmc.Tallies.from_xml(
tallies) if Path(tallies).exists() else None
plots = openmc.Plots.from_xml(plots) if Path(plots).exists() else None
return cls(geometry, materials, settings, tallies, plots)
@classmethod
def from_model_xml(cls, path: PathLike = "model.xml") -> Model:
"""Create model from single XML file
.. versionadded:: 0.13.3
Parameters
----------
path : PathLike
Path to model.xml file
"""
with set_xml_input_path(path):
parser = ET.XMLParser(huge_tree=True)
tree = ET.parse(path, parser=parser)
root = tree.getroot()
model = cls()
desc_elem = root.find('description')
if desc_elem is not None and desc_elem.text:
model.description = desc_elem.text
meshes = {}
model.settings = openmc.Settings.from_xml_element(
root.find('settings'), meshes)
model.materials = openmc.Materials.from_xml_element(
root.find('materials'))
model.geometry = openmc.Geometry.from_xml_element(
root.find('geometry'), model.materials)
if root.find('tallies') is not None:
model.tallies = openmc.Tallies.from_xml_element(
root.find('tallies'), meshes)
if root.find('plots') is not None:
model.plots = openmc.Plots.from_xml_element(root.find('plots'))
return model
def init_lib(
self,
threads: int | None = None,
geometry_debug: bool = False,
restart_file: PathLike | None = None,
tracks: bool = False,
output: bool = True,
event_based: bool | None = None,
intracomm=None,
directory: PathLike | None = None,
):
"""Initializes the model in memory via the C API
.. versionadded:: 0.13.0
Parameters
----------
threads : int, optional
Number of OpenMP threads. If OpenMC is compiled with OpenMP
threading enabled, the default is implementation-dependent but is
usually equal to the number of hardware threads available
(or a value set by the :envvar:`OMP_NUM_THREADS` environment
variable).
geometry_debug : bool, optional
Turn on geometry debugging during simulation. Defaults to False.
restart_file : PathLike, optional
Path to restart file to use
tracks : bool, optional
Enables the writing of particles tracks. The number of particle
tracks written to tracks.h5 is limited to 1000 unless
Settings.max_tracks is set. Defaults to False.
output : bool
Capture OpenMC output from standard out
event_based : None or bool, optional
Turns on event-based parallelism if True. If None, the value in
the Settings will be used.
intracomm : mpi4py.MPI.Intracomm or None, optional
MPI intracommunicator
directory : PathLike or None, optional
Directory to write XML files to. Defaults to None.
"""
import openmc.lib
# TODO: right now the only way to set most of the above parameters via
# the C API are at initialization time despite use-cases existing to
# set them for individual runs. For now this functionality is exposed
# where it exists (here in init), but in the future the functionality
# should be exposed so that it can be accessed via model.run(...)
args = _process_CLI_arguments(
volume=False, geometry_debug=geometry_debug,
restart_file=restart_file, threads=threads, tracks=tracks,
event_based=event_based, path_input=directory)
# Args adds the openmc_exec command in the first entry; remove it
args = args[1:]
self.finalize_lib()
# The Model object needs to be aware of the communicator so it can
# use it in certain cases, therefore lets store the communicator
if intracomm is not None:
self._intracomm = intracomm
else:
self._intracomm = DummyCommunicator()
if self._intracomm.rank == 0:
if directory is not None:
self.export_to_xml(directory=directory)
else:
self.export_to_xml()
self._intracomm.barrier()
# We cannot pass DummyCommunicator to openmc.lib.init so pass instead
# the user-provided intracomm which will either be None or an mpi4py
# communicator
openmc.lib.init(args=args, intracomm=intracomm, output=output)
def sync_dagmc_universes(self):
"""Synchronize all DAGMC universes in the current geometry.
This method iterates over all DAGMC universes in the geometry and
synchronizes their cells with the current material assignments. Requires
that the model has been initialized via :meth:`Model.init_lib`.
Synchronized DAGMC cells can then be edited and exported as nested
`<cell>` overrides inside each `<dagmc_universe>` element.
.. versionadded:: 0.15.1
"""
if self.is_initialized:
if self.materials:
materials = self.materials
else:
materials = list(self.geometry.get_all_materials().values())
for univ in self.geometry.get_all_universes().values():
if isinstance(univ, openmc.DAGMCUniverse):
univ.sync_dagmc_cells(materials)
else:
raise ValueError("The model must be initialized before calling "
"this method")
def finalize_lib(self):
"""Finalize simulation and free memory allocated for the C API
.. versionadded:: 0.13.0
"""
import openmc.lib
openmc.lib.finalize()
def deplete(
self,
method: str = "cecm",
final_step: bool = True,
operator_kwargs: dict | None = None,
directory: PathLike = ".",
output: bool = True,
**integrator_kwargs,
):
"""Deplete model using specified timesteps/power
.. versionchanged:: 0.13.0
The *final_step*, *operator_kwargs*, *directory*, and *output*
arguments were added.
Parameters
----------
timesteps : iterable of float or iterable of tuple
Array of timesteps. Note that values are not cumulative. The units are
specified by the `timestep_units` argument when `timesteps` is an
iterable of float. Alternatively, units can be specified for each step
by passing an iterable of (value, unit) tuples.
method : str
Integration method used for depletion (e.g., 'cecm', 'predictor').
Defaults to 'cecm'.
final_step : bool, optional
Indicate whether or not a transport solve should be run at the end
of the last timestep. Defaults to running this transport solve.
operator_kwargs : dict
Keyword arguments passed to the depletion operator initializer
(e.g., :func:`openmc.deplete.Operator`)
directory : PathLike, optional
Directory to write XML files to. If it doesn't exist already, it
will be created. Defaults to the current working directory
output : bool
Capture OpenMC output from standard out
integrator_kwargs : dict
Remaining keyword arguments passed to the depletion integrator
(e.g., :class:`openmc.deplete.CECMIntegrator`).
"""
if operator_kwargs is None:
op_kwargs = {}
elif isinstance(operator_kwargs, dict):
op_kwargs = operator_kwargs
else:
raise ValueError("operator_kwargs must be a dict or None")
# Import openmc.deplete here so the Model can be used even if the
# shared library is unavailable.
import openmc.deplete as dep
# Store whether or not the library was initialized when we started
started_initialized = self.is_initialized
with change_directory(directory):
with openmc.lib.quiet_dll(output):
# TODO: Support use of IndependentOperator too
depletion_operator = dep.CoupledOperator(self, **op_kwargs)
# Tell depletion_operator.finalize NOT to clear C API memory when
# it is done
depletion_operator.cleanup_when_done = False
# Set up the integrator
check_value('method', method,
dep.integrators.integrator_by_name.keys())
integrator_class = dep.integrators.integrator_by_name[method]
integrator = integrator_class(depletion_operator, **integrator_kwargs)
# Now perform the depletion
with openmc.lib.quiet_dll(output):
integrator.integrate(final_step)
# Now make the python Materials match the C API material data
for mat_id, mat in self._materials_by_id.items():
if mat.depletable:
# Get the C data
c_mat = openmc.lib.materials[mat_id]
nuclides, densities = c_mat._get_densities()
# And now we can remove isotopes and add these ones in
mat.nuclides.clear()
for nuc, density in zip(nuclides, densities):
mat.add_nuclide(nuc, density)
mat.set_density('atom/b-cm', sum(densities))
# If we didnt start intialized, we should cleanup after ourselves
if not started_initialized:
depletion_operator.cleanup_when_done = True
depletion_operator.finalize()
def _link_geometry_to_filters(self):
"""Establishes a link between distribcell filters and the geometry"""
for tally in self.tallies:
for f in tally.filters:
if isinstance(f, openmc.DistribcellFilter):
f._geometry = self.geometry
def export_to_xml(self, directory: PathLike = '.', remove_surfs: bool = False,
nuclides_to_ignore: Iterable[str] | None = None):
"""Export model to separate XML files.
Parameters
----------
directory : PathLike
Directory to write XML files to. If it doesn't exist already, it
will be created.
remove_surfs : bool
Whether or not to remove redundant surfaces from the geometry when
exporting.
.. versionadded:: 0.13.1
nuclides_to_ignore : list of str
Nuclides to ignore when exporting to XML.
"""
# Create directory if required
d = Path(directory)
if not d.is_dir():
d.mkdir(parents=True, exist_ok=True)
self._assign_fw_cadis_tally_IDs()
self.settings.export_to_xml(d)
self.geometry.export_to_xml(d, remove_surfs=remove_surfs)
# If a materials collection was specified, export it. Otherwise, look
# for all materials in the geometry and use that to automatically build
# a collection.
if self.materials:
self.materials.export_to_xml(d, nuclides_to_ignore=nuclides_to_ignore)
else:
materials = openmc.Materials(self.geometry.get_all_materials()
.values())
materials.export_to_xml(d, nuclides_to_ignore=nuclides_to_ignore)
if self.tallies:
self.tallies.export_to_xml(d)
if self.plots:
self.plots.export_to_xml(d)
self._link_geometry_to_filters()
def export_to_model_xml(self, path: PathLike = 'model.xml', remove_surfs: bool = False,
nuclides_to_ignore: Iterable[str] | None = None):
"""Export model to a single XML file.
.. versionadded:: 0.13.3
Parameters
----------
path : str or PathLike
Location of the XML file to write (default is 'model.xml'). Can be a
directory or file path.
remove_surfs : bool
Whether or not to remove redundant surfaces from the geometry when
exporting.
nuclides_to_ignore : list of str
Nuclides to ignore when exporting to XML.
"""
xml_path = Path(path)
# if the provided path doesn't end with the XML extension, assume the
# input path is meant to be a directory. If the directory does not
# exist, create it and place a 'model.xml' file there.
if not str(xml_path).endswith('.xml'):
if not xml_path.exists():
xml_path.mkdir(parents=True, exist_ok=True)
elif not xml_path.is_dir():
raise FileExistsError(f"File exists and is not a directory: '{xml_path}'")
xml_path /= 'model.xml'
# if this is an XML file location and the file's parent directory does
# not exist, create it before continuing
elif not xml_path.parent.exists():
xml_path.parent.mkdir(parents=True, exist_ok=True)
if remove_surfs:
warnings.warn("remove_surfs kwarg will be deprecated soon, please "
"set the Geometry.merge_surfaces attribute instead.")
self.geometry.merge_surfaces = True
# Link FW-CADIS WeightWindowGenerator target tallies, if present
self._assign_fw_cadis_tally_IDs()
# provide a memo to track which meshes have been written
mesh_memo = set()
settings_element = self.settings.to_xml_element(mesh_memo)
geometry_element = self.geometry.to_xml_element()
xml.clean_indentation(geometry_element, level=1)
xml.clean_indentation(settings_element, level=1)
# If a materials collection was specified, export it. Otherwise, look
# for all materials in the geometry and use that to automatically build
# a collection.
if self.materials:
materials = self.materials
else:
materials = openmc.Materials(self.geometry.get_all_materials()
.values())
with open(xml_path, 'w', encoding='utf-8', errors='xmlcharrefreplace') as fh:
# write the XML header
fh.write("<?xml version='1.0' encoding='utf-8'?>\n")
fh.write("<model>\n")
if self.description:
description_element = ET.Element('description')
description_element.text = self.description
fh.write(" ")
fh.write(ET.tostring(description_element, encoding="unicode"))
fh.write("\n")
# Write the materials collection to the open XML file first.
# This will write the XML header also
materials._write_xml(fh, False, level=1,
nuclides_to_ignore=nuclides_to_ignore)
# Write remaining elements as a tree
fh.write(ET.tostring(geometry_element, encoding="unicode"))
fh.write(ET.tostring(settings_element, encoding="unicode"))
if self.tallies:
tallies_element = self.tallies.to_xml_element(mesh_memo)
xml.clean_indentation(
tallies_element, level=1, trailing_indent=self.plots)
fh.write(ET.tostring(tallies_element, encoding="unicode"))
if self.plots:
plots_element = self.plots.to_xml_element()
xml.clean_indentation(
plots_element, level=1, trailing_indent=False)
fh.write(ET.tostring(plots_element, encoding="unicode"))
fh.write("</model>\n")
self._link_geometry_to_filters()
def import_properties(self, filename: PathLike):
"""Import physical properties
.. versionchanged:: 0.13.0
This method now updates values as loaded in memory with the C API
Parameters
----------
filename : PathLike
Path to properties HDF5 file
See Also
--------
openmc.lib.export_properties
"""
import openmc.lib
cells = self.geometry.get_all_cells()
materials = self.geometry.get_all_materials()
with h5py.File(filename, 'r') as fh:
cells_group = fh['geometry/cells']
# Make sure number of cells matches
n_cells = fh['geometry'].attrs['n_cells']
if n_cells != len(cells):
raise ValueError("Number of cells in properties file doesn't "
"match current model.")
# Update temperatures and densities for cells filled with materials
for name, group in cells_group.items():
cell_id = int(name.split()[1])
cell = cells[cell_id]
if cell.fill_type in ('material', 'distribmat'):
temperature = group['temperature'][()]
cell.temperature = temperature
if self.is_initialized:
lib_cell = openmc.lib.cells[cell_id]
if temperature.size > 1:
for i, T in enumerate(temperature):
lib_cell.set_temperature(T, i)
else:
lib_cell.set_temperature(temperature[0])
if group['density']:
density = group['density'][()]
if density.size > 1:
cell.density = [rho for rho in density]
else:
cell.density = density
if self.is_initialized:
lib_cell = openmc.lib.cells[cell_id]
if density.size > 1:
for i, rho in enumerate(density):
lib_cell.set_density(rho, i)
else:
lib_cell.set_density(density[0])
# Make sure number of materials matches
mats_group = fh['materials']
n_cells = mats_group.attrs['n_materials']
if n_cells != len(materials):
raise ValueError("Number of materials in properties file "
"doesn't match current model.")
# Update material densities
for name, group in mats_group.items():
mat_id = int(name.split()[1])
atom_density = group.attrs['atom_density']
materials[mat_id].set_density('atom/b-cm', atom_density)
if self.is_initialized:
C_mat = openmc.lib.materials[mat_id]
C_mat.set_density(atom_density, 'atom/b-cm')
def run(
self,
particles: int | None = None,
threads: int | None = None,
geometry_debug: bool = False,
restart_file: PathLike | None = None,
tracks: bool = False,
output: bool = True,
cwd: PathLike = ".",
openmc_exec: PathLike = "openmc",
mpi_args: Iterable[str] = None,
event_based: bool | None = None,
export_model_xml: bool = True,
apply_tally_results: bool = False,
**export_kwargs,
) -> Path:
"""Run OpenMC
If the C API has been initialized, then the C API is used, otherwise,
this method creates the XML files and runs OpenMC via a system call. In
both cases this method returns the path to the last statepoint file
generated.
.. versionchanged:: 0.12
Instead of returning the final k-effective value, this function now
returns the path to the final statepoint written.
.. versionchanged:: 0.13.0
This method can utilize the C API for execution
Parameters
----------
particles : int, optional
Number of particles to simulate per generation.
threads : int, optional
Number of OpenMP threads. If OpenMC is compiled with OpenMP
threading enabled, the default is implementation-dependent but is
usually equal to the number of hardware threads available (or a
value set by the :envvar:`OMP_NUM_THREADS` environment variable).
geometry_debug : bool, optional
Turn on geometry debugging during simulation. Defaults to False.
restart_file : str or PathLike
Path to restart file to use
tracks : bool, optional
Enables the writing of particles tracks. The number of particle
tracks written to tracks.h5 is limited to 1000 unless
Settings.max_tracks is set. Defaults to False.
output : bool, optional
Capture OpenMC output from standard out
cwd : PathLike, optional
Path to working directory to run in. Defaults to the current working
directory.
openmc_exec : str, optional
Path to OpenMC executable. Defaults to 'openmc'.
mpi_args : list of str, optional
MPI execute command and any additional MPI arguments to pass, e.g.
['mpiexec', '-n', '8'].
event_based : None or bool, optional
Turns on event-based parallelism if True. If None, the value in the
Settings will be used.
export_model_xml : bool, optional
Exports a single model.xml file rather than separate files. Defaults
to True.
.. versionadded:: 0.13.3
apply_tally_results : bool
Whether to apply results of the final statepoint file to the
model's tally objects.
.. versionadded:: 0.15.1
**export_kwargs
Keyword arguments passed to either :meth:`Model.export_to_model_xml`
or :meth:`Model.export_to_xml`.
Returns
-------
Path
Path to the last statepoint written by this run (None if no
statepoint was written)
"""
last_statepoint = None
last_mtime = None
# Operate in the provided working directory
with change_directory(cwd):
if self.settings.output and 'path' in self.settings.output:
output_dir = Path(self.settings.output['path'])
else:
output_dir = Path.cwd()
# Record modification times before execution.
existing = {sp: sp.stat().st_mtime_ns
for sp in output_dir.glob('statepoint.*.h5')}
if self.is_initialized:
# Handle the run options as applicable
# First dont allow ones that must be set via init
for arg_name, arg, default in zip(
['threads', 'geometry_debug', 'restart_file', 'tracks'],
[threads, geometry_debug, restart_file, tracks],
[None, False, None, False]
):
if arg != default:
msg = f"{arg_name} must be set via Model.is_initialized(...)"
raise ValueError(msg)
init_particles = openmc.lib.settings.particles
if particles is not None:
if isinstance(particles, Integral) and particles > 0:
openmc.lib.settings.particles = particles
init_event_based = openmc.lib.settings.event_based
if event_based is not None:
openmc.lib.settings.event_based = event_based
# Then run using the C API
openmc.lib.run(output)
# Reset changes for the openmc.run kwargs handling
openmc.lib.settings.particles = init_particles
openmc.lib.settings.event_based = init_event_based
else:
# Then run via the command line
if export_model_xml:
self.export_to_model_xml(**export_kwargs)
else:
self.export_to_xml(**export_kwargs)
path_input = export_kwargs.get("path", None)
openmc.run(particles, threads, geometry_debug, restart_file,