stacknordic 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stacknordic/__init__.py +47 -0
- stacknordic/__main__.py +5 -0
- stacknordic/_progress.py +21 -0
- stacknordic/cli.py +122 -0
- stacknordic/computing.py +348 -0
- stacknordic/dataset/__init__.py +39 -0
- stacknordic/dataset/_contract.py +136 -0
- stacknordic/dataset/_manifest.py +16 -0
- stacknordic/dataset/compute.py +294 -0
- stacknordic/dataset/derived.py +89 -0
- stacknordic/dataset/downsample.py +790 -0
- stacknordic/dataset/export.py +1070 -0
- stacknordic/dataset/package.py +415 -0
- stacknordic/dataset/postprocess.py +354 -0
- stacknordic/dataset/thermodynamics.py +112 -0
- stacknordic/filtering.py +160 -0
- stacknordic/openfoam/__init__.py +9 -0
- stacknordic/openfoam/case.py +189 -0
- stacknordic/openfoam/environment.py +48 -0
- stacknordic/openfoam/io.py +252 -0
- stacknordic/openfoam/postprocess.py +208 -0
- stacknordic/openfoam/write.py +295 -0
- stacknordic/postprocess.py +109 -0
- stacknordic/reconstruction.py +561 -0
- stacknordic/resources.py +88 -0
- stacknordic/selection.py +52 -0
- stacknordic-0.1.0.dist-info/METADATA +103 -0
- stacknordic-0.1.0.dist-info/RECORD +31 -0
- stacknordic-0.1.0.dist-info/WHEEL +4 -0
- stacknordic-0.1.0.dist-info/entry_points.txt +2 -0
- stacknordic-0.1.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Stored OpenFOAM case orchestration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from ..computing import ProgressComputation
|
|
10
|
+
from ..dataset.export import ExportedDataset, export
|
|
11
|
+
from ..postprocess import PostprocessOperation
|
|
12
|
+
from ..reconstruction import (
|
|
13
|
+
Reconstruction,
|
|
14
|
+
_numeric_directories,
|
|
15
|
+
_processor_directories,
|
|
16
|
+
_source_identity,
|
|
17
|
+
reconstruct,
|
|
18
|
+
)
|
|
19
|
+
from ..selection import TimeSelection
|
|
20
|
+
from .environment import _Toolchain, toolchain
|
|
21
|
+
from .postprocess import PostprocessedCase, postprocess
|
|
22
|
+
from .write import ComputedFields, materialise
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _runtime_family(command: str | None) -> str:
|
|
26
|
+
value = (command or "").lower()
|
|
27
|
+
if "openfoam-org" in value or "openfoam.org" in value:
|
|
28
|
+
return "foundation"
|
|
29
|
+
if "openfoam" in value:
|
|
30
|
+
return "esi"
|
|
31
|
+
return "unknown"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _family_name(family: str) -> str:
|
|
35
|
+
return {
|
|
36
|
+
"esi": "OpenFOAM.com",
|
|
37
|
+
"foundation": "OpenFOAM Foundation",
|
|
38
|
+
"unknown": "unknown OpenFOAM",
|
|
39
|
+
}[family]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _warn_runtime_mismatch(source_family: str, selected_toolchain: _Toolchain) -> None:
|
|
43
|
+
runtime_family = _runtime_family(selected_toolchain.command)
|
|
44
|
+
if source_family == "unknown" or runtime_family in {"unknown", source_family}:
|
|
45
|
+
return
|
|
46
|
+
print(
|
|
47
|
+
f"[StackNordic] Active runtime: {_family_name(runtime_family)}; "
|
|
48
|
+
f"case: {_family_name(source_family)}."
|
|
49
|
+
)
|
|
50
|
+
print("[StackNordic] Direct reads remain available; OpenFOAM commands may need a matching runtime.")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, slots=True)
|
|
54
|
+
class Case:
|
|
55
|
+
"""Inspected OpenFOAM case with a case-local runtime."""
|
|
56
|
+
|
|
57
|
+
case_dir: Path
|
|
58
|
+
family: str
|
|
59
|
+
source_versions: tuple[str, ...]
|
|
60
|
+
reconstructed_times: tuple[float, ...]
|
|
61
|
+
decomposed_times: tuple[float, ...]
|
|
62
|
+
processor_count: int
|
|
63
|
+
collated: bool
|
|
64
|
+
_toolchain: _Toolchain = field(repr=False)
|
|
65
|
+
|
|
66
|
+
def compute(
|
|
67
|
+
self,
|
|
68
|
+
*,
|
|
69
|
+
computations: Sequence[ProgressComputation],
|
|
70
|
+
times: TimeSelection = None,
|
|
71
|
+
n_jobs: int | None = None,
|
|
72
|
+
progress: bool = False,
|
|
73
|
+
overwrite: bool = False,
|
|
74
|
+
) -> ComputedFields:
|
|
75
|
+
"""Materialise derived fields in the existing OpenFOAM time layout."""
|
|
76
|
+
|
|
77
|
+
return materialise(
|
|
78
|
+
case_dir=self.case_dir,
|
|
79
|
+
computations=computations,
|
|
80
|
+
times=times,
|
|
81
|
+
n_jobs=n_jobs,
|
|
82
|
+
progress=progress,
|
|
83
|
+
overwrite=overwrite,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def export(
|
|
87
|
+
self,
|
|
88
|
+
*,
|
|
89
|
+
output_dir: str | Path,
|
|
90
|
+
fields: Mapping[str, str | Sequence[str]],
|
|
91
|
+
times: TimeSelection = None,
|
|
92
|
+
dtype: str = "float32",
|
|
93
|
+
mode: str = "direct",
|
|
94
|
+
metadata: Mapping[str, object] | None = None,
|
|
95
|
+
n_jobs: int | None = None,
|
|
96
|
+
progress: bool = False,
|
|
97
|
+
overwrite: bool = False,
|
|
98
|
+
) -> ExportedDataset:
|
|
99
|
+
"""Export stored fields as one analysis-ready dataset."""
|
|
100
|
+
|
|
101
|
+
return export(
|
|
102
|
+
case_dir=self.case_dir,
|
|
103
|
+
output_dir=output_dir,
|
|
104
|
+
fields=fields,
|
|
105
|
+
times=times,
|
|
106
|
+
dtype=dtype,
|
|
107
|
+
mode=mode,
|
|
108
|
+
metadata=metadata,
|
|
109
|
+
n_jobs=n_jobs,
|
|
110
|
+
progress=progress,
|
|
111
|
+
overwrite=overwrite,
|
|
112
|
+
_toolchain_override=self._toolchain,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def postprocess(
|
|
116
|
+
self,
|
|
117
|
+
*,
|
|
118
|
+
operations: Sequence[PostprocessOperation],
|
|
119
|
+
times: TimeSelection = None,
|
|
120
|
+
n_jobs: int | None = None,
|
|
121
|
+
progress: bool = False,
|
|
122
|
+
overwrite: bool = False,
|
|
123
|
+
) -> PostprocessedCase:
|
|
124
|
+
"""Run supported OpenFOAM function objects on reconstructed times."""
|
|
125
|
+
|
|
126
|
+
if not self.reconstructed_times:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
"[StackNordic] case post-processing requires reconstructed times; "
|
|
129
|
+
"export decomposed data directly for Cartesian dataset post-processing"
|
|
130
|
+
)
|
|
131
|
+
names = _numeric_directories(self.case_dir)
|
|
132
|
+
return postprocess(
|
|
133
|
+
case_dir=self.case_dir,
|
|
134
|
+
time_names={value: names[value] for value in self.reconstructed_times},
|
|
135
|
+
toolchain=self._toolchain,
|
|
136
|
+
operations=operations,
|
|
137
|
+
times=times,
|
|
138
|
+
n_jobs=n_jobs,
|
|
139
|
+
progress=progress,
|
|
140
|
+
overwrite=overwrite,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def reconstruct(self, **kwargs) -> Reconstruction:
|
|
144
|
+
"""Reconstruct selected stored fields with the configured OpenFOAM runtime."""
|
|
145
|
+
|
|
146
|
+
return reconstruct(
|
|
147
|
+
case_dir=self.case_dir,
|
|
148
|
+
_toolchain_override=self._toolchain,
|
|
149
|
+
**kwargs,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def case(
|
|
154
|
+
*,
|
|
155
|
+
case_dir: str | Path,
|
|
156
|
+
of_cmd: str | None = None,
|
|
157
|
+
shell: str = "bash",
|
|
158
|
+
) -> Case:
|
|
159
|
+
"""Inspect an OpenFOAM case without changing its stored results."""
|
|
160
|
+
|
|
161
|
+
root = Path(case_dir).expanduser().resolve()
|
|
162
|
+
if not (root / "system/controlDict").is_file() or not (root / "constant").is_dir():
|
|
163
|
+
raise FileNotFoundError(f"[StackNordic] OpenFOAM case is incomplete: {root}")
|
|
164
|
+
reconstructed = tuple(sorted(_numeric_directories(root)))
|
|
165
|
+
try:
|
|
166
|
+
processors, processor_count, collated = _processor_directories(root)
|
|
167
|
+
rank_times = [_numeric_directories(path) for path in processors]
|
|
168
|
+
common = set(rank_times[0])
|
|
169
|
+
for values in rank_times[1:]:
|
|
170
|
+
common.intersection_update(values)
|
|
171
|
+
decomposed = tuple(sorted(common))
|
|
172
|
+
except FileNotFoundError:
|
|
173
|
+
processors, processor_count, collated, decomposed = (root,), 0, False, ()
|
|
174
|
+
family, versions = _source_identity(root, processors)
|
|
175
|
+
selected_toolchain = toolchain(of_cmd=of_cmd, shell=shell)
|
|
176
|
+
_warn_runtime_mismatch(family, selected_toolchain)
|
|
177
|
+
return Case(
|
|
178
|
+
case_dir=root,
|
|
179
|
+
family=family,
|
|
180
|
+
source_versions=versions,
|
|
181
|
+
reconstructed_times=reconstructed,
|
|
182
|
+
decomposed_times=decomposed,
|
|
183
|
+
processor_count=processor_count,
|
|
184
|
+
collated=collated,
|
|
185
|
+
_toolchain=selected_toolchain,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
__all__ = ["Case", "case"]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""OpenFOAM runtime selection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shlex
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class _Toolchain:
|
|
12
|
+
command: str | None
|
|
13
|
+
shell: str
|
|
14
|
+
|
|
15
|
+
def wrap(self, command: tuple[str, ...]) -> tuple[str, ...]:
|
|
16
|
+
if self.command is None:
|
|
17
|
+
return command
|
|
18
|
+
payload = shlex.join(command)
|
|
19
|
+
words = tuple(shlex.split(self.command))
|
|
20
|
+
if words and Path(words[0]).name == "openfoam":
|
|
21
|
+
return (*words, "-c", payload)
|
|
22
|
+
return (self.shell, "-lc", f"{self.command} && {payload}")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _normalise_command(of_cmd: str | None) -> str | None:
|
|
26
|
+
if of_cmd is None:
|
|
27
|
+
return None
|
|
28
|
+
value = of_cmd.strip()
|
|
29
|
+
if not value:
|
|
30
|
+
raise ValueError("of_cmd must not be empty")
|
|
31
|
+
if "/" in value and not any(character.isspace() for character in value):
|
|
32
|
+
return f"module load {shlex.quote(value)}"
|
|
33
|
+
return value
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def toolchain(*, of_cmd: str | None = None, shell: str = "bash") -> _Toolchain:
|
|
37
|
+
"""Create one case-local OpenFOAM toolchain."""
|
|
38
|
+
if not shell.strip():
|
|
39
|
+
raise ValueError("shell must not be empty")
|
|
40
|
+
return _Toolchain(_normalise_command(of_cmd), shell)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _toolchain() -> _Toolchain:
|
|
44
|
+
return _Toolchain(None, "bash")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def __dir__() -> list[str]:
|
|
48
|
+
return []
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""Decode stored OpenFOAM fields and collated processor blocks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class OpenFOAMDecodeError(ValueError):
|
|
14
|
+
"""Raised when stored OpenFOAM data cannot be decoded safely."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class FieldData:
|
|
19
|
+
field_class: str
|
|
20
|
+
values: np.ndarray
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_COMMENTS = re.compile(rb"/\*.*?\*/|//[^\n]*", re.DOTALL)
|
|
24
|
+
_COMPONENTS = {
|
|
25
|
+
b"scalar": 1,
|
|
26
|
+
b"sphericalTensor": 1,
|
|
27
|
+
b"vector": 3,
|
|
28
|
+
b"symmTensor": 6,
|
|
29
|
+
b"tensor": 9,
|
|
30
|
+
}
|
|
31
|
+
_NONUNIFORM = re.compile(
|
|
32
|
+
rb"\b(?:internalField\s+)?nonuniform\s+"
|
|
33
|
+
rb"List<(scalar|sphericalTensor|vector|symmTensor|tensor)>\s+(\d+)\s*\("
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _block(payload: bytes, name: bytes) -> bytes | None:
|
|
38
|
+
match = re.search(rb"\b" + re.escape(name) + rb"\s*\{", payload)
|
|
39
|
+
if match is None:
|
|
40
|
+
return None
|
|
41
|
+
depth = 1
|
|
42
|
+
for index in range(match.end(), len(payload)):
|
|
43
|
+
if payload[index] == ord("{"):
|
|
44
|
+
depth += 1
|
|
45
|
+
elif payload[index] == ord("}"):
|
|
46
|
+
depth -= 1
|
|
47
|
+
if depth == 0:
|
|
48
|
+
return payload[match.end() : index]
|
|
49
|
+
raise OpenFOAMDecodeError(f"unterminated {name.decode()} dictionary")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _block_end(payload: bytes, name: bytes) -> int:
|
|
53
|
+
match = re.search(rb"\b" + re.escape(name) + rb"\s*\{", payload)
|
|
54
|
+
if match is None:
|
|
55
|
+
raise OpenFOAMDecodeError(f"data is missing its {name.decode()} dictionary")
|
|
56
|
+
depth = 1
|
|
57
|
+
for index in range(match.end(), len(payload)):
|
|
58
|
+
if payload[index] == ord("{"):
|
|
59
|
+
depth += 1
|
|
60
|
+
elif payload[index] == ord("}"):
|
|
61
|
+
depth -= 1
|
|
62
|
+
if depth == 0:
|
|
63
|
+
return index + 1
|
|
64
|
+
raise OpenFOAMDecodeError(f"unterminated {name.decode()} dictionary")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _entry(block: bytes, name: bytes) -> str | None:
|
|
68
|
+
match = re.search(rb"\b" + re.escape(name) + rb'\s+(?:"([^"]*)"|([^;]+));', block)
|
|
69
|
+
if match is None:
|
|
70
|
+
return None
|
|
71
|
+
value = match.group(1) if match.group(1) is not None else match.group(2)
|
|
72
|
+
return value.decode().strip()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _header(payload: bytes) -> tuple[str, str, str | None]:
|
|
76
|
+
header = _block(_COMMENTS.sub(b" ", payload), b"FoamFile")
|
|
77
|
+
if header is None:
|
|
78
|
+
raise OpenFOAMDecodeError("data is missing its FoamFile dictionary")
|
|
79
|
+
field_class = _entry(header, b"class")
|
|
80
|
+
if not field_class:
|
|
81
|
+
raise OpenFOAMDecodeError("data is missing its OpenFOAM class")
|
|
82
|
+
return field_class, _entry(header, b"format") or "ascii", _entry(header, b"arch")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _binary_dtypes(arch: str | None, kind: str) -> tuple[np.dtype, ...]:
|
|
86
|
+
code = "i" if kind == "label" else "f"
|
|
87
|
+
if arch is None:
|
|
88
|
+
widths = (8, 4)
|
|
89
|
+
byte_order = "<"
|
|
90
|
+
else:
|
|
91
|
+
byte_order = "<" if arch.startswith("LSB;") else ">" if arch.startswith("MSB;") else "="
|
|
92
|
+
match = re.search(rf"(?:^|;){kind}=(32|64)(?:;|$)", arch)
|
|
93
|
+
widths = (int(match.group(1)) // 8,) if match is not None else (8, 4)
|
|
94
|
+
return tuple(np.dtype(f"{byte_order}{code}{width}") for width in widths)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _binary_values(
|
|
98
|
+
payload: bytes,
|
|
99
|
+
start: int,
|
|
100
|
+
count: int,
|
|
101
|
+
components: int,
|
|
102
|
+
arch: str | None,
|
|
103
|
+
kind: str,
|
|
104
|
+
) -> np.ndarray:
|
|
105
|
+
starts = (start,)
|
|
106
|
+
if payload[start : start + 2] == b"\r\n":
|
|
107
|
+
starts = (start + 2, start)
|
|
108
|
+
elif payload[start : start + 1] == b"\n":
|
|
109
|
+
starts = (start + 1, start)
|
|
110
|
+
for dtype in _binary_dtypes(arch, kind):
|
|
111
|
+
size = count * components * dtype.itemsize
|
|
112
|
+
for data_start in starts:
|
|
113
|
+
data_end = data_start + size
|
|
114
|
+
if re.match(rb"\s*\)\s*;?", payload[data_end:]) is not None:
|
|
115
|
+
return np.frombuffer(payload[data_start:data_end], dtype=dtype).astype(
|
|
116
|
+
dtype.newbyteorder("="), copy=True
|
|
117
|
+
)
|
|
118
|
+
raise OpenFOAMDecodeError("binary list byte count does not match its declaration")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def read_field_payload(payload: bytes, *, cell_count: int | None = None) -> FieldData:
|
|
122
|
+
"""Decode one complete OpenFOAM volume-field payload."""
|
|
123
|
+
|
|
124
|
+
field_class, format_name, arch = _header(payload)
|
|
125
|
+
uniform = re.search(rb"\binternalField\s+uniform\s+([^;]+);", payload, re.DOTALL)
|
|
126
|
+
if uniform is not None:
|
|
127
|
+
values = np.fromstring(
|
|
128
|
+
uniform.group(1).replace(b"(", b" ").replace(b")", b" "), sep=" "
|
|
129
|
+
)
|
|
130
|
+
if values.size not in {1, 3, 6, 9}:
|
|
131
|
+
raise OpenFOAMDecodeError("uniform internalField has an invalid component count")
|
|
132
|
+
if cell_count is None:
|
|
133
|
+
raise OpenFOAMDecodeError("uniform internalField requires its local cell count")
|
|
134
|
+
values = np.broadcast_to(values, (cell_count, values.size)).copy()
|
|
135
|
+
if values.shape[1] == 1:
|
|
136
|
+
values = values[:, 0]
|
|
137
|
+
return FieldData(field_class, values)
|
|
138
|
+
match = re.search(rb"\binternalField\s+" + _NONUNIFORM.pattern, payload)
|
|
139
|
+
if match is None:
|
|
140
|
+
raise OpenFOAMDecodeError("could not locate a supported internalField")
|
|
141
|
+
kind, raw_count = match.groups()
|
|
142
|
+
count = int(raw_count)
|
|
143
|
+
components = _COMPONENTS[kind]
|
|
144
|
+
if format_name == "binary":
|
|
145
|
+
values = _binary_values(payload, match.end(), count, components, arch, "scalar")
|
|
146
|
+
else:
|
|
147
|
+
end = re.search(rb"\)\s*;", payload[match.end() :], re.DOTALL)
|
|
148
|
+
if end is None:
|
|
149
|
+
raise OpenFOAMDecodeError("ASCII internalField is unterminated")
|
|
150
|
+
raw = payload[match.end() : match.end() + end.start()]
|
|
151
|
+
values = np.fromstring(raw.replace(b"(", b" ").replace(b")", b" "), sep=" ")
|
|
152
|
+
if values.size != count * components:
|
|
153
|
+
raise OpenFOAMDecodeError("ASCII internalField count does not match its declaration")
|
|
154
|
+
if components > 1:
|
|
155
|
+
values = values.reshape(count, components)
|
|
156
|
+
return FieldData(field_class, values)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def read_label_payload(payload: bytes) -> np.ndarray:
|
|
160
|
+
"""Decode an OpenFOAM label list."""
|
|
161
|
+
|
|
162
|
+
_, format_name, arch = _header(payload)
|
|
163
|
+
header_end = _block_end(payload, b"FoamFile")
|
|
164
|
+
trailing = _COMMENTS.sub(lambda match: b" " * len(match.group()), payload[header_end:])
|
|
165
|
+
match = re.search(rb"\b(\d+)\s*\(", trailing)
|
|
166
|
+
if match is None:
|
|
167
|
+
raise OpenFOAMDecodeError("could not locate label-list contents")
|
|
168
|
+
count = int(match.group(1))
|
|
169
|
+
start = header_end + match.end()
|
|
170
|
+
if format_name == "binary":
|
|
171
|
+
values = _binary_values(payload, start, count, 1, arch, "label")
|
|
172
|
+
else:
|
|
173
|
+
end = re.search(rb"\)\s*;?", payload[start:], re.DOTALL)
|
|
174
|
+
if end is None:
|
|
175
|
+
raise OpenFOAMDecodeError("ASCII label list is unterminated")
|
|
176
|
+
values = np.fromstring(payload[start : start + end.start()], sep=" ", dtype=np.int64)
|
|
177
|
+
if values.size != count:
|
|
178
|
+
raise OpenFOAMDecodeError("ASCII label-list count does not match its declaration")
|
|
179
|
+
return values.astype(np.int64, copy=False)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def collated_blocks(path: Path) -> Iterator[tuple[int, bytes]]:
|
|
183
|
+
"""Yield processor number and exact local payload from decomposedBlockData."""
|
|
184
|
+
|
|
185
|
+
marker = re.compile(rb"\s*//\s*Processor(\d+)\s*")
|
|
186
|
+
seen: set[int] = set()
|
|
187
|
+
local_header: bytes | None = None
|
|
188
|
+
with path.open("rb") as stream:
|
|
189
|
+
preamble = bytearray()
|
|
190
|
+
first_marker: tuple[int, bytes] | None = None
|
|
191
|
+
while line := stream.readline():
|
|
192
|
+
match = marker.fullmatch(line)
|
|
193
|
+
if match is not None:
|
|
194
|
+
first_marker = (int(match.group(1)), line)
|
|
195
|
+
break
|
|
196
|
+
preamble.extend(line)
|
|
197
|
+
field_class, _, _ = _header(bytes(preamble))
|
|
198
|
+
if field_class != "decomposedBlockData":
|
|
199
|
+
raise OpenFOAMDecodeError(f"{path} is not collated decomposedBlockData")
|
|
200
|
+
pending = first_marker
|
|
201
|
+
while pending is not None:
|
|
202
|
+
processor = pending[0]
|
|
203
|
+
size_line = stream.readline()
|
|
204
|
+
while size_line and not size_line.strip():
|
|
205
|
+
size_line = stream.readline()
|
|
206
|
+
try:
|
|
207
|
+
size = int(size_line.strip())
|
|
208
|
+
except ValueError as error:
|
|
209
|
+
raise OpenFOAMDecodeError(
|
|
210
|
+
f"collated block for processor{processor} has no byte count"
|
|
211
|
+
) from error
|
|
212
|
+
opening = stream.read(1)
|
|
213
|
+
while opening and opening.isspace():
|
|
214
|
+
opening = stream.read(1)
|
|
215
|
+
if opening != b"(":
|
|
216
|
+
raise OpenFOAMDecodeError(
|
|
217
|
+
f"collated block for processor{processor} has no opening delimiter"
|
|
218
|
+
)
|
|
219
|
+
block = stream.read(size)
|
|
220
|
+
if len(block) != size or stream.read(1) != b")":
|
|
221
|
+
raise OpenFOAMDecodeError(
|
|
222
|
+
f"collated block for processor{processor} is truncated"
|
|
223
|
+
)
|
|
224
|
+
if processor in seen:
|
|
225
|
+
raise OpenFOAMDecodeError(f"collated data repeats processor{processor}")
|
|
226
|
+
seen.add(processor)
|
|
227
|
+
header_start = re.search(rb"\bFoamFile\s*\{", block)
|
|
228
|
+
if header_start is not None:
|
|
229
|
+
local_header = block[header_start.start() : _block_end(block, b"FoamFile")]
|
|
230
|
+
elif local_header is not None:
|
|
231
|
+
block = local_header + b"\n" + block
|
|
232
|
+
else:
|
|
233
|
+
raise OpenFOAMDecodeError(
|
|
234
|
+
f"first collated block in {path} does not contain its local FoamFile header"
|
|
235
|
+
)
|
|
236
|
+
yield processor, block
|
|
237
|
+
pending = None
|
|
238
|
+
while line := stream.readline():
|
|
239
|
+
match = marker.fullmatch(line)
|
|
240
|
+
if match is not None:
|
|
241
|
+
pending = (int(match.group(1)), line)
|
|
242
|
+
break
|
|
243
|
+
if not seen:
|
|
244
|
+
raise OpenFOAMDecodeError(f"{path} contains no processor blocks")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def read_field(path: Path, *, cell_count: int | None = None) -> FieldData:
|
|
248
|
+
return read_field_payload(path.read_bytes(), cell_count=cell_count)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def read_labels(path: Path) -> np.ndarray:
|
|
252
|
+
return read_label_payload(path.read_bytes())
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""OpenFOAM-backed case post-processing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from time import perf_counter
|
|
11
|
+
|
|
12
|
+
from .._progress import finish_progress, start_progress
|
|
13
|
+
from ..postprocess import PostprocessOperation
|
|
14
|
+
from ..resources import workers
|
|
15
|
+
from ..selection import TimeSelection, select_times
|
|
16
|
+
from .environment import _Toolchain
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, slots=True)
|
|
20
|
+
class PostprocessedCase:
|
|
21
|
+
"""Summary of OpenFOAM function objects applied to one case."""
|
|
22
|
+
|
|
23
|
+
case_dir: Path
|
|
24
|
+
fields: tuple[str, ...]
|
|
25
|
+
times: tuple[float, ...]
|
|
26
|
+
n_jobs: int
|
|
27
|
+
elapsed_seconds: float
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _error(message: str, error_type: type[Exception] = ValueError):
|
|
31
|
+
raise error_type(f"[StackNordic] {message}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _function(operation: PostprocessOperation) -> str:
|
|
35
|
+
field = operation.field
|
|
36
|
+
if operation.kind in {"vorticity", "Q", "Lambda2"} and field != "U":
|
|
37
|
+
_error(f"OpenFOAM {operation.kind} currently requires field='U'")
|
|
38
|
+
return {
|
|
39
|
+
"grad": f"grad({field})",
|
|
40
|
+
"div": f"div({field})",
|
|
41
|
+
"ddt": f"ddt({field})",
|
|
42
|
+
"components": f"components({field})",
|
|
43
|
+
"mag": f"mag({field})",
|
|
44
|
+
"mag_sqr": f"magSqr({field})",
|
|
45
|
+
"vorticity": "vorticity",
|
|
46
|
+
"Q": "Q",
|
|
47
|
+
"Lambda2": "Lambda2",
|
|
48
|
+
"write_cell_centres": "writeCellCentres",
|
|
49
|
+
"write_cell_volumes": "writeCellVolumes",
|
|
50
|
+
}[operation.kind]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _generated(operation: PostprocessOperation) -> tuple[str, ...]:
|
|
54
|
+
field = operation.field
|
|
55
|
+
return {
|
|
56
|
+
"grad": (f"grad({field})",),
|
|
57
|
+
"div": (f"div({field})",),
|
|
58
|
+
"ddt": (f"ddt({field})",),
|
|
59
|
+
"components": tuple(f"{field}{axis}" for axis in "xyz"),
|
|
60
|
+
"mag": (f"mag({field})",),
|
|
61
|
+
"mag_sqr": (f"magSqr({field})",),
|
|
62
|
+
"vorticity": ("vorticity",),
|
|
63
|
+
"Q": ("Q",),
|
|
64
|
+
"Lambda2": ("Lambda2",),
|
|
65
|
+
"write_cell_centres": ("C",),
|
|
66
|
+
"write_cell_volumes": ("V",),
|
|
67
|
+
}[operation.kind]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _validate_operation(operation: PostprocessOperation) -> None:
|
|
71
|
+
try:
|
|
72
|
+
generated = _generated(operation)
|
|
73
|
+
except KeyError:
|
|
74
|
+
_error(f"unsupported post-processing operation {operation.kind!r}")
|
|
75
|
+
if len(generated) != len(operation.outputs):
|
|
76
|
+
_error(f"{operation.kind} output count does not match its OpenFOAM result")
|
|
77
|
+
_function(operation)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _run_one(
|
|
81
|
+
case_dir: Path,
|
|
82
|
+
time_name: str,
|
|
83
|
+
operation: PostprocessOperation,
|
|
84
|
+
toolchain: _Toolchain,
|
|
85
|
+
overwrite: bool,
|
|
86
|
+
) -> None:
|
|
87
|
+
_validate_operation(operation)
|
|
88
|
+
generated = _generated(operation)
|
|
89
|
+
targets = tuple(case_dir / time_name / name for name in operation.outputs)
|
|
90
|
+
generated_paths = tuple(case_dir / time_name / name for name in generated)
|
|
91
|
+
existing = tuple(path for path in {*targets, *generated_paths} if path.exists())
|
|
92
|
+
if existing and not overwrite:
|
|
93
|
+
_error(
|
|
94
|
+
f"post-processing output already exists at t={time_name}: {existing[0].name}",
|
|
95
|
+
FileExistsError,
|
|
96
|
+
)
|
|
97
|
+
command = toolchain.wrap(
|
|
98
|
+
(
|
|
99
|
+
"postProcess",
|
|
100
|
+
"-case",
|
|
101
|
+
str(case_dir),
|
|
102
|
+
"-func",
|
|
103
|
+
_function(operation),
|
|
104
|
+
"-time",
|
|
105
|
+
time_name,
|
|
106
|
+
)
|
|
107
|
+
)
|
|
108
|
+
result = subprocess.run(
|
|
109
|
+
command,
|
|
110
|
+
check=False,
|
|
111
|
+
stdout=subprocess.PIPE,
|
|
112
|
+
stderr=subprocess.STDOUT,
|
|
113
|
+
text=True,
|
|
114
|
+
)
|
|
115
|
+
if result.returncode != 0:
|
|
116
|
+
lines = result.stdout.strip().splitlines()
|
|
117
|
+
detail = "\n".join(lines[-20:]) if lines else "postProcess failed without output"
|
|
118
|
+
raise RuntimeError(
|
|
119
|
+
f"[StackNordic] OpenFOAM {_function(operation)} failed at t={time_name}:\n{detail}"
|
|
120
|
+
)
|
|
121
|
+
for source_name, target in zip(generated, targets, strict=True):
|
|
122
|
+
source = case_dir / time_name / source_name
|
|
123
|
+
if not source.is_file():
|
|
124
|
+
_error(
|
|
125
|
+
f"OpenFOAM {_function(operation)} completed without {source_name!r}",
|
|
126
|
+
RuntimeError,
|
|
127
|
+
)
|
|
128
|
+
if source != target:
|
|
129
|
+
if target.exists():
|
|
130
|
+
target.unlink()
|
|
131
|
+
source.replace(target)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def postprocess(
|
|
135
|
+
*,
|
|
136
|
+
case_dir: Path,
|
|
137
|
+
time_names: dict[float, str],
|
|
138
|
+
toolchain: _Toolchain,
|
|
139
|
+
operations: Sequence[PostprocessOperation],
|
|
140
|
+
times: TimeSelection,
|
|
141
|
+
n_jobs: int | None,
|
|
142
|
+
progress: bool,
|
|
143
|
+
overwrite: bool,
|
|
144
|
+
) -> PostprocessedCase:
|
|
145
|
+
"""Run supported OpenFOAM function objects on reconstructed times."""
|
|
146
|
+
|
|
147
|
+
started = perf_counter()
|
|
148
|
+
selected_operations = tuple(operations)
|
|
149
|
+
if not selected_operations or any(
|
|
150
|
+
not isinstance(item, PostprocessOperation) for item in selected_operations
|
|
151
|
+
):
|
|
152
|
+
raise TypeError("operations must contain StackNordic post-processing contracts")
|
|
153
|
+
for operation in selected_operations:
|
|
154
|
+
_validate_operation(operation)
|
|
155
|
+
selected_times = select_times(tuple(time_names), times)
|
|
156
|
+
work = tuple(
|
|
157
|
+
(value, operation)
|
|
158
|
+
for value in selected_times
|
|
159
|
+
for operation in selected_operations
|
|
160
|
+
)
|
|
161
|
+
selected_workers = workers(n_jobs, len(work))
|
|
162
|
+
reporter = (
|
|
163
|
+
start_progress(len(work), "StackNordic OpenFOAM post-processing")
|
|
164
|
+
if progress
|
|
165
|
+
else None
|
|
166
|
+
)
|
|
167
|
+
try:
|
|
168
|
+
if selected_workers == 1:
|
|
169
|
+
for value, operation in work:
|
|
170
|
+
_run_one(
|
|
171
|
+
case_dir,
|
|
172
|
+
time_names[value],
|
|
173
|
+
operation,
|
|
174
|
+
toolchain,
|
|
175
|
+
overwrite,
|
|
176
|
+
)
|
|
177
|
+
if reporter is not None:
|
|
178
|
+
reporter.update()
|
|
179
|
+
else:
|
|
180
|
+
with ThreadPoolExecutor(max_workers=selected_workers) as executor:
|
|
181
|
+
futures = [
|
|
182
|
+
executor.submit(
|
|
183
|
+
_run_one,
|
|
184
|
+
case_dir,
|
|
185
|
+
time_names[value],
|
|
186
|
+
operation,
|
|
187
|
+
toolchain,
|
|
188
|
+
overwrite,
|
|
189
|
+
)
|
|
190
|
+
for value, operation in work
|
|
191
|
+
]
|
|
192
|
+
for future in as_completed(futures):
|
|
193
|
+
future.result()
|
|
194
|
+
if reporter is not None:
|
|
195
|
+
reporter.update()
|
|
196
|
+
finally:
|
|
197
|
+
if reporter is not None:
|
|
198
|
+
finish_progress(reporter)
|
|
199
|
+
return PostprocessedCase(
|
|
200
|
+
case_dir=case_dir,
|
|
201
|
+
fields=tuple(name for operation in selected_operations for name in operation.outputs),
|
|
202
|
+
times=selected_times,
|
|
203
|
+
n_jobs=selected_workers,
|
|
204
|
+
elapsed_seconds=perf_counter() - started,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
__all__ = ["PostprocessedCase", "postprocess"]
|