use NotImplementedError to indicate non-implemented combinations

This commit is contained in:
Martin Diehl 2023-12-18 23:55:38 +01:00
parent 84af516cdb
commit 7245aa24d4
No known key found for this signature in database
GPG Key ID: 1FD50837275A0A9B
3 changed files with 27 additions and 16 deletions

View File

@ -115,8 +115,6 @@ class Result:
self.cells = f['geometry'].attrs['cells'] self.cells = f['geometry'].attrs['cells']
self.size = f['geometry'].attrs['size'] self.size = f['geometry'].attrs['size']
self.origin = f['geometry'].attrs['origin'] self.origin = f['geometry'].attrs['origin']
else:
self.add_curl = self.add_divergence = self.add_gradient = None # type: ignore
r = re.compile(rf'{prefix_inc}([0-9]+)') r = re.compile(rf'{prefix_inc}([0-9]+)')
self.increments = sorted([i for i in f.keys() if r.match(i)],key=util.natural_sort) self.increments = sorted([i for i in f.keys() if r.match(i)],key=util.natural_sort)
@ -1313,8 +1311,8 @@ class Result:
Notes Notes
----- -----
This function is only available for structured grids, This function is implemented only for structured grids
i.e. fields resulting from the grid solver. with one constituent and a single phase.
""" """
def curl(f: DADF5Dataset, size: np.ndarray) -> DADF5Dataset: def curl(f: DADF5Dataset, size: np.ndarray) -> DADF5Dataset:
@ -1342,8 +1340,8 @@ class Result:
Notes Notes
----- -----
This function is only available for structured grids, This function is implemented only for structured grids
i.e. fields resulting from the grid solver. with one constituent and a single phase.
""" """
def divergence(f: DADF5Dataset, size: np.ndarray) -> DADF5Dataset: def divergence(f: DADF5Dataset, size: np.ndarray) -> DADF5Dataset:
@ -1371,8 +1369,8 @@ class Result:
Notes Notes
----- -----
This function is only available for structured grids, This function is implemented only for structured grids
i.e. fields resulting from the grid solver. with one constituent and a single phase.
""" """
def gradient(f: DADF5Dataset, size: np.ndarray) -> DADF5Dataset: def gradient(f: DADF5Dataset, size: np.ndarray) -> DADF5Dataset:
@ -1410,13 +1408,13 @@ class Result:
Arguments parsed to func. Arguments parsed to func.
""" """
if len(datasets) != 1 or self.N_constituents != 1: if self.N_constituents != 1 or len(datasets) != 1 or not self.structured:
raise NotImplementedError raise NotImplementedError('not a structured grid with one constituent and a single phase')
at_cell_ph,in_data_ph,at_cell_ho,in_data_ho = self._mappings() at_cell_ph,in_data_ph,at_cell_ho,in_data_ho = self._mappings()
increments = self.place(list(datasets.values()),False) increments = self.place(list(datasets.values()),False)
if not increments: raise RuntimeError("received invalid dataset") if not increments: raise RuntimeError('received invalid dataset')
with h5py.File(self.fname, 'a') as f: with h5py.File(self.fname, 'a') as f:
for increment in increments.items(): for increment in increments.items():
for ty in increment[1].items(): for ty in increment[1].items():
@ -1722,9 +1720,14 @@ class Result:
Defaults to False, i.e. the XDMF file expects the Defaults to False, i.e. the XDMF file expects the
DADF5 file at a stable relative path. DADF5 file at a stable relative path.
Notes
-----
This function is implemented only for structured grids with
one constituent and a single phase.
""" """
if self.N_constituents != 1 or len(self.phases) != 1 or not self.structured: if self.N_constituents != 1 or len(self.phases) != 1 or not self.structured:
raise TypeError('XDMF output requires structured grid with single phase and single constituent.') raise NotImplementedError('not a structured grid with one constituent and a single phase')
attribute_type_map = defaultdict(lambda:'Matrix', ( ((),'Scalar'), ((3,),'Vector'), ((3,3),'Tensor')) ) attribute_type_map = defaultdict(lambda:'Matrix', ( ((),'Scalar'), ((3,),'Vector'), ((3,3),'Tensor')) )
@ -1949,6 +1952,11 @@ class Result:
target_dir : str or pathlib.Path, optional target_dir : str or pathlib.Path, optional
Directory to save DREAM3D files. Will be created if non-existent. Directory to save DREAM3D files. Will be created if non-existent.
Notes
-----
This function is implemented only for structured grids with
one constituent.
""" """
def add_attribute(obj,name,data): def add_attribute(obj,name,data):
"""DREAM.3D requires fixed length string.""" """DREAM.3D requires fixed length string."""
@ -1964,11 +1972,10 @@ class Result:
return obj[name] return obj[name]
if self.N_constituents != 1 or not self.structured: if self.N_constituents != 1 or not self.structured:
raise TypeError('DREAM3D output requires structured grid with single constituent.') raise NotImplementedError('not a structured grid with one constituent')
N_digits = int(np.floor(np.log10(max(1,self.incs[-1]))))+1 N_digits = int(np.floor(np.log10(max(1,self.incs[-1]))))+1
at_cell_ph,in_data_ph,_,_ = self._mappings() at_cell_ph,in_data_ph,_,_ = self._mappings()
out_dir = Path.cwd() if target_dir is None else Path(target_dir) out_dir = Path.cwd() if target_dir is None else Path(target_dir)

View File

@ -618,7 +618,7 @@ def _docstringer(docstring: _Union[str, _Callable],
adopted_, adopted_,
flags=_re.MULTILINE|_re.DOTALL).group('content') flags=_re.MULTILINE|_re.DOTALL).group('content')
except AttributeError: except AttributeError:
raise RuntimeError(f"Function docstring passed for docstring section '{key}' is invalid:\n{docstring}") raise RuntimeError(f"function docstring passed for docstring section '{key}' is invalid:\n{docstring}")
docstring_indent, adopted_indent = (min([len(line)-len(line.lstrip()) for line in section.split('\n') if line.strip()]) docstring_indent, adopted_indent = (min([len(line)-len(line.lstrip()) for line in section.split('\n') if line.strip()])
for section in [docstring_, adopted_]) for section in [docstring_, adopted_])

View File

@ -478,6 +478,10 @@ class TestResult:
for attr in dset.attrs: for attr in dset.attrs:
assert np.array_equal(dset.attrs[attr],cur[path].attrs[attr]) assert np.array_equal(dset.attrs[attr],cur[path].attrs[attr])
def test_export_DREAM3D_invalid(self,res_path):
with pytest.raises(NotImplementedError):
Result(res_path/'4grains2x4x3_compressionY.hdf5').export_DREAM3D()
def test_XDMF_datatypes(self,tmp_path,single_phase,update,res_path): def test_XDMF_datatypes(self,tmp_path,single_phase,update,res_path):
for what,shape in {'scalar':(),'vector':(3,),'tensor':(3,3),'matrix':(12,)}.items(): for what,shape in {'scalar':(),'vector':(3,),'tensor':(3,3),'matrix':(12,)}.items():
@ -509,7 +513,7 @@ class TestResult:
assert dim_vti == dim_xdmf and bounds_vti == bounds_xdmf assert dim_vti == dim_xdmf and bounds_vti == bounds_xdmf
def test_XDMF_invalid(self,default): def test_XDMF_invalid(self,default):
with pytest.raises(TypeError): with pytest.raises(NotImplementedError):
default.export_XDMF() default.export_XDMF()
def test_XDMF_custom_path(self,single_phase,tmp_path): def test_XDMF_custom_path(self,single_phase,tmp_path):