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,790 @@
1
+ """Memory-bounded Cartesian dataset filtering and downsampling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+ import shutil
9
+ import tempfile
10
+ from collections.abc import Mapping
11
+ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, 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
+ from scipy.ndimage import affine_transform, gaussian_filter
19
+
20
+ from .._progress import finish_progress, start_progress
21
+ from ..filtering import Filtering
22
+ from ..resources import memory_bounded_workers
23
+ from ._contract import (
24
+ SERIES_SCHEMA,
25
+ SNAPSHOT_SCHEMA,
26
+ SNAPSHOTS_ATTRIBUTE,
27
+ compatible,
28
+ contract,
29
+ normalise_hdf5_path,
30
+ read_contract,
31
+ write_contract,
32
+ )
33
+ from ._manifest import component_file
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class DownsampledDataset:
38
+ """Summary of one completed downsampling operation."""
39
+
40
+ input_dir: Path
41
+ output_dir: Path
42
+ kernel: str
43
+ factor: tuple[int, int, int]
44
+ snapshots: int
45
+ n_jobs: int
46
+ elapsed_seconds: float
47
+ output_file: Path | None = None
48
+
49
+
50
+ def _error(message: str, error_type: type[Exception] = ValueError):
51
+ raise error_type(f"[StackNordic] {message}")
52
+
53
+
54
+ def _triplet(values, name: str, value_type):
55
+ try:
56
+ selected = tuple(value_type(value) for value in values)
57
+ except (TypeError, ValueError) as error:
58
+ raise ValueError(f"{name} must contain three values") from error
59
+ if len(selected) != 3 or any(value <= 0 for value in selected):
60
+ raise ValueError(f"{name} must contain three positive values")
61
+ return selected
62
+
63
+
64
+ class _Snapshot:
65
+ def __init__(self, root: Path, info: dict[str, object], record: dict[str, object]):
66
+ global_info = info["global"]
67
+ self.root = root
68
+ self.record = record
69
+ self.dtype = np.dtype(global_info["dtype"])
70
+ self.nxyz = tuple(int(value) for value in global_info["Nxyz"])
71
+ self.shape = tuple(reversed(self.nxyz))
72
+ self.fields = {
73
+ name: tuple(components)
74
+ for name, components in global_info["fields"].items()
75
+ }
76
+ self.hdf_fields = global_info.get("hdf_fields")
77
+
78
+ def field(self, name: str) -> np.ndarray:
79
+ if name not in self.fields:
80
+ _error(f"filtering requested unavailable field {name!r}", KeyError)
81
+ components = self.fields[name]
82
+ if self.hdf_fields is not None:
83
+ filename = self.record["__hdf5_file__"]
84
+ group = str(self.record.get("__hdf5_group__") or "").strip("/")
85
+ target = self.hdf_fields[name]
86
+ path = f"{group}/{target}" if group else target
87
+ with h5py.File(filename, "r") as file:
88
+ return np.asarray(file[path])
89
+ arrays: list[np.memmap] = []
90
+ for component in components:
91
+ try:
92
+ filename = component_file(self.record, component)
93
+ except KeyError:
94
+ _error(f"snapshot {self.record['id']} has no file for {component!r}")
95
+ path = self.root / filename
96
+ arrays.append(np.memmap(path, dtype=self.dtype, mode="r", shape=self.shape))
97
+ if len(arrays) == 1:
98
+ return np.asarray(arrays[0], dtype=np.float64)
99
+ result = np.empty((*self.shape, len(arrays)), dtype=np.float64)
100
+ for index, array in enumerate(arrays):
101
+ result[..., index] = array
102
+ return result
103
+
104
+
105
+ def _hdf5_info(source: Path) -> tuple[dict[str, object], Path]:
106
+ paths = (source,) if source.is_file() else tuple(sorted(source.glob("*.h5")))
107
+ if not paths:
108
+ _error(f"dataset manifest or HDF5 packages were not found in {source}")
109
+ records = []
110
+ definitions = []
111
+ grid_reference: dict[str, np.ndarray] | None = None
112
+ for path in paths:
113
+ with h5py.File(path, "r") as file:
114
+ definition = read_contract(file)
115
+ definitions.append(definition)
116
+ current_grid = {
117
+ axis: np.asarray(file[f"grid/{axis}_axis"])
118
+ for axis in "xyz"
119
+ }
120
+ if grid_reference is None:
121
+ grid_reference = current_grid
122
+ elif any(
123
+ not np.array_equal(grid_reference[axis], current_grid[axis])
124
+ for axis in "xyz"
125
+ ):
126
+ _error("HDF5 snapshot packages do not share one Cartesian grid")
127
+ if definition.schema == SNAPSHOT_SCHEMA:
128
+ records.append(
129
+ {
130
+ "id": int(file.attrs["snapshot_id"]),
131
+ "time [s]": float(file.attrs["time_s"]),
132
+ "__hdf5_file__": str(path),
133
+ "__hdf5_group__": "",
134
+ }
135
+ )
136
+ elif definition.schema == SERIES_SCHEMA:
137
+ try:
138
+ snapshots = json.loads(str(file.attrs[SNAPSHOTS_ATTRIBUTE]))
139
+ except (KeyError, json.JSONDecodeError) as error:
140
+ raise ValueError(
141
+ "[StackNordic] compiled HDF5 series has invalid snapshot metadata"
142
+ ) from error
143
+ records.extend(
144
+ {
145
+ "id": int(item["id"]),
146
+ "time [s]": float(item["time_s"]),
147
+ "__hdf5_file__": str(path),
148
+ "__hdf5_group__": str(item["group"]),
149
+ }
150
+ for item in snapshots
151
+ )
152
+ else:
153
+ _error(f"unsupported StackNordic HDF5 schema: {definition.schema!r}")
154
+ reference = definitions[0]
155
+ for path, definition in zip(paths[1:], definitions[1:], strict=True):
156
+ if not compatible(reference, definition):
157
+ _error(f"HDF5 package contract differs: {path.name}")
158
+ identifiers = [int(record["id"]) for record in records]
159
+ times = [float(record["time [s]"]) for record in records]
160
+ if len(set(identifiers)) != len(identifiers) or len(set(times)) != len(times):
161
+ _error("HDF5 packages contain duplicate snapshot identifiers or physical times")
162
+ records.sort(key=lambda record: (float(record["time [s]"]), int(record["id"])))
163
+ info = {
164
+ "global": {
165
+ "snapshots": len(records),
166
+ "variables": [
167
+ component
168
+ for components in reference.components.values()
169
+ for component in components
170
+ ],
171
+ "dtype": reference.dtype,
172
+ "layout": "cartesian",
173
+ "grid": {axis: f"grid/{axis}_axis" for axis in "xyz"},
174
+ "fields": {
175
+ name: list(components)
176
+ for name, components in reference.components.items()
177
+ },
178
+ "hdf_fields": dict(reference.fields),
179
+ "hdf_grid_file": str(paths[0]),
180
+ "Nxyz": list(reversed(reference.shape_zyx)),
181
+ "metadata": dict(reference.metadata),
182
+ },
183
+ "local": records,
184
+ }
185
+ return info, source
186
+
187
+
188
+ def _source_info(source: Path) -> tuple[dict[str, object], Path]:
189
+ manifest = source / "info.json" if source.is_dir() else None
190
+ if manifest is not None and manifest.is_file():
191
+ try:
192
+ return json.loads(manifest.read_text()), source
193
+ except json.JSONDecodeError as error:
194
+ raise ValueError(f"[StackNordic] invalid dataset manifest in {source}") from error
195
+ return _hdf5_info(source)
196
+
197
+
198
+ def _grid_axis(source: Path, global_info: dict[str, object], axis: str) -> np.ndarray:
199
+ if "hdf_grid_file" in global_info:
200
+ with h5py.File(global_info["hdf_grid_file"], "r") as file:
201
+ return np.asarray(file[global_info["grid"][axis]])
202
+ return np.memmap(
203
+ source / global_info["grid"][axis],
204
+ dtype=np.dtype(global_info["dtype"]),
205
+ mode="r",
206
+ )
207
+
208
+
209
+ def _box(array: np.ndarray, factor_zyx: tuple[int, int, int]) -> np.ndarray:
210
+ spatial = array.shape[:3]
211
+ trimmed = tuple(size // factor * factor for size, factor in zip(spatial, factor_zyx, strict=True))
212
+ slices = tuple(slice(0, size) for size in trimmed)
213
+ selected = array[slices]
214
+ bz, by, bx = factor_zyx
215
+ nz, ny, nx = trimmed
216
+ tail = array.shape[3:]
217
+ viewed = selected.reshape(nz // bz, bz, ny // by, by, nx // bx, bx, *tail)
218
+ return viewed.mean(axis=(1, 3, 5), dtype=np.float64)
219
+
220
+
221
+ def _gaussian(
222
+ array: np.ndarray,
223
+ factor_zyx: tuple[int, int, int],
224
+ sigma_zyx: tuple[float, float, float],
225
+ boundary: str,
226
+ ) -> np.ndarray:
227
+ spatial = array.shape[:3]
228
+ output_shape = tuple(size // factor for size, factor in zip(spatial, factor_zyx, strict=True))
229
+ offset = tuple((factor - 1.0) / 2.0 for factor in factor_zyx)
230
+
231
+ def component(values: np.ndarray) -> np.ndarray:
232
+ filtered = gaussian_filter(values, sigma=sigma_zyx, mode=boundary)
233
+ return affine_transform(
234
+ filtered,
235
+ matrix=np.diag(factor_zyx),
236
+ offset=offset,
237
+ output_shape=output_shape,
238
+ order=1,
239
+ mode=boundary,
240
+ prefilter=False,
241
+ )
242
+
243
+ if array.ndim == 3:
244
+ return component(array)
245
+ return np.stack([component(array[..., index]) for index in range(array.shape[-1])], axis=-1)
246
+
247
+
248
+ def _reducer(
249
+ kernel: str,
250
+ factor_xyz: tuple[int, int, int],
251
+ sigma_xyz: tuple[float, float, float] | None,
252
+ boundary: str,
253
+ ):
254
+ factor_zyx = tuple(reversed(factor_xyz))
255
+ if kernel == "box":
256
+ return lambda array: _box(array, factor_zyx)
257
+ assert sigma_xyz is not None
258
+ sigma_zyx = tuple(reversed(sigma_xyz))
259
+ return lambda array: _gaussian(array, factor_zyx, sigma_zyx, boundary)
260
+
261
+
262
+ def _filtered_fields(snapshot: _Snapshot, filtering: Filtering, reduce) -> dict[str, np.ndarray]:
263
+ result: dict[str, np.ndarray] = {}
264
+ retained: dict[str, np.ndarray] = {}
265
+ reused = set(filtering.variance).union(filtering.stress)
266
+
267
+ def field(name: str) -> np.ndarray:
268
+ return retained[name] if name in retained else snapshot.field(name)
269
+
270
+ density = field(filtering.density) if filtering.density is not None else None
271
+ density_filtered = reduce(density) if density is not None else None
272
+ for name in filtering.mean:
273
+ values = density if name == filtering.density else field(name)
274
+ assert values is not None
275
+ result[name] = reduce(values)
276
+ if name in reused:
277
+ retained[name] = values
278
+ for name in filtering.favre:
279
+ assert density is not None and density_filtered is not None
280
+ values = field(name)
281
+ weighted = density[..., None] * values if values.ndim == 4 else density * values
282
+ denominator = density_filtered[..., None] if values.ndim == 4 else density_filtered
283
+ if np.any(denominator <= 0.0):
284
+ _error(f"Favre filtering of {name!r} encountered non-positive density")
285
+ result[name] = reduce(weighted) / denominator
286
+ if name in reused:
287
+ retained[name] = values
288
+ for source, target in filtering.variance.items():
289
+ values = field(source)
290
+ if values.ndim != 3:
291
+ _error(f"variance source {source!r} must be scalar")
292
+ if filtering.density is None:
293
+ mean = result.get(source, reduce(values))
294
+ second = reduce(values * values)
295
+ else:
296
+ assert density is not None and density_filtered is not None
297
+ mean = result.get(source)
298
+ if mean is None:
299
+ mean = reduce(density * values) / density_filtered
300
+ second = reduce(density * values * values) / density_filtered
301
+ result[target] = np.maximum(second - mean * mean, 0.0)
302
+ retained.pop(source, None)
303
+ for source, target in filtering.stress.items():
304
+ velocity = field(source)
305
+ if velocity.ndim != 4 or velocity.shape[-1] != 3:
306
+ _error(f"stress source {source!r} must have three components")
307
+ mean = result.get(source)
308
+ if mean is None:
309
+ if filtering.density is None:
310
+ mean = reduce(velocity)
311
+ else:
312
+ assert density is not None and density_filtered is not None
313
+ mean = reduce(density[..., None] * velocity) / density_filtered[..., None]
314
+ pairs = ((0, 0), (1, 1), (2, 2), (0, 1), (0, 2), (1, 2))
315
+ stress = np.empty((*mean.shape[:3], 6), dtype=np.float64)
316
+ for index, (first, second) in enumerate(pairs):
317
+ product = velocity[..., first] * velocity[..., second]
318
+ moment = (
319
+ reduce(product)
320
+ if filtering.density is None
321
+ else reduce(density * product) / density_filtered
322
+ )
323
+ stress[..., index] = moment - mean[..., first] * mean[..., second]
324
+ result[target] = stress
325
+ retained.pop(source, None)
326
+ for stress_name, energy_name in filtering.energy.items():
327
+ stress = result[stress_name]
328
+ result[energy_name] = 0.5 * np.maximum(
329
+ stress[..., 0] + stress[..., 1] + stress[..., 2], 0.0
330
+ )
331
+ for source, target in filtering.specific.items():
332
+ assert density_filtered is not None
333
+ if np.any(density_filtered <= 0.0):
334
+ _error(f"specific source {target!r} encountered non-positive density")
335
+ result[target] = result[source] / density_filtered
336
+ return result
337
+
338
+
339
+ def _component_names(name: str, values: np.ndarray, source_fields: dict[str, tuple[str, ...]]):
340
+ if name in source_fields and len(source_fields[name]) == (1 if values.ndim == 3 else values.shape[-1]):
341
+ return source_fields[name]
342
+ if values.ndim == 3:
343
+ return (name,)
344
+ suffixes = ("x", "y", "z") if values.shape[-1] == 3 else ("xx", "yy", "zz", "xy", "xz", "yz")
345
+ return tuple(f"{name}_{suffix}" for suffix in suffixes)
346
+
347
+
348
+ def _write_snapshot(
349
+ root: Path,
350
+ data_dir: Path,
351
+ info: dict[str, object],
352
+ record: dict[str, object],
353
+ filtering: Filtering,
354
+ reduce,
355
+ dtype: np.dtype,
356
+ ) -> tuple[dict[str, object], dict[str, tuple[str, ...]]]:
357
+ snapshot = _Snapshot(root, info, record)
358
+ fields = _filtered_fields(snapshot, filtering, reduce)
359
+ output: dict[str, object] = {"id": record["id"], "time [s]": record["time [s]"]}
360
+ mappings: dict[str, tuple[str, ...]] = {}
361
+ for name, values in fields.items():
362
+ names = _component_names(name, values, snapshot.fields)
363
+ mappings[name] = names
364
+ columns = (values,) if values.ndim == 3 else tuple(
365
+ values[..., index] for index in range(values.shape[-1])
366
+ )
367
+ for component, column in zip(names, columns, strict=True):
368
+ filename = f"{component}_id{int(record['id']):03d}.dat"
369
+ np.asarray(column, dtype=dtype).tofile(data_dir / filename)
370
+ output[f"{component} filename"] = f"./data/{filename}"
371
+ first = next(iter(fields.values()))
372
+ output["cells"] = math.prod(first.shape[:3])
373
+ return output, mappings
374
+
375
+
376
+ def _hdf5_options(compression: str | None) -> dict[str, object]:
377
+ if compression not in {None, "lzf", "gzip"}:
378
+ _error("compression must be None, 'lzf', or 'gzip'")
379
+ return {} if compression is None else {
380
+ "compression": compression,
381
+ "shuffle": True,
382
+ "chunks": True,
383
+ }
384
+
385
+
386
+ def _hdf5_fields(fields: Mapping[str, str] | None) -> dict[str, str]:
387
+ if not isinstance(fields, Mapping) or not fields:
388
+ raise TypeError("fields must be a non-empty mapping when output_file is used")
389
+ try:
390
+ selected = {
391
+ str(name): normalise_hdf5_path(target)
392
+ for name, target in fields.items()
393
+ }
394
+ except ValueError as error:
395
+ _error(str(error))
396
+ targets = tuple(selected.values())
397
+ if any(not name for name in selected):
398
+ _error("field names must be non-empty")
399
+ if len(set(targets)) != len(targets):
400
+ _error("HDF5 field paths must be unique")
401
+ for first in targets:
402
+ for second in targets:
403
+ if first != second and second.startswith(first + "/"):
404
+ _error(f"HDF5 field path {first!r} conflicts with {second!r}")
405
+ return selected
406
+
407
+
408
+ def _write_hdf5_snapshot(
409
+ root: Path,
410
+ stage: Path,
411
+ info: dict[str, object],
412
+ record: dict[str, object],
413
+ filtering: Filtering,
414
+ reduce,
415
+ dtype: np.dtype,
416
+ fields: Mapping[str, str],
417
+ compression: str | None,
418
+ ) -> tuple[Path, dict[str, tuple[str, ...]]]:
419
+ snapshot = _Snapshot(root, info, record)
420
+ filtered = _filtered_fields(snapshot, filtering, reduce)
421
+ unavailable = set(fields).difference(filtered)
422
+ if unavailable:
423
+ _error(f"HDF5 output requested unavailable fields: {sorted(unavailable)}", KeyError)
424
+ mappings = {
425
+ name: _component_names(name, filtered[name], snapshot.fields)
426
+ for name in fields
427
+ }
428
+ path = stage / f"snapshot-{int(record['id']):06d}.h5"
429
+ options = _hdf5_options(compression)
430
+ with h5py.File(path, "w") as file:
431
+ for name, target in fields.items():
432
+ parent_name, _, dataset_name = target.rpartition("/")
433
+ parent = file.require_group(parent_name) if parent_name else file
434
+ parent.create_dataset(
435
+ dataset_name,
436
+ data=np.asarray(filtered[name], dtype=dtype),
437
+ dtype=dtype,
438
+ **options,
439
+ )
440
+ return path, mappings
441
+
442
+
443
+ def _copy_hdf5_snapshot(
444
+ source_path: Path,
445
+ output: h5py.File,
446
+ record: dict[str, object],
447
+ fields: Mapping[str, str],
448
+ ) -> None:
449
+ group = output.create_group(f"id_{int(record['id']):03d}")
450
+ group.attrs["snapshot_id"] = int(record["id"])
451
+ group.attrs["time_s"] = float(record["time [s]"])
452
+ with h5py.File(source_path, "r") as source:
453
+ for target in fields.values():
454
+ parent_name, _, dataset_name = target.rpartition("/")
455
+ parent = group.require_group(parent_name) if parent_name else group
456
+ source.copy(source[target], parent, name=dataset_name)
457
+
458
+
459
+ def _downsample_hdf5(
460
+ *,
461
+ source: Path,
462
+ destination: Path,
463
+ info: dict[str, object],
464
+ records: tuple[dict[str, object], ...],
465
+ filtering: Filtering,
466
+ reduce,
467
+ factor_xyz: tuple[int, int, int],
468
+ sigma_xyz: tuple[float, float, float] | None,
469
+ boundary: str,
470
+ kernel: str,
471
+ dtype: str,
472
+ fields: Mapping[str, str],
473
+ compression: str | None,
474
+ workers: int,
475
+ progress: bool,
476
+ overwrite: bool,
477
+ started: float,
478
+ ) -> DownsampledDataset:
479
+ destination.parent.mkdir(parents=True, exist_ok=True)
480
+ stage = Path(tempfile.mkdtemp(prefix=".stacknordic-downsample-", dir=destination.parent))
481
+ temporary = stage / destination.name
482
+ reporter = start_progress(len(records), "StackNordic downsampling") if progress else None
483
+ mappings: dict[str, tuple[str, ...]] | None = None
484
+ snapshots: list[dict[str, object]] = []
485
+ global_info = info["global"]
486
+ try:
487
+ with h5py.File(temporary, "w") as output:
488
+ grid = output.create_group("grid")
489
+ for axis, factor_value in zip("xyz", factor_xyz, strict=True):
490
+ values = _grid_axis(source, global_info, axis)
491
+ count = len(values) // factor_value * factor_value
492
+ reduced = np.asarray(values[:count]).reshape(-1, factor_value).mean(axis=1)
493
+ grid.create_dataset(f"{axis}_axis", data=reduced.astype(dtype))
494
+
495
+ def task(index: int):
496
+ path, current_mappings = _write_hdf5_snapshot(
497
+ source,
498
+ stage,
499
+ info,
500
+ records[index],
501
+ filtering,
502
+ reduce,
503
+ np.dtype(dtype),
504
+ fields,
505
+ compression,
506
+ )
507
+ return index, path, current_mappings
508
+
509
+ with ThreadPoolExecutor(max_workers=workers) as executor:
510
+ pending = {
511
+ executor.submit(task, index): index
512
+ for index in range(min(workers, len(records)))
513
+ }
514
+ next_index = len(pending)
515
+ while pending:
516
+ done, _ = wait(pending, return_when=FIRST_COMPLETED)
517
+ for future in done:
518
+ pending.pop(future)
519
+ index, path, current_mappings = future.result()
520
+ if mappings is None:
521
+ mappings = current_mappings
522
+ elif mappings != current_mappings:
523
+ _error("filtered field components changed between snapshots")
524
+ record = records[index]
525
+ _copy_hdf5_snapshot(path, output, record, fields)
526
+ path.unlink()
527
+ snapshots.append(
528
+ {
529
+ "id": int(record["id"]),
530
+ "time_s": float(record["time [s]"]),
531
+ "group": f"id_{int(record['id']):03d}",
532
+ }
533
+ )
534
+ if reporter is not None:
535
+ reporter.update()
536
+ if next_index < len(records):
537
+ pending[executor.submit(task, next_index)] = next_index
538
+ next_index += 1
539
+
540
+ assert mappings is not None
541
+ snapshots.sort(key=lambda item: (item["time_s"], item["id"]))
542
+ nxyz = tuple(int(value) for value in global_info["Nxyz"])
543
+ reduced_nxyz = tuple(
544
+ size // factor
545
+ for size, factor in zip(nxyz, factor_xyz, strict=True)
546
+ )
547
+ definition = contract(
548
+ schema=SERIES_SCHEMA,
549
+ name=destination.stem,
550
+ dtype=dtype,
551
+ shape_zyx=tuple(reversed(reduced_nxyz)),
552
+ fields=dict(fields),
553
+ components=mappings,
554
+ metadata={
555
+ **dict(global_info.get("metadata") or {}),
556
+ "downsampling": {
557
+ "kernel": kernel,
558
+ "factor_xyz": list(factor_xyz),
559
+ "sigma_xyz": list(sigma_xyz) if sigma_xyz is not None else None,
560
+ "boundary": boundary if kernel == "gaussian" else None,
561
+ "source": str(source),
562
+ },
563
+ },
564
+ )
565
+ write_contract(output, definition)
566
+ output.attrs["schema"] = SERIES_SCHEMA
567
+ output.attrs["snapshots"] = len(snapshots)
568
+ output.attrs[SNAPSHOTS_ATTRIBUTE] = json.dumps(snapshots, separators=(",", ":"))
569
+ if destination.exists():
570
+ if not overwrite:
571
+ _error(f"output file already exists: {destination}", FileExistsError)
572
+ destination.unlink()
573
+ temporary.replace(destination)
574
+ except BaseException:
575
+ shutil.rmtree(stage, ignore_errors=True)
576
+ raise
577
+ finally:
578
+ if reporter is not None:
579
+ finish_progress(reporter)
580
+ stage.rmdir()
581
+ return DownsampledDataset(
582
+ input_dir=source,
583
+ output_dir=destination.parent,
584
+ output_file=destination,
585
+ kernel=kernel,
586
+ factor=factor_xyz,
587
+ snapshots=len(records),
588
+ n_jobs=workers,
589
+ elapsed_seconds=perf_counter() - started,
590
+ )
591
+
592
+
593
+ def downsample(
594
+ *,
595
+ dataset_dir: str | Path,
596
+ factor: tuple[int, int, int],
597
+ filtering: Filtering,
598
+ output_dir: str | Path | None = None,
599
+ output_file: str | Path | None = None,
600
+ fields: Mapping[str, str] | None = None,
601
+ kernel: str = "box",
602
+ sigma: tuple[float, float, float] | None = None,
603
+ boundary: str = "reflect",
604
+ dtype: str = "float32",
605
+ compression: str | None = "lzf",
606
+ n_jobs: int | None = None,
607
+ progress: bool = False,
608
+ overwrite: bool = False,
609
+ ) -> DownsampledDataset:
610
+ """Downsample a Cartesian exported dataset with explicit physical rules."""
611
+
612
+ started = perf_counter()
613
+ source = Path(dataset_dir).expanduser().resolve()
614
+ if (output_dir is None) == (output_file is None):
615
+ _error("provide exactly one of output_dir and output_file")
616
+ destination = Path(output_dir or output_file).expanduser().resolve()
617
+ selected_fields = _hdf5_fields(fields) if output_file is not None else None
618
+ if output_dir is not None and fields is not None:
619
+ _error("fields is only valid with output_file")
620
+ _hdf5_options(compression)
621
+ if kernel not in {"box", "gaussian"}:
622
+ _error("kernel must be 'box' or 'gaussian'")
623
+ factor_xyz = _triplet(factor, "factor", int)
624
+ sigma_xyz = None if sigma is None else _triplet(sigma, "sigma", float)
625
+ if kernel == "box" and sigma is not None:
626
+ _error("sigma is only valid for the Gaussian kernel")
627
+ if kernel == "gaussian" and sigma_xyz is None:
628
+ _error("the Gaussian kernel requires sigma")
629
+ if boundary not in {"reflect", "nearest", "wrap"}:
630
+ _error("boundary must be 'reflect', 'nearest', or 'wrap'")
631
+ if dtype not in {"float32", "float64"}:
632
+ _error("dtype must be 'float32' or 'float64'")
633
+ if not isinstance(filtering, Filtering):
634
+ raise TypeError("filtering must be a StackNordic Filtering contract")
635
+ if destination.exists() and not overwrite:
636
+ kind = "file" if output_file is not None else "directory"
637
+ _error(f"output {kind} already exists: {destination}", FileExistsError)
638
+ info, source = _source_info(source)
639
+ global_info = info.get("global", {})
640
+ if global_info.get("layout") != "cartesian" or "Nxyz" not in global_info:
641
+ _error("downsampling currently requires a verified Cartesian dataset")
642
+ if not isinstance(global_info.get("fields"), dict):
643
+ _error("dataset manifest does not contain logical field mappings")
644
+ records = tuple(info.get("local", ()))
645
+ if not records:
646
+ _error("dataset contains no snapshots")
647
+ first_record = records[0]
648
+ requested = set(filtering.mean).union(filtering.favre, filtering.variance, filtering.stress)
649
+ if filtering.density is not None:
650
+ requested.add(filtering.density)
651
+ unavailable = requested.difference(global_info["fields"])
652
+ if unavailable:
653
+ _error(f"filtering requested unavailable fields: {sorted(unavailable)}", KeyError)
654
+ if "hdf_fields" in global_info:
655
+ cell_count = int(np.prod(tuple(global_info["Nxyz"])))
656
+ input_bytes = sum(
657
+ cell_count
658
+ * np.dtype(global_info["dtype"]).itemsize
659
+ * len(global_info["fields"][name])
660
+ for name in requested
661
+ )
662
+ else:
663
+ input_bytes = sum(
664
+ (source / component_file(first_record, component)).stat().st_size
665
+ for name in requested
666
+ for component in global_info["fields"][name]
667
+ )
668
+ estimated_worker_bytes = max(input_bytes * 6, 256 * 1024**2)
669
+ selected_workers = memory_bounded_workers(n_jobs, len(records), estimated_worker_bytes)
670
+ if n_jobs == -1 and selected_workers < min(len(records), os.cpu_count() or 1):
671
+ print(
672
+ f"[StackNordic] Downsampling workers: n_jobs=-1 resolved to {selected_workers} "
673
+ "from the available memory and selected fields."
674
+ )
675
+ reduce = _reducer(kernel, factor_xyz, sigma_xyz, boundary)
676
+ if output_file is not None:
677
+ assert selected_fields is not None
678
+ return _downsample_hdf5(
679
+ source=source,
680
+ destination=destination,
681
+ info=info,
682
+ records=records,
683
+ filtering=filtering,
684
+ reduce=reduce,
685
+ factor_xyz=factor_xyz,
686
+ sigma_xyz=sigma_xyz,
687
+ boundary=boundary,
688
+ kernel=kernel,
689
+ dtype=dtype,
690
+ fields=selected_fields,
691
+ compression=compression,
692
+ workers=selected_workers,
693
+ progress=progress,
694
+ overwrite=overwrite,
695
+ started=started,
696
+ )
697
+ destination.parent.mkdir(parents=True, exist_ok=True)
698
+ stage = Path(tempfile.mkdtemp(prefix=".stacknordic-downsample-", dir=destination.parent))
699
+ data_dir = stage / "data"
700
+ grid_dir = stage / "grid"
701
+ data_dir.mkdir()
702
+ grid_dir.mkdir()
703
+ output_records: list[dict[str, object] | None] = [None] * len(records)
704
+ mappings: dict[str, tuple[str, ...]] = {}
705
+ reporter = (
706
+ start_progress(len(records), "StackNordic downsampling")
707
+ if progress
708
+ else None
709
+ )
710
+ try:
711
+ def task(index: int):
712
+ record, fields = _write_snapshot(
713
+ source,
714
+ data_dir,
715
+ info,
716
+ records[index],
717
+ filtering,
718
+ reduce,
719
+ np.dtype(dtype),
720
+ )
721
+ return index, record, fields
722
+
723
+ if selected_workers == 1:
724
+ completed = (task(index) for index in range(len(records)))
725
+ for index, record, current_mappings in completed:
726
+ output_records[index] = record
727
+ mappings.update(current_mappings)
728
+ if reporter is not None:
729
+ reporter.update()
730
+ else:
731
+ with ThreadPoolExecutor(max_workers=selected_workers) as executor:
732
+ futures = [executor.submit(task, index) for index in range(len(records))]
733
+ for future in as_completed(futures):
734
+ index, record, current_mappings = future.result()
735
+ output_records[index] = record
736
+ mappings.update(current_mappings)
737
+ if reporter is not None:
738
+ reporter.update()
739
+ nxyz = tuple(int(value) for value in global_info["Nxyz"])
740
+ reduced_nxyz = tuple(size // factor for size, factor in zip(nxyz, factor_xyz, strict=True))
741
+ grid_entries: dict[str, str] = {}
742
+ for axis, factor_value in zip("xyz", factor_xyz, strict=True):
743
+ values = _grid_axis(source, global_info, axis)
744
+ count = len(values) // factor_value * factor_value
745
+ reduced = np.asarray(values[:count]).reshape(-1, factor_value).mean(axis=1)
746
+ filename = f"{axis.upper()}_m.dat"
747
+ reduced.astype(dtype).tofile(grid_dir / filename)
748
+ grid_entries[axis] = f"./grid/{filename}"
749
+ output_info = {
750
+ "global": {
751
+ "snapshots": len(records),
752
+ "variables": [component for names in mappings.values() for component in names],
753
+ "dtype": dtype,
754
+ "layout": "cartesian",
755
+ "grid": grid_entries,
756
+ "fields": {name: list(names) for name, names in mappings.items()},
757
+ "Nxyz": list(reduced_nxyz),
758
+ "metadata": {
759
+ **dict(global_info.get("metadata") or {}),
760
+ "downsampling": {
761
+ "kernel": kernel,
762
+ "factor_xyz": list(factor_xyz),
763
+ "sigma_xyz": list(sigma_xyz) if sigma_xyz is not None else None,
764
+ "boundary": boundary if kernel == "gaussian" else None,
765
+ "source": str(source),
766
+ },
767
+ },
768
+ },
769
+ "local": output_records,
770
+ }
771
+ (stage / "info.json").write_text(json.dumps(output_info, indent=4) + "\n")
772
+ if destination.exists():
773
+ shutil.rmtree(destination)
774
+ stage.replace(destination)
775
+ except BaseException:
776
+ shutil.rmtree(stage, ignore_errors=True)
777
+ raise
778
+ finally:
779
+ if reporter is not None:
780
+ finish_progress(reporter)
781
+ return DownsampledDataset(
782
+ input_dir=source,
783
+ output_dir=destination,
784
+ kernel=kernel,
785
+ factor=factor_xyz,
786
+ snapshots=len(records),
787
+ n_jobs=selected_workers,
788
+ elapsed_seconds=perf_counter() - started,
789
+ output_file=None,
790
+ )