Skip to content

Commit 3298360

Browse files
committed
dimensions: extract apply_factors
1 parent 6ea3fd5 commit 3298360

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

src/stagpy/dimensions.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,29 @@
1010
from .config import Scaling
1111

1212
if typing.TYPE_CHECKING:
13+
from typing import TypeVar
14+
1315
from numpy.typing import NDArray
1416

1517
from .parfile import StagyyPar
1618
from .stagyydata import StagyyData
1719

18-
T = float | NDArray[np.float64]
20+
T = TypeVar("T", float, NDArray[np.float64])
21+
22+
23+
def apply_factors(data: T, unit: str, scaling: Scaling) -> tuple[T, str]:
24+
"""Rescale a dimensional quantity according to scaling factors."""
25+
factor = scaling.factors.get(unit, "")
26+
if scaling.time_in_y and unit == "s":
27+
data /= scaling.yearins
28+
unit = "yr"
29+
elif scaling.vel_in_cmpy and unit == "m/s":
30+
data *= 100 * scaling.yearins
31+
unit = "cm/yr"
32+
if factor in phyvars.PREFIXES:
33+
data *= 10 ** (-3 * (phyvars.PREFIXES.index(factor) + 1))
34+
unit = factor + unit
35+
return data, unit
1936

2037

2138
@dataclass(frozen=True)
@@ -33,17 +50,8 @@ def make_dimensional(self, data: T, unit: str, scaling: Scaling) -> tuple[T, str
3350
if self.par.get("switches", "dimensional_units", True) or unit == "1":
3451
return data, ""
3552
scale = phyvars.SCALES[unit](self)
36-
factor = scaling.factors.get(unit, " ")
37-
if scaling.time_in_y and unit == "s":
38-
scale /= scaling.yearins
39-
unit = "yr"
40-
elif scaling.vel_in_cmpy and unit == "m/s":
41-
scale *= 100 * scaling.yearins
42-
unit = "cm/y"
43-
if factor in phyvars.PREFIXES:
44-
scale *= 10 ** (-3 * (phyvars.PREFIXES.index(factor) + 1))
45-
unit = factor + unit
46-
return data * scale, unit # type: ignore
53+
scale, unit = apply_factors(scale, unit, scaling)
54+
return data * scale, unit
4755

4856
@cached_property
4957
def length(self) -> float:

0 commit comments

Comments
 (0)