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,1070 @@
1
+ """Export OpenFOAM fields as compact machine-learning datasets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import multiprocessing
8
+ import os
9
+ import re
10
+ import shutil
11
+ import tempfile
12
+ from collections.abc import Mapping, Sequence
13
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from time import perf_counter
17
+
18
+ import numpy as np
19
+
20
+ from .._progress import finish_progress, start_progress
21
+ from ..openfoam.environment import _Toolchain, toolchain
22
+ from ..openfoam.io import (
23
+ FieldData,
24
+ OpenFOAMDecodeError,
25
+ collated_blocks,
26
+ read_field,
27
+ read_field_payload,
28
+ read_label_payload,
29
+ )
30
+ from ..reconstruction import _numeric_directories, reconstruct
31
+ from ..resources import available_memory as _available_memory
32
+ from ..resources import workers as _workers
33
+ from ..selection import TimeSelection
34
+ from ..selection import select_times as _select_times
35
+ from .derived import gradient_source, materialise_gradients, reconstruction_fields
36
+ from .thermodynamics import PerfectGasMixture, perfect_gas_mixture
37
+
38
+ _PROCESSOR = re.compile(r"processor(\d+)$")
39
+ _COLLATED = re.compile(r"processors(\d+)(?:_(\d+)-(\d+))?$")
40
+ _FIELD_COMPONENTS = {
41
+ "volScalarField": 1,
42
+ "volSphericalTensorField": 1,
43
+ "volVectorField": 3,
44
+ "volSymmTensorField": 6,
45
+ "volTensorField": 9,
46
+ }
47
+
48
+
49
+ @dataclass(frozen=True, slots=True)
50
+ class ExportedDataset:
51
+ """Summary of one dataset export."""
52
+
53
+ case_dir: Path
54
+ output_dir: Path
55
+ fields: tuple[str, ...]
56
+ times: tuple[float, ...]
57
+ dtype: str
58
+ mode: str
59
+ snapshots: int
60
+ elapsed_seconds: float
61
+
62
+ def downsample(self, **kwargs):
63
+ """Downsample this exported dataset with a declared filtering contract."""
64
+
65
+ from .downsample import downsample
66
+
67
+ return downsample(dataset_dir=self.output_dir, **kwargs)
68
+
69
+ def compute(self, **kwargs):
70
+ """Compute and persist declared fields in this dataset."""
71
+
72
+ from .compute import compute
73
+
74
+ return compute(dataset_dir=self.output_dir, **kwargs)
75
+
76
+ def postprocess(self, **kwargs):
77
+ """Materialise supported operations in this Cartesian dataset."""
78
+
79
+ from .postprocess import postprocess
80
+
81
+ return postprocess(dataset_dir=self.output_dir, **kwargs)
82
+
83
+
84
+ @dataclass(frozen=True, slots=True)
85
+ class _Source:
86
+ path: Path
87
+ first_rank: int
88
+ last_rank: int
89
+ collated: bool
90
+
91
+
92
+ @dataclass(frozen=True, slots=True)
93
+ class _TimeLayout:
94
+ name: str
95
+ sources: tuple[_Source, ...]
96
+
97
+
98
+ @dataclass(frozen=True, slots=True)
99
+ class _AddressingIndex:
100
+ """Disk-backed processor addressing shared by export workers."""
101
+
102
+ path: Path
103
+ offsets: tuple[int, ...]
104
+ global_count: int
105
+
106
+
107
+ @dataclass(frozen=True, slots=True)
108
+ class _DirectFieldTask:
109
+ """One independently executable decomposed-field export."""
110
+
111
+ sources: tuple[_Source, ...]
112
+ time_name: str
113
+ field_name: str
114
+ output_names: tuple[str, ...]
115
+ addressing: _AddressingIndex
116
+ dtype: str
117
+ data_dir: Path
118
+ snapshot_id: int
119
+ density_mixture: PerfectGasMixture | None
120
+
121
+
122
+ def _error(message: str, error_type: type[Exception] = ValueError):
123
+ raise error_type(f"[StackNordic] {message}")
124
+
125
+
126
+ def _release_file_cache(path: Path) -> None:
127
+ """Release clean file-backed pages after a staged array is complete."""
128
+
129
+ if not hasattr(os, "posix_fadvise") or not hasattr(os, "POSIX_FADV_DONTNEED"):
130
+ return
131
+ descriptor = os.open(path, os.O_RDONLY)
132
+ try:
133
+ os.posix_fadvise(descriptor, 0, 0, os.POSIX_FADV_DONTNEED)
134
+ except OSError:
135
+ pass
136
+ finally:
137
+ os.close(descriptor)
138
+
139
+
140
+ def _source_groups(case_dir: Path) -> tuple[tuple[_Source, ...], ...]:
141
+ uncollated: list[_Source] = []
142
+ collated: dict[int, list[_Source]] = {}
143
+ for path in case_dir.iterdir():
144
+ if not path.is_dir():
145
+ continue
146
+ if match := _PROCESSOR.fullmatch(path.name):
147
+ rank = int(match.group(1))
148
+ uncollated.append(_Source(path, rank, rank, False))
149
+ elif match := _COLLATED.fullmatch(path.name):
150
+ total = int(match.group(1))
151
+ first = int(match.group(2) or 0)
152
+ last = int(match.group(3) or total - 1)
153
+ collated.setdefault(total, []).append(_Source(path, first, last, True))
154
+ groups: list[tuple[_Source, ...]] = []
155
+ if uncollated:
156
+ groups.append(tuple(sorted(uncollated, key=lambda source: source.first_rank)))
157
+ groups.extend(
158
+ tuple(sorted(sources, key=lambda source: source.first_rank))
159
+ for _, sources in sorted(collated.items())
160
+ )
161
+ if not groups:
162
+ _error(f"no decomposed processor data was found in {case_dir}", FileNotFoundError)
163
+ return tuple(groups)
164
+
165
+
166
+ def _validate_sources(sources: tuple[_Source, ...]) -> None:
167
+ expected = 0
168
+ total = max(source.last_rank for source in sources) + 1
169
+ for source in sources:
170
+ if source.first_rank != expected or source.last_rank < source.first_rank:
171
+ _error("processor ranges are incomplete or overlap")
172
+ expected = source.last_rank + 1
173
+ if expected != total:
174
+ _error("processor ranges do not cover a consecutive decomposition")
175
+
176
+
177
+ def _available_layouts(case_dir: Path) -> dict[float, _TimeLayout]:
178
+ candidates: dict[float, list[_TimeLayout]] = {}
179
+ for original in _source_groups(case_dir):
180
+ per_source = {source: _numeric_directories(source.path) for source in original}
181
+ union = set().union(*(set(values) for values in per_source.values()))
182
+ for value in union:
183
+ present = tuple(source for source in original if value in per_source[source])
184
+ if not present:
185
+ continue
186
+ try:
187
+ _validate_sources(present)
188
+ except ValueError:
189
+ continue
190
+ spellings = {per_source[source][value] for source in present}
191
+ if len(spellings) != 1:
192
+ _error(f"processor data uses inconsistent names for time {value:g}")
193
+ candidates.setdefault(value, []).append(_TimeLayout(spellings.pop(), present))
194
+ layouts: dict[float, _TimeLayout] = {}
195
+ for value, options in candidates.items():
196
+ if len(options) > 1:
197
+ descriptions = ", ".join(
198
+ f"{len(option.sources)} source director{'y' if len(option.sources) == 1 else 'ies'}"
199
+ for option in options
200
+ )
201
+ _error(f"multiple complete decompositions exist at t={value:g}: {descriptions}")
202
+ layouts[value] = options[0]
203
+ if not layouts:
204
+ _error("processor data has no common physical times")
205
+ return dict(sorted(layouts.items()))
206
+
207
+
208
+ def _mesh_file(source: _Source, time_value: float, name: str) -> Path:
209
+ candidates: list[tuple[float, Path]] = []
210
+ constant = source.path / "constant/polyMesh" / name
211
+ if constant.is_file():
212
+ candidates.append((-math.inf, constant))
213
+ for value, spelling in _numeric_directories(source.path).items():
214
+ path = source.path / spelling / "polyMesh" / name
215
+ if value <= time_value and path.is_file():
216
+ candidates.append((value, path))
217
+ if not candidates:
218
+ _error(
219
+ f"{name} is unavailable for {source.path.name} at t={time_value:g}",
220
+ FileNotFoundError,
221
+ )
222
+ return max(candidates, key=lambda item: item[0])[1]
223
+
224
+
225
+ def _processor_payloads(source: _Source, path: Path):
226
+ if source.collated:
227
+ expected = set(range(source.first_rank, source.last_rank + 1))
228
+ seen: set[int] = set()
229
+ rank_offset: int | None = None
230
+ for rank, payload in collated_blocks(path):
231
+ if rank_offset is None:
232
+ if rank == source.first_rank:
233
+ rank_offset = 0
234
+ elif rank == 0:
235
+ rank_offset = source.first_rank
236
+ else:
237
+ _error(f"{path} does not start at its declared processor range")
238
+ rank += rank_offset
239
+ if rank not in expected or rank in seen:
240
+ _error(f"{path} does not contain its declared processor range")
241
+ seen.add(rank)
242
+ yield rank, payload
243
+ if seen != expected:
244
+ _error(f"{path} does not contain its declared processor range")
245
+ return
246
+ yield source.first_rank, path.read_bytes()
247
+
248
+
249
+ def _addressing(sources: tuple[_Source, ...], time_value: float) -> dict[int, np.ndarray]:
250
+ result: dict[int, np.ndarray] = {}
251
+ for source in sources:
252
+ path = _mesh_file(source, time_value, "cellProcAddressing")
253
+ for rank, payload in _processor_payloads(source, path):
254
+ result[rank] = read_label_payload(payload)
255
+ expected = set(range(max(result) + 1))
256
+ if set(result) != expected:
257
+ _error(f"cellProcAddressing is incomplete at t={time_value:g}")
258
+ return result
259
+
260
+
261
+ def _global_cell_count(addressing: Mapping[int, np.ndarray]) -> int:
262
+ arrays = tuple(addressing[rank] for rank in sorted(addressing))
263
+ if any(np.any(values < 0) for values in arrays):
264
+ _error("cellProcAddressing contains negative global cell indices")
265
+ entries = sum(values.size for values in arrays)
266
+ count = max((int(values.max()) + 1 for values in arrays if values.size), default=0)
267
+ if entries != count:
268
+ _error("cellProcAddressing does not provide one complete global-cell permutation")
269
+ seen = np.zeros(count, dtype=np.bool_)
270
+ for values in arrays:
271
+ seen[values] = True
272
+ if not np.all(seen):
273
+ _error("cellProcAddressing does not provide one complete global-cell permutation")
274
+ return count
275
+
276
+
277
+ def _addressing_key(sources: tuple[_Source, ...], time_value: float) -> tuple[str, ...]:
278
+ """Identify one mesh generation by its exact addressing files."""
279
+
280
+ return tuple(str(_mesh_file(source, time_value, "cellProcAddressing").resolve()) for source in sources)
281
+
282
+
283
+ def _store_addressing_index(
284
+ sources: tuple[_Source, ...],
285
+ time_value: float,
286
+ work_dir: Path,
287
+ index: int,
288
+ ) -> _AddressingIndex:
289
+ addressing = _addressing(sources, time_value)
290
+ global_count = _global_cell_count(addressing)
291
+ ranks = tuple(sorted(addressing))
292
+ if ranks != tuple(range(len(ranks))):
293
+ _error(f"cellProcAddressing is incomplete at t={time_value:g}")
294
+ offsets = [0]
295
+ for rank in ranks:
296
+ offsets.append(offsets[-1] + addressing[rank].size)
297
+ path = work_dir / f"addressing-{index:03d}.dat"
298
+ output = np.memmap(path, dtype=np.int64, mode="w+", shape=(offsets[-1],))
299
+ try:
300
+ for rank in ranks:
301
+ output[offsets[rank] : offsets[rank + 1]] = addressing[rank]
302
+ output.flush()
303
+ finally:
304
+ del output
305
+ for source in sources:
306
+ _release_file_cache(_mesh_file(source, time_value, "cellProcAddressing"))
307
+ return _AddressingIndex(path=path, offsets=tuple(offsets), global_count=global_count)
308
+
309
+
310
+ def _open_addressing(index: _AddressingIndex) -> tuple[dict[int, np.ndarray], np.memmap]:
311
+ storage = np.memmap(index.path, dtype=np.int64, mode="r")
312
+ addressing = {
313
+ rank: storage[index.offsets[rank] : index.offsets[rank + 1]]
314
+ for rank in range(len(index.offsets) - 1)
315
+ }
316
+ return addressing, storage
317
+
318
+
319
+ def _write_direct_field(
320
+ sources: tuple[_Source, ...],
321
+ time_name: str,
322
+ field_name: str,
323
+ output_names: tuple[str, ...],
324
+ addressing: Mapping[int, np.ndarray],
325
+ dtype: np.dtype,
326
+ data_dir: Path,
327
+ snapshot_id: int,
328
+ global_count: int,
329
+ ) -> dict[str, str]:
330
+ outputs: tuple[np.memmap, ...] | None = None
331
+ field_class: str | None = None
332
+ seen: set[int] = set()
333
+ filenames = tuple(f"{name}_id{snapshot_id:03d}.dat" for name in output_names)
334
+ try:
335
+ for source in sources:
336
+ path = source.path / time_name / field_name
337
+ if not path.is_file():
338
+ source_field = gradient_source(field_name)
339
+ if source_field is not None:
340
+ _error(
341
+ f"field {field_name!r} is missing at t={time_name}. "
342
+ f"Use mode='reconstruct' to generate grad({source_field}) with "
343
+ "OpenFOAM postProcess in an isolated workspace",
344
+ FileNotFoundError,
345
+ )
346
+ _error(
347
+ f"field {field_name!r} is missing at t={time_name} in {source.path.name}",
348
+ FileNotFoundError,
349
+ )
350
+ payloads = _processor_payloads(source, path)
351
+ for rank, payload in payloads:
352
+ data = read_field_payload(payload, cell_count=addressing[rank].size)
353
+ _validate_components(field_name, output_names, data)
354
+ if field_class is None:
355
+ field_class = data.field_class
356
+ outputs = tuple(
357
+ np.memmap(data_dir / filename, dtype=dtype, mode="w+", shape=(global_count,))
358
+ for filename in filenames
359
+ )
360
+ elif data.field_class != field_class:
361
+ _error("processor field classes are inconsistent")
362
+ values = np.asarray(data.values)
363
+ if values.shape[0] != addressing[rank].size:
364
+ _error(f"processor{rank} field length does not match cellProcAddressing")
365
+ columns = (values,) if values.ndim == 1 else tuple(
366
+ values[:, index] for index in range(values.shape[1])
367
+ )
368
+ assert outputs is not None
369
+ for output, column in zip(outputs, columns, strict=True):
370
+ output[addressing[rank]] = column
371
+ seen.add(rank)
372
+ _release_file_cache(path)
373
+ if seen != set(addressing):
374
+ _error(f"field {field_name!r} has incomplete processor coverage at t={time_name}")
375
+ assert outputs is not None
376
+ for output in outputs:
377
+ output.flush()
378
+ finally:
379
+ if outputs is not None:
380
+ del outputs
381
+ for filename in filenames:
382
+ path = data_dir / filename
383
+ if path.is_file():
384
+ _release_file_cache(path)
385
+ return {name: f"./data/{filename}" for name, filename in zip(output_names, filenames, strict=True)}
386
+
387
+
388
+ def _write_direct_density(
389
+ sources: tuple[_Source, ...],
390
+ time_name: str,
391
+ output_name: str,
392
+ addressing: Mapping[int, np.ndarray],
393
+ dtype: np.dtype,
394
+ data_dir: Path,
395
+ snapshot_id: int,
396
+ global_count: int,
397
+ mixture: PerfectGasMixture,
398
+ ) -> dict[str, str]:
399
+ filename = f"{output_name}_id{snapshot_id:03d}.dat"
400
+ output = np.memmap(data_dir / filename, dtype=dtype, mode="w+", shape=(global_count,))
401
+ try:
402
+ seen: set[int] = set()
403
+ field_names = ("p", "T", *mixture.species)
404
+ for source in sources:
405
+ paths = tuple(source.path / time_name / name for name in field_names)
406
+ missing = next((path for path in paths if not path.is_file()), None)
407
+ if missing is not None:
408
+ _error(
409
+ f"field {missing.name!r} required to derive rho is missing at t={time_name}",
410
+ FileNotFoundError,
411
+ )
412
+ streams = tuple(_processor_payloads(source, path) for path in paths)
413
+ for blocks in zip(*streams, strict=True):
414
+ ranks = {rank for rank, _ in blocks}
415
+ if len(ranks) != 1:
416
+ _error(f"thermodynamic processor blocks are misaligned at t={time_name}")
417
+ rank = blocks[0][0]
418
+ fields = {
419
+ name: np.asarray(
420
+ read_field_payload(payload, cell_count=addressing[rank].size).values
421
+ )
422
+ for name, (_, payload) in zip(field_names, blocks, strict=True)
423
+ }
424
+ output[addressing[rank]] = mixture.density(
425
+ lambda name, fields=fields: fields[name]
426
+ )
427
+ seen.add(rank)
428
+ for path in paths:
429
+ _release_file_cache(path)
430
+ if seen != set(addressing):
431
+ _error(f"fields required to derive rho have incomplete coverage at t={time_name}")
432
+ output.flush()
433
+ finally:
434
+ del output
435
+ if (data_dir / filename).is_file():
436
+ _release_file_cache(data_dir / filename)
437
+ print(f"[StackNordic] Derived rho at t={time_name} from perfectGas thermodynamics.")
438
+ return {output_name: f"./data/{filename}"}
439
+
440
+
441
+ def _run_direct_field_task(task: _DirectFieldTask) -> tuple[int, dict[str, str]]:
442
+ """Execute one field export in a worker process."""
443
+
444
+ addressing, storage = _open_addressing(task.addressing)
445
+ try:
446
+ missing = any(
447
+ not (source.path / task.time_name / task.field_name).is_file()
448
+ for source in task.sources
449
+ )
450
+ if task.field_name == "rho" and missing and task.density_mixture is not None:
451
+ if len(task.output_names) != 1:
452
+ _error("field 'rho' requires one output name")
453
+ filenames = _write_direct_density(
454
+ task.sources,
455
+ task.time_name,
456
+ task.output_names[0],
457
+ addressing,
458
+ np.dtype(task.dtype),
459
+ task.data_dir,
460
+ task.snapshot_id,
461
+ task.addressing.global_count,
462
+ task.density_mixture,
463
+ )
464
+ else:
465
+ filenames = _write_direct_field(
466
+ task.sources,
467
+ task.time_name,
468
+ task.field_name,
469
+ task.output_names,
470
+ addressing,
471
+ np.dtype(task.dtype),
472
+ task.data_dir,
473
+ task.snapshot_id,
474
+ task.addressing.global_count,
475
+ )
476
+ return task.snapshot_id, filenames
477
+ finally:
478
+ del addressing
479
+ del storage
480
+
481
+
482
+ def _normalise_fields(
483
+ fields: Mapping[str, str | Sequence[str]],
484
+ ) -> tuple[tuple[str, tuple[str, ...]], ...]:
485
+ if not isinstance(fields, Mapping) or not fields:
486
+ _error("fields must be a non-empty mapping")
487
+ result: list[tuple[str, tuple[str, ...]]] = []
488
+ outputs: set[str] = set()
489
+ for field, names in fields.items():
490
+ if not field or Path(field).name != field:
491
+ _error("each input field must be one non-empty path component")
492
+ selected = (names,) if isinstance(names, str) else tuple(names)
493
+ if not selected or any(not name or Path(name).name != name for name in selected):
494
+ _error(f"output names for field {field!r} must be non-empty filenames")
495
+ duplicate = outputs.intersection(selected)
496
+ if duplicate:
497
+ _error(f"output name {min(duplicate)!r} is used more than once")
498
+ outputs.update(selected)
499
+ result.append((field, selected))
500
+ return tuple(result)
501
+
502
+
503
+ def _validate_components(field: str, output_names: tuple[str, ...], data: FieldData) -> None:
504
+ expected = _FIELD_COMPONENTS.get(data.field_class)
505
+ if expected is None:
506
+ _error(f"field {field!r} uses unsupported OpenFOAM class {data.field_class!r}")
507
+ if len(output_names) != expected:
508
+ noun = "name" if expected == 1 else "component names"
509
+ _error(
510
+ f"field {field!r} is {data.field_class} and requires {expected} output {noun}; "
511
+ f"received {len(output_names)}"
512
+ )
513
+
514
+
515
+ def _cartesian_grid(case_dir: Path, cell_count: int, dtype: np.dtype) -> dict[str, np.ndarray] | None:
516
+ path = case_dir / "system/blockMeshDict"
517
+ if not path.is_file():
518
+ return None
519
+ payload = re.sub(r"/\*.*?\*/|//[^\n]*", " ", path.read_text(errors="replace"), flags=re.DOTALL)
520
+ scalars = {
521
+ name: float(value)
522
+ for name, value in re.findall(
523
+ r"(?m)^\s*([A-Za-z_]\w*)\s+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)\s*;",
524
+ payload,
525
+ )
526
+ }
527
+ scale = scalars.get("scale", scalars.get("convertToMeters", 1.0))
528
+ blocks = re.findall(
529
+ r"hex\s*\(([^)]*)\)\s*\(\s*\$?(\w+)\s+\$?(\w+)\s+\$?(\w+)\s*\)"
530
+ r"\s*simpleGrading\s*\(([^)]*)\)",
531
+ payload,
532
+ )
533
+ if len(blocks) != 1:
534
+ return None
535
+ vertices_text, *dimension_tokens, grading_text = blocks[0]
536
+ try:
537
+ dimensions = tuple(
538
+ int(scalars.get(token, token)) for token in dimension_tokens
539
+ )
540
+ grading = tuple(
541
+ float(scalars.get(token.lstrip("$"), token.lstrip("$")))
542
+ for token in grading_text.split()
543
+ )
544
+ vertex_indices = tuple(int(token) for token in vertices_text.split())
545
+ except ValueError:
546
+ return None
547
+ if len(grading) != 3 or any(not math.isclose(value, 1.0) for value in grading):
548
+ return None
549
+ if len(vertex_indices) != 8:
550
+ return None
551
+ if math.prod(dimensions) != cell_count:
552
+ return None
553
+ names = (("xMin", "xMax"), ("yMin", "yMax"), ("zMin", "zMax"))
554
+ bounds: tuple[tuple[float, float], ...] | None = None
555
+ if all(item in scalars for pair in names for item in pair):
556
+ bounds = tuple(
557
+ (scalars[lower] * scale, scalars[upper] * scale)
558
+ for lower, upper in names
559
+ )
560
+ else:
561
+ section = re.search(r"vertices\s*\((.*?)\)\s*;", payload, flags=re.DOTALL)
562
+ if section is None:
563
+ return None
564
+ vertices: list[tuple[float, float, float]] = []
565
+ for entry in re.findall(r"\(([^()]*)\)", section.group(1)):
566
+ tokens = entry.split()
567
+ if len(tokens) != 3:
568
+ return None
569
+ try:
570
+ vertices.append(
571
+ tuple(
572
+ float(scalars.get(token.lstrip("$"), token.lstrip("$")))
573
+ * scale
574
+ for token in tokens
575
+ )
576
+ )
577
+ except ValueError:
578
+ return None
579
+ if max(vertex_indices, default=-1) >= len(vertices):
580
+ return None
581
+ selected = tuple(vertices[index] for index in vertex_indices)
582
+ coordinates = tuple(tuple(sorted({point[axis] for point in selected})) for axis in range(3))
583
+ if any(len(values) != 2 for values in coordinates):
584
+ return None
585
+ corners = {
586
+ (x, y, z)
587
+ for x in coordinates[0]
588
+ for y in coordinates[1]
589
+ for z in coordinates[2]
590
+ }
591
+ if set(selected) != corners:
592
+ return None
593
+ bounds = tuple((values[0], values[1]) for values in coordinates)
594
+ result: dict[str, np.ndarray] = {}
595
+ for axis, size, (lower, upper) in zip("XYZ", dimensions, bounds, strict=True):
596
+ spacing = (upper - lower) / size
597
+ result[axis] = (lower + (np.arange(size) + 0.5) * spacing).astype(dtype)
598
+ return result
599
+
600
+
601
+ def _write_snapshot(
602
+ case_dir: Path,
603
+ sources: tuple[_Source, ...],
604
+ time_value: float,
605
+ time_name: str,
606
+ fields: tuple[tuple[str, tuple[str, ...]], ...],
607
+ dtype: np.dtype,
608
+ data_dir: Path,
609
+ snapshot_id: int,
610
+ density_mixture: PerfectGasMixture | None,
611
+ ) -> tuple[dict[str, object], int]:
612
+ addressing = _addressing(sources, time_value)
613
+ global_count = _global_cell_count(addressing)
614
+ local: dict[str, object] = {"id": snapshot_id, "time [s]": time_value}
615
+ for field_name, output_names in fields:
616
+ missing = any(not (source.path / time_name / field_name).is_file() for source in sources)
617
+ if field_name == "rho" and missing and density_mixture is not None:
618
+ if len(output_names) != 1:
619
+ _error("field 'rho' requires one output name")
620
+ filenames = _write_direct_density(
621
+ sources,
622
+ time_name,
623
+ output_names[0],
624
+ addressing,
625
+ dtype,
626
+ data_dir,
627
+ snapshot_id,
628
+ global_count,
629
+ density_mixture,
630
+ )
631
+ else:
632
+ filenames = _write_direct_field(
633
+ sources,
634
+ time_name,
635
+ field_name,
636
+ output_names,
637
+ addressing,
638
+ dtype,
639
+ data_dir,
640
+ snapshot_id,
641
+ global_count,
642
+ )
643
+ for output_name, filename in filenames.items():
644
+ local[f"{output_name} filename"] = filename
645
+ local["cells"] = global_count
646
+ return local, global_count
647
+
648
+
649
+ def _write_reconstructed_snapshot(
650
+ case_dir: Path,
651
+ time_value: float,
652
+ time_name: str,
653
+ fields: tuple[tuple[str, tuple[str, ...]], ...],
654
+ dtype: np.dtype,
655
+ data_dir: Path,
656
+ snapshot_id: int,
657
+ ) -> tuple[dict[str, object], int]:
658
+ local: dict[str, object] = {"id": snapshot_id, "time [s]": time_value}
659
+ global_count: int | None = None
660
+ decoded: list[tuple[tuple[str, ...], FieldData]] = []
661
+ for field_name, output_names in fields:
662
+ path = case_dir / time_name / field_name
663
+ if not path.is_file():
664
+ _error(f"field {field_name!r} is missing at t={time_name}", FileNotFoundError)
665
+ data = read_field(path, cell_count=global_count)
666
+ if data.values.ndim == 0:
667
+ if global_count is None:
668
+ _error(
669
+ f"uniform field {field_name!r} cannot establish the global cell count; "
670
+ "place a nonuniform field first"
671
+ )
672
+ data = read_field(path, cell_count=global_count)
673
+ _validate_components(field_name, output_names, data)
674
+ count = data.values.shape[0]
675
+ global_count = count if global_count is None else global_count
676
+ if count != global_count:
677
+ _error(f"field {field_name!r} has an inconsistent global cell count")
678
+ decoded.append((output_names, data))
679
+ assert global_count is not None
680
+ for output_names, data in decoded:
681
+ values = np.asarray(data.values, dtype=dtype)
682
+ columns = (values,) if values.ndim == 1 else tuple(
683
+ values[:, index] for index in range(values.shape[1])
684
+ )
685
+ for output_name, column in zip(output_names, columns, strict=True):
686
+ filename = f"{output_name}_id{snapshot_id:03d}.dat"
687
+ np.asarray(column, dtype=dtype).tofile(data_dir / filename)
688
+ local[f"{output_name} filename"] = f"./data/{filename}"
689
+ local["cells"] = global_count
690
+ return local, global_count
691
+
692
+
693
+ def _mesh_varies(sources: tuple[_Source, ...], selected_times: tuple[float, ...]) -> bool:
694
+ for source in sources:
695
+ names = _numeric_directories(source.path)
696
+ for value in selected_times:
697
+ spelling = names.get(value)
698
+ if spelling is not None and (source.path / spelling / "polyMesh").is_dir():
699
+ return True
700
+ return False
701
+
702
+
703
+ def _estimated_worker_bytes(
704
+ available: Mapping[float, _TimeLayout],
705
+ selected_times: tuple[float, ...],
706
+ fields: tuple[tuple[str, tuple[str, ...]], ...],
707
+ density_mixture: PerfectGasMixture | None,
708
+ ) -> int:
709
+ largest = 0
710
+ for value in selected_times:
711
+ time_name = available[value]
712
+ sources = time_name.sources
713
+ addressing_bytes = sum(
714
+ _mesh_file(source, value, "cellProcAddressing").stat().st_size
715
+ for source in sources
716
+ )
717
+ sizes: list[int] = []
718
+ for field, _ in fields:
719
+ paths = tuple(source.path / time_name.name / field for source in sources)
720
+ missing = next((path for path in paths if not path.is_file()), None)
721
+ if missing is not None:
722
+ if field == "rho" and density_mixture is not None:
723
+ dependencies = ("p", "T", *density_mixture.species)
724
+ by_field = tuple(
725
+ tuple(source.path / time_name.name / dependency for source in sources)
726
+ for dependency in dependencies
727
+ )
728
+ dependency_paths = tuple(path for paths in by_field for path in paths)
729
+ absent = next((path for path in dependency_paths if not path.is_file()), None)
730
+ if absent is not None:
731
+ _error(
732
+ f"field {absent.name!r} required to derive rho is missing "
733
+ f"at t={time_name.name}",
734
+ FileNotFoundError,
735
+ )
736
+ sizes.append(max(sum(path.stat().st_size for path in paths) for paths in by_field))
737
+ continue
738
+ source_field = gradient_source(field)
739
+ if source_field is not None:
740
+ _error(
741
+ f"field {field!r} is missing at t={time_name.name}. "
742
+ f"Use mode='reconstruct' to generate grad({source_field}) with "
743
+ "OpenFOAM postProcess in an isolated workspace",
744
+ FileNotFoundError,
745
+ )
746
+ _error(f"field {field!r} is missing at t={time_name.name}", FileNotFoundError)
747
+ sizes.append(sum(path.stat().st_size for path in paths))
748
+ field_bytes = max(sizes)
749
+ largest = max(largest, addressing_bytes + field_bytes)
750
+ return max(1, math.ceil(largest * 1.5))
751
+
752
+
753
+ def _export_workers(
754
+ n_jobs: int | None,
755
+ work_count: int,
756
+ estimated_worker_bytes: int | None,
757
+ ) -> int:
758
+ workers = _workers(n_jobs, work_count)
759
+ if n_jobs != -1 or estimated_worker_bytes is None:
760
+ return workers
761
+ available = _available_memory()
762
+ if available is None:
763
+ return workers
764
+ memory_workers = max(1, int(available * 0.75) // estimated_worker_bytes)
765
+ selected = min(workers, memory_workers)
766
+ if selected < workers:
767
+ print(
768
+ f"[StackNordic] Dataset workers: n_jobs=-1 resolved to {selected} "
769
+ "from the available memory and selected fields."
770
+ )
771
+ return selected
772
+
773
+
774
+ def export(
775
+ *,
776
+ case_dir: str | Path,
777
+ output_dir: str | Path,
778
+ fields: Mapping[str, str | Sequence[str]],
779
+ times: TimeSelection = None,
780
+ dtype: str = "float32",
781
+ mode: str = "direct",
782
+ metadata: Mapping[str, object] | None = None,
783
+ n_jobs: int | None = None,
784
+ progress: bool = False,
785
+ overwrite: bool = False,
786
+ _toolchain_override: _Toolchain | None = None,
787
+ ) -> ExportedDataset:
788
+ """Export selected OpenFOAM fields without assuming a fixed decomposition."""
789
+
790
+ started = perf_counter()
791
+ source_case = Path(case_dir).expanduser().resolve()
792
+ destination = Path(output_dir).expanduser().resolve()
793
+ if mode not in {"direct", "reconstruct"}:
794
+ _error("mode must be 'direct' or 'reconstruct'")
795
+ if dtype not in {"float32", "float64"}:
796
+ _error("dtype must be 'float32' or 'float64'")
797
+ if not isinstance(progress, bool) or not isinstance(overwrite, bool):
798
+ raise TypeError("progress and overwrite must be booleans")
799
+ selected_fields = _normalise_fields(fields)
800
+ if destination.exists():
801
+ if not destination.is_dir():
802
+ _error(f"output path is not a directory: {destination}", FileExistsError)
803
+ if any(destination.iterdir()) and not overwrite:
804
+ _error(f"output directory is not empty: {destination}", FileExistsError)
805
+ destination.parent.mkdir(parents=True, exist_ok=True)
806
+ stage = Path(tempfile.mkdtemp(prefix=".stacknordic-export-", dir=destination.parent))
807
+ reconstructed_stage: Path | None = None
808
+ try:
809
+ export_case = source_case
810
+ layouts: dict[float, _TimeLayout] | None = None
811
+ if mode == "reconstruct":
812
+ reconstructed_stage = Path(
813
+ tempfile.mkdtemp(prefix=".stacknordic-reconstructed-", dir=destination.parent)
814
+ )
815
+ reconstruct(
816
+ case_dir=source_case,
817
+ output_dir=reconstructed_stage,
818
+ times=times,
819
+ fields=reconstruction_fields(name for name, _ in selected_fields),
820
+ n_jobs=n_jobs,
821
+ progress=progress,
822
+ _toolchain_override=_toolchain_override,
823
+ )
824
+ export_case = reconstructed_stage
825
+ available = _numeric_directories(export_case)
826
+ selected_for_derivation = _select_times(tuple(available), times)
827
+ materialise_gradients(
828
+ export_case,
829
+ source_case,
830
+ tuple((value, available[value]) for value in selected_for_derivation),
831
+ (name for name, _ in selected_fields),
832
+ _toolchain_override or toolchain(),
833
+ )
834
+ else:
835
+ root_times = _numeric_directories(export_case)
836
+ try:
837
+ layouts = _available_layouts(export_case)
838
+ except FileNotFoundError:
839
+ layouts = {}
840
+ available = dict(layouts)
841
+ available.update(root_times)
842
+ if not available:
843
+ _error("no exportable physical times were found")
844
+ selected_times = _select_times(tuple(available), times)
845
+ density_mixture = perfect_gas_mixture(source_case)
846
+ reconstructed_times = {
847
+ value
848
+ for value in selected_times
849
+ if value in root_times
850
+ and all((export_case / root_times[value] / name).is_file() for name, _ in selected_fields)
851
+ } if mode == "direct" else set(selected_times)
852
+ estimated_worker_bytes = (
853
+ _estimated_worker_bytes(layouts, selected_times, selected_fields, density_mixture)
854
+ if layouts is not None and not reconstructed_times
855
+ else None
856
+ )
857
+ data_dir = stage / "data"
858
+ grid_dir = stage / "grid"
859
+ data_dir.mkdir()
860
+ local: list[dict[str, object] | None] = [None] * len(selected_times)
861
+ cell_counts: list[int | None] = [None] * len(selected_times)
862
+ if mode == "direct" and not reconstructed_times:
863
+ assert layouts is not None
864
+ work_dir = stage / ".work"
865
+ work_dir.mkdir()
866
+ addressing_cache: dict[tuple[str, ...], _AddressingIndex] = {}
867
+ tasks: list[_DirectFieldTask] = []
868
+ derived_tasks: list[_DirectFieldTask] = []
869
+ for snapshot_id, value in enumerate(selected_times):
870
+ layout = layouts[value]
871
+ key = _addressing_key(layout.sources, value)
872
+ addressing = addressing_cache.get(key)
873
+ if addressing is None:
874
+ if progress:
875
+ print(
876
+ f"[StackNordic] Indexing mesh addressing at t={value:g} "
877
+ f"from {len(layout.sources)} source director"
878
+ f"{'y' if len(layout.sources) == 1 else 'ies'}."
879
+ )
880
+ addressing = _store_addressing_index(
881
+ layout.sources,
882
+ value,
883
+ work_dir,
884
+ len(addressing_cache),
885
+ )
886
+ addressing_cache[key] = addressing
887
+ local[snapshot_id] = {"id": snapshot_id, "time [s]": value}
888
+ cell_counts[snapshot_id] = addressing.global_count
889
+ for field_name, output_names in selected_fields:
890
+ field_task = _DirectFieldTask(
891
+ sources=layout.sources,
892
+ time_name=layout.name,
893
+ field_name=field_name,
894
+ output_names=output_names,
895
+ addressing=addressing,
896
+ dtype=dtype,
897
+ data_dir=data_dir,
898
+ snapshot_id=snapshot_id,
899
+ density_mixture=density_mixture,
900
+ )
901
+ missing = any(
902
+ not (source.path / layout.name / field_name).is_file()
903
+ for source in layout.sources
904
+ )
905
+ target = derived_tasks if field_name == "rho" and missing else tasks
906
+ target.append(field_task)
907
+ tasks.extend(derived_tasks)
908
+ workers = _export_workers(n_jobs, len(tasks), estimated_worker_bytes)
909
+ if progress:
910
+ print(
911
+ f"[StackNordic] Dataset workers: {workers} for {len(tasks)} "
912
+ "time-field tasks."
913
+ )
914
+ reporter = start_progress(len(tasks), "StackNordic export") if progress else None
915
+ try:
916
+ if workers == 1:
917
+ results = map(_run_direct_field_task, tasks)
918
+ for snapshot_id, filenames in results:
919
+ assert local[snapshot_id] is not None
920
+ local[snapshot_id].update(filenames)
921
+ if reporter is not None:
922
+ reporter.update()
923
+ else:
924
+ with ProcessPoolExecutor(
925
+ max_workers=workers,
926
+ mp_context=multiprocessing.get_context("fork"),
927
+ ) as executor:
928
+ futures = tuple(executor.submit(_run_direct_field_task, task) for task in tasks)
929
+ for future in as_completed(futures):
930
+ snapshot_id, filenames = future.result()
931
+ assert local[snapshot_id] is not None
932
+ local[snapshot_id].update(filenames)
933
+ if reporter is not None:
934
+ reporter.update()
935
+ finally:
936
+ if reporter is not None:
937
+ finish_progress(reporter)
938
+ shutil.rmtree(work_dir, ignore_errors=True)
939
+ else:
940
+ workers = _export_workers(n_jobs, len(selected_times), estimated_worker_bytes)
941
+ reporter = (
942
+ start_progress(len(selected_times), "StackNordic export")
943
+ if progress
944
+ else None
945
+ )
946
+
947
+ def task(index: int, value: float):
948
+ if value in reconstructed_times:
949
+ result = _write_reconstructed_snapshot(
950
+ export_case,
951
+ value,
952
+ root_times[value] if mode == "direct" else available[value],
953
+ selected_fields,
954
+ np.dtype(dtype),
955
+ data_dir,
956
+ index,
957
+ )
958
+ else:
959
+ if layouts is None or value not in layouts:
960
+ _error(
961
+ f"selected fields are incomplete in the reconstructed case and "
962
+ f"no complete decomposition exists at t={value:g}",
963
+ FileNotFoundError,
964
+ )
965
+ layout = layouts[value]
966
+ result = _write_snapshot(
967
+ export_case,
968
+ layout.sources,
969
+ value,
970
+ layout.name,
971
+ selected_fields,
972
+ np.dtype(dtype),
973
+ data_dir,
974
+ index,
975
+ density_mixture,
976
+ )
977
+ return index, result
978
+
979
+ try:
980
+ if workers == 1:
981
+ results = (task(index, value) for index, value in enumerate(selected_times))
982
+ for index, (record, count) in results:
983
+ local[index], cell_counts[index] = record, count
984
+ if reporter is not None:
985
+ reporter.update()
986
+ else:
987
+ with ThreadPoolExecutor(max_workers=workers) as executor:
988
+ futures = {
989
+ executor.submit(task, index, value): index
990
+ for index, value in enumerate(selected_times)
991
+ }
992
+ for future in as_completed(futures):
993
+ index, (record, count) = future.result()
994
+ local[index], cell_counts[index] = record, count
995
+ if reporter is not None:
996
+ reporter.update()
997
+ finally:
998
+ if reporter is not None:
999
+ finish_progress(reporter)
1000
+ counts = {count for count in cell_counts if count is not None}
1001
+ grid: dict[str, np.ndarray] | None = None
1002
+ root_mesh_varies = any(
1003
+ value in reconstructed_times
1004
+ and (
1005
+ export_case
1006
+ / (root_times[value] if mode == "direct" else available[value])
1007
+ / "polyMesh"
1008
+ ).is_dir()
1009
+ for value in selected_times
1010
+ )
1011
+ decomposed_mesh_varies = layouts is not None and any(
1012
+ value in layouts
1013
+ and value not in reconstructed_times
1014
+ and _mesh_varies(layouts[value].sources, (value,))
1015
+ for value in selected_times
1016
+ )
1017
+ mesh_varies = root_mesh_varies or decomposed_mesh_varies
1018
+ if len(counts) == 1 and not mesh_varies:
1019
+ grid = _cartesian_grid(source_case, next(iter(counts)), np.dtype(dtype))
1020
+ grid_entries: dict[str, str] = {}
1021
+ if grid is not None:
1022
+ grid_dir.mkdir()
1023
+ for axis, values in grid.items():
1024
+ filename = f"{axis}_m.dat"
1025
+ values.tofile(grid_dir / filename)
1026
+ grid_entries[axis.lower()] = f"./grid/{filename}"
1027
+ variables = [name for _, names in selected_fields for name in names]
1028
+ info = {
1029
+ "global": {
1030
+ "snapshots": len(selected_times),
1031
+ "variables": variables,
1032
+ "dtype": dtype,
1033
+ "layout": "cartesian" if grid is not None else "cells",
1034
+ "grid": grid_entries or None,
1035
+ "fields": {field: list(names) for field, names in selected_fields},
1036
+ "metadata": dict(metadata or {}),
1037
+ },
1038
+ "local": local,
1039
+ }
1040
+ if grid is not None:
1041
+ info["global"]["Nxyz"] = [len(grid[axis]) for axis in "XYZ"]
1042
+ (stage / "info.json").write_text(
1043
+ json.dumps(info, indent=4, ensure_ascii=False) + "\n", encoding="utf-8"
1044
+ )
1045
+ if destination.exists():
1046
+ shutil.rmtree(destination)
1047
+ stage.replace(destination)
1048
+ except OpenFOAMDecodeError as error:
1049
+ shutil.rmtree(stage, ignore_errors=True)
1050
+ raise ValueError(f"[StackNordic] {error}") from error
1051
+ except BaseException:
1052
+ shutil.rmtree(stage, ignore_errors=True)
1053
+ raise
1054
+ finally:
1055
+ if reconstructed_stage is not None:
1056
+ shutil.rmtree(reconstructed_stage, ignore_errors=True)
1057
+ return ExportedDataset(
1058
+ case_dir=source_case,
1059
+ output_dir=destination,
1060
+ fields=tuple(name for name, _ in selected_fields),
1061
+ times=selected_times,
1062
+ dtype=dtype,
1063
+ mode=mode,
1064
+ snapshots=len(selected_times),
1065
+ elapsed_seconds=perf_counter() - started,
1066
+ )
1067
+
1068
+
1069
+ def __dir__() -> list[str]:
1070
+ return ["ExportedDataset", "export"]