stacknordic 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stacknordic/__init__.py +47 -0
- stacknordic/__main__.py +5 -0
- stacknordic/_progress.py +21 -0
- stacknordic/cli.py +122 -0
- stacknordic/computing.py +348 -0
- stacknordic/dataset/__init__.py +39 -0
- stacknordic/dataset/_contract.py +136 -0
- stacknordic/dataset/_manifest.py +16 -0
- stacknordic/dataset/compute.py +294 -0
- stacknordic/dataset/derived.py +89 -0
- stacknordic/dataset/downsample.py +790 -0
- stacknordic/dataset/export.py +1070 -0
- stacknordic/dataset/package.py +415 -0
- stacknordic/dataset/postprocess.py +354 -0
- stacknordic/dataset/thermodynamics.py +112 -0
- stacknordic/filtering.py +160 -0
- stacknordic/openfoam/__init__.py +9 -0
- stacknordic/openfoam/case.py +189 -0
- stacknordic/openfoam/environment.py +48 -0
- stacknordic/openfoam/io.py +252 -0
- stacknordic/openfoam/postprocess.py +208 -0
- stacknordic/openfoam/write.py +295 -0
- stacknordic/postprocess.py +109 -0
- stacknordic/reconstruction.py +561 -0
- stacknordic/resources.py +88 -0
- stacknordic/selection.py +52 -0
- stacknordic-0.1.0.dist-info/METADATA +103 -0
- stacknordic-0.1.0.dist-info/RECORD +31 -0
- stacknordic-0.1.0.dist-info/WHEEL +4 -0
- stacknordic-0.1.0.dist-info/entry_points.txt +2 -0
- stacknordic-0.1.0.dist-info/licenses/LICENSE +674 -0
stacknordic/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""OpenFOAM reconstruction and post-processing."""
|
|
2
|
+
|
|
3
|
+
from . import openfoam
|
|
4
|
+
from .computing import Computing, ProgressComputation, ReactionRateComputation
|
|
5
|
+
from .dataset import (
|
|
6
|
+
CompiledDataset,
|
|
7
|
+
ComputedDataset,
|
|
8
|
+
Dataset,
|
|
9
|
+
DownsampledDataset,
|
|
10
|
+
ExportedDataset,
|
|
11
|
+
PackagedDataset,
|
|
12
|
+
PostprocessedDataset,
|
|
13
|
+
)
|
|
14
|
+
from .filtering import Filtering
|
|
15
|
+
from .openfoam.postprocess import PostprocessedCase
|
|
16
|
+
from .openfoam.write import ComputedFields
|
|
17
|
+
from .postprocess import Postprocess, PostprocessOperation
|
|
18
|
+
from .reconstruction import Reconstruction, reconstruct
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
OpenFOAM = openfoam
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"CompiledDataset",
|
|
26
|
+
"ComputedDataset",
|
|
27
|
+
"ComputedFields",
|
|
28
|
+
"Computing",
|
|
29
|
+
"Dataset",
|
|
30
|
+
"DownsampledDataset",
|
|
31
|
+
"ExportedDataset",
|
|
32
|
+
"Filtering",
|
|
33
|
+
"OpenFOAM",
|
|
34
|
+
"PackagedDataset",
|
|
35
|
+
"Postprocess",
|
|
36
|
+
"PostprocessOperation",
|
|
37
|
+
"PostprocessedCase",
|
|
38
|
+
"PostprocessedDataset",
|
|
39
|
+
"ProgressComputation",
|
|
40
|
+
"ReactionRateComputation",
|
|
41
|
+
"Reconstruction",
|
|
42
|
+
"reconstruct",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def __dir__() -> list[str]:
|
|
47
|
+
return sorted(__all__)
|
stacknordic/__main__.py
ADDED
stacknordic/_progress.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Shared progress-display lifecycle."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import onsaemiro as osm
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def start_progress(total: int, description: str):
|
|
9
|
+
"""Create and immediately render a progress display."""
|
|
10
|
+
|
|
11
|
+
progress_type = getattr(osm, "Progress", None) or osm.ProgressBar
|
|
12
|
+
reporter = progress_type(total=total, desc=description)
|
|
13
|
+
reporter.update(0)
|
|
14
|
+
return reporter
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def finish_progress(reporter) -> None:
|
|
18
|
+
"""Preserve the final display across supported Onsaemiro versions."""
|
|
19
|
+
|
|
20
|
+
finish = getattr(reporter, "finish", None)
|
|
21
|
+
finish() if finish is not None else reporter.close()
|
stacknordic/cli.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Command-line interface for StackNordic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .reconstruction import Reconstruction, reconstruct
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _parser() -> argparse.ArgumentParser:
|
|
15
|
+
parser = argparse.ArgumentParser(
|
|
16
|
+
prog="stacknordic",
|
|
17
|
+
description="Prepare stored OpenFOAM results.",
|
|
18
|
+
)
|
|
19
|
+
parser.add_argument(
|
|
20
|
+
"--version",
|
|
21
|
+
action="version",
|
|
22
|
+
version=f"%(prog)s {__version__}",
|
|
23
|
+
)
|
|
24
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
25
|
+
reconstruction = commands.add_parser(
|
|
26
|
+
"reconstruct",
|
|
27
|
+
help="reconstruct decomposed OpenFOAM times",
|
|
28
|
+
)
|
|
29
|
+
reconstruction.add_argument(
|
|
30
|
+
"--case-dir",
|
|
31
|
+
type=Path,
|
|
32
|
+
default=Path.cwd(),
|
|
33
|
+
help="OpenFOAM case directory (default: current directory)",
|
|
34
|
+
)
|
|
35
|
+
reconstruction.add_argument(
|
|
36
|
+
"--output-dir",
|
|
37
|
+
type=Path,
|
|
38
|
+
default=None,
|
|
39
|
+
help="destination directory (default: case directory)",
|
|
40
|
+
)
|
|
41
|
+
times = reconstruction.add_mutually_exclusive_group()
|
|
42
|
+
times.add_argument(
|
|
43
|
+
"--time",
|
|
44
|
+
type=float,
|
|
45
|
+
action="append",
|
|
46
|
+
dest="selected_times",
|
|
47
|
+
metavar="VALUE",
|
|
48
|
+
help="exact physical time; repeat for multiple times",
|
|
49
|
+
)
|
|
50
|
+
times.add_argument(
|
|
51
|
+
"--time-range",
|
|
52
|
+
type=float,
|
|
53
|
+
nargs=2,
|
|
54
|
+
metavar=("START", "END"),
|
|
55
|
+
help="inclusive physical-time range",
|
|
56
|
+
)
|
|
57
|
+
reconstruction.add_argument(
|
|
58
|
+
"--fields",
|
|
59
|
+
nargs="+",
|
|
60
|
+
default=None,
|
|
61
|
+
metavar="FIELD",
|
|
62
|
+
help="fields to reconstruct (default: all fields)",
|
|
63
|
+
)
|
|
64
|
+
reconstruction.add_argument(
|
|
65
|
+
"--n-jobs",
|
|
66
|
+
type=int,
|
|
67
|
+
default=None,
|
|
68
|
+
help="concurrent physical times; -1 uses all available CPUs",
|
|
69
|
+
)
|
|
70
|
+
reconstruction.add_argument(
|
|
71
|
+
"--progress",
|
|
72
|
+
action="store_true",
|
|
73
|
+
help="show reconstruction progress",
|
|
74
|
+
)
|
|
75
|
+
return parser
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _times(arguments: argparse.Namespace) -> list[float] | tuple[float, float] | None:
|
|
79
|
+
if arguments.selected_times is not None:
|
|
80
|
+
return arguments.selected_times
|
|
81
|
+
if arguments.time_range is not None:
|
|
82
|
+
return tuple(arguments.time_range)
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _print_reconstruction(result: Reconstruction) -> None:
|
|
87
|
+
reconstructed = ", ".join(f"{value:g}" for value in result.reconstructed_times) or "none"
|
|
88
|
+
skipped = ", ".join(f"{value:g}" for value in result.skipped_times) or "none"
|
|
89
|
+
print(f"[StackNordic] Output: {result.output_dir}")
|
|
90
|
+
print(f"[StackNordic] Reconstructed times: {reconstructed}")
|
|
91
|
+
print(f"[StackNordic] Existing times: {skipped}")
|
|
92
|
+
print(f"[StackNordic] Workers: {result.n_jobs}")
|
|
93
|
+
print(f"[StackNordic] Elapsed time: {result.elapsed_seconds:.3f} s")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
97
|
+
"""Run the StackNordic command-line interface."""
|
|
98
|
+
|
|
99
|
+
selected = list(sys.argv[1:] if argv is None else argv)
|
|
100
|
+
if selected and selected[0] == "-reconstructPar":
|
|
101
|
+
selected[0] = "reconstruct"
|
|
102
|
+
arguments = _parser().parse_args(selected)
|
|
103
|
+
try:
|
|
104
|
+
if arguments.command == "reconstruct":
|
|
105
|
+
result = reconstruct(
|
|
106
|
+
case_dir=arguments.case_dir,
|
|
107
|
+
output_dir=arguments.output_dir,
|
|
108
|
+
times=_times(arguments),
|
|
109
|
+
fields=arguments.fields,
|
|
110
|
+
n_jobs=arguments.n_jobs,
|
|
111
|
+
progress=arguments.progress,
|
|
112
|
+
)
|
|
113
|
+
_print_reconstruction(result)
|
|
114
|
+
return 0
|
|
115
|
+
except (FileNotFoundError, NotADirectoryError, ValueError, RuntimeError) as error:
|
|
116
|
+
print(f"[StackNordic] Error: {error}", file=sys.stderr)
|
|
117
|
+
return 1
|
|
118
|
+
raise RuntimeError(f"unsupported command: {arguments.command}")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
raise SystemExit(main())
|
stacknordic/computing.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""Explicit field computations applied before spatial reduction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from types import MappingProxyType
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _cantera():
|
|
14
|
+
try:
|
|
15
|
+
import cantera as ct
|
|
16
|
+
except ImportError as error:
|
|
17
|
+
raise ImportError("[StackNordic] This computation requires Cantera.") from error
|
|
18
|
+
return ct
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _composition(
|
|
22
|
+
values: Mapping[str, float],
|
|
23
|
+
name: str,
|
|
24
|
+
*,
|
|
25
|
+
allow_negative: bool = False,
|
|
26
|
+
) -> Mapping[str, float]:
|
|
27
|
+
result = MappingProxyType({str(key): float(value) for key, value in values.items()})
|
|
28
|
+
if not result:
|
|
29
|
+
raise ValueError(f"{name} must not be empty")
|
|
30
|
+
if not allow_negative and any(value < 0.0 for value in result.values()):
|
|
31
|
+
raise ValueError(f"{name} values must be non-negative")
|
|
32
|
+
return result
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class ProgressComputation:
|
|
37
|
+
"""Normalised linear progress variable with fixed reference states."""
|
|
38
|
+
|
|
39
|
+
output: str
|
|
40
|
+
coefficients: Mapping[str, float]
|
|
41
|
+
offset: float
|
|
42
|
+
weights: Mapping[str, float]
|
|
43
|
+
mechanism: str
|
|
44
|
+
equivalence_ratio: float
|
|
45
|
+
fuel: Mapping[str, float]
|
|
46
|
+
oxidizer: Mapping[str, float]
|
|
47
|
+
temperature: float
|
|
48
|
+
pressure: float
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def inputs(self) -> tuple[str, ...]:
|
|
52
|
+
return tuple(self.coefficients)
|
|
53
|
+
|
|
54
|
+
def evaluate(self, field: Callable[[str], np.ndarray]) -> np.ndarray:
|
|
55
|
+
values: np.ndarray | None = None
|
|
56
|
+
for name, coefficient in self.coefficients.items():
|
|
57
|
+
contribution = coefficient * np.asarray(field(name), dtype=np.float64)
|
|
58
|
+
values = contribution if values is None else values + contribution
|
|
59
|
+
if values is None:
|
|
60
|
+
raise RuntimeError("progress computation has no active species")
|
|
61
|
+
return values + self.offset
|
|
62
|
+
|
|
63
|
+
def manifest(self) -> dict[str, object]:
|
|
64
|
+
return {
|
|
65
|
+
"kind": "progress",
|
|
66
|
+
"output": self.output,
|
|
67
|
+
"inputs": list(self.inputs),
|
|
68
|
+
"weights": dict(self.weights),
|
|
69
|
+
"coefficients": dict(self.coefficients),
|
|
70
|
+
"offset": self.offset,
|
|
71
|
+
"units": "1",
|
|
72
|
+
"reference": {
|
|
73
|
+
"provider": "cantera",
|
|
74
|
+
"mechanism": self.mechanism,
|
|
75
|
+
"equivalence_ratio": self.equivalence_ratio,
|
|
76
|
+
"fuel": dict(self.fuel),
|
|
77
|
+
"oxidizer": dict(self.oxidizer),
|
|
78
|
+
"temperature_K": self.temperature,
|
|
79
|
+
"pressure_Pa": self.pressure,
|
|
80
|
+
"composition_basis": "mole",
|
|
81
|
+
"burnt_state": "HP",
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True, slots=True)
|
|
87
|
+
class ReactionRateComputation:
|
|
88
|
+
"""Cantera species or progress-variable mass source term."""
|
|
89
|
+
|
|
90
|
+
output: str
|
|
91
|
+
mechanism: str
|
|
92
|
+
species_fields: Mapping[str, str]
|
|
93
|
+
temperature_field: str
|
|
94
|
+
pressure_field: str | None
|
|
95
|
+
density_field: str | None
|
|
96
|
+
target_coefficients: Mapping[str, float]
|
|
97
|
+
target: str
|
|
98
|
+
units: str
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def inputs(self) -> tuple[str, ...]:
|
|
102
|
+
names = [*self.species_fields.values(), self.temperature_field]
|
|
103
|
+
names.append(self.pressure_field or self.density_field or "")
|
|
104
|
+
return tuple(dict.fromkeys(name for name in names if name))
|
|
105
|
+
|
|
106
|
+
def evaluate(self, field: Callable[[str], np.ndarray]) -> np.ndarray:
|
|
107
|
+
source = np.asarray(field(self.temperature_field))
|
|
108
|
+
result = np.empty(source.size)
|
|
109
|
+
for start, stop, outputs in reaction_rate_chunks((self,), field):
|
|
110
|
+
result[start:stop] = outputs[self.output]
|
|
111
|
+
return result.reshape(source.shape)
|
|
112
|
+
|
|
113
|
+
def manifest(self) -> dict[str, object]:
|
|
114
|
+
return {
|
|
115
|
+
"kind": "reaction_rate",
|
|
116
|
+
"output": self.output,
|
|
117
|
+
"inputs": list(self.inputs),
|
|
118
|
+
"provider": "cantera",
|
|
119
|
+
"mechanism": self.mechanism,
|
|
120
|
+
"species_fields": dict(self.species_fields),
|
|
121
|
+
"temperature_field": self.temperature_field,
|
|
122
|
+
"pressure_field": self.pressure_field,
|
|
123
|
+
"density_field": self.density_field,
|
|
124
|
+
"target": self.target,
|
|
125
|
+
"target_coefficients": dict(self.target_coefficients),
|
|
126
|
+
"units": self.units,
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
def state_key(self) -> tuple[object, ...]:
|
|
130
|
+
"""Return the immutable state contract used for execution fusion."""
|
|
131
|
+
|
|
132
|
+
return (
|
|
133
|
+
self.mechanism,
|
|
134
|
+
tuple(self.species_fields.items()),
|
|
135
|
+
self.temperature_field,
|
|
136
|
+
self.pressure_field,
|
|
137
|
+
self.density_field,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def reaction_rate_chunks(
|
|
142
|
+
definitions: tuple[ReactionRateComputation, ...],
|
|
143
|
+
field: Callable[[str], np.ndarray],
|
|
144
|
+
*,
|
|
145
|
+
chunk_cells: int | None = None,
|
|
146
|
+
):
|
|
147
|
+
"""Yield fused reaction-rate outputs for one compatible state contract."""
|
|
148
|
+
|
|
149
|
+
if not definitions:
|
|
150
|
+
return
|
|
151
|
+
first = definitions[0]
|
|
152
|
+
if any(item.state_key() != first.state_key() for item in definitions[1:]):
|
|
153
|
+
raise ValueError("fused reaction-rate definitions must share one state contract")
|
|
154
|
+
ct = _cantera()
|
|
155
|
+
gas = ct.Solution(first.mechanism)
|
|
156
|
+
if chunk_cells is None:
|
|
157
|
+
bytes_per_cell = max((2 * gas.n_species + 8) * np.dtype(np.float64).itemsize, 1)
|
|
158
|
+
chunk_cells = max(4_096, min(262_144, (64 * 1024**2) // bytes_per_cell))
|
|
159
|
+
temperature = np.asarray(field(first.temperature_field)).reshape(-1)
|
|
160
|
+
species_values = {
|
|
161
|
+
species: np.asarray(field(name)).reshape(-1)
|
|
162
|
+
for species, name in first.species_fields.items()
|
|
163
|
+
}
|
|
164
|
+
if first.pressure_field is not None:
|
|
165
|
+
thermodynamic = np.asarray(field(first.pressure_field)).reshape(-1)
|
|
166
|
+
thermodynamic_name = "pressure"
|
|
167
|
+
else:
|
|
168
|
+
thermodynamic = np.asarray(field(first.density_field or "")).reshape(-1)
|
|
169
|
+
thermodynamic_name = "density"
|
|
170
|
+
size = temperature.size
|
|
171
|
+
if thermodynamic.size != size or any(values.size != size for values in species_values.values()):
|
|
172
|
+
raise ValueError("reaction-rate fields must share one shape")
|
|
173
|
+
indices = {name: gas.species_index(name) for name in first.species_fields}
|
|
174
|
+
molecular_weights = gas.molecular_weights
|
|
175
|
+
for start in range(0, size, chunk_cells):
|
|
176
|
+
stop = min(start + chunk_cells, size)
|
|
177
|
+
chunk_temperature = np.asarray(temperature[start:stop], dtype=np.float64)
|
|
178
|
+
chunk_thermodynamic = np.asarray(thermodynamic[start:stop], dtype=np.float64)
|
|
179
|
+
if np.any(~np.isfinite(chunk_temperature)) or np.any(chunk_temperature <= 0.0):
|
|
180
|
+
raise ValueError("reaction-rate temperature must be finite and positive")
|
|
181
|
+
if np.any(~np.isfinite(chunk_thermodynamic)) or np.any(chunk_thermodynamic <= 0.0):
|
|
182
|
+
raise ValueError(f"reaction-rate {thermodynamic_name} must be finite and positive")
|
|
183
|
+
mass_fractions = np.zeros((stop - start, gas.n_species))
|
|
184
|
+
for species, values in species_values.items():
|
|
185
|
+
mass_fractions[:, indices[species]] = np.asarray(
|
|
186
|
+
values[start:stop], dtype=np.float64
|
|
187
|
+
)
|
|
188
|
+
totals = mass_fractions.sum(axis=1)
|
|
189
|
+
if np.any(~np.isfinite(mass_fractions)) or np.any(mass_fractions < 0.0):
|
|
190
|
+
raise ValueError("reaction-rate mass fractions must be finite and non-negative")
|
|
191
|
+
if not np.allclose(totals, 1.0, rtol=1.0e-6, atol=1.0e-8):
|
|
192
|
+
raise ValueError(
|
|
193
|
+
"reaction-rate mass fractions must include a complete state summing to one"
|
|
194
|
+
)
|
|
195
|
+
states = ct.SolutionArray(gas, stop - start)
|
|
196
|
+
state = (chunk_temperature, chunk_thermodynamic, mass_fractions)
|
|
197
|
+
if first.pressure_field is not None:
|
|
198
|
+
states.TPY = state
|
|
199
|
+
else:
|
|
200
|
+
states.TDY = state
|
|
201
|
+
rates = states.net_production_rates
|
|
202
|
+
outputs: dict[str, np.ndarray] = {}
|
|
203
|
+
for definition in definitions:
|
|
204
|
+
values = np.zeros(stop - start)
|
|
205
|
+
for species, coefficient in definition.target_coefficients.items():
|
|
206
|
+
index = gas.species_index(species)
|
|
207
|
+
values += coefficient * molecular_weights[index] * rates[:, index]
|
|
208
|
+
if definition.units == "1/s":
|
|
209
|
+
values /= states.density
|
|
210
|
+
outputs[definition.output] = values
|
|
211
|
+
yield start, stop, outputs
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
Computation = ProgressComputation | ReactionRateComputation
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Computing:
|
|
218
|
+
"""Factories for explicit pre-filter field computations."""
|
|
219
|
+
|
|
220
|
+
@staticmethod
|
|
221
|
+
def progress(
|
|
222
|
+
*,
|
|
223
|
+
mechanism: str | Path,
|
|
224
|
+
equivalence_ratio: float,
|
|
225
|
+
fuel: Mapping[str, float],
|
|
226
|
+
oxidizer: Mapping[str, float],
|
|
227
|
+
species: Mapping[str, float],
|
|
228
|
+
temperature: float,
|
|
229
|
+
pressure: float,
|
|
230
|
+
output: str = "c",
|
|
231
|
+
) -> ProgressComputation:
|
|
232
|
+
"""Define a normalised linear progress variable."""
|
|
233
|
+
|
|
234
|
+
ct = _cantera()
|
|
235
|
+
mechanism_path = str(Path(mechanism).expanduser())
|
|
236
|
+
weights = _composition(species, "species", allow_negative=True)
|
|
237
|
+
if not output:
|
|
238
|
+
raise ValueError("output must be a non-empty field name")
|
|
239
|
+
if equivalence_ratio <= 0.0:
|
|
240
|
+
raise ValueError("equivalence_ratio must be positive")
|
|
241
|
+
if temperature <= 0.0 or pressure <= 0.0:
|
|
242
|
+
raise ValueError("temperature and pressure must be positive")
|
|
243
|
+
gas = ct.Solution(mechanism_path)
|
|
244
|
+
fuel_composition = _composition(fuel, "fuel")
|
|
245
|
+
oxidizer_composition = _composition(oxidizer, "oxidizer")
|
|
246
|
+
missing = set(weights).difference(gas.species_names)
|
|
247
|
+
if missing:
|
|
248
|
+
raise ValueError(f"mechanism does not contain progress species: {sorted(missing)}")
|
|
249
|
+
gas.TP = float(temperature), float(pressure)
|
|
250
|
+
gas.set_equivalence_ratio(
|
|
251
|
+
phi=float(equivalence_ratio),
|
|
252
|
+
fuel=dict(fuel_composition),
|
|
253
|
+
oxidizer=dict(oxidizer_composition),
|
|
254
|
+
basis="mole",
|
|
255
|
+
)
|
|
256
|
+
indices = np.asarray([gas.species_index(name) for name in weights])
|
|
257
|
+
alpha = np.asarray(tuple(weights.values()))
|
|
258
|
+
unburnt = float(alpha @ gas.Y[indices])
|
|
259
|
+
gas.equilibrate("HP")
|
|
260
|
+
burnt = float(alpha @ gas.Y[indices])
|
|
261
|
+
denominator = burnt - unburnt
|
|
262
|
+
tolerance = np.finfo(np.float64).eps * 64.0
|
|
263
|
+
if abs(denominator) <= tolerance:
|
|
264
|
+
raise ValueError("progress-variable reference denominator is negligible")
|
|
265
|
+
coefficients = MappingProxyType(
|
|
266
|
+
{name: float(weight / denominator) for name, weight in weights.items()}
|
|
267
|
+
)
|
|
268
|
+
return ProgressComputation(
|
|
269
|
+
output=output,
|
|
270
|
+
coefficients=coefficients,
|
|
271
|
+
offset=-unburnt / denominator,
|
|
272
|
+
weights=weights,
|
|
273
|
+
mechanism=mechanism_path,
|
|
274
|
+
equivalence_ratio=float(equivalence_ratio),
|
|
275
|
+
fuel=fuel_composition,
|
|
276
|
+
oxidizer=oxidizer_composition,
|
|
277
|
+
temperature=float(temperature),
|
|
278
|
+
pressure=float(pressure),
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
@staticmethod
|
|
282
|
+
def reaction_rate(
|
|
283
|
+
*,
|
|
284
|
+
mechanism: str | Path,
|
|
285
|
+
species: Mapping[str, str],
|
|
286
|
+
temperature: str,
|
|
287
|
+
target: str | ProgressComputation,
|
|
288
|
+
output: str,
|
|
289
|
+
pressure: str | None = None,
|
|
290
|
+
density: str | None = None,
|
|
291
|
+
units: str = "kg/m^3/s",
|
|
292
|
+
) -> ReactionRateComputation:
|
|
293
|
+
"""Define a species or progress-variable reaction rate."""
|
|
294
|
+
|
|
295
|
+
ct = _cantera()
|
|
296
|
+
mechanism_path = str(Path(mechanism).expanduser())
|
|
297
|
+
gas = ct.Solution(mechanism_path)
|
|
298
|
+
fields = MappingProxyType({str(name): str(field) for name, field in species.items()})
|
|
299
|
+
if not fields or any(not name for name in fields.values()):
|
|
300
|
+
raise ValueError("species must map mechanism names to non-empty field names")
|
|
301
|
+
missing = set(fields).difference(gas.species_names)
|
|
302
|
+
if missing:
|
|
303
|
+
raise ValueError(f"mechanism does not contain state species: {sorted(missing)}")
|
|
304
|
+
if (pressure is None) == (density is None):
|
|
305
|
+
raise ValueError("exactly one of pressure or density must be provided")
|
|
306
|
+
if not temperature or not output or (pressure == "") or (density == ""):
|
|
307
|
+
raise ValueError("temperature, thermodynamic input, and output names must be non-empty")
|
|
308
|
+
if units not in {"kg/m^3/s", "1/s"}:
|
|
309
|
+
raise ValueError("units must be 'kg/m^3/s' or '1/s'")
|
|
310
|
+
if isinstance(target, ProgressComputation):
|
|
311
|
+
target_coefficients = MappingProxyType(dict(target.coefficients))
|
|
312
|
+
target_name = target.output
|
|
313
|
+
elif isinstance(target, str) and target:
|
|
314
|
+
if target not in gas.species_names:
|
|
315
|
+
raise ValueError(f"mechanism does not contain target species: {target!r}")
|
|
316
|
+
target_coefficients = MappingProxyType({target: 1.0})
|
|
317
|
+
target_name = target
|
|
318
|
+
else:
|
|
319
|
+
raise TypeError("target must be a species name or ProgressComputation")
|
|
320
|
+
unavailable = set(target_coefficients).difference(fields)
|
|
321
|
+
missing_targets = set(target_coefficients).difference(gas.species_names)
|
|
322
|
+
if missing_targets:
|
|
323
|
+
raise ValueError(
|
|
324
|
+
f"mechanism does not contain target species: {sorted(missing_targets)}"
|
|
325
|
+
)
|
|
326
|
+
if unavailable:
|
|
327
|
+
raise ValueError(
|
|
328
|
+
"reaction-rate target species require state fields: "
|
|
329
|
+
f"{sorted(unavailable)}"
|
|
330
|
+
)
|
|
331
|
+
return ReactionRateComputation(
|
|
332
|
+
output=output,
|
|
333
|
+
mechanism=mechanism_path,
|
|
334
|
+
species_fields=fields,
|
|
335
|
+
temperature_field=temperature,
|
|
336
|
+
pressure_field=pressure,
|
|
337
|
+
density_field=density,
|
|
338
|
+
target_coefficients=target_coefficients,
|
|
339
|
+
target=target_name,
|
|
340
|
+
units=units,
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
__all__ = ["Computation", "Computing", "ProgressComputation", "ReactionRateComputation"]
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def __dir__() -> list[str]:
|
|
348
|
+
return sorted(__all__)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Dataset preparation operations."""
|
|
2
|
+
|
|
3
|
+
from .compute import ComputedDataset, compute
|
|
4
|
+
from .downsample import DownsampledDataset, downsample
|
|
5
|
+
from .export import ExportedDataset, export
|
|
6
|
+
from .package import CompiledDataset, PackagedDataset, compile, package
|
|
7
|
+
from .postprocess import PostprocessedDataset, postprocess
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Dataset:
|
|
11
|
+
"""Dataset creation and reduction operations."""
|
|
12
|
+
|
|
13
|
+
export = staticmethod(export)
|
|
14
|
+
compute = staticmethod(compute)
|
|
15
|
+
downsample = staticmethod(downsample)
|
|
16
|
+
postprocess = staticmethod(postprocess)
|
|
17
|
+
package = staticmethod(package)
|
|
18
|
+
compile = staticmethod(compile)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"CompiledDataset",
|
|
23
|
+
"ComputedDataset",
|
|
24
|
+
"Dataset",
|
|
25
|
+
"DownsampledDataset",
|
|
26
|
+
"ExportedDataset",
|
|
27
|
+
"PackagedDataset",
|
|
28
|
+
"PostprocessedDataset",
|
|
29
|
+
"compile",
|
|
30
|
+
"compute",
|
|
31
|
+
"downsample",
|
|
32
|
+
"export",
|
|
33
|
+
"package",
|
|
34
|
+
"postprocess",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def __dir__() -> list[str]:
|
|
39
|
+
return sorted(__all__)
|