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,354 @@
|
|
|
1
|
+
"""Post-process Cartesian StackNordic datasets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
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 ..postprocess import PostprocessOperation
|
|
18
|
+
from ..resources import memory_bounded_workers
|
|
19
|
+
from ._manifest import component_file
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class PostprocessedDataset:
|
|
24
|
+
"""Summary of fields added to one Cartesian dataset."""
|
|
25
|
+
|
|
26
|
+
dataset_dir: Path
|
|
27
|
+
fields: tuple[str, ...]
|
|
28
|
+
snapshots: int
|
|
29
|
+
elapsed_seconds: float
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _error(message: str, error_type: type[Exception] = ValueError):
|
|
33
|
+
raise error_type(f"[StackNordic] {message}")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _Dataset:
|
|
37
|
+
def __init__(self, root: Path, info: dict[str, object]):
|
|
38
|
+
global_info = info["global"]
|
|
39
|
+
if global_info.get("layout") != "cartesian" or "Nxyz" not in global_info:
|
|
40
|
+
_error("dataset post-processing requires a Cartesian dataset")
|
|
41
|
+
self.root = root
|
|
42
|
+
self.info = info
|
|
43
|
+
self.records = tuple(info["local"])
|
|
44
|
+
self.dtype = np.dtype(global_info["dtype"])
|
|
45
|
+
self.nxyz = tuple(int(value) for value in global_info["Nxyz"])
|
|
46
|
+
self.shape = tuple(reversed(self.nxyz))
|
|
47
|
+
self.fields = {
|
|
48
|
+
name: tuple(components)
|
|
49
|
+
for name, components in global_info["fields"].items()
|
|
50
|
+
}
|
|
51
|
+
self.coordinates = tuple(
|
|
52
|
+
np.fromfile(root / global_info["grid"][axis], dtype=self.dtype)
|
|
53
|
+
for axis in "xyz"
|
|
54
|
+
)
|
|
55
|
+
if tuple(axis.size for axis in self.coordinates) != self.nxyz:
|
|
56
|
+
_error("Cartesian coordinate lengths do not match Nxyz")
|
|
57
|
+
if any(axis.size > 1 and np.any(np.diff(axis) <= 0.0) for axis in self.coordinates):
|
|
58
|
+
_error("Cartesian coordinates must be strictly increasing")
|
|
59
|
+
times = np.asarray([float(record["time [s]"]) for record in self.records])
|
|
60
|
+
if times.size > 1 and np.any(np.diff(times) <= 0.0):
|
|
61
|
+
_error("dataset times must be strictly increasing")
|
|
62
|
+
|
|
63
|
+
def field(self, index: int, name: str) -> np.ndarray:
|
|
64
|
+
if name not in self.fields:
|
|
65
|
+
_error(f"post-processing requested unavailable field {name!r}", KeyError)
|
|
66
|
+
record = self.records[index]
|
|
67
|
+
arrays = [
|
|
68
|
+
np.memmap(
|
|
69
|
+
self.root / component_file(record, component),
|
|
70
|
+
dtype=self.dtype,
|
|
71
|
+
mode="r",
|
|
72
|
+
shape=self.shape,
|
|
73
|
+
)
|
|
74
|
+
for component in self.fields[name]
|
|
75
|
+
]
|
|
76
|
+
if len(arrays) == 1:
|
|
77
|
+
return np.asarray(arrays[0], dtype=np.float64)
|
|
78
|
+
return np.stack(arrays, axis=-1).astype(np.float64, copy=False)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _derivative(values: np.ndarray, coordinates: np.ndarray, axis: int) -> np.ndarray:
|
|
82
|
+
if values.shape[axis] == 1:
|
|
83
|
+
return np.zeros_like(values, dtype=np.float64)
|
|
84
|
+
edge_order = 2 if values.shape[axis] > 2 else 1
|
|
85
|
+
return np.gradient(values, coordinates, axis=axis, edge_order=edge_order)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _gradient(values: np.ndarray, coordinates: tuple[np.ndarray, ...]) -> np.ndarray:
|
|
89
|
+
derivatives = tuple(
|
|
90
|
+
_derivative(values, coordinate, axis)
|
|
91
|
+
for coordinate, axis in zip(reversed(coordinates), range(3), strict=True)
|
|
92
|
+
)
|
|
93
|
+
ordered = tuple(reversed(derivatives))
|
|
94
|
+
if values.ndim == 3:
|
|
95
|
+
return np.stack(ordered, axis=-1)
|
|
96
|
+
return np.stack(ordered, axis=-1).reshape((*values.shape[:3], -1))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _velocity_gradient(dataset: _Dataset, index: int, field: str) -> np.ndarray:
|
|
100
|
+
values = dataset.field(index, field)
|
|
101
|
+
if values.ndim != 4 or values.shape[-1] != 3:
|
|
102
|
+
_error(f"{field!r} must have three components")
|
|
103
|
+
return _gradient(values, dataset.coordinates).reshape((*dataset.shape, 3, 3))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _evaluate(
|
|
107
|
+
dataset: _Dataset,
|
|
108
|
+
operation: PostprocessOperation,
|
|
109
|
+
index: int,
|
|
110
|
+
) -> dict[str, np.ndarray]:
|
|
111
|
+
kind = operation.kind
|
|
112
|
+
field = operation.field
|
|
113
|
+
if kind == "write_cell_centres":
|
|
114
|
+
x_values, y_values, z_values = dataset.coordinates
|
|
115
|
+
z, y, x = np.meshgrid(z_values, y_values, x_values, indexing="ij")
|
|
116
|
+
return {operation.outputs[0]: np.stack((x, y, z), axis=-1)}
|
|
117
|
+
if kind == "write_cell_volumes":
|
|
118
|
+
if any(axis.size < 2 for axis in dataset.coordinates):
|
|
119
|
+
_error("cell volumes require at least two centres along every Cartesian axis")
|
|
120
|
+
widths = []
|
|
121
|
+
for coordinates in dataset.coordinates:
|
|
122
|
+
faces = np.empty(coordinates.size + 1, dtype=np.float64)
|
|
123
|
+
faces[1:-1] = 0.5 * (coordinates[:-1] + coordinates[1:])
|
|
124
|
+
faces[0] = coordinates[0] - 0.5 * (coordinates[1] - coordinates[0])
|
|
125
|
+
faces[-1] = coordinates[-1] + 0.5 * (coordinates[-1] - coordinates[-2])
|
|
126
|
+
widths.append(np.diff(faces))
|
|
127
|
+
dx, dy, dz = widths
|
|
128
|
+
return {operation.outputs[0]: dz[:, None, None] * dy[None, :, None] * dx[None, None, :]}
|
|
129
|
+
assert field is not None
|
|
130
|
+
values = dataset.field(index, field)
|
|
131
|
+
if kind == "components":
|
|
132
|
+
if values.ndim != 4 or len(operation.outputs) != values.shape[-1]:
|
|
133
|
+
_error(f"components({field}) requires one output per component")
|
|
134
|
+
return {
|
|
135
|
+
name: values[..., component]
|
|
136
|
+
for component, name in enumerate(operation.outputs)
|
|
137
|
+
}
|
|
138
|
+
if kind == "mag":
|
|
139
|
+
return {operation.outputs[0]: np.abs(values) if values.ndim == 3 else np.linalg.norm(values, axis=-1)}
|
|
140
|
+
if kind == "mag_sqr":
|
|
141
|
+
return {operation.outputs[0]: values * values if values.ndim == 3 else np.sum(values * values, axis=-1)}
|
|
142
|
+
if kind == "grad":
|
|
143
|
+
return {operation.outputs[0]: _gradient(values, dataset.coordinates)}
|
|
144
|
+
if kind == "ddt":
|
|
145
|
+
times = np.asarray([float(record["time [s]"]) for record in dataset.records])
|
|
146
|
+
if times.size < 2:
|
|
147
|
+
_error("ddt requires at least two snapshots")
|
|
148
|
+
if index == 0:
|
|
149
|
+
result = (dataset.field(1, field) - values) / (times[1] - times[0])
|
|
150
|
+
elif index == times.size - 1:
|
|
151
|
+
result = (values - dataset.field(index - 1, field)) / (times[index] - times[index - 1])
|
|
152
|
+
else:
|
|
153
|
+
result = (
|
|
154
|
+
dataset.field(index + 1, field) - dataset.field(index - 1, field)
|
|
155
|
+
) / (times[index + 1] - times[index - 1])
|
|
156
|
+
return {operation.outputs[0]: result}
|
|
157
|
+
gradient = _velocity_gradient(dataset, index, field)
|
|
158
|
+
if kind == "div":
|
|
159
|
+
return {operation.outputs[0]: np.trace(gradient, axis1=-2, axis2=-1)}
|
|
160
|
+
if kind == "vorticity":
|
|
161
|
+
return {
|
|
162
|
+
operation.outputs[0]: np.stack(
|
|
163
|
+
(
|
|
164
|
+
gradient[..., 2, 1] - gradient[..., 1, 2],
|
|
165
|
+
gradient[..., 0, 2] - gradient[..., 2, 0],
|
|
166
|
+
gradient[..., 1, 0] - gradient[..., 0, 1],
|
|
167
|
+
),
|
|
168
|
+
axis=-1,
|
|
169
|
+
)
|
|
170
|
+
}
|
|
171
|
+
symmetric = 0.5 * (gradient + np.swapaxes(gradient, -1, -2))
|
|
172
|
+
rotation = 0.5 * (gradient - np.swapaxes(gradient, -1, -2))
|
|
173
|
+
if kind == "Q":
|
|
174
|
+
value = 0.5 * (
|
|
175
|
+
np.sum(rotation * rotation, axis=(-2, -1))
|
|
176
|
+
- np.sum(symmetric * symmetric, axis=(-2, -1))
|
|
177
|
+
)
|
|
178
|
+
return {operation.outputs[0]: value}
|
|
179
|
+
if kind == "Lambda2":
|
|
180
|
+
matrix = symmetric @ symmetric + rotation @ rotation
|
|
181
|
+
return {operation.outputs[0]: np.linalg.eigvalsh(matrix)[..., 1]}
|
|
182
|
+
_error(f"unsupported post-processing operation {kind!r}")
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _components(name: str, values: np.ndarray) -> tuple[str, ...]:
|
|
186
|
+
count = 1 if values.ndim == 3 else values.shape[-1]
|
|
187
|
+
suffixes = {
|
|
188
|
+
1: ("",),
|
|
189
|
+
3: ("_x", "_y", "_z"),
|
|
190
|
+
9: tuple(f"_{first}{second}" for first in "xyz" for second in "xyz"),
|
|
191
|
+
}.get(count)
|
|
192
|
+
if suffixes is None:
|
|
193
|
+
_error(f"field {name!r} has unsupported component count {count}")
|
|
194
|
+
return tuple(f"{name}{suffix}" for suffix in suffixes)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def postprocess(
|
|
198
|
+
*,
|
|
199
|
+
dataset_dir: str | Path,
|
|
200
|
+
operations: Sequence[PostprocessOperation],
|
|
201
|
+
n_jobs: int | None = None,
|
|
202
|
+
progress: bool = False,
|
|
203
|
+
overwrite: bool = False,
|
|
204
|
+
) -> PostprocessedDataset:
|
|
205
|
+
"""Materialise supported operations in a Cartesian dataset."""
|
|
206
|
+
|
|
207
|
+
started = perf_counter()
|
|
208
|
+
root = Path(dataset_dir).expanduser().resolve()
|
|
209
|
+
info = json.loads((root / "info.json").read_text(encoding="utf-8"))
|
|
210
|
+
dataset = _Dataset(root, info)
|
|
211
|
+
selected = tuple(operations)
|
|
212
|
+
if not selected or any(not isinstance(item, PostprocessOperation) for item in selected):
|
|
213
|
+
raise TypeError("operations must contain StackNordic post-processing contracts")
|
|
214
|
+
output_names = tuple(name for item in selected for name in item.outputs)
|
|
215
|
+
if len(set(output_names)) != len(output_names):
|
|
216
|
+
_error("post-processing outputs must be unique")
|
|
217
|
+
existing = set(output_names).intersection(dataset.fields)
|
|
218
|
+
if existing and not overwrite:
|
|
219
|
+
_error(f"post-processing fields already exist: {sorted(existing)}", FileExistsError)
|
|
220
|
+
planned: dict[str, tuple[str, ...]] = {}
|
|
221
|
+
for operation in selected:
|
|
222
|
+
for name, values in _evaluate(dataset, operation, 0).items():
|
|
223
|
+
planned[name] = _components(name, values)
|
|
224
|
+
component_owners = {
|
|
225
|
+
component: name
|
|
226
|
+
for name, components in dataset.fields.items()
|
|
227
|
+
for component in components
|
|
228
|
+
}
|
|
229
|
+
new_components: dict[str, str] = {}
|
|
230
|
+
for name, components in planned.items():
|
|
231
|
+
for component in components:
|
|
232
|
+
owner = component_owners.get(component)
|
|
233
|
+
if owner is not None and owner != name:
|
|
234
|
+
_error(
|
|
235
|
+
f"output component {component!r} is already owned by field {owner!r}"
|
|
236
|
+
)
|
|
237
|
+
previous = new_components.setdefault(component, name)
|
|
238
|
+
if previous != name:
|
|
239
|
+
_error(
|
|
240
|
+
f"post-processing fields {previous!r} and {name!r} share component "
|
|
241
|
+
f"{component!r}"
|
|
242
|
+
)
|
|
243
|
+
stage = Path(tempfile.mkdtemp(prefix=".stacknordic-postprocess-", dir=root))
|
|
244
|
+
work = tuple(
|
|
245
|
+
(index, operation)
|
|
246
|
+
for index in range(len(dataset.records))
|
|
247
|
+
for operation in selected
|
|
248
|
+
)
|
|
249
|
+
estimated_worker_bytes = max(1, int(np.prod(dataset.shape))) * 256
|
|
250
|
+
selected_workers = memory_bounded_workers(n_jobs, len(work), estimated_worker_bytes)
|
|
251
|
+
reporter = (
|
|
252
|
+
start_progress(len(work), "StackNordic post-processing")
|
|
253
|
+
if progress
|
|
254
|
+
else None
|
|
255
|
+
)
|
|
256
|
+
results: dict[tuple[int, str], tuple[Path, ...]] = {}
|
|
257
|
+
mappings: dict[str, tuple[str, ...]] = dict(planned)
|
|
258
|
+
published: list[Path] = []
|
|
259
|
+
superseded: list[Path] = []
|
|
260
|
+
committed = False
|
|
261
|
+
try:
|
|
262
|
+
def task(index: int, operation: PostprocessOperation):
|
|
263
|
+
evaluated = _evaluate(dataset, operation, index)
|
|
264
|
+
written: dict[str, tuple[tuple[str, ...], tuple[Path, ...]]] = {}
|
|
265
|
+
for name, values in evaluated.items():
|
|
266
|
+
if not np.all(np.isfinite(values)):
|
|
267
|
+
_error(f"post-processed field {name!r} contains non-finite values")
|
|
268
|
+
components = _components(name, values)
|
|
269
|
+
if components != planned[name]:
|
|
270
|
+
_error(f"post-processed field {name!r} changed component shape")
|
|
271
|
+
columns = (values,) if values.ndim == 3 else tuple(
|
|
272
|
+
values[..., component] for component in range(values.shape[-1])
|
|
273
|
+
)
|
|
274
|
+
paths = []
|
|
275
|
+
for component, column in zip(components, columns, strict=True):
|
|
276
|
+
path = stage / f"{component}_id{index:03d}.dat"
|
|
277
|
+
np.asarray(column, dtype=dataset.dtype).tofile(path)
|
|
278
|
+
paths.append(path)
|
|
279
|
+
written[name] = components, tuple(paths)
|
|
280
|
+
return index, written
|
|
281
|
+
|
|
282
|
+
if selected_workers == 1:
|
|
283
|
+
completed = (task(index, operation) for index, operation in work)
|
|
284
|
+
for index, evaluated in completed:
|
|
285
|
+
for name, values in evaluated.items():
|
|
286
|
+
_, paths = values
|
|
287
|
+
results[index, name] = paths
|
|
288
|
+
if reporter is not None:
|
|
289
|
+
reporter.update()
|
|
290
|
+
else:
|
|
291
|
+
with ThreadPoolExecutor(max_workers=selected_workers) as executor:
|
|
292
|
+
futures = [
|
|
293
|
+
executor.submit(task, index, operation)
|
|
294
|
+
for index, operation in work
|
|
295
|
+
]
|
|
296
|
+
for future in as_completed(futures):
|
|
297
|
+
index, evaluated = future.result()
|
|
298
|
+
for name, values in evaluated.items():
|
|
299
|
+
_, paths = values
|
|
300
|
+
results[index, name] = paths
|
|
301
|
+
if reporter is not None:
|
|
302
|
+
reporter.update()
|
|
303
|
+
data_dir = root / "data"
|
|
304
|
+
for index, record in enumerate(dataset.records):
|
|
305
|
+
for name, components in mappings.items():
|
|
306
|
+
for component, path in zip(components, results[index, name], strict=True):
|
|
307
|
+
destination = data_dir / f"{path.stem}_{stage.name[1:]}{path.suffix}"
|
|
308
|
+
path.replace(destination)
|
|
309
|
+
published.append(destination)
|
|
310
|
+
previous = record.get(f"{component} filename")
|
|
311
|
+
if previous is not None:
|
|
312
|
+
superseded.append(root / previous)
|
|
313
|
+
record[f"{component} filename"] = f"./data/{destination.name}"
|
|
314
|
+
global_info = info["global"]
|
|
315
|
+
for name, components in mappings.items():
|
|
316
|
+
old = global_info["fields"].get(name, ())
|
|
317
|
+
for component in old:
|
|
318
|
+
if component not in components:
|
|
319
|
+
for record in dataset.records:
|
|
320
|
+
filename = record.pop(f"{component} filename", None)
|
|
321
|
+
if filename is not None:
|
|
322
|
+
superseded.append(root / filename)
|
|
323
|
+
global_info["fields"][name] = list(components)
|
|
324
|
+
global_info["variables"] = [
|
|
325
|
+
component
|
|
326
|
+
for components in global_info["fields"].values()
|
|
327
|
+
for component in components
|
|
328
|
+
]
|
|
329
|
+
manifest = stage / "info.json"
|
|
330
|
+
manifest.write_text(json.dumps(info, indent=4) + "\n", encoding="utf-8")
|
|
331
|
+
manifest.replace(root / "info.json")
|
|
332
|
+
committed = True
|
|
333
|
+
for path in superseded:
|
|
334
|
+
if path not in published:
|
|
335
|
+
path.unlink(missing_ok=True)
|
|
336
|
+
except BaseException:
|
|
337
|
+
if not committed:
|
|
338
|
+
for path in published:
|
|
339
|
+
path.unlink(missing_ok=True)
|
|
340
|
+
shutil.rmtree(stage, ignore_errors=True)
|
|
341
|
+
raise
|
|
342
|
+
finally:
|
|
343
|
+
if reporter is not None:
|
|
344
|
+
finish_progress(reporter)
|
|
345
|
+
shutil.rmtree(stage, ignore_errors=True)
|
|
346
|
+
return PostprocessedDataset(
|
|
347
|
+
dataset_dir=root,
|
|
348
|
+
fields=tuple(mappings),
|
|
349
|
+
snapshots=len(dataset.records),
|
|
350
|
+
elapsed_seconds=perf_counter() - started,
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
__all__ = ["PostprocessedDataset", "postprocess"]
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Derive stored thermodynamic fields from explicit OpenFOAM contracts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
_UNIVERSAL_GAS_CONSTANT = 8314.46261815324
|
|
13
|
+
_COMMENTS = re.compile(r"/\*.*?\*/|//[^\n]*", re.DOTALL)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _block(payload: str, name: str) -> str | None:
|
|
17
|
+
match = re.search(rf"\b{re.escape(name)}\s*\{{", payload)
|
|
18
|
+
if match is None:
|
|
19
|
+
return None
|
|
20
|
+
depth = 1
|
|
21
|
+
for index in range(match.end(), len(payload)):
|
|
22
|
+
if payload[index] == "{":
|
|
23
|
+
depth += 1
|
|
24
|
+
elif payload[index] == "}":
|
|
25
|
+
depth -= 1
|
|
26
|
+
if depth == 0:
|
|
27
|
+
return payload[match.end() : index]
|
|
28
|
+
raise ValueError(f"[StackNordic] unterminated OpenFOAM dictionary for {name!r}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _expanded_thermophysical_properties(case_dir: Path) -> str:
|
|
32
|
+
root = case_dir / "constant/thermophysicalProperties"
|
|
33
|
+
seen: set[Path] = set()
|
|
34
|
+
|
|
35
|
+
def expand(path: Path) -> str:
|
|
36
|
+
selected = path.resolve()
|
|
37
|
+
if selected in seen:
|
|
38
|
+
return ""
|
|
39
|
+
seen.add(selected)
|
|
40
|
+
payload = path.read_text(errors="replace")
|
|
41
|
+
|
|
42
|
+
def include(match: re.Match[str]) -> str:
|
|
43
|
+
value = match.group(1).replace("$FOAM_CASE", str(case_dir))
|
|
44
|
+
target = Path(value)
|
|
45
|
+
if not target.is_absolute():
|
|
46
|
+
target = path.parent / target
|
|
47
|
+
return expand(target) if target.is_file() else match.group(0)
|
|
48
|
+
|
|
49
|
+
return re.sub(r'^\s*#include\s+["<]([^">]+)[">]\s*$', include, payload, flags=re.MULTILINE)
|
|
50
|
+
|
|
51
|
+
return _COMMENTS.sub(" ", expand(root))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, slots=True)
|
|
55
|
+
class PerfectGasMixture:
|
|
56
|
+
"""Mass-fraction perfect-gas density contract."""
|
|
57
|
+
|
|
58
|
+
molecular_weights: dict[str, float]
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def species(self) -> tuple[str, ...]:
|
|
62
|
+
return tuple(self.molecular_weights)
|
|
63
|
+
|
|
64
|
+
def density(self, field: Callable[[str], np.ndarray]) -> np.ndarray:
|
|
65
|
+
pressure = np.asarray(field("p"), dtype=np.float64)
|
|
66
|
+
temperature = np.asarray(field("T"), dtype=np.float64)
|
|
67
|
+
reciprocal_weight = np.zeros_like(pressure)
|
|
68
|
+
mass_fraction_sum = np.zeros_like(pressure)
|
|
69
|
+
for name, molecular_weight in self.molecular_weights.items():
|
|
70
|
+
mass_fraction = np.asarray(field(name), dtype=np.float64)
|
|
71
|
+
reciprocal_weight += mass_fraction / molecular_weight
|
|
72
|
+
mass_fraction_sum += mass_fraction
|
|
73
|
+
if pressure.shape != temperature.shape or reciprocal_weight.shape != pressure.shape:
|
|
74
|
+
raise ValueError("[StackNordic] thermodynamic fields must share one shape")
|
|
75
|
+
if np.any(~np.isfinite(pressure)) or np.any(pressure <= 0.0):
|
|
76
|
+
raise ValueError("[StackNordic] pressure must be finite and positive to derive rho")
|
|
77
|
+
if np.any(~np.isfinite(temperature)) or np.any(temperature <= 0.0):
|
|
78
|
+
raise ValueError("[StackNordic] temperature must be finite and positive to derive rho")
|
|
79
|
+
if not np.allclose(mass_fraction_sum, 1.0, rtol=1.0e-6, atol=1.0e-8):
|
|
80
|
+
raise ValueError("[StackNordic] species mass fractions must sum to one to derive rho")
|
|
81
|
+
return pressure / (_UNIVERSAL_GAS_CONSTANT * temperature * reciprocal_weight)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def perfect_gas_mixture(case_dir: Path) -> PerfectGasMixture | None:
|
|
85
|
+
"""Read a supported multicomponent perfect-gas contract from one case."""
|
|
86
|
+
|
|
87
|
+
path = case_dir / "constant/thermophysicalProperties"
|
|
88
|
+
if not path.is_file():
|
|
89
|
+
return None
|
|
90
|
+
payload = _expanded_thermophysical_properties(case_dir)
|
|
91
|
+
thermo_type = _block(payload, "thermoType")
|
|
92
|
+
if thermo_type is None or re.search(r"\bequationOfState\s+perfectGas\s*;", thermo_type) is None:
|
|
93
|
+
return None
|
|
94
|
+
species_match = re.search(r"\bspecies\s+\d+\s*\((.*?)\)\s*;", payload, re.DOTALL)
|
|
95
|
+
if species_match is None:
|
|
96
|
+
return None
|
|
97
|
+
species = tuple(species_match.group(1).split())
|
|
98
|
+
molecular_weights: dict[str, float] = {}
|
|
99
|
+
for name in species:
|
|
100
|
+
definition = _block(payload, name)
|
|
101
|
+
specie = _block(definition or "", "specie")
|
|
102
|
+
match = re.search(
|
|
103
|
+
r"\bmolWeight\s+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)\s*;",
|
|
104
|
+
specie or "",
|
|
105
|
+
)
|
|
106
|
+
if match is None or float(match.group(1)) <= 0.0:
|
|
107
|
+
return None
|
|
108
|
+
molecular_weights[name] = float(match.group(1))
|
|
109
|
+
return PerfectGasMixture(molecular_weights)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
__all__ = ["PerfectGasMixture", "perfect_gas_mixture"]
|
stacknordic/filtering.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Declarative physical filtering rules for dataset reduction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from types import MappingProxyType
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _names(values: Sequence[str], label: str) -> tuple[str, ...]:
|
|
11
|
+
result = tuple(values)
|
|
12
|
+
if any(not isinstance(value, str) or not value for value in result):
|
|
13
|
+
raise ValueError(f"{label} must contain non-empty field names")
|
|
14
|
+
if len(set(result)) != len(result):
|
|
15
|
+
raise ValueError(f"{label} must not contain duplicate field names")
|
|
16
|
+
return result
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _mapping(values: Mapping[str, str], label: str) -> Mapping[str, str]:
|
|
20
|
+
result = dict(values)
|
|
21
|
+
if any(not source or not target for source, target in result.items()):
|
|
22
|
+
raise ValueError(f"{label} must map non-empty field names")
|
|
23
|
+
return MappingProxyType(result)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class Filtering:
|
|
28
|
+
"""Complete physical reduction contract for one downsampling operation."""
|
|
29
|
+
|
|
30
|
+
density: str | None = None
|
|
31
|
+
mean: tuple[str, ...] = ()
|
|
32
|
+
favre: tuple[str, ...] = ()
|
|
33
|
+
variance: Mapping[str, str] = field(default_factory=dict)
|
|
34
|
+
stress: Mapping[str, str] = field(default_factory=dict)
|
|
35
|
+
energy: Mapping[str, str] = field(default_factory=dict)
|
|
36
|
+
specific: Mapping[str, str] = field(default_factory=dict)
|
|
37
|
+
|
|
38
|
+
def __post_init__(self) -> None:
|
|
39
|
+
if self.density is not None and not self.density:
|
|
40
|
+
raise ValueError("density must be a non-empty field name or None")
|
|
41
|
+
object.__setattr__(self, "mean", _names(self.mean, "mean"))
|
|
42
|
+
object.__setattr__(self, "favre", _names(self.favre, "favre"))
|
|
43
|
+
object.__setattr__(self, "variance", _mapping(self.variance, "variance"))
|
|
44
|
+
object.__setattr__(self, "stress", _mapping(self.stress, "stress"))
|
|
45
|
+
object.__setattr__(self, "energy", _mapping(self.energy, "energy"))
|
|
46
|
+
object.__setattr__(self, "specific", _mapping(self.specific, "specific"))
|
|
47
|
+
overlap = set(self.mean).intersection(self.favre)
|
|
48
|
+
if overlap:
|
|
49
|
+
raise ValueError(f"fields cannot use both mean and Favre filtering: {sorted(overlap)}")
|
|
50
|
+
if self.favre and self.density is None:
|
|
51
|
+
raise ValueError("Favre filtering requires density")
|
|
52
|
+
if self.specific and self.density is None:
|
|
53
|
+
raise ValueError("specific source conversion requires density")
|
|
54
|
+
missing_specific = set(self.specific).difference(self.mean)
|
|
55
|
+
if missing_specific:
|
|
56
|
+
raise ValueError("specific keys must name fields declared by mean")
|
|
57
|
+
missing_stress = set(self.energy).difference(self.stress.values())
|
|
58
|
+
if missing_stress:
|
|
59
|
+
raise ValueError("energy keys must name outputs declared by stress")
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def flow(
|
|
63
|
+
cls,
|
|
64
|
+
*,
|
|
65
|
+
regime: str,
|
|
66
|
+
velocity: str = "U",
|
|
67
|
+
pressure: str = "p",
|
|
68
|
+
density: str | None = None,
|
|
69
|
+
sgs_stress: str | None = None,
|
|
70
|
+
sgs_energy: str | None = None,
|
|
71
|
+
) -> Filtering:
|
|
72
|
+
"""Build an incompressible or compressible flow filtering contract."""
|
|
73
|
+
|
|
74
|
+
if regime not in {"incompressible", "compressible"}:
|
|
75
|
+
raise ValueError("flow regime must be 'incompressible' or 'compressible'")
|
|
76
|
+
if regime == "compressible" and density is None:
|
|
77
|
+
raise ValueError("compressible flow filtering requires density")
|
|
78
|
+
mean = [pressure]
|
|
79
|
+
favre: list[str] = []
|
|
80
|
+
if density is not None:
|
|
81
|
+
mean.append(density)
|
|
82
|
+
if regime == "compressible":
|
|
83
|
+
favre.append(velocity)
|
|
84
|
+
else:
|
|
85
|
+
mean.append(velocity)
|
|
86
|
+
stress = {velocity: sgs_stress} if sgs_stress is not None else {}
|
|
87
|
+
energy = {sgs_stress: sgs_energy} if sgs_stress and sgs_energy else {}
|
|
88
|
+
return cls(
|
|
89
|
+
density=density,
|
|
90
|
+
mean=tuple(mean),
|
|
91
|
+
favre=tuple(favre),
|
|
92
|
+
stress=stress,
|
|
93
|
+
energy=energy,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
@classmethod
|
|
97
|
+
def combustion(
|
|
98
|
+
cls,
|
|
99
|
+
*,
|
|
100
|
+
regime: str,
|
|
101
|
+
flow: str,
|
|
102
|
+
density: str | None = None,
|
|
103
|
+
velocity: str = "U",
|
|
104
|
+
pressure: str = "p",
|
|
105
|
+
temperature: str = "T",
|
|
106
|
+
progress: str | None = None,
|
|
107
|
+
progress_variance: str | None = None,
|
|
108
|
+
mixture_fraction: str | None = None,
|
|
109
|
+
mixture_fraction_variance: str | None = None,
|
|
110
|
+
species: Sequence[str] = (),
|
|
111
|
+
reaction_rate: str | None = None,
|
|
112
|
+
specific_reaction_rate: str | None = None,
|
|
113
|
+
sgs_stress: str | None = None,
|
|
114
|
+
sgs_energy: str | None = None,
|
|
115
|
+
) -> Filtering:
|
|
116
|
+
"""Build a premixed or non-premixed combustion filtering contract."""
|
|
117
|
+
|
|
118
|
+
if regime not in {"premixed", "non-premixed"}:
|
|
119
|
+
raise ValueError("combustion regime must be 'premixed' or 'non-premixed'")
|
|
120
|
+
if flow not in {"incompressible", "compressible"}:
|
|
121
|
+
raise ValueError("combustion flow must be 'incompressible' or 'compressible'")
|
|
122
|
+
if flow == "compressible" and density is None:
|
|
123
|
+
raise ValueError("compressible combustion filtering requires density")
|
|
124
|
+
if regime == "premixed":
|
|
125
|
+
if progress is None:
|
|
126
|
+
raise ValueError("premixed combustion filtering requires progress")
|
|
127
|
+
coordinate = progress
|
|
128
|
+
variance_name = progress_variance
|
|
129
|
+
else:
|
|
130
|
+
if mixture_fraction is None:
|
|
131
|
+
raise ValueError("non-premixed combustion filtering requires mixture_fraction")
|
|
132
|
+
coordinate = mixture_fraction
|
|
133
|
+
variance_name = mixture_fraction_variance
|
|
134
|
+
mean = [pressure]
|
|
135
|
+
if density is not None:
|
|
136
|
+
mean.insert(0, density)
|
|
137
|
+
if reaction_rate is not None:
|
|
138
|
+
mean.append(reaction_rate)
|
|
139
|
+
if specific_reaction_rate is not None and reaction_rate is None:
|
|
140
|
+
raise ValueError("specific_reaction_rate requires reaction_rate")
|
|
141
|
+
transported = [velocity, temperature, coordinate, *_names(species, "species")]
|
|
142
|
+
favre = transported if flow == "compressible" else []
|
|
143
|
+
if flow == "incompressible":
|
|
144
|
+
mean.extend(transported)
|
|
145
|
+
variance = {coordinate: variance_name} if variance_name is not None else {}
|
|
146
|
+
stress = {velocity: sgs_stress} if sgs_stress is not None else {}
|
|
147
|
+
energy = {sgs_stress: sgs_energy} if sgs_stress and sgs_energy else {}
|
|
148
|
+
return cls(
|
|
149
|
+
density=density,
|
|
150
|
+
mean=tuple(mean),
|
|
151
|
+
favre=tuple(favre),
|
|
152
|
+
variance=variance,
|
|
153
|
+
stress=stress,
|
|
154
|
+
energy=energy,
|
|
155
|
+
specific=(
|
|
156
|
+
{reaction_rate: specific_reaction_rate}
|
|
157
|
+
if reaction_rate is not None and specific_reaction_rate is not None
|
|
158
|
+
else {}
|
|
159
|
+
),
|
|
160
|
+
)
|