Skip to content

Commit 2e6dc43

Browse files
authored
Merge pull request openmc-dev#2471 from youngwki/typehint_material_return
Added return types for Material class
2 parents a85ba85 + df7ed01 commit 2e6dc43

1 file changed

Lines changed: 38 additions & 37 deletions

File tree

‎openmc/material.py‎

Lines changed: 38 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import annotations
12
from collections import OrderedDict, defaultdict, namedtuple, Counter
23
from collections.abc import Iterable
34
from copy import deepcopy
@@ -6,11 +7,11 @@
67
import re
78
import typing # imported separately as py3.8 requires typing.Iterable
89
import warnings
9-
from typing import Optional
10+
from typing import Optional, List, Union, Dict
1011
from xml.etree import ElementTree as ET
1112

12-
import h5py
1313
import numpy as np
14+
import h5py
1415

1516
import openmc
1617
import openmc.data
@@ -134,7 +135,7 @@ def __init__(self, material_id=None, name='', temperature=None):
134135
# If specified, a list of table names
135136
self._sab = []
136137

137-
def __repr__(self):
138+
def __repr__(self) -> str:
138139
string = 'Material\n'
139140
string += '{: <16}=\t{}\n'.format('\tID', self._id)
140141
string += '{: <16}=\t{}\n'.format('\tName', self._name)
@@ -166,50 +167,50 @@ def __repr__(self):
166167
return string
167168

168169
@property
169-
def name(self):
170+
def name(self) -> Optional[str]:
170171
return self._name
171172

172173
@property
173-
def temperature(self):
174+
def temperature(self) -> Optional[float]:
174175
return self._temperature
175176

176177
@property
177-
def density(self):
178+
def density(self) -> Optional[float]:
178179
return self._density
179180

180181
@property
181-
def density_units(self):
182+
def density_units(self) -> str:
182183
return self._density_units
183184

184185
@property
185-
def depletable(self):
186+
def depletable(self) -> bool:
186187
return self._depletable
187188

188189
@property
189-
def paths(self):
190+
def paths(self) -> List[str]:
190191
if self._paths is None:
191192
raise ValueError('Material instance paths have not been determined. '
192193
'Call the Geometry.determine_paths() method.')
193194
return self._paths
194195

195196
@property
196-
def num_instances(self):
197+
def num_instances(self) -> int:
197198
if self._num_instances is None:
198199
raise ValueError(
199200
'Number of material instances have not been determined. Call '
200201
'the Geometry.determine_paths() method.')
201202
return self._num_instances
202203

203204
@property
204-
def nuclides(self):
205+
def nuclides(self) -> List[namedtuple]:
205206
return self._nuclides
206207

207208
@property
208-
def isotropic(self):
209+
def isotropic(self) -> List[str]:
209210
return self._isotropic
210211

211212
@property
212-
def average_molar_mass(self):
213+
def average_molar_mass(self) -> float:
213214
# Using the sum of specified atomic or weight amounts as a basis, sum
214215
# the mass and moles of the material
215216
mass = 0.
@@ -226,11 +227,11 @@ def average_molar_mass(self):
226227
return mass / moles
227228

228229
@property
229-
def volume(self):
230+
def volume(self) -> Optional[float]:
230231
return self._volume
231232

232233
@property
233-
def ncrystal_cfg(self):
234+
def ncrystal_cfg(self) -> Optional[str]:
234235
return self._ncrystal_cfg
235236

236237
@name.setter
@@ -267,7 +268,7 @@ def isotropic(self, isotropic: typing.Iterable[str]):
267268
self._isotropic = list(isotropic)
268269

269270
@property
270-
def fissionable_mass(self):
271+
def fissionable_mass(self) -> float:
271272
if self.volume is None:
272273
raise ValueError("Volume must be set in order to determine mass.")
273274
density = 0.0
@@ -291,7 +292,7 @@ def decay_photon_energy(self) -> Optional[Univariate]:
291292
return openmc.data.combine_distributions(dists, probs) if dists else None
292293

293294
@classmethod
294-
def from_hdf5(cls, group: h5py.Group):
295+
def from_hdf5(cls, group: h5py.Group) -> Material:
295296
"""Create material from HDF5 group
296297
297298
Parameters
@@ -346,7 +347,7 @@ def from_hdf5(cls, group: h5py.Group):
346347
return material
347348

348349
@classmethod
349-
def from_ncrystal(cls, cfg, **kwargs):
350+
def from_ncrystal(cls, cfg, **kwargs) -> Material:
350351
"""Create material from NCrystal configuration string.
351352
352353
Density, temperature, and material composition, and (ultimately) thermal
@@ -881,7 +882,7 @@ def add_s_alpha_beta(self, name: str, fraction: float = 1.0):
881882
def make_isotropic_in_lab(self):
882883
self.isotropic = [x.name for x in self._nuclides]
883884

884-
def get_elements(self):
885+
def get_elements(self) -> List[str]:
885886
"""Returns all elements in the material
886887
887888
.. versionadded:: 0.12
@@ -895,7 +896,7 @@ def get_elements(self):
895896

896897
return sorted({re.split(r'(\d+)', i)[0] for i in self.get_nuclides()})
897898

898-
def get_nuclides(self, element: Optional[str] = None):
899+
def get_nuclides(self, element: Optional[str] = None) -> List[str]:
899900
"""Returns a list of all nuclides in the material, if the element
900901
argument is specified then just nuclides of that element are returned.
901902
@@ -925,7 +926,7 @@ def get_nuclides(self, element: Optional[str] = None):
925926

926927
return matching_nuclides
927928

928-
def get_nuclide_densities(self):
929+
def get_nuclide_densities(self) -> Dict[str, tuple]:
929930
"""Returns all nuclides in the material and their densities
930931
931932
Returns
@@ -944,7 +945,7 @@ def get_nuclide_densities(self):
944945

945946
return nuclides
946947

947-
def get_nuclide_atom_densities(self, nuclide: Optional[str] = None):
948+
def get_nuclide_atom_densities(self, nuclide: Optional[str] = None) -> Dict[str, float]:
948949
"""Returns one or all nuclides in the material and their atomic
949950
densities in units of atom/b-cm
950951
@@ -1030,7 +1031,7 @@ def get_nuclide_atom_densities(self, nuclide: Optional[str] = None):
10301031
return nuclides
10311032

10321033
def get_activity(self, units: str = 'Bq/cm3', by_nuclide: bool = False,
1033-
volume: Optional[float] = None):
1034+
volume: Optional[float] = None) -> Union[Dict[str, float], float]:
10341035
"""Returns the activity of the material or for each nuclide in the
10351036
material in units of [Bq], [Bq/g] or [Bq/cm3].
10361037
@@ -1077,7 +1078,7 @@ def get_activity(self, units: str = 'Bq/cm3', by_nuclide: bool = False,
10771078
return activity if by_nuclide else sum(activity.values())
10781079

10791080
def get_decay_heat(self, units: str = 'W', by_nuclide: bool = False,
1080-
volume: Optional[float] = None):
1081+
volume: Optional[float] = None) -> Union[Dict[str, float], float]:
10811082
"""Returns the decay heat of the material or for each nuclide in the
10821083
material in units of [W], [W/g] or [W/cm3].
10831084
@@ -1125,7 +1126,7 @@ def get_decay_heat(self, units: str = 'W', by_nuclide: bool = False,
11251126

11261127
return decayheat if by_nuclide else sum(decayheat.values())
11271128

1128-
def get_nuclide_atoms(self, volume: Optional[float] = None):
1129+
def get_nuclide_atoms(self, volume: Optional[float] = None) -> Dict[str, float]:
11291130
"""Return number of atoms of each nuclide in the material
11301131
11311132
.. versionadded:: 0.13.1
@@ -1154,7 +1155,7 @@ def get_nuclide_atoms(self, volume: Optional[float] = None):
11541155
atoms[nuclide] = 1.0e24 * atom_per_bcm * volume
11551156
return atoms
11561157

1157-
def get_mass_density(self, nuclide: Optional[str] = None):
1158+
def get_mass_density(self, nuclide: Optional[str] = None) -> float:
11581159
"""Return mass density of one or all nuclides
11591160
11601161
Parameters
@@ -1176,7 +1177,7 @@ def get_mass_density(self, nuclide: Optional[str] = None):
11761177
mass_density += density_i
11771178
return mass_density
11781179

1179-
def get_mass(self, nuclide: Optional[str] = None, volume: Optional[float] = None):
1180+
def get_mass(self, nuclide: Optional[str] = None, volume: Optional[float] = None) -> float:
11801181
"""Return mass of one or all nuclides.
11811182
11821183
Note that this method requires that the :attr:`Material.volume` has
@@ -1206,7 +1207,7 @@ def get_mass(self, nuclide: Optional[str] = None, volume: Optional[float] = None
12061207
raise ValueError("Volume must be set in order to determine mass.")
12071208
return volume*self.get_mass_density(nuclide)
12081209

1209-
def clone(self, memo: Optional[dict] = None):
1210+
def clone(self, memo: Optional[dict] = None) -> Material:
12101211
"""Create a copy of this material with a new unique ID.
12111212
12121213
Parameters
@@ -1245,7 +1246,7 @@ def clone(self, memo: Optional[dict] = None):
12451246

12461247
return memo[self]
12471248

1248-
def _get_nuclide_xml(self, nuclide: str):
1249+
def _get_nuclide_xml(self, nuclide: str) -> ET.Element:
12491250
xml_element = ET.Element("nuclide")
12501251
xml_element.set("name", nuclide.name)
12511252

@@ -1256,19 +1257,19 @@ def _get_nuclide_xml(self, nuclide: str):
12561257

12571258
return xml_element
12581259

1259-
def _get_macroscopic_xml(self, macroscopic: str):
1260+
def _get_macroscopic_xml(self, macroscopic: str) -> ET.Element:
12601261
xml_element = ET.Element("macroscopic")
12611262
xml_element.set("name", macroscopic)
12621263

12631264
return xml_element
12641265

1265-
def _get_nuclides_xml(self, nuclides: typing.Iterable[str]):
1266+
def _get_nuclides_xml(self, nuclides: typing.Iterable[str]) -> List[ET.Element]:
12661267
xml_elements = []
12671268
for nuclide in nuclides:
12681269
xml_elements.append(self._get_nuclide_xml(nuclide))
12691270
return xml_elements
12701271

1271-
def to_xml_element(self):
1272+
def to_xml_element(self) -> ET.Element:
12721273
"""Return XML representation of the material
12731274
12741275
Returns
@@ -1338,7 +1339,7 @@ def to_xml_element(self):
13381339

13391340
@classmethod
13401341
def mix_materials(cls, materials, fracs: typing.Iterable[float],
1341-
percent_type: str = 'ao', name: Optional[str] = None):
1342+
percent_type: str = 'ao', name: Optional[str] = None) -> Material:
13421343
"""Mix materials together based on atom, weight, or volume fractions
13431344
13441345
.. versionadded:: 0.12
@@ -1436,7 +1437,7 @@ def mix_materials(cls, materials, fracs: typing.Iterable[float],
14361437
return new_mat
14371438

14381439
@classmethod
1439-
def from_xml_element(cls, elem: ET.Element):
1440+
def from_xml_element(cls, elem: ET.Element) -> Material:
14401441
"""Generate material from an XML element
14411442
14421443
Parameters
@@ -1530,7 +1531,7 @@ def __init__(self, materials=None):
15301531
self += materials
15311532

15321533
@property
1533-
def cross_sections(self):
1534+
def cross_sections(self) -> Optional[Path]:
15341535
return self._cross_sections
15351536

15361537
@cross_sections.setter
@@ -1638,7 +1639,7 @@ def export_to_xml(self, path: PathLike = 'materials.xml'):
16381639
self._write_xml(fh)
16391640

16401641
@classmethod
1641-
def from_xml_element(cls, elem):
1642+
def from_xml_element(cls, elem) -> Material:
16421643
"""Generate materials collection from XML file
16431644
16441645
Parameters
@@ -1665,7 +1666,7 @@ def from_xml_element(cls, elem):
16651666
return materials
16661667

16671668
@classmethod
1668-
def from_xml(cls, path: PathLike = 'materials.xml'):
1669+
def from_xml(cls, path: PathLike = 'materials.xml') -> Material:
16691670
"""Generate materials collection from XML file
16701671
16711672
Parameters

0 commit comments

Comments
 (0)