Skip to content

Commit

Permalink
Updates throughout dagmc.py and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
paulromano committed Jan 7, 2025
1 parent 08fa0a9 commit 636160e
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 126 deletions.
126 changes: 55 additions & 71 deletions openmc/dagmc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from collections.abc import Iterable, Mapping
from numbers import Integral
from pathlib import Path

import h5py
import lxml.etree as ET
Expand All @@ -21,9 +20,6 @@ class DAGMCUniverse(openmc.UniverseBase):
.. versionadded:: 0.13.0
.. versionadded:: 0.15.1-dev
Moved this classe from openmc.universe to openmc.dagmc
Parameters
----------
filename : str
Expand All @@ -39,11 +35,11 @@ class DAGMCUniverse(openmc.UniverseBase):
auto_mat_ids : bool
Set IDs automatically on initialization (True) or report overlaps in ID
space between OpenMC and UWUW materials (False)
material_overrides : dict
A dictionary of material overrides. The keys are material name
strings and the values are Iterables of openmc.Material objects. If a
material name is found in the DAGMC file, the material will be replaced
with the openmc.Material object in the value.
material_overrides : dict, optional
A dictionary of material overrides. The keys are material name strings
and the values are Iterables of openmc.Material objects. If a material
name is found in the DAGMC file, the material will be replaced with the
openmc.Material object in the value.
Attributes
----------
Expand All @@ -66,9 +62,9 @@ class DAGMCUniverse(openmc.UniverseBase):
.. versionadded:: 0.13.1
material_names : list of str
Return a sorted list of materials names that are contained within the
DAGMC h5m file. This is useful when naming openmc.Material() objects
as each material name present in the DAGMC h5m file must have a
matching openmc.Material() with the same name.
DAGMC h5m file. This is useful when naming openmc.Material() objects as
each material name present in the DAGMC h5m file must have a matching
openmc.Material() with the same name.
.. versionadded:: 0.13.2
n_cells : int
Expand All @@ -80,13 +76,16 @@ class DAGMCUniverse(openmc.UniverseBase):
n_surfaces : int
The number of surfaces in the model.
.. versionadded:: 0.15
.. versionadded:: 0.13.2
material_overrides : dict
A dictionary of material overrides. Keys are Cell IDs; values
are Iterables of openmc.Material objects. The material assignment of
each DAGMC Cell id key will be replaced with the openmc.Material object
in the value. If the value contains multiple openmc.Material objects, each
Material in the list be assigned to the corresponding instance of the Cell.
A dictionary of material overrides. Keys are cell IDs; values are
iterables of :class:`openmc.Material` objects. The material assignment
of each DAGMC cell ID key will be replaced with the
:class:`~openmc.Material` object in the value. If the value contains
multiple :class:`~openmc.Material` objects, each Material in the list
will be assigned to the corresponding instance of the cell.
.. versionadded:: 0.15.1
"""

def __init__(self,
Expand All @@ -95,13 +94,15 @@ def __init__(self,
name='',
auto_geom_ids=False,
auto_mat_ids=False,
mat_overrides=None):
material_overrides=None):
super().__init__(universe_id, name)
# Initialize class attributes
self.filename = filename
self.auto_geom_ids = auto_geom_ids
self.auto_mat_ids = auto_mat_ids
self._material_overrides = {} if mat_overrides is None else mat_overrides
self._material_overrides = {}
if material_overrides is not None:
self.material_overrides = material_overrides

def __repr__(self):
string = super().__repr__()
Expand Down Expand Up @@ -132,21 +133,19 @@ def material_overrides(self):

@material_overrides.setter
def material_overrides(self, val):
if val is None:
self._material_overrides = val
return
else:
cv.check_type('material overrides', val, Mapping)
for key, value in val.items():
self.add_material_override(key, value)
cv.check_type('material overrides', val, Mapping)
for key, value in val.items():
self.add_material_override(key, value)

def replace_material_assignment(self, material_name, material):
"""Replace the material assignment of all cells filled with a material
in the DAGMC universe. The universe must be synchronized in an
initialized Model (see :meth:`openmc.DAGMCUniverse.sync_dagmc_cells`)
before calling this method.
def replace_material_assignment(self, material_name: str, material: openmc.Material):
"""Replace a material assignment within the DAGMC universe.
.. versionadded:: 0.15
Replace the material assignment of all cells filled with a material in
the DAGMC universe. The universe must be synchronized in an initialized
Model (see :meth:`~openmc.DAGMCUniverse.sync_dagmc_cells`) before
calling this method.
.. versionadded:: 0.15.1
Parameters
----------
Expand All @@ -161,7 +160,8 @@ def replace_material_assignment(self, material_name, material):
f"No material with name '{material_name}' found in the DAGMC universe")

if not self.cells:
raise RuntimeError("This DAGMC universe has not been synchronized in an initialized Model.")
raise RuntimeError("This DAGMC universe has not been synchronized "
"on an initialized Model.")

for cell in self.cells.values():
if cell.fill is None:
Expand All @@ -187,7 +187,7 @@ def add_material_override(self, key, overrides=None):
# Ensure that they key is a valid type
if not isinstance(key, (int, openmc.DAGMCCell)):
raise ValueError("Unrecognized key type. "
"Must be a integer, or openmc.DAGMCCell object")
"Must be an integer or openmc.DAGMCCell object")

# Ensure that overrides is an iterable of openmc.Material
overrides = overrides if isinstance(overrides, openmc.Iterable) else [overrides]
Expand All @@ -198,8 +198,7 @@ def add_material_override(self, key, overrides=None):
key = key.id

if key not in self.cells:
raise ValueError(
f"Cell ID '{key}' not found in DAGMC universe")
raise ValueError(f"Cell ID '{key}' not found in DAGMC universe")

self._material_overrides[key] = overrides

Expand Down Expand Up @@ -534,10 +533,15 @@ def remove_cell(self, cell):
# If the Cell is in the Universe's list of Cells, delete it
self._cells.pop(cell.id, None)

def sync_dagmc_cells(self, mats):
def sync_dagmc_cells(self, mats: Iterable[openmc.Material]):
"""Synchronize DAGMC cell information between Python and C API
.. versionadded:: 0.15.1-dev
.. versionadded:: 0.15.1
Parameters
----------
mats : iterable of openmc.Material
Iterable of materials to assign to the DAGMC cells
"""
import openmc.lib
Expand All @@ -557,23 +561,16 @@ def sync_dagmc_cells(self, mats):
for dag_cell_id in dagmc_cell_ids:
dag_cell = openmc.lib.cells[dag_cell_id]
if isinstance(dag_cell.fill, Iterable):
fill = [mats_per_id[mat.id]
for mat in dag_cell.fill if mat]
fill = [mats_per_id[mat.id] for mat in dag_cell.fill if mat]
else:
if dag_cell.fill:
fill = mats_per_id[dag_cell.fill.id]
else:
fill = None
dag_pseudo_cell = openmc.DAGMCCell(
cell_id=dag_cell_id, fill=fill
)
self.add_cell(dag_pseudo_cell)
fill = mats_per_id[dag_cell.fill.id] if dag_cell.fill else None
self.add_cell(openmc.DAGMCCell(cell_id=dag_cell_id, fill=fill))


class DAGMCCell(openmc.Cell):
"""
.. versionadded:: 0.15.1-dev
A cell class for DAGMC-based geometries.
"""A cell class for DAGMC-based geometries.
.. versionadded:: 0.15.1
Parameters
----------
Expand Down Expand Up @@ -604,38 +601,25 @@ def DAG_parent_universe(self, universe):
"""Set the parent universe of the cell."""
self._parent_universe = universe.id

def boundingbox(self):
warnings.warn("Bounding box is not available for cells in a DAGMC "
"universe", Warning)
def bounding_box(self):
return BoundingBox.infinite()

def get_all_cells(self, memo=None):
warnings.warn("get_all_cells is not available for cells in a DAGMC "
"universe", Warning)
return {}

def get_all_universes(self, memo=None):
warnings.warn("get_all_universes is not available for cells in a "
"DAGMC universe", Warning)
return {}

def clone(self, clone_materials=True, clone_regions=True, memo=None):
warnings.warn("clone is not available for cells in a DAGMC universe",
Warning)
return None
warnings.warn("clone is not available for cells in a DAGMC universe")
return self

def plot(self, *args, **kwargs):
warnings.warn("plot is not available for cells in a DAGMC universe",
Warning)
return None
raise TypeError("plot is not available for DAGMC cells.")

def create_xml_subelement(self, xml_element, memo=None):
warnings.warn("create_xml_subelement is not available for cells in a "
"DAGMC universe", Warning)
return None
raise TypeError("create_xml_subelement is not available for DAGMC cells.")

@classmethod
def from_xml_element(cls, elem, surfaces, materials, get_universe):
warnings.warn("from_xml_element is not available for cells in a DAGMC "
"universe", Warning)
return None
raise TypeError("from_xml_element is not available for DAGMC cells.")
15 changes: 7 additions & 8 deletions openmc/model/model.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations
from collections.abc import Iterable
from functools import lru_cache
import os
from pathlib import Path
from numbers import Integral
from tempfile import NamedTemporaryFile
Expand All @@ -15,7 +14,7 @@
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, PathLike
from openmc.checkvalue import check_type, check_value
from openmc.exceptions import InvalidIDError
import openmc.lib
from openmc.utility_funcs import change_directory
Expand Down Expand Up @@ -326,13 +325,13 @@ def init_lib(self, threads=None, geometry_debug=False, restart_file=None,
openmc.lib.init(args=args, intracomm=intracomm, output=output)

def sync_dagmc_universes(self):
"""
Synchronize all DAGMC universes in the current geometry.
"""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`.
.. versionadded:: 0.15.1-dev
.. versionadded:: 0.15.1
"""
if self.is_initialized:
Expand Down Expand Up @@ -1177,12 +1176,12 @@ def update_material_volumes(self, names_or_ids, volume):

self._change_py_lib_attribs(names_or_ids, volume, 'material', 'volume')

def differentiate_depletable_mats(self, diff_volume_method : str = None):
def differentiate_depletable_mats(self, diff_volume_method: str = None):
"""Assign distribmats for each depletable material
.. versionadded:: 0.14.0
.. version added:: 0.15.1-dev
.. versionchanged:: 0.15.1
diff_volume_method default is None, do not set volumes on the new
material ovjects. Is now a convenience method for
differentiate_mats(diff_volume_method, depletable_only=True)
Expand All @@ -1200,7 +1199,7 @@ def differentiate_depletable_mats(self, diff_volume_method : str = None):
def differentiate_mats(self, diff_volume_method: str = None, depletable_only: bool = True):
"""Assign distribmats for each material
.. versionadded:: 0.15.1-dev
.. versionadded:: 0.15.1
Parameters
----------
Expand Down
10 changes: 2 additions & 8 deletions openmc/universe.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,16 @@
import math
from abc import ABC, abstractmethod
from collections.abc import Iterable
from numbers import Integral, Real
from numbers import Real
from pathlib import Path
from tempfile import TemporaryDirectory
import warnings

import h5py
import lxml.etree as ET
import numpy as np

import openmc
import openmc.checkvalue as cv
from ._xml import get_text
from .checkvalue import check_type, check_value
from .mixin import IDManagerMixin
from .surface import _BOUNDARY_TYPES
from .utility_funcs import input_path


class UniverseBase(ABC, IDManagerMixin):
Expand Down Expand Up @@ -207,7 +201,7 @@ def add_cell(self, cell):
@abstractmethod
def remove_cell(self, cell):
pass

def clear_cells(self):
"""Remove all cells from the universe."""

Expand Down
4 changes: 1 addition & 3 deletions tests/unit_tests/dagmc/test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import pkg_resources
import shutil

import lxml.etree as ET
import numpy as np
from pathlib import Path
import pytest
Expand Down Expand Up @@ -85,4 +83,4 @@ def dagmc_model(request):
(3, 293.6))) # assigned by default
def test_dagmc_temperatures(cell_id, exp_temp):
cell = openmc.lib.cells[cell_id]
assert np.isclose(cell.get_temperature(), exp_temp)
assert np.isclose(cell.get_temperature(), exp_temp)
Loading

0 comments on commit 636160e

Please sign in to comment.