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.
@@ -0,0 +1,136 @@
1
+ """Self-describing HDF5 dataset contracts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from types import MappingProxyType
8
+ from typing import Any
9
+
10
+ import h5py
11
+
12
+ SNAPSHOT_SCHEMA = "stacknordic-hdf5-snapshot-v1"
13
+ SERIES_SCHEMA = "stacknordic-hdf5-series-v1"
14
+ CONTRACT_ATTRIBUTE = "stacknordic_contract"
15
+ SNAPSHOTS_ATTRIBUTE = "stacknordic_snapshots"
16
+
17
+
18
+ def normalise_hdf5_path(value: str) -> str:
19
+ """Normalise one relative HDF5 path without accepting traversal."""
20
+
21
+ if not isinstance(value, str):
22
+ raise TypeError("field output paths must be strings")
23
+ parts = tuple(part.strip() for part in value.split("/"))
24
+ if not parts or any(not part or part in {".", ".."} for part in parts):
25
+ raise ValueError(f"invalid HDF5 field path: {value!r}")
26
+ return "/".join(parts)
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class HDF5Contract:
31
+ """Immutable logical-field contract stored with every package."""
32
+
33
+ schema: str
34
+ name: str
35
+ dtype: str
36
+ shape_zyx: tuple[int, int, int]
37
+ fields: MappingProxyType
38
+ components: MappingProxyType
39
+ metadata: MappingProxyType
40
+
41
+ def payload(self) -> dict[str, Any]:
42
+ return {
43
+ "schema": self.schema,
44
+ "name": self.name,
45
+ "dtype": self.dtype,
46
+ "shape_zyx": list(self.shape_zyx),
47
+ "fields": dict(self.fields),
48
+ "components": {
49
+ name: list(values) for name, values in self.components.items()
50
+ },
51
+ "grid": {
52
+ "x": "grid/x_axis",
53
+ "y": "grid/y_axis",
54
+ "z": "grid/z_axis",
55
+ },
56
+ "metadata": dict(self.metadata),
57
+ }
58
+
59
+ def with_schema(self, schema: str) -> HDF5Contract:
60
+ return HDF5Contract(
61
+ schema=schema,
62
+ name=self.name,
63
+ dtype=self.dtype,
64
+ shape_zyx=self.shape_zyx,
65
+ fields=self.fields,
66
+ components=self.components,
67
+ metadata=self.metadata,
68
+ )
69
+
70
+
71
+ def contract(
72
+ *,
73
+ schema: str,
74
+ name: str,
75
+ dtype: str,
76
+ shape_zyx: tuple[int, int, int],
77
+ fields: dict[str, str],
78
+ components: dict[str, tuple[str, ...]],
79
+ metadata: dict[str, object],
80
+ ) -> HDF5Contract:
81
+ if schema not in {SNAPSHOT_SCHEMA, SERIES_SCHEMA}:
82
+ raise ValueError(f"unsupported StackNordic HDF5 schema: {schema!r}")
83
+ if set(fields) != set(components):
84
+ raise ValueError("HDF5 fields and component mappings must have identical keys")
85
+ return HDF5Contract(
86
+ schema=schema,
87
+ name=name,
88
+ dtype=dtype,
89
+ shape_zyx=tuple(int(value) for value in shape_zyx),
90
+ fields=MappingProxyType(dict(fields)),
91
+ components=MappingProxyType(
92
+ {key: tuple(values) for key, values in components.items()}
93
+ ),
94
+ metadata=MappingProxyType(dict(metadata)),
95
+ )
96
+
97
+
98
+ def write_contract(file: h5py.File, definition: HDF5Contract) -> None:
99
+ file.attrs[CONTRACT_ATTRIBUTE] = json.dumps(
100
+ definition.payload(), ensure_ascii=False, separators=(",", ":")
101
+ )
102
+
103
+
104
+ def read_contract(file: h5py.File) -> HDF5Contract:
105
+ raw = file.attrs.get(CONTRACT_ATTRIBUTE)
106
+ if raw is None:
107
+ raise ValueError("HDF5 file does not contain a StackNordic contract")
108
+ try:
109
+ payload = json.loads(str(raw))
110
+ return contract(
111
+ schema=str(payload["schema"]),
112
+ name=str(payload["name"]),
113
+ dtype=str(payload["dtype"]),
114
+ shape_zyx=tuple(payload["shape_zyx"]),
115
+ fields={
116
+ str(name): normalise_hdf5_path(path)
117
+ for name, path in payload["fields"].items()
118
+ },
119
+ components={
120
+ str(name): tuple(str(component) for component in values)
121
+ for name, values in payload["components"].items()
122
+ },
123
+ metadata=dict(payload.get("metadata") or {}),
124
+ )
125
+ except (KeyError, TypeError, json.JSONDecodeError) as error:
126
+ raise ValueError("HDF5 file contains an invalid StackNordic contract") from error
127
+
128
+
129
+ def compatible(first: HDF5Contract, second: HDF5Contract) -> bool:
130
+ return (
131
+ first.name == second.name
132
+ and first.dtype == second.dtype
133
+ and first.shape_zyx == second.shape_zyx
134
+ and dict(first.fields) == dict(second.fields)
135
+ and dict(first.components) == dict(second.components)
136
+ )
@@ -0,0 +1,16 @@
1
+ """Dataset manifest compatibility helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+
7
+
8
+ def component_file(record: Mapping[str, object], component: str) -> str:
9
+ """Return a component path from current or legacy export manifests."""
10
+
11
+ key = f"{component} filename"
12
+ if key in record:
13
+ return str(record[key])
14
+ if component in record:
15
+ return str(record[component])
16
+ raise KeyError(key)
@@ -0,0 +1,294 @@
1
+ """Persistent derived-field computation for exported datasets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import queue
8
+ import shutil
9
+ import tempfile
10
+ from collections.abc import Sequence
11
+ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from time import perf_counter
15
+
16
+ import numpy as np
17
+
18
+ from .._progress import finish_progress, start_progress
19
+ from ..computing import (
20
+ Computation,
21
+ ProgressComputation,
22
+ ReactionRateComputation,
23
+ reaction_rate_chunks,
24
+ )
25
+ from ..resources import memory_bounded_workers
26
+ from ._manifest import component_file
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class ComputedDataset:
31
+ """Summary of persisted derived fields."""
32
+
33
+ dataset_dir: Path
34
+ fields: tuple[str, ...]
35
+ snapshots: int
36
+ n_jobs: int
37
+ elapsed_seconds: float
38
+
39
+
40
+ def _error(message: str, error_type: type[Exception] = ValueError):
41
+ raise error_type(f"[StackNordic] {message}")
42
+
43
+
44
+ class _Snapshot:
45
+ def __init__(self, root: Path, info: dict[str, object], record: dict[str, object]):
46
+ global_info = info["global"]
47
+ self.root = root
48
+ self.record = record
49
+ self.dtype = np.dtype(global_info["dtype"])
50
+ self.shape = tuple(reversed(tuple(int(value) for value in global_info["Nxyz"])))
51
+ self.fields = {
52
+ name: tuple(components)
53
+ for name, components in global_info["fields"].items()
54
+ }
55
+
56
+ def field(self, name: str) -> np.ndarray:
57
+ if name not in self.fields:
58
+ _error(f"computation requested unavailable field {name!r}", KeyError)
59
+ components = self.fields[name]
60
+ if len(components) != 1:
61
+ _error(f"computation input {name!r} must be scalar")
62
+ path = self.root / component_file(self.record, components[0])
63
+ return np.memmap(path, dtype=self.dtype, mode="r", shape=self.shape)
64
+
65
+
66
+ def _compute_snapshot(
67
+ root: Path,
68
+ stage: Path,
69
+ info: dict[str, object],
70
+ record: dict[str, object],
71
+ computations: tuple[Computation, ...],
72
+ dtype: np.dtype,
73
+ progress_callback=None,
74
+ ) -> tuple[int, dict[str, Path]]:
75
+ snapshot = _Snapshot(root, info, record)
76
+ outputs: dict[str, Path] = {}
77
+ snapshot_id = int(record["id"])
78
+ cell_count = int(np.prod(snapshot.shape))
79
+ chunk_cells = 262_144
80
+ reaction_groups: dict[tuple[object, ...], list[ReactionRateComputation]] = {}
81
+ for definition in computations:
82
+ if isinstance(definition, ReactionRateComputation):
83
+ reaction_groups.setdefault(definition.state_key(), []).append(definition)
84
+ continue
85
+ path = stage / f"{definition.output}_id{snapshot_id:03d}.dat"
86
+ output = np.memmap(path, dtype=dtype, mode="w+", shape=(cell_count,))
87
+ fields = {
88
+ name: np.asarray(snapshot.field(name)).reshape(-1)
89
+ for name in definition.inputs
90
+ }
91
+ for start in range(0, cell_count, chunk_cells):
92
+ stop = min(start + chunk_cells, cell_count)
93
+ values = np.full(stop - start, definition.offset)
94
+ for name, coefficient in definition.coefficients.items():
95
+ values += coefficient * np.asarray(fields[name][start:stop], dtype=np.float64)
96
+ if not np.all(np.isfinite(values)):
97
+ _error(
98
+ f"computed field {definition.output!r} contains non-finite values "
99
+ f"at snapshot {snapshot_id}"
100
+ )
101
+ output[start:stop] = values
102
+ if progress_callback is not None:
103
+ progress_callback(stop - start)
104
+ output.flush()
105
+ del output
106
+ outputs[definition.output] = path
107
+ for definitions in reaction_groups.values():
108
+ paths = {
109
+ definition.output: stage / f"{definition.output}_id{snapshot_id:03d}.dat"
110
+ for definition in definitions
111
+ }
112
+ mapped = {
113
+ name: np.memmap(path, dtype=dtype, mode="w+", shape=(cell_count,))
114
+ for name, path in paths.items()
115
+ }
116
+ try:
117
+ for start, stop, values in reaction_rate_chunks(tuple(definitions), snapshot.field):
118
+ for name, chunk in values.items():
119
+ if not np.all(np.isfinite(chunk)):
120
+ _error(
121
+ f"computed field {name!r} contains non-finite values "
122
+ f"at snapshot {snapshot_id}"
123
+ )
124
+ mapped[name][start:stop] = chunk
125
+ if progress_callback is not None:
126
+ progress_callback(stop - start)
127
+ for output in mapped.values():
128
+ output.flush()
129
+ finally:
130
+ mapped.clear()
131
+ outputs.update(paths)
132
+ return snapshot_id, outputs
133
+
134
+
135
+ def compute(
136
+ *,
137
+ dataset_dir: str | Path,
138
+ computations: Sequence[Computation],
139
+ dtype: str | None = None,
140
+ n_jobs: int | None = None,
141
+ progress: bool = False,
142
+ overwrite: bool = False,
143
+ ) -> ComputedDataset:
144
+ """Compute and persist declared fields in an exported dataset."""
145
+
146
+ started = perf_counter()
147
+ root = Path(dataset_dir).expanduser().resolve()
148
+ try:
149
+ info = json.loads((root / "info.json").read_text())
150
+ except (FileNotFoundError, json.JSONDecodeError):
151
+ _error(f"dataset manifest is unavailable or invalid in {root}")
152
+ global_info = info.get("global", {})
153
+ if global_info.get("layout") != "cartesian" or "Nxyz" not in global_info:
154
+ _error("stored field computation currently requires a verified Cartesian dataset")
155
+ if not isinstance(global_info.get("fields"), dict):
156
+ _error("dataset manifest does not contain logical field mappings")
157
+ records = tuple(info.get("local", ()))
158
+ if not records:
159
+ _error("dataset contains no snapshots")
160
+ definitions = tuple(computations)
161
+ if not definitions:
162
+ _error("computations must contain at least one definition")
163
+ if any(
164
+ not isinstance(item, (ProgressComputation, ReactionRateComputation))
165
+ for item in definitions
166
+ ):
167
+ raise TypeError("computations must contain StackNordic computation contracts")
168
+ names = tuple(item.output for item in definitions)
169
+ if len(set(names)) != len(names):
170
+ _error("computation outputs must be unique")
171
+ existing = set(names).intersection(global_info["fields"])
172
+ if existing and not overwrite:
173
+ _error(f"computed fields already exist: {sorted(existing)}", FileExistsError)
174
+ required = set().union(*(set(item.inputs) for item in definitions))
175
+ unavailable = required.difference(global_info["fields"])
176
+ if unavailable:
177
+ _error(f"computations requested unavailable fields: {sorted(unavailable)}", KeyError)
178
+ output_dtype = np.dtype(global_info["dtype"] if dtype is None else dtype)
179
+ if output_dtype.name not in {"float32", "float64"}:
180
+ _error("dtype must be 'float32', 'float64', or None")
181
+ selected_workers = memory_bounded_workers(
182
+ n_jobs,
183
+ len(records),
184
+ 512 * 1024**2,
185
+ )
186
+ if n_jobs == -1 and selected_workers < min(len(records), os.cpu_count() or 1):
187
+ print(
188
+ f"[StackNordic] Computing workers: n_jobs=-1 resolved to {selected_workers} "
189
+ "from the available memory and bounded Cantera workspace."
190
+ )
191
+ stage = Path(tempfile.mkdtemp(prefix=".stacknordic-compute-", dir=root))
192
+ algebraic_count = sum(
193
+ isinstance(definition, ProgressComputation) for definition in definitions
194
+ )
195
+ reaction_count = len(
196
+ {
197
+ definition.state_key()
198
+ for definition in definitions
199
+ if isinstance(definition, ReactionRateComputation)
200
+ }
201
+ )
202
+ work_per_cell = algebraic_count + reaction_count
203
+ total_cells = sum(
204
+ int(record.get("cells", np.prod(tuple(reversed(global_info["Nxyz"])))))
205
+ for record in records
206
+ )
207
+ reporter = (
208
+ start_progress(total_cells * work_per_cell, "StackNordic computing")
209
+ if progress
210
+ else None
211
+ )
212
+ results: dict[int, dict[str, Path]] = {}
213
+ try:
214
+ updates: queue.SimpleQueue[int] = queue.SimpleQueue()
215
+
216
+ def task(index: int, callback=None):
217
+ return _compute_snapshot(
218
+ root,
219
+ stage,
220
+ info,
221
+ records[index],
222
+ definitions,
223
+ output_dtype,
224
+ callback,
225
+ )
226
+
227
+ def report_updates() -> None:
228
+ if reporter is None:
229
+ return
230
+ completed = 0
231
+ while True:
232
+ try:
233
+ completed += updates.get_nowait()
234
+ except queue.Empty:
235
+ break
236
+ if completed:
237
+ reporter.update(completed)
238
+
239
+ if selected_workers == 1:
240
+ callback = reporter.update if reporter is not None else None
241
+ completed = (task(index, callback) for index in range(len(records)))
242
+ for snapshot_id, outputs in completed:
243
+ results[snapshot_id] = outputs
244
+ else:
245
+ with ThreadPoolExecutor(max_workers=selected_workers) as executor:
246
+ callback = updates.put if reporter is not None else None
247
+ pending = {
248
+ executor.submit(task, index, callback)
249
+ for index in range(len(records))
250
+ }
251
+ while pending:
252
+ done, pending = wait(
253
+ pending,
254
+ timeout=0.1,
255
+ return_when=FIRST_COMPLETED,
256
+ )
257
+ report_updates()
258
+ for future in done:
259
+ snapshot_id, outputs = future.result()
260
+ results[snapshot_id] = outputs
261
+ report_updates()
262
+ data_dir = root / "data"
263
+ data_dir.mkdir(exist_ok=True)
264
+ for record in records:
265
+ snapshot_id = int(record["id"])
266
+ for name, staged_path in results[snapshot_id].items():
267
+ filename = staged_path.name
268
+ staged_path.replace(data_dir / filename)
269
+ record[f"{name} filename"] = f"./data/{filename}"
270
+ for definition in definitions:
271
+ global_info["fields"][definition.output] = [definition.output]
272
+ if definition.output not in global_info["variables"]:
273
+ global_info["variables"].append(definition.output)
274
+ metadata = global_info.setdefault("metadata", {})
275
+ computation_metadata = metadata.setdefault("computing", {})
276
+ for definition in definitions:
277
+ computation_metadata[definition.output] = definition.manifest()
278
+ manifest = stage / "info.json"
279
+ manifest.write_text(json.dumps(info, indent=4) + "\n")
280
+ manifest.replace(root / "info.json")
281
+ except BaseException:
282
+ shutil.rmtree(stage, ignore_errors=True)
283
+ raise
284
+ finally:
285
+ if reporter is not None:
286
+ finish_progress(reporter)
287
+ shutil.rmtree(stage, ignore_errors=True)
288
+ return ComputedDataset(
289
+ dataset_dir=root,
290
+ fields=names,
291
+ snapshots=len(records),
292
+ n_jobs=selected_workers,
293
+ elapsed_seconds=perf_counter() - started,
294
+ )
@@ -0,0 +1,89 @@
1
+ """OpenFOAM-backed derivation of recognised stored fields."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+ from collections.abc import Iterable
8
+ from pathlib import Path
9
+
10
+ from ..openfoam.environment import _Toolchain
11
+
12
+
13
+ def gradient_source(name: str) -> str | None:
14
+ """Return the source field for the conventional ``grad<field>`` name."""
15
+
16
+ if not name.startswith("grad") or len(name) == 4:
17
+ return None
18
+ return name[4:]
19
+
20
+
21
+ def reconstruction_fields(fields: Iterable[str]) -> tuple[str, ...]:
22
+ """Replace recognised derived fields with the fields needed to compute them."""
23
+
24
+ result: list[str] = []
25
+ for field in fields:
26
+ source = gradient_source(field) or field
27
+ if source not in result:
28
+ result.append(source)
29
+ return tuple(result)
30
+
31
+
32
+ def _run(command: tuple[str, ...]) -> subprocess.CompletedProcess[str]:
33
+ return subprocess.run(
34
+ command,
35
+ check=False,
36
+ stdout=subprocess.PIPE,
37
+ stderr=subprocess.STDOUT,
38
+ text=True,
39
+ )
40
+
41
+
42
+ def materialise_gradients(
43
+ case_dir: Path,
44
+ source_case: Path,
45
+ times: tuple[tuple[float, str], ...],
46
+ fields: Iterable[str],
47
+ toolchain: _Toolchain,
48
+ ) -> None:
49
+ """Compute missing recognised gradients in an isolated reconstructed case."""
50
+
51
+ system = case_dir / "system"
52
+ constant = case_dir / "constant"
53
+ if not system.exists():
54
+ system.symlink_to(source_case / "system", target_is_directory=True)
55
+ if not constant.exists():
56
+ constant.symlink_to(source_case / "constant", target_is_directory=True)
57
+ for field in fields:
58
+ source = gradient_source(field)
59
+ if source is None:
60
+ continue
61
+ expression = f"grad({source})"
62
+ missing = tuple((value, name) for value, name in times if not (case_dir / name / field).is_file())
63
+ if not missing:
64
+ continue
65
+ print(
66
+ f"[StackNordic] Field {field!r} was not detected. "
67
+ f"Using OpenFOAM postProcess for {expression}."
68
+ )
69
+ for _, time_name in missing:
70
+ command = toolchain.wrap(
71
+ ("postProcess", "-case", str(case_dir), "-func", expression, "-time", time_name)
72
+ )
73
+ result = _run(command)
74
+ if result.returncode != 0:
75
+ detail = result.stdout.strip().splitlines()
76
+ tail = "\n".join(detail[-20:]) if detail else "postProcess failed without output"
77
+ raise RuntimeError(
78
+ f"[StackNordic] OpenFOAM postProcess could not generate {field!r} "
79
+ f"at t={time_name}:\n{tail}"
80
+ )
81
+ generated = case_dir / time_name / expression
82
+ target = case_dir / time_name / field
83
+ if generated.is_file() and generated != target:
84
+ shutil.move(generated, target)
85
+ if not target.is_file():
86
+ raise RuntimeError(
87
+ f"[StackNordic] OpenFOAM postProcess completed without generating "
88
+ f"{field!r} at t={time_name}"
89
+ )