Skip to content

Commit 3502448

Browse files
committed
processing.stream_function returns a Field
It was previously returning an array. This change is to improve the type soundness of the public API. To avoid cyclic dependencies, a new `datatypes` is created to hold definitions of several types that are ubiquitous in the code base.
1 parent c49d088 commit 3502448

File tree

11 files changed

+62
-49
lines changed

11 files changed

+62
-49
lines changed

docs/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Welcome to StagPy's documentation!
4242
sources/apiref/args
4343
sources/apiref/commands
4444
sources/apiref/config
45+
sources/apiref/datatypes
4546
sources/apiref/error
4647
sources/apiref/field
4748
sources/apiref/parfile

docs/sources/apiref/datatypes.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
datatypes
2+
=========
3+
4+
.. automodule:: stagpy.datatypes
5+
6+
.. autoclass:: Varf
7+
.. autoclass:: Field

docs/sources/apiref/phyvars.rst

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ phyvars
33

44
.. automodule:: stagpy.phyvars
55

6-
.. autoclass:: Varf
7-
86
.. data:: FIELD
97
:annotation: = {fieldvar: Varf()}
108

docs/sources/apiref/step.rst

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ _step
55
:members:
66
:private-members:
77
:exclude-members: _init_shape, _get_raw_data, _scale_radius_mo,
8-
Field, Rprof, _present_fields
8+
Rprof, _present_fields
99

10-
.. autoclass:: Field
1110
.. autoclass:: Rprof

stagpy/_step.py

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,15 @@
1515

1616
from . import error, phyvars, stagyyparsers, _helpers
1717
from ._helpers import CachedReadOnlyProperty as crop
18+
from .datatypes import Field
1819

1920
if TYPE_CHECKING:
20-
from typing import Dict, Any, Mapping, List, Iterator, Tuple, Optional
21+
from typing import (Dict, Any, Mapping, List, Iterator, Tuple, Optional,
22+
Callable)
2123
from numpy import ndarray, signedinteger
2224
from pandas import DataFrame, Series
23-
from .phyvars import Varf, Varr
25+
from .datatypes import Varf
26+
from .phyvars import Varr
2427
from .stagyydata import StagyyData
2528

2629

@@ -226,34 +229,22 @@ def at_r(self, rval: float) -> signedinteger:
226229
return np.argmin(np.abs(self.r_centers - rval))
227230

228231

229-
class Field(NamedTuple):
230-
"""Scalar field and associated metadata.
231-
232-
Attributes:
233-
values: the field itself.
234-
meta: the metadata of the field.
235-
"""
236-
237-
values: ndarray
238-
meta: Varf
239-
240-
241232
class _Fields(abc.Mapping):
242233
"""Fields data structure.
243234
244235
The :attr:`Step.fields` attribute is an instance of this class.
245236
246237
:class:`_Fields` inherits from :class:`collections.abc.Mapping`. Keys are
247238
fields names defined in :data:`stagpy.phyvars.[S]FIELD[_EXTRA]`. Each item
248-
is a name tuple ('values', 'meta'), respectively the field itself, and a
249-
:class:`stagpy.phyvars.Varf` instance with relevant metadata.
239+
is a :class:`stagpy.datatypes.Field` instance.
250240
251241
Attributes:
252242
step: the step object owning the :class:`_Fields` instance.
253243
"""
254244

255245
def __init__(self, step: Step, variables: Mapping[str, Varf],
256-
extravars: Mapping[str, Varf], files: Mapping[str, List[str]],
246+
extravars: Mapping[str, Callable[[Step], Field]],
247+
files: Mapping[str, List[str]],
257248
filesh5: Mapping[str, List[str]]):
258249
self.step = step
259250
self._vars = variables
@@ -269,10 +260,7 @@ def __getitem__(self, name: str) -> Field:
269260
if name in self._vars:
270261
fld_names, parsed_data = self._get_raw_data(name)
271262
elif name in self._extra:
272-
meta = self._extra[name]
273-
field = meta.description(self.step)
274-
meta = phyvars.Varf(_helpers.baredoc(meta.description), meta.dim)
275-
self._data[name] = Field(field, meta)
263+
self._data[name] = self._extra[name](self.step)
276264
return self._data[name]
277265
else:
278266
raise error.UnknownFieldVarError(name)

stagpy/commands.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,7 @@ def _pretty_print(key_val, sep=': ', min_col_width=39, text_width=None):
110110
def _layout(dict_vars, dict_vars_extra):
111111
"""Print nicely [(var, description)] from phyvars."""
112112
desc = [(v, m.description) for v, m in dict_vars.items()]
113-
desc.extend((v, baredoc(m.description))
114-
for v, m in dict_vars_extra.items())
113+
desc.extend((v, baredoc(m)) for v, m in dict_vars_extra.items())
115114
_pretty_print(desc, min_col_width=26)
116115

117116

stagpy/datatypes.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""Types describing StagYY output data."""
2+
3+
from __future__ import annotations
4+
from typing import NamedTuple, TYPE_CHECKING
5+
6+
if TYPE_CHECKING:
7+
from numpy import ndarray
8+
9+
10+
class Varf(NamedTuple):
11+
"""Metadata of scalar field.
12+
13+
Attributes:
14+
description: short description of the variable.
15+
dim: dimension used to :func:`~stagpy.stagyydata.StagyyData.scale` to
16+
dimensional values.
17+
"""
18+
19+
description: str
20+
dim: str
21+
22+
23+
class Field(NamedTuple):
24+
"""Scalar field and associated metadata.
25+
26+
Attributes:
27+
values: the field itself.
28+
meta: the metadata of the field.
29+
"""
30+
31+
values: ndarray
32+
meta: Varf

stagpy/phyvars.py

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from typing import NamedTuple, TYPE_CHECKING
1212

1313
from . import processing
14+
from .datatypes import Varf
1415

1516
if TYPE_CHECKING:
1617
from typing import Union, Callable, Tuple
@@ -19,20 +20,6 @@
1920
from .stagyydata import StagyyData
2021

2122

22-
class Varf(NamedTuple):
23-
"""Metadata of scalar fields.
24-
25-
Attributes:
26-
description: short description of the variable if it is output by
27-
StagYY, function to compute it otherwise.
28-
dim: dimension used to :func:`~stagpy.stagyydata.StagyyData.scale` to
29-
dimensional values.
30-
"""
31-
32-
description: Union[str, Callable[[Step], ndarray]]
33-
dim: str
34-
35-
3623
FIELD = MappingProxyType({
3724
'T': Varf('Temperature', 'K'),
3825
'v1': Varf('x Velocity', 'm/s'),
@@ -66,7 +53,7 @@ class Varf(NamedTuple):
6653
})
6754

6855
FIELD_EXTRA = MappingProxyType({
69-
'stream': Varf(processing.stream_function, 'm2/s'),
56+
'stream': processing.stream_function,
7057
})
7158

7259
FIELD_FILES = MappingProxyType({

stagpy/processing.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from scipy import integrate
1313

1414
from .error import NotAvailableError
15+
from .datatypes import Field, Varf
1516

1617
if typing.TYPE_CHECKING:
1718
from typing import Tuple
@@ -277,13 +278,13 @@ def c_overturned(step: Step) -> Tuple[ndarray, ndarray]:
277278
return cinit, radf
278279

279280

280-
def stream_function(step: Step) -> ndarray:
281-
"""Stream function.
281+
def stream_function(step: Step) -> Field:
282+
"""Compute the stream function in 2D geometry.
282283
283284
Args:
284285
step: a :class:`~stagpy._step.Step` of a StagyyData instance.
285286
Returns:
286-
the stream function field, with four dimensions (x, y, z and block).
287+
the stream function field.
287288
"""
288289
if step.geom.twod_yz:
289290
x_coord = step.geom.y_walls
@@ -327,4 +328,4 @@ def stream_function(step: Step) -> ndarray:
327328
if step.geom.twod_xz:
328329
psi = - psi
329330
psi = np.reshape(psi, shape)
330-
return psi
331+
return Field(psi, Varf("Stream function", 'm2/s'))

tests/test_phyvars.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44

55
def test_dim():
6-
allvars = chain(phyvars.FIELD.values(), phyvars.FIELD_EXTRA.values(),
6+
allvars = chain(phyvars.FIELD.values(),
77
phyvars.RPROF.values(), phyvars.RPROF_EXTRA.values(),
88
phyvars.TIME.values(), phyvars.TIME_EXTRA.values())
99
for var in allvars:

0 commit comments

Comments
 (0)