Skip to content

Commit

Permalink
Replace all deprecated Python typing imports and syntax with updated …
Browse files Browse the repository at this point in the history
…forms (#3085)

Co-authored-by: Paul Romano <[email protected]>
  • Loading branch information
johvincau and paulromano committed Jul 18, 2024
1 parent 32440ad commit 4c0e08b
Show file tree
Hide file tree
Showing 23 changed files with 204 additions and 227 deletions.
2 changes: 1 addition & 1 deletion openmc/bounding_box.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from __future__ import annotations
from typing import Iterable
from collections.abc import Iterable

import numpy as np

Expand Down
3 changes: 1 addition & 2 deletions openmc/checkvalue.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import copy
import os
import typing # required to prevent typing.Union namespace overwriting Union
from collections.abc import Iterable

import numpy as np

# Type for arguments that accept file paths
PathLike = typing.Union[str, os.PathLike]
PathLike = str | os.PathLike


def check_type(name, value, expected_type, expected_iter_type=None, *, none_ok=False):
Expand Down
5 changes: 2 additions & 3 deletions openmc/data/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from pathlib import Path
from math import sqrt, log
from warnings import warn
from typing import Dict

# Isotopic abundances from Meija J, Coplen T B, et al, "Isotopic compositions
# of the elements 2013 (IUPAC Technical Report)", Pure. Appl. Chem. 88 (3),
Expand Down Expand Up @@ -283,13 +282,13 @@
NEUTRON_MASS = 1.00866491595

# Used in atomic_mass function as a cache
_ATOMIC_MASS: Dict[str, float] = {}
_ATOMIC_MASS: dict[str, float] = {}

# Regex for GNDS nuclide names (used in zam function)
_GNDS_NAME_RE = re.compile(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)')

# Used in half_life function as a cache
_HALF_LIFE: Dict[str, float] = {}
_HALF_LIFE: dict[str, float] = {}
_LOG_TWO = log(2.0)

def atomic_mass(isotope):
Expand Down
3 changes: 1 addition & 2 deletions openmc/data/decay.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from io import StringIO
from math import log
import re
from typing import Optional
from warnings import warn

import numpy as np
Expand Down Expand Up @@ -579,7 +578,7 @@ def sources(self):
_DECAY_PHOTON_ENERGY = {}


def decay_photon_energy(nuclide: str) -> Optional[Univariate]:
def decay_photon_energy(nuclide: str) -> Univariate | None:
"""Get photon energy distribution resulting from the decay of a nuclide
This function relies on data stored in a depletion chain. Before calling it
Expand Down
3 changes: 1 addition & 2 deletions openmc/deplete/coupled_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

import copy
from warnings import warn
from typing import Optional

import numpy as np
from uncertainties import ufloat
Expand All @@ -34,7 +33,7 @@
__all__ = ["CoupledOperator", "Operator", "OperatorResult"]


def _find_cross_sections(model: Optional[str] = None):
def _find_cross_sections(model: str | None = None):
"""Determine cross sections to use for depletion
Parameters
Expand Down
3 changes: 1 addition & 2 deletions openmc/deplete/independent_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from __future__ import annotations
from collections.abc import Iterable
import copy
from typing import List, Set

import numpy as np
from uncertainties import ufloat
Expand Down Expand Up @@ -279,7 +278,7 @@ def _load_previous_results(self):
new_res = res_obj.distribute(self.local_mats, mat_indexes)
self.prev_res.append(new_res)

def _get_nuclides_with_data(self, cross_sections: List[MicroXS]) -> Set[str]:
def _get_nuclides_with_data(self, cross_sections: list[MicroXS]) -> set[str]:
"""Finds nuclides with cross section data"""
return set(cross_sections[0].nuclides)

Expand Down
24 changes: 12 additions & 12 deletions openmc/deplete/microxs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"""

from __future__ import annotations
from collections.abc import Iterable, Sequence
from tempfile import TemporaryDirectory
from typing import List, Tuple, Iterable, Optional, Union, Sequence

import pandas as pd
import numpy as np
Expand All @@ -27,7 +27,7 @@
_valid_rxns.append('damage-energy')


def _resolve_chain_file_path(chain_file: str):
def _resolve_chain_file_path(chain_file: str | None):
if chain_file is None:
chain_file = openmc.config.get('chain_file')
if 'chain_file' not in openmc.config:
Expand All @@ -41,12 +41,12 @@ def _resolve_chain_file_path(chain_file: str):
def get_microxs_and_flux(
model: openmc.Model,
domains,
nuclides: Optional[Iterable[str]] = None,
reactions: Optional[Iterable[str]] = None,
energies: Optional[Union[Iterable[float], str]] = None,
chain_file: Optional[PathLike] = None,
nuclides: Iterable[str] | None = None,
reactions: Iterable[str] | None = None,
energies: Iterable[float] | str | None = None,
chain_file: PathLike | None = None,
run_kwargs=None
) -> Tuple[List[np.ndarray], List[MicroXS]]:
) -> tuple[list[np.ndarray], list[MicroXS]]:
"""Generate a microscopic cross sections and flux from a Model
.. versionadded:: 0.14.0
Expand Down Expand Up @@ -183,7 +183,7 @@ class MicroXS:
:data:`openmc.deplete.chain.REACTIONS`
"""
def __init__(self, data: np.ndarray, nuclides: List[str], reactions: List[str]):
def __init__(self, data: np.ndarray, nuclides: list[str], reactions: list[str]):
# Validate inputs
if data.shape[:2] != (len(nuclides), len(reactions)):
raise ValueError(
Expand All @@ -205,12 +205,12 @@ def __init__(self, data: np.ndarray, nuclides: List[str], reactions: List[str]):
@classmethod
def from_multigroup_flux(
cls,
energies: Union[Sequence[float], str],
energies: Sequence[float] | str,
multigroup_flux: Sequence[float],
chain_file: Optional[PathLike] = None,
chain_file: PathLike | None = None,
temperature: float = 293.6,
nuclides: Optional[Sequence[str]] = None,
reactions: Optional[Sequence[str]] = None,
nuclides: Sequence[str] | None = None,
reactions: Sequence[str] | None = None,
**init_kwargs: dict,
) -> MicroXS:
"""Generated microscopic cross sections from a known flux.
Expand Down
3 changes: 1 addition & 2 deletions openmc/deplete/openmc_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

from abc import abstractmethod
from warnings import warn
from typing import List, Tuple, Dict

import numpy as np

Expand Down Expand Up @@ -185,7 +184,7 @@ def _differentiate_burnable_mats(self):
"""Assign distribmats for each burnable material"""
pass

def _get_burnable_mats(self) -> Tuple[List[str], Dict[str, float], List[str]]:
def _get_burnable_mats(self) -> tuple[list[str], dict[str, float], list[str]]:
"""Determine depletable materials, volumes, and nuclides
Returns
Expand Down
7 changes: 3 additions & 4 deletions openmc/deplete/reaction_rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
An ndarray to store reaction rates with string, integer, or slice indexing.
"""
from typing import Dict

import numpy as np

Expand Down Expand Up @@ -53,9 +52,9 @@ class ReactionRates(np.ndarray):
# the __array_finalize__ method (discussed here:
# https://docs.scipy.org/doc/numpy/user/basics.subclassing.html)

index_mat: Dict[str, int]
index_nuc: Dict[str, int]
index_rx: Dict[str, int]
index_mat: dict[str, int]
index_nuc: dict[str, int]
index_rx: dict[str, int]

def __new__(cls, local_mats, nuclides, reactions, from_results=False):
# Create appropriately-sized zeroed-out ndarray
Expand Down
35 changes: 17 additions & 18 deletions openmc/deplete/results.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import numbers
import bisect
import math
import typing # required to prevent typing.Union namespace overwriting Union
from typing import Iterable, Optional, Tuple, List
from collections.abc import Iterable
from warnings import warn

import h5py
Expand Down Expand Up @@ -97,11 +96,11 @@ def from_hdf5(cls, filename: PathLike):

def get_activity(
self,
mat: typing.Union[Material, str],
mat: Material | str,
units: str = "Bq/cm3",
by_nuclide: bool = False,
volume: Optional[float] = None
) -> Tuple[np.ndarray, typing.Union[np.ndarray, List[dict]]]:
volume: float | None = None
) -> tuple[np.ndarray, np.ndarray | list[dict]]:
"""Get activity of material over time.
.. versionadded:: 0.14.0
Expand Down Expand Up @@ -152,11 +151,11 @@ def get_activity(

def get_atoms(
self,
mat: typing.Union[Material, str],
mat: Material | str,
nuc: str,
nuc_units: str = "atoms",
time_units: str = "s"
) -> Tuple[np.ndarray, np.ndarray]:
) -> tuple[np.ndarray, np.ndarray]:
"""Get number of nuclides over time from a single material
Parameters
Expand Down Expand Up @@ -215,11 +214,11 @@ def get_atoms(

def get_decay_heat(
self,
mat: typing.Union[Material, str],
mat: Material | str,
units: str = "W",
by_nuclide: bool = False,
volume: Optional[float] = None
) -> Tuple[np.ndarray, typing.Union[np.ndarray, List[dict]]]:
volume: float | None = None
) -> tuple[np.ndarray, np.ndarray | list[dict]]:
"""Get decay heat of material over time.
.. versionadded:: 0.14.0
Expand All @@ -242,7 +241,7 @@ def get_decay_heat(
-------
times : numpy.ndarray
Array of times in [s]
decay_heat : numpy.ndarray or List[dict]
decay_heat : numpy.ndarray or list[dict]
Array of total decay heat values if by_nuclide = False (default)
or list of dictionaries of decay heat values by nuclide if
by_nuclide = True.
Expand Down Expand Up @@ -270,11 +269,11 @@ def get_decay_heat(
return times, decay_heat

def get_mass(self,
mat: typing.Union[Material, str],
mat: Material | str,
nuc: str,
mass_units: str = "g",
time_units: str = "s"
) -> Tuple[np.ndarray, np.ndarray]:
) -> tuple[np.ndarray, np.ndarray]:
"""Get mass of nuclides over time from a single material
.. versionadded:: 0.14.0
Expand Down Expand Up @@ -324,10 +323,10 @@ def get_mass(self,

def get_reaction_rate(
self,
mat: typing.Union[Material, str],
mat: Material | str,
nuc: str,
rx: str
) -> Tuple[np.ndarray, np.ndarray]:
) -> tuple[np.ndarray, np.ndarray]:
"""Get reaction rate in a single material/nuclide over time
Parameters
Expand Down Expand Up @@ -364,7 +363,7 @@ def get_reaction_rate(

return times, rates

def get_keff(self, time_units: str = 's') -> Tuple[np.ndarray, np.ndarray]:
def get_keff(self, time_units: str = 's') -> tuple[np.ndarray, np.ndarray]:
"""Evaluates the eigenvalue from a results list.
.. versionadded:: 0.13.1
Expand Down Expand Up @@ -400,7 +399,7 @@ def get_keff(self, time_units: str = 's') -> Tuple[np.ndarray, np.ndarray]:
times = _get_time_as(times, time_units)
return times, eigenvalues

def get_eigenvalue(self, time_units: str = 's') -> Tuple[np.ndarray, np.ndarray]:
def get_eigenvalue(self, time_units: str = 's') -> tuple[np.ndarray, np.ndarray]:
warn("The get_eigenvalue(...) function has been renamed get_keff and "
"will be removed in a future version of OpenMC.", FutureWarning)
return self.get_keff(time_units)
Expand Down Expand Up @@ -526,7 +525,7 @@ def get_step_where(
def export_to_materials(
self,
burnup_index: int,
nuc_with_data: Optional[Iterable[str]] = None,
nuc_with_data: Iterable[str] | None = None,
path: PathLike = 'materials.xml'
) -> Materials:
"""Return openmc.Materials object based on results at a given step
Expand Down
Loading

0 comments on commit 4c0e08b

Please sign in to comment.