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,415 @@
1
+ """Package StackNordic snapshots into portable analysis files."""
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 Mapping
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 h5py
17
+ import numpy as np
18
+
19
+ from .._progress import finish_progress, start_progress
20
+ from ..resources import memory_bounded_workers
21
+ from ._contract import (
22
+ SERIES_SCHEMA,
23
+ SNAPSHOT_SCHEMA,
24
+ SNAPSHOTS_ATTRIBUTE,
25
+ compatible,
26
+ contract,
27
+ normalise_hdf5_path,
28
+ read_contract,
29
+ write_contract,
30
+ )
31
+ from ._manifest import component_file
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class PackagedDataset:
36
+ """Summary of one completed dataset packaging operation."""
37
+
38
+ dataset_dir: Path
39
+ output_dir: Path
40
+ files: tuple[Path, ...]
41
+ format: str
42
+ snapshots: int
43
+ n_jobs: int
44
+ elapsed_seconds: float
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class CompiledDataset:
49
+ """Summary of one compiled HDF5 time series."""
50
+
51
+ dataset_dir: Path
52
+ output_file: Path
53
+ source_files: tuple[Path, ...]
54
+ snapshots: int
55
+ elapsed_seconds: float
56
+
57
+
58
+ def _error(message: str, error_type: type[Exception] = ValueError):
59
+ raise error_type(f"[StackNordic] {message}")
60
+
61
+
62
+ def _normalise_fields(fields: Mapping[str, str]) -> tuple[tuple[str, str], ...]:
63
+ if not isinstance(fields, Mapping) or not fields:
64
+ raise TypeError("fields must be a non-empty mapping")
65
+ try:
66
+ selected = tuple(
67
+ (str(name), normalise_hdf5_path(target)) for name, target in fields.items()
68
+ )
69
+ except ValueError as error:
70
+ _error(str(error))
71
+ if any(not name for name, _ in selected):
72
+ _error("field names must be non-empty")
73
+ targets = tuple(target for _, target in selected)
74
+ if len(set(targets)) != len(targets):
75
+ _error("HDF5 field paths must be unique")
76
+ for first in targets:
77
+ for second in targets:
78
+ if first != second and second.startswith(first + "/"):
79
+ _error(f"HDF5 field path {first!r} conflicts with {second!r}")
80
+ return selected
81
+
82
+
83
+ def _dataset_options(compression: str | None) -> dict[str, object]:
84
+ if compression not in {None, "lzf", "gzip"}:
85
+ _error("compression must be None, 'lzf', or 'gzip'")
86
+ if compression is None:
87
+ return {}
88
+ return {"compression": compression, "shuffle": True, "chunks": True}
89
+
90
+
91
+ def _write_array(
92
+ output: h5py.Dataset,
93
+ source: np.memmap,
94
+ *,
95
+ component: int | None = None,
96
+ ) -> None:
97
+ cells_per_plane = int(np.prod(source.shape[1:]))
98
+ planes = max(1, (64 * 1024**2) // max(cells_per_plane * source.dtype.itemsize, 1))
99
+ for start in range(0, source.shape[0], planes):
100
+ stop = min(start + planes, source.shape[0])
101
+ if component is None:
102
+ output[start:stop] = source[start:stop]
103
+ else:
104
+ output[start:stop, ..., component] = source[start:stop]
105
+
106
+
107
+ def _write_field(
108
+ file: h5py.File,
109
+ root: Path,
110
+ record: Mapping[str, object],
111
+ components: tuple[str, ...],
112
+ target: str,
113
+ shape: tuple[int, int, int],
114
+ dtype: np.dtype,
115
+ options: Mapping[str, object],
116
+ ) -> None:
117
+ parent_name, _, dataset_name = target.rpartition("/")
118
+ parent = file.require_group(parent_name) if parent_name else file
119
+ output_shape = shape if len(components) == 1 else (*shape, len(components))
120
+ output = parent.create_dataset(dataset_name, shape=output_shape, dtype=dtype, **options)
121
+ for index, component in enumerate(components):
122
+ source = np.memmap(
123
+ root / component_file(record, component),
124
+ dtype=dtype,
125
+ mode="r",
126
+ shape=shape,
127
+ )
128
+ _write_array(output, source, component=None if len(components) == 1 else index)
129
+
130
+
131
+ def _write_snapshot(
132
+ root: Path,
133
+ stage: Path,
134
+ name: str,
135
+ record: Mapping[str, object],
136
+ global_info: Mapping[str, object],
137
+ fields: tuple[tuple[str, str], ...],
138
+ compression: str | None,
139
+ progress_callback=None,
140
+ ) -> Path:
141
+ snapshot_id = int(record["id"])
142
+ destination = stage / f"{name}_id{snapshot_id:03d}.h5"
143
+ dtype = np.dtype(global_info["dtype"])
144
+ shape = tuple(reversed(tuple(int(value) for value in global_info["Nxyz"])))
145
+ mappings = global_info["fields"]
146
+ options = _dataset_options(compression)
147
+ definition = contract(
148
+ schema=SNAPSHOT_SCHEMA,
149
+ name=name,
150
+ dtype=dtype.name,
151
+ shape_zyx=shape,
152
+ fields=dict(fields),
153
+ components={source: tuple(mappings[source]) for source, _ in fields},
154
+ metadata=dict(global_info.get("metadata") or {}),
155
+ )
156
+ with h5py.File(destination, "w") as file:
157
+ file.attrs["name"] = name
158
+ file.attrs["snapshot_id"] = snapshot_id
159
+ file.attrs["time_s"] = float(record["time [s]"])
160
+ file.attrs["dtype"] = dtype.name
161
+ file.attrs["schema"] = "stacknordic-hdf5-v1"
162
+ metadata = dict(global_info.get("metadata") or {})
163
+ file.attrs["metadata_json"] = json.dumps(metadata, ensure_ascii=False)
164
+ if "equivalence_ratio" in metadata:
165
+ file.attrs["phi"] = float(metadata["equivalence_ratio"])
166
+ write_contract(file, definition)
167
+ grid = file.create_group("grid")
168
+ for axis in "xyz":
169
+ values = np.fromfile(root / global_info["grid"][axis], dtype=dtype)
170
+ grid.create_dataset(f"{axis}_axis", data=values, dtype=dtype, **options)
171
+ if progress_callback is not None:
172
+ progress_callback(1)
173
+ for source, target in fields:
174
+ _write_field(
175
+ file,
176
+ root,
177
+ record,
178
+ tuple(mappings[source]),
179
+ target,
180
+ shape,
181
+ dtype,
182
+ options,
183
+ )
184
+ if progress_callback is not None:
185
+ progress_callback(1)
186
+ return destination
187
+
188
+
189
+ def package(
190
+ *,
191
+ dataset_dir: str | Path,
192
+ output_dir: str | Path,
193
+ name: str,
194
+ format: str = "hdf5",
195
+ fields: Mapping[str, str],
196
+ compression: str | None = "lzf",
197
+ n_jobs: int | None = None,
198
+ progress: bool = False,
199
+ overwrite: bool = False,
200
+ ) -> PackagedDataset:
201
+ """Package each Cartesian snapshot as one HDF5 file."""
202
+
203
+ started = perf_counter()
204
+ source = Path(dataset_dir).expanduser().resolve()
205
+ destination = Path(output_dir).expanduser().resolve()
206
+ if format != "hdf5":
207
+ _error("format must be 'hdf5'")
208
+ if not isinstance(name, str) or not name.strip() or "/" in name:
209
+ _error("name must be a non-empty filename stem")
210
+ selected = _normalise_fields(fields)
211
+ try:
212
+ info = json.loads((source / "info.json").read_text())
213
+ except (FileNotFoundError, json.JSONDecodeError):
214
+ _error(f"dataset manifest is unavailable or invalid in {source}")
215
+ global_info = info.get("global", {})
216
+ if global_info.get("layout") != "cartesian" or "Nxyz" not in global_info:
217
+ _error("HDF5 packaging requires a verified Cartesian dataset")
218
+ if not isinstance(global_info.get("grid"), dict):
219
+ _error("dataset manifest does not contain a Cartesian grid")
220
+ available = set(global_info.get("fields", {}))
221
+ missing = {field for field, _ in selected}.difference(available)
222
+ if missing:
223
+ _error(f"packaging requested unavailable fields: {sorted(missing)}", KeyError)
224
+ records = tuple(info.get("local", ()))
225
+ if not records:
226
+ _error("dataset contains no snapshots")
227
+ if destination.exists():
228
+ if not destination.is_dir():
229
+ _error(f"output path is not a directory: {destination}", FileExistsError)
230
+ if any(destination.iterdir()) and not overwrite:
231
+ _error(f"output directory is not empty: {destination}", FileExistsError)
232
+ destination.parent.mkdir(parents=True, exist_ok=True)
233
+ estimated_worker_bytes = 192 * 1024**2
234
+ selected_workers = memory_bounded_workers(n_jobs, len(records), estimated_worker_bytes)
235
+ stage = Path(tempfile.mkdtemp(prefix=".stacknordic-package-", dir=destination.parent))
236
+ reporter = (
237
+ start_progress(len(records) * (len(selected) + 3), "StackNordic packaging")
238
+ if progress
239
+ else None
240
+ )
241
+ outputs: list[Path | None] = [None] * len(records)
242
+ try:
243
+ updates: queue.SimpleQueue[int] = queue.SimpleQueue()
244
+
245
+ def task(index: int, callback=None) -> tuple[int, Path]:
246
+ return index, _write_snapshot(
247
+ source,
248
+ stage,
249
+ name.strip(),
250
+ records[index],
251
+ global_info,
252
+ selected,
253
+ compression,
254
+ callback,
255
+ )
256
+
257
+ def report_updates() -> None:
258
+ if reporter is None:
259
+ return
260
+ completed = 0
261
+ while True:
262
+ try:
263
+ completed += updates.get_nowait()
264
+ except queue.Empty:
265
+ break
266
+ if completed:
267
+ reporter.update(completed)
268
+
269
+ if selected_workers == 1:
270
+ callback = reporter.update if reporter is not None else None
271
+ completed = (task(index, callback) for index in range(len(records)))
272
+ for index, path in completed:
273
+ outputs[index] = path
274
+ else:
275
+ with ThreadPoolExecutor(max_workers=selected_workers) as executor:
276
+ callback = updates.put if reporter is not None else None
277
+ pending = {
278
+ executor.submit(task, index, callback)
279
+ for index in range(len(records))
280
+ }
281
+ while pending:
282
+ done, pending = wait(
283
+ pending,
284
+ timeout=0.1,
285
+ return_when=FIRST_COMPLETED,
286
+ )
287
+ report_updates()
288
+ for future in done:
289
+ index, path = future.result()
290
+ outputs[index] = path
291
+ report_updates()
292
+ if destination.exists():
293
+ shutil.rmtree(destination)
294
+ stage.replace(destination)
295
+ except BaseException:
296
+ shutil.rmtree(stage, ignore_errors=True)
297
+ raise
298
+ finally:
299
+ if reporter is not None:
300
+ finish_progress(reporter)
301
+ files = tuple(destination / path.name for path in outputs if path is not None)
302
+ return PackagedDataset(
303
+ dataset_dir=source,
304
+ output_dir=destination,
305
+ files=files,
306
+ format=format,
307
+ snapshots=len(records),
308
+ n_jobs=selected_workers,
309
+ elapsed_seconds=perf_counter() - started,
310
+ )
311
+
312
+
313
+ def _copy_dataset(source: h5py.File, target: h5py.Group, path: str) -> None:
314
+ parent_name, _, dataset_name = path.rpartition("/")
315
+ parent = target.require_group(parent_name) if parent_name else target
316
+ source.copy(source[path], parent, name=dataset_name)
317
+
318
+
319
+ def compile(
320
+ *,
321
+ dataset_dir: str | Path,
322
+ output_file: str | Path,
323
+ pattern: str,
324
+ progress: bool = False,
325
+ overwrite: bool = False,
326
+ ) -> CompiledDataset:
327
+ """Compile self-describing snapshot packages into one HDF5 series."""
328
+
329
+ started = perf_counter()
330
+ source = Path(dataset_dir).expanduser().resolve()
331
+ destination = Path(output_file).expanduser().resolve()
332
+ if not source.is_dir():
333
+ _error(f"dataset directory was not found: {source}", FileNotFoundError)
334
+ if not isinstance(pattern, str) or not pattern.strip():
335
+ _error("pattern must be a non-empty glob string")
336
+ candidates = tuple(
337
+ path for path in sorted(source.glob(pattern))
338
+ if path.is_file() and path.resolve() != destination
339
+ )
340
+ if not candidates:
341
+ _error(f"pattern matched no snapshot packages in {source}", FileNotFoundError)
342
+ snapshots: list[tuple[int, float, Path]] = []
343
+ definitions = []
344
+ for path in candidates:
345
+ with h5py.File(path, "r") as file:
346
+ definition = read_contract(file)
347
+ if definition.schema != SNAPSHOT_SCHEMA:
348
+ _error(f"input is not a snapshot package: {path.name}")
349
+ definitions.append(definition)
350
+ snapshots.append((int(file.attrs["snapshot_id"]), float(file.attrs["time_s"]), path))
351
+ reference = definitions[0]
352
+ for path, definition in zip(candidates[1:], definitions[1:], strict=True):
353
+ if not compatible(reference, definition):
354
+ _error(f"snapshot package contract differs: {path.name}")
355
+ snapshot_ids = [item[0] for item in snapshots]
356
+ times = [item[1] for item in snapshots]
357
+ if len(set(snapshot_ids)) != len(snapshot_ids):
358
+ _error("snapshot packages contain duplicate snapshot identifiers")
359
+ if len(set(times)) != len(times):
360
+ _error("snapshot packages contain duplicate physical times")
361
+ snapshots.sort(key=lambda item: (item[1], item[0]))
362
+ if destination.exists() and not overwrite:
363
+ _error(f"output file already exists: {destination}", FileExistsError)
364
+ destination.parent.mkdir(parents=True, exist_ok=True)
365
+ descriptor, temporary_name = tempfile.mkstemp(
366
+ prefix=f".{destination.stem}-",
367
+ suffix=destination.suffix or ".h5",
368
+ dir=destination.parent,
369
+ )
370
+ os.close(descriptor)
371
+ Path(temporary_name).unlink()
372
+ temporary = Path(temporary_name)
373
+ reporter = start_progress(len(snapshots), "StackNordic compiling") if progress else None
374
+ try:
375
+ with h5py.File(temporary, "w") as output:
376
+ write_contract(output, reference.with_schema(SERIES_SCHEMA))
377
+ output.attrs["schema"] = "stacknordic-hdf5-series-v1"
378
+ output.attrs["snapshots"] = len(snapshots)
379
+ output.attrs[SNAPSHOTS_ATTRIBUTE] = json.dumps(
380
+ [
381
+ {"id": snapshot_id, "time_s": time, "group": f"id_{snapshot_id:03d}"}
382
+ for snapshot_id, time, _ in snapshots
383
+ ],
384
+ separators=(",", ":"),
385
+ )
386
+ with h5py.File(snapshots[0][2], "r") as first:
387
+ first.copy(first["grid"], output, name="grid")
388
+ for snapshot_id, time, path in snapshots:
389
+ group = output.create_group(f"id_{snapshot_id:03d}")
390
+ group.attrs["snapshot_id"] = snapshot_id
391
+ group.attrs["time_s"] = time
392
+ with h5py.File(path, "r") as input_file:
393
+ for target in reference.fields.values():
394
+ _copy_dataset(input_file, group, target)
395
+ if reporter is not None:
396
+ reporter.update()
397
+ if destination.exists():
398
+ destination.unlink()
399
+ temporary.replace(destination)
400
+ except BaseException:
401
+ temporary.unlink(missing_ok=True)
402
+ raise
403
+ finally:
404
+ if reporter is not None:
405
+ finish_progress(reporter)
406
+ return CompiledDataset(
407
+ dataset_dir=source,
408
+ output_file=destination,
409
+ source_files=tuple(item[2] for item in snapshots),
410
+ snapshots=len(snapshots),
411
+ elapsed_seconds=perf_counter() - started,
412
+ )
413
+
414
+
415
+ __all__ = ["CompiledDataset", "PackagedDataset", "compile", "package"]