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,295 @@
|
|
|
1
|
+
"""Materialise derived scalar fields in stored OpenFOAM layouts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import tempfile
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from time import perf_counter
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from .._progress import finish_progress, start_progress
|
|
17
|
+
from ..computing import ProgressComputation
|
|
18
|
+
from ..dataset.export import (
|
|
19
|
+
_available_layouts,
|
|
20
|
+
_mesh_file,
|
|
21
|
+
_processor_payloads,
|
|
22
|
+
_Source,
|
|
23
|
+
)
|
|
24
|
+
from ..reconstruction import _numeric_directories
|
|
25
|
+
from ..resources import workers
|
|
26
|
+
from ..selection import TimeSelection, select_times
|
|
27
|
+
from .io import _block, collated_blocks, read_field_payload, read_label_payload
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class ComputedFields:
|
|
32
|
+
"""Summary of derived fields written into an OpenFOAM case."""
|
|
33
|
+
|
|
34
|
+
case_dir: Path
|
|
35
|
+
fields: tuple[str, ...]
|
|
36
|
+
times: tuple[float, ...]
|
|
37
|
+
n_jobs: int
|
|
38
|
+
elapsed_seconds: float
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _error(message: str, error_type: type[Exception] = ValueError):
|
|
42
|
+
raise error_type(f"[StackNordic] {message}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _cell_counts(source: _Source, time_value: float) -> dict[int, int]:
|
|
46
|
+
path = _mesh_file(source, time_value, "cellProcAddressing")
|
|
47
|
+
return {
|
|
48
|
+
rank: read_label_payload(payload).size
|
|
49
|
+
for rank, payload in _processor_payloads(source, path)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _transform_boundary(payload: bytes, scale: float, offset: float) -> str:
|
|
54
|
+
block = _block(payload, b"boundaryField")
|
|
55
|
+
if block is None:
|
|
56
|
+
return "boundaryField\n{}\n"
|
|
57
|
+
text = block.decode("utf-8", errors="replace")
|
|
58
|
+
uniform = re.compile(
|
|
59
|
+
r"(?m)^(\s*(?:value|inletValue|refValue)\s+uniform\s+)"
|
|
60
|
+
r"([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)(\s*;)"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def replace(match: re.Match[str]) -> str:
|
|
64
|
+
value = scale * float(match.group(2)) + offset
|
|
65
|
+
return f"{match.group(1)}{value:.16g}{match.group(3)}"
|
|
66
|
+
|
|
67
|
+
text = uniform.sub(replace, text)
|
|
68
|
+
nonuniform = re.compile(
|
|
69
|
+
r"((?:value|inletValue|refValue)\s+nonuniform\s+List<scalar>\s+"
|
|
70
|
+
r"(\d+)\s*\()(.*?)(\)\s*;)",
|
|
71
|
+
re.DOTALL,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def replace_list(match: re.Match[str]) -> str:
|
|
75
|
+
count = int(match.group(2))
|
|
76
|
+
values = np.fromstring(match.group(3), sep=" ")
|
|
77
|
+
if values.size != count:
|
|
78
|
+
_error("boundary scalar list cannot be decoded safely")
|
|
79
|
+
transformed = scale * values + offset
|
|
80
|
+
body = "\n".join(f"{value:.16g}" for value in transformed)
|
|
81
|
+
return f"{match.group(1)}\n{body}\n{match.group(4)}"
|
|
82
|
+
|
|
83
|
+
return f"boundaryField\n{{{nonuniform.sub(replace_list, text)}}}\n"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _scalar_payload(
|
|
87
|
+
template: bytes,
|
|
88
|
+
values: np.ndarray,
|
|
89
|
+
name: str,
|
|
90
|
+
scale: float,
|
|
91
|
+
offset: float,
|
|
92
|
+
) -> bytes:
|
|
93
|
+
dimensions = re.search(rb"(?m)^\s*dimensions\s+([^;]+);", template)
|
|
94
|
+
dimension_set = (
|
|
95
|
+
dimensions.group(1).decode("ascii", errors="replace").strip()
|
|
96
|
+
if dimensions is not None
|
|
97
|
+
else "[0 0 0 0 0 0 0]"
|
|
98
|
+
)
|
|
99
|
+
body = "\n".join(f"{value:.16g}" for value in np.asarray(values).reshape(-1))
|
|
100
|
+
return (
|
|
101
|
+
"FoamFile\n"
|
|
102
|
+
"{\n"
|
|
103
|
+
" format ascii;\n"
|
|
104
|
+
" class volScalarField;\n"
|
|
105
|
+
f" object {name};\n"
|
|
106
|
+
"}\n\n"
|
|
107
|
+
f"dimensions {dimension_set};\n\n"
|
|
108
|
+
f"internalField nonuniform List<scalar>\n{values.size}\n(\n{body}\n);\n\n"
|
|
109
|
+
f"{_transform_boundary(template, scale, offset)}"
|
|
110
|
+
).encode()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _write_atomic(path: Path, payload: bytes) -> None:
|
|
114
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
115
|
+
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
|
116
|
+
try:
|
|
117
|
+
with os.fdopen(descriptor, "wb") as stream:
|
|
118
|
+
stream.write(payload)
|
|
119
|
+
stream.flush()
|
|
120
|
+
os.fsync(stream.fileno())
|
|
121
|
+
Path(temporary).replace(path)
|
|
122
|
+
except Exception:
|
|
123
|
+
Path(temporary).unlink(missing_ok=True)
|
|
124
|
+
raise
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _evaluate(
|
|
128
|
+
definition: ProgressComputation,
|
|
129
|
+
payload: bytes,
|
|
130
|
+
cell_count: int | None,
|
|
131
|
+
) -> tuple[np.ndarray, float, float]:
|
|
132
|
+
source = definition.inputs[0]
|
|
133
|
+
data = read_field_payload(payload, cell_count=cell_count)
|
|
134
|
+
if data.field_class != "volScalarField":
|
|
135
|
+
_error(f"progress input {source!r} must be a volScalarField")
|
|
136
|
+
scale = float(definition.coefficients[source])
|
|
137
|
+
values = scale * np.asarray(data.values, dtype=np.float64) + definition.offset
|
|
138
|
+
if not np.all(np.isfinite(values)):
|
|
139
|
+
_error(f"computed field {definition.output!r} contains non-finite values")
|
|
140
|
+
return values, scale, definition.offset
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _write_reconstructed(
|
|
144
|
+
case_dir: Path,
|
|
145
|
+
time_name: str,
|
|
146
|
+
definition: ProgressComputation,
|
|
147
|
+
overwrite: bool,
|
|
148
|
+
) -> None:
|
|
149
|
+
source = case_dir / time_name / definition.inputs[0]
|
|
150
|
+
destination = case_dir / time_name / definition.output
|
|
151
|
+
if destination.exists() and not overwrite:
|
|
152
|
+
_error(f"field {definition.output!r} already exists at t={time_name}", FileExistsError)
|
|
153
|
+
template = source.read_bytes()
|
|
154
|
+
values, scale, offset = _evaluate(definition, template, None)
|
|
155
|
+
_write_atomic(
|
|
156
|
+
destination,
|
|
157
|
+
_scalar_payload(template, values, definition.output, scale, offset),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _write_uncollated(
|
|
162
|
+
source: _Source,
|
|
163
|
+
time_value: float,
|
|
164
|
+
time_name: str,
|
|
165
|
+
definition: ProgressComputation,
|
|
166
|
+
overwrite: bool,
|
|
167
|
+
) -> None:
|
|
168
|
+
input_path = source.path / time_name / definition.inputs[0]
|
|
169
|
+
output_path = source.path / time_name / definition.output
|
|
170
|
+
if output_path.exists() and not overwrite:
|
|
171
|
+
_error(
|
|
172
|
+
f"field {definition.output!r} already exists at t={time_name} in {source.path.name}",
|
|
173
|
+
FileExistsError,
|
|
174
|
+
)
|
|
175
|
+
template = input_path.read_bytes()
|
|
176
|
+
count = _cell_counts(source, time_value)[source.first_rank]
|
|
177
|
+
values, scale, offset = _evaluate(definition, template, count)
|
|
178
|
+
_write_atomic(
|
|
179
|
+
output_path,
|
|
180
|
+
_scalar_payload(template, values, definition.output, scale, offset),
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _write_collated(
|
|
185
|
+
source: _Source,
|
|
186
|
+
time_value: float,
|
|
187
|
+
time_name: str,
|
|
188
|
+
definition: ProgressComputation,
|
|
189
|
+
overwrite: bool,
|
|
190
|
+
) -> None:
|
|
191
|
+
input_path = source.path / time_name / definition.inputs[0]
|
|
192
|
+
output_path = source.path / time_name / definition.output
|
|
193
|
+
if output_path.exists() and not overwrite:
|
|
194
|
+
_error(
|
|
195
|
+
f"field {definition.output!r} already exists at t={time_name} in {source.path.name}",
|
|
196
|
+
FileExistsError,
|
|
197
|
+
)
|
|
198
|
+
counts = _cell_counts(source, time_value)
|
|
199
|
+
blocks: list[tuple[int, bytes]] = []
|
|
200
|
+
for local_rank, template in collated_blocks(input_path):
|
|
201
|
+
rank = local_rank if local_rank >= source.first_rank else local_rank + source.first_rank
|
|
202
|
+
count = counts[rank]
|
|
203
|
+
values, scale, offset = _evaluate(definition, template, count)
|
|
204
|
+
blocks.append(
|
|
205
|
+
(local_rank, _scalar_payload(template, values, definition.output, scale, offset))
|
|
206
|
+
)
|
|
207
|
+
preamble = (
|
|
208
|
+
"FoamFile\n{\n"
|
|
209
|
+
" format binary;\n"
|
|
210
|
+
" class decomposedBlockData;\n"
|
|
211
|
+
f" object {definition.output};\n"
|
|
212
|
+
"}\n"
|
|
213
|
+
).encode()
|
|
214
|
+
payload = bytearray(preamble)
|
|
215
|
+
for rank, block in blocks:
|
|
216
|
+
payload.extend(f"\n// Processor{rank}\n\n{len(block)}\n(".encode())
|
|
217
|
+
payload.extend(block)
|
|
218
|
+
payload.extend(b")\n")
|
|
219
|
+
_write_atomic(output_path, bytes(payload))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def materialise(
|
|
223
|
+
*,
|
|
224
|
+
case_dir: Path,
|
|
225
|
+
computations: Sequence[ProgressComputation],
|
|
226
|
+
times: TimeSelection,
|
|
227
|
+
n_jobs: int | None,
|
|
228
|
+
progress: bool,
|
|
229
|
+
overwrite: bool,
|
|
230
|
+
) -> ComputedFields:
|
|
231
|
+
"""Write derived scalar fields into existing OpenFOAM time layouts."""
|
|
232
|
+
|
|
233
|
+
started = perf_counter()
|
|
234
|
+
definitions = tuple(computations)
|
|
235
|
+
if not definitions or any(not isinstance(item, ProgressComputation) for item in definitions):
|
|
236
|
+
raise TypeError("computations must contain StackNordic computation contracts")
|
|
237
|
+
if any(len(item.inputs) != 1 for item in definitions):
|
|
238
|
+
_error(
|
|
239
|
+
"case.compute currently accepts single-species progress definitions; "
|
|
240
|
+
"use Dataset.compute for multi-species progress and reaction rates"
|
|
241
|
+
)
|
|
242
|
+
outputs = tuple(item.output for item in definitions)
|
|
243
|
+
if len(set(outputs)) != len(outputs):
|
|
244
|
+
_error("computation outputs must be unique")
|
|
245
|
+
root_times = {
|
|
246
|
+
value: name
|
|
247
|
+
for value, name in _numeric_directories(case_dir).items()
|
|
248
|
+
if all((case_dir / name / item.inputs[0]).is_file() for item in definitions)
|
|
249
|
+
}
|
|
250
|
+
try:
|
|
251
|
+
layouts = _available_layouts(case_dir)
|
|
252
|
+
except FileNotFoundError:
|
|
253
|
+
layouts = {}
|
|
254
|
+
available = dict(layouts)
|
|
255
|
+
available.update(root_times)
|
|
256
|
+
selected = select_times(tuple(available), times)
|
|
257
|
+
work = tuple((value, definition) for value in selected for definition in definitions)
|
|
258
|
+
selected_workers = workers(n_jobs, len(work))
|
|
259
|
+
reporter = start_progress(len(work), "StackNordic computing") if progress else None
|
|
260
|
+
|
|
261
|
+
def task(value: float, definition: ProgressComputation) -> None:
|
|
262
|
+
if value in root_times:
|
|
263
|
+
_write_reconstructed(case_dir, root_times[value], definition, overwrite)
|
|
264
|
+
return
|
|
265
|
+
layout = layouts[value]
|
|
266
|
+
for source in layout.sources:
|
|
267
|
+
writer = _write_collated if source.collated else _write_uncollated
|
|
268
|
+
writer(source, value, layout.name, definition, overwrite)
|
|
269
|
+
|
|
270
|
+
try:
|
|
271
|
+
if selected_workers == 1:
|
|
272
|
+
for item in work:
|
|
273
|
+
task(*item)
|
|
274
|
+
if reporter is not None:
|
|
275
|
+
reporter.update()
|
|
276
|
+
else:
|
|
277
|
+
with ThreadPoolExecutor(max_workers=selected_workers) as executor:
|
|
278
|
+
futures = [executor.submit(task, *item) for item in work]
|
|
279
|
+
for future in as_completed(futures):
|
|
280
|
+
future.result()
|
|
281
|
+
if reporter is not None:
|
|
282
|
+
reporter.update()
|
|
283
|
+
finally:
|
|
284
|
+
if reporter is not None:
|
|
285
|
+
finish_progress(reporter)
|
|
286
|
+
return ComputedFields(
|
|
287
|
+
case_dir=case_dir,
|
|
288
|
+
fields=outputs,
|
|
289
|
+
times=selected,
|
|
290
|
+
n_jobs=selected_workers,
|
|
291
|
+
elapsed_seconds=perf_counter() - started,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
__all__ = ["ComputedFields", "materialise"]
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Portable post-processing operation declarations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class PostprocessOperation:
|
|
10
|
+
"""One post-processing operation shared by supported backends."""
|
|
11
|
+
|
|
12
|
+
kind: str
|
|
13
|
+
field: str | None
|
|
14
|
+
outputs: tuple[str, ...]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _field_operation(kind: str, field: str, output: str | None) -> PostprocessOperation:
|
|
18
|
+
if not field:
|
|
19
|
+
raise ValueError("field must be a non-empty name")
|
|
20
|
+
selected = output or f"{kind}{field[0].upper()}{field[1:]}"
|
|
21
|
+
if not selected:
|
|
22
|
+
raise ValueError("output must be a non-empty name")
|
|
23
|
+
return PostprocessOperation(kind, field, (selected,))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Postprocess:
|
|
27
|
+
"""Factories for the supported OpenFOAM and Cartesian operations."""
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def grad(*, field: str, output: str | None = None) -> PostprocessOperation:
|
|
31
|
+
"""Return the spatial gradient of a scalar or vector field."""
|
|
32
|
+
|
|
33
|
+
return _field_operation("grad", field, output or f"grad{field}")
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def div(*, field: str, output: str | None = None) -> PostprocessOperation:
|
|
37
|
+
"""Return the divergence of a vector field."""
|
|
38
|
+
|
|
39
|
+
return _field_operation("div", field, output or f"div{field}")
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def ddt(*, field: str, output: str | None = None) -> PostprocessOperation:
|
|
43
|
+
"""Return the temporal derivative of a stored field."""
|
|
44
|
+
|
|
45
|
+
return _field_operation("ddt", field, output or f"ddt{field}")
|
|
46
|
+
|
|
47
|
+
@staticmethod
|
|
48
|
+
def components(
|
|
49
|
+
*,
|
|
50
|
+
field: str,
|
|
51
|
+
outputs: tuple[str, ...] | None = None,
|
|
52
|
+
) -> PostprocessOperation:
|
|
53
|
+
"""Split a vector field into scalar components."""
|
|
54
|
+
|
|
55
|
+
if not field:
|
|
56
|
+
raise ValueError("field must be a non-empty name")
|
|
57
|
+
selected = outputs or tuple(f"{field}{axis}" for axis in "xyz")
|
|
58
|
+
if not selected or any(not name for name in selected):
|
|
59
|
+
raise ValueError("outputs must contain non-empty names")
|
|
60
|
+
return PostprocessOperation("components", field, tuple(selected))
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def mag(*, field: str, output: str | None = None) -> PostprocessOperation:
|
|
64
|
+
"""Return a field magnitude."""
|
|
65
|
+
|
|
66
|
+
return _field_operation("mag", field, output or f"mag{field}")
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def mag_sqr(*, field: str, output: str | None = None) -> PostprocessOperation:
|
|
70
|
+
"""Return a squared field magnitude."""
|
|
71
|
+
|
|
72
|
+
return _field_operation("mag_sqr", field, output or f"magSqr{field}")
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def vorticity(*, field: str = "U", output: str = "vorticity") -> PostprocessOperation:
|
|
76
|
+
"""Return the curl of a velocity field."""
|
|
77
|
+
|
|
78
|
+
return _field_operation("vorticity", field, output)
|
|
79
|
+
|
|
80
|
+
@staticmethod
|
|
81
|
+
def Q(*, field: str = "U", output: str = "Q") -> PostprocessOperation:
|
|
82
|
+
"""Return the second invariant of the velocity-gradient tensor."""
|
|
83
|
+
|
|
84
|
+
return _field_operation("Q", field, output)
|
|
85
|
+
|
|
86
|
+
@staticmethod
|
|
87
|
+
def Lambda2(*, field: str = "U", output: str = "Lambda2") -> PostprocessOperation:
|
|
88
|
+
"""Return the Lambda2 vortex criterion."""
|
|
89
|
+
|
|
90
|
+
return _field_operation("Lambda2", field, output)
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
def write_cell_centres(*, output: str = "C") -> PostprocessOperation:
|
|
94
|
+
"""Return cell-centre coordinates."""
|
|
95
|
+
|
|
96
|
+
return PostprocessOperation("write_cell_centres", None, (output,))
|
|
97
|
+
|
|
98
|
+
@staticmethod
|
|
99
|
+
def write_cell_volumes(*, output: str = "V") -> PostprocessOperation:
|
|
100
|
+
"""Return cell volumes."""
|
|
101
|
+
|
|
102
|
+
return PostprocessOperation("write_cell_volumes", None, (output,))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
__all__ = ["Postprocess", "PostprocessOperation"]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def __dir__() -> list[str]:
|
|
109
|
+
return sorted(__all__)
|