sorbflow 0.3.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.
- sorbflow/__init__.py +41 -0
- sorbflow/__main__.py +5 -0
- sorbflow/_arrays.py +40 -0
- sorbflow/_version.py +3 -0
- sorbflow/adapters/__init__.py +1 -0
- sorbflow/calibration/__init__.py +5 -0
- sorbflow/calibration/batch_objective.py +118 -0
- sorbflow/calibration/least_squares.py +207 -0
- sorbflow/calibration/measurements.py +49 -0
- sorbflow/calibration/profile.py +327 -0
- sorbflow/cli.py +64 -0
- sorbflow/design/__init__.py +6 -0
- sorbflow/design/cad.py +65 -0
- sorbflow/design/hydraulics.py +99 -0
- sorbflow/equilibrium/__init__.py +17 -0
- sorbflow/equilibrium/isotherms.py +117 -0
- sorbflow/fit.py +7 -0
- sorbflow/io/__init__.py +7 -0
- sorbflow/io/experimental.py +159 -0
- sorbflow/io/parquet.py +79 -0
- sorbflow/io/results.py +50 -0
- sorbflow/kinetics/__init__.py +5 -0
- sorbflow/kinetics/sphere.py +112 -0
- sorbflow/observation.py +174 -0
- sorbflow/optimization/__init__.py +5 -0
- sorbflow/optimization/nsga2.py +161 -0
- sorbflow/optimize.py +5 -0
- sorbflow/py.typed +0 -0
- sorbflow/reactors/__init__.py +6 -0
- sorbflow/reactors/_ldf_jacobian.py +58 -0
- sorbflow/reactors/batch.py +87 -0
- sorbflow/reactors/column.py +151 -0
- sorbflow/reactors/hsdm.py +167 -0
- sorbflow/schemas.py +496 -0
- sorbflow/simulate.py +6 -0
- sorbflow/solvers/__init__.py +7 -0
- sorbflow/solvers/integration.py +152 -0
- sorbflow/solvers/options.py +74 -0
- sorbflow/solvers/results.py +318 -0
- sorbflow/uncertainty/__init__.py +5 -0
- sorbflow/uncertainty/monte_carlo.py +129 -0
- sorbflow/units.py +53 -0
- sorbflow/validate/__init__.py +35 -0
- sorbflow/web/__init__.py +5 -0
- sorbflow/web/__main__.py +6 -0
- sorbflow/web/app.py +278 -0
- sorbflow/web/config.py +213 -0
- sorbflow/web/server.py +302 -0
- sorbflow/web/ui.py +50 -0
- sorbflow-0.3.0.dist-info/METADATA +121 -0
- sorbflow-0.3.0.dist-info/RECORD +56 -0
- sorbflow-0.3.0.dist-info/WHEEL +5 -0
- sorbflow-0.3.0.dist-info/entry_points.txt +2 -0
- sorbflow-0.3.0.dist-info/licenses/LICENSE +202 -0
- sorbflow-0.3.0.dist-info/licenses/NOTICE +12 -0
- sorbflow-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Independent, vectorized mass-based equilibrium in SI units."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import ArrayLike
|
|
10
|
+
from scipy.special import expit
|
|
11
|
+
|
|
12
|
+
from .._arrays import FloatArray, nonnegative_array
|
|
13
|
+
from ..schemas import Freundlich, Langmuir, Linear
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Isotherm(Protocol):
|
|
17
|
+
"""Extensible concentration -> loading contract at a fixed calibration T.
|
|
18
|
+
|
|
19
|
+
Concentration: kg solute/m3 liquid. Loading: kg solute/kg dry adsorbent.
|
|
20
|
+
Derivative: m3/kg dry adsorbent. Output preserves the input shape.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def loading(self, concentration_kg_m3: ArrayLike) -> FloatArray: ...
|
|
24
|
+
|
|
25
|
+
def derivative(self, concentration_kg_m3: ArrayLike) -> FloatArray: ...
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _checked(value: ArrayLike) -> FloatArray:
|
|
29
|
+
result = np.asarray(value, dtype=np.float64)
|
|
30
|
+
if not np.all(np.isfinite(result)):
|
|
31
|
+
raise ValueError("Isotherm result exceeds finite floating-point range")
|
|
32
|
+
return result
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class LangmuirIsotherm:
|
|
37
|
+
"""Saturating equilibrium, evaluated in log form to avoid b*c overflow."""
|
|
38
|
+
|
|
39
|
+
parameters: Langmuir
|
|
40
|
+
|
|
41
|
+
def loading(self, concentration_kg_m3: ArrayLike) -> FloatArray:
|
|
42
|
+
c = nonnegative_array(concentration_kg_m3, "concentration_kg_m3")
|
|
43
|
+
with np.errstate(divide="ignore"):
|
|
44
|
+
log_bc = np.log(self.parameters.affinity_m3_kg) + np.log(c)
|
|
45
|
+
return _checked(self.parameters.qmax_kg_kg * expit(log_bc))
|
|
46
|
+
|
|
47
|
+
def derivative(self, concentration_kg_m3: ArrayLike) -> FloatArray:
|
|
48
|
+
c = nonnegative_array(concentration_kg_m3, "concentration_kg_m3")
|
|
49
|
+
p = self.parameters
|
|
50
|
+
with np.errstate(divide="ignore", over="ignore"):
|
|
51
|
+
log_bc = np.log(p.affinity_m3_kg) + np.log(c)
|
|
52
|
+
value = np.exp(
|
|
53
|
+
np.log(p.qmax_kg_kg) + np.log(p.affinity_m3_kg) - 2 * np.logaddexp(0, log_bc)
|
|
54
|
+
)
|
|
55
|
+
return _checked(value)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True, slots=True)
|
|
59
|
+
class FreundlichIsotherm:
|
|
60
|
+
"""Normalized power law. A singular derivative at zero is an explicit error."""
|
|
61
|
+
|
|
62
|
+
parameters: Freundlich
|
|
63
|
+
|
|
64
|
+
def loading(self, concentration_kg_m3: ArrayLike) -> FloatArray:
|
|
65
|
+
c = nonnegative_array(concentration_kg_m3, "concentration_kg_m3")
|
|
66
|
+
p = self.parameters
|
|
67
|
+
with np.errstate(divide="ignore", over="ignore", under="ignore"):
|
|
68
|
+
value = np.exp(np.log(p.q_ref_kg_kg) + p.exponent * (np.log(c) - np.log(p.c_ref_kg_m3)))
|
|
69
|
+
return _checked(value)
|
|
70
|
+
|
|
71
|
+
def derivative(self, concentration_kg_m3: ArrayLike) -> FloatArray:
|
|
72
|
+
c = nonnegative_array(concentration_kg_m3, "concentration_kg_m3")
|
|
73
|
+
p = self.parameters
|
|
74
|
+
if p.exponent < 1 and np.any(c == 0):
|
|
75
|
+
raise ValueError("Freundlich derivative is singular at zero when exponent < 1")
|
|
76
|
+
if p.exponent == 1:
|
|
77
|
+
return _checked(np.full_like(c, p.q_ref_kg_kg / p.c_ref_kg_m3))
|
|
78
|
+
with np.errstate(divide="ignore", over="ignore", under="ignore"):
|
|
79
|
+
value = np.exp(
|
|
80
|
+
np.log(p.exponent)
|
|
81
|
+
+ np.log(p.q_ref_kg_kg)
|
|
82
|
+
- np.log(p.c_ref_kg_m3)
|
|
83
|
+
+ (p.exponent - 1) * (np.log(c) - np.log(p.c_ref_kg_m3))
|
|
84
|
+
)
|
|
85
|
+
return _checked(value)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True, slots=True)
|
|
89
|
+
class LinearIsotherm:
|
|
90
|
+
"""Henry-type mass-based equilibrium, also providing an exact tracer limit."""
|
|
91
|
+
|
|
92
|
+
parameters: Linear
|
|
93
|
+
|
|
94
|
+
def loading(self, concentration_kg_m3: ArrayLike) -> FloatArray:
|
|
95
|
+
c = nonnegative_array(concentration_kg_m3, "concentration_kg_m3")
|
|
96
|
+
with np.errstate(over="ignore"):
|
|
97
|
+
return _checked(self.parameters.distribution_m3_kg * c)
|
|
98
|
+
|
|
99
|
+
def derivative(self, concentration_kg_m3: ArrayLike) -> FloatArray:
|
|
100
|
+
c = nonnegative_array(concentration_kg_m3, "concentration_kg_m3")
|
|
101
|
+
return np.full_like(c, self.parameters.distribution_m3_kg)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def isotherm_from_parameters(parameters: Langmuir | Freundlich | Linear) -> Isotherm:
|
|
105
|
+
"""Resolve explicit parameter types; no contaminant or material is hardcoded."""
|
|
106
|
+
if isinstance(parameters, Langmuir):
|
|
107
|
+
return LangmuirIsotherm(parameters)
|
|
108
|
+
if isinstance(parameters, Freundlich):
|
|
109
|
+
return FreundlichIsotherm(parameters)
|
|
110
|
+
if isinstance(parameters, Linear):
|
|
111
|
+
return LinearIsotherm(parameters)
|
|
112
|
+
raise ValueError("Unsupported equilibrium parameter type")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def trial_loading(model: Isotherm, concentration: FloatArray) -> FloatArray:
|
|
116
|
+
"""Odd extension for implicit trial states only; physical outputs are checked."""
|
|
117
|
+
return np.asarray(np.sign(concentration) * model.loading(np.abs(concentration)))
|
sorbflow/fit.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Inverse-workflow facade, with local diagnostics and explicit physical units."""
|
|
2
|
+
|
|
3
|
+
from .calibration.least_squares import FitError, FitResult
|
|
4
|
+
from .calibration.least_squares import fit_batch_rate as batch_rate
|
|
5
|
+
from .calibration.least_squares import fit_isotherm as isotherm
|
|
6
|
+
|
|
7
|
+
__all__ = ["FitError", "FitResult", "batch_rate", "isotherm"]
|
sorbflow/io/__init__.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Explicit, read-only CSV import for one experimental breakthrough series."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import hashlib
|
|
7
|
+
import io
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ..schemas import Observations
|
|
11
|
+
from ..units import quantity, to_si
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _column_name(value: str, name: str) -> None:
|
|
15
|
+
if not isinstance(value, str) or not value.strip():
|
|
16
|
+
raise ValueError(f"{name} must be an explicit nonempty column name")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _number(
|
|
20
|
+
value: str,
|
|
21
|
+
*,
|
|
22
|
+
row: int,
|
|
23
|
+
column: str,
|
|
24
|
+
unit: str,
|
|
25
|
+
target: str,
|
|
26
|
+
positive: bool = False,
|
|
27
|
+
) -> float:
|
|
28
|
+
try:
|
|
29
|
+
result = to_si(quantity(float(value), unit), target)
|
|
30
|
+
if result < 0 or (positive and result == 0):
|
|
31
|
+
raise ValueError("value must be positive" if positive else "value must be nonnegative")
|
|
32
|
+
return result
|
|
33
|
+
except ValueError as exc:
|
|
34
|
+
raise ValueError(f"CSV row {row}, column {column!r}: {exc}") from exc
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _check_records(text: str, delimiter: str, width: int) -> None:
|
|
38
|
+
"""Detect blank records that DictReader would otherwise silently skip."""
|
|
39
|
+
scanner = csv.reader(io.StringIO(text, newline=""), delimiter=delimiter, strict=True)
|
|
40
|
+
try:
|
|
41
|
+
for record in scanner:
|
|
42
|
+
if not record:
|
|
43
|
+
raise ValueError(f"CSV row {scanner.line_num}: blank records are not supported")
|
|
44
|
+
if len(record) != width:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"CSV row {scanner.line_num}: expected {width} fields, found {len(record)}"
|
|
47
|
+
)
|
|
48
|
+
except csv.Error as exc:
|
|
49
|
+
raise ValueError(f"CSV row {scanner.line_num}: malformed CSV: {exc}") from exc
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_breakthrough_csv(
|
|
53
|
+
path: str | Path,
|
|
54
|
+
*,
|
|
55
|
+
experiment_id: str,
|
|
56
|
+
species_name: str,
|
|
57
|
+
time_column: str,
|
|
58
|
+
concentration_column: str,
|
|
59
|
+
time_unit: str,
|
|
60
|
+
concentration_unit: str,
|
|
61
|
+
std_column: str | None = None,
|
|
62
|
+
std_unit: str | None = None,
|
|
63
|
+
delimiter: str = ",",
|
|
64
|
+
) -> Observations:
|
|
65
|
+
"""Read one explicitly mapped UTF-8 CSV without mutating or cleaning its source.
|
|
66
|
+
|
|
67
|
+
Time is converted to seconds; concentration and optional measurement standard
|
|
68
|
+
deviation become kg solute/m3 liquid. Units, identities and column mappings are
|
|
69
|
+
mandatory. Molar concentration, ppm and censored values are not inferred.
|
|
70
|
+
Standard-deviation column and unit must be supplied together.
|
|
71
|
+
|
|
72
|
+
Source SHA-256 covers the exact original bytes, including any UTF-8 BOM. Times
|
|
73
|
+
must already strictly increase. Blank/malformed records, duplicate headers,
|
|
74
|
+
nonfinite numbers and invalid physical values fail rather than being removed,
|
|
75
|
+
sorted, imputed or averaged. Additional metadata columns are ignored in the
|
|
76
|
+
returned Observations and remain untouched in the source file.
|
|
77
|
+
"""
|
|
78
|
+
if not isinstance(delimiter, str) or len(delimiter) != 1 or delimiter in "\r\n\0":
|
|
79
|
+
raise ValueError("delimiter must be one non-newline, non-NUL character")
|
|
80
|
+
_column_name(time_column, "time_column")
|
|
81
|
+
_column_name(concentration_column, "concentration_column")
|
|
82
|
+
if (std_column is None) != (std_unit is None):
|
|
83
|
+
raise ValueError("std_column and std_unit must be supplied together")
|
|
84
|
+
required = [time_column, concentration_column]
|
|
85
|
+
if std_column is not None:
|
|
86
|
+
_column_name(std_column, "std_column")
|
|
87
|
+
required.append(std_column)
|
|
88
|
+
if len(set(required)) != len(required):
|
|
89
|
+
raise ValueError("Mapped measurement columns must be distinct")
|
|
90
|
+
for name, unit, target in (
|
|
91
|
+
("time_unit", time_unit, "s"),
|
|
92
|
+
("concentration_unit", concentration_unit, "kg/m^3"),
|
|
93
|
+
):
|
|
94
|
+
try:
|
|
95
|
+
to_si(quantity(1, unit), target)
|
|
96
|
+
except ValueError as exc:
|
|
97
|
+
raise ValueError(f"Invalid {name}: {exc}") from exc
|
|
98
|
+
if std_unit is not None:
|
|
99
|
+
try:
|
|
100
|
+
to_si(quantity(1, std_unit), "kg/m^3")
|
|
101
|
+
except ValueError as exc:
|
|
102
|
+
raise ValueError(f"Invalid std_unit: {exc}") from exc
|
|
103
|
+
|
|
104
|
+
source = Path(path).read_bytes()
|
|
105
|
+
try:
|
|
106
|
+
text = source.decode("utf-8-sig")
|
|
107
|
+
except UnicodeDecodeError as exc:
|
|
108
|
+
raise ValueError("Experimental CSV must use UTF-8 encoding") from exc
|
|
109
|
+
reader = csv.DictReader(io.StringIO(text, newline=""), delimiter=delimiter, strict=True)
|
|
110
|
+
try:
|
|
111
|
+
headers = reader.fieldnames
|
|
112
|
+
except csv.Error as exc:
|
|
113
|
+
raise ValueError(f"CSV header: malformed CSV: {exc}") from exc
|
|
114
|
+
if not headers or any(not header.strip() for header in headers):
|
|
115
|
+
raise ValueError("CSV requires nonempty named headers")
|
|
116
|
+
if len(set(headers)) != len(headers):
|
|
117
|
+
raise ValueError("CSV header names must be unique")
|
|
118
|
+
missing = set(required) - set(headers)
|
|
119
|
+
if missing:
|
|
120
|
+
raise ValueError(f"CSV is missing required columns: {sorted(missing)}")
|
|
121
|
+
_check_records(text, delimiter, len(headers))
|
|
122
|
+
|
|
123
|
+
times: list[float] = []
|
|
124
|
+
concentrations: list[float] = []
|
|
125
|
+
deviations: list[float] = []
|
|
126
|
+
for record in reader:
|
|
127
|
+
row = reader.line_num
|
|
128
|
+
time = _number(record[time_column], row=row, column=time_column, unit=time_unit, target="s")
|
|
129
|
+
if times and time <= times[-1]:
|
|
130
|
+
raise ValueError(f"CSV row {row}, column {time_column!r}: times must strictly increase")
|
|
131
|
+
times.append(time)
|
|
132
|
+
concentrations.append(
|
|
133
|
+
_number(
|
|
134
|
+
record[concentration_column],
|
|
135
|
+
row=row,
|
|
136
|
+
column=concentration_column,
|
|
137
|
+
unit=concentration_unit,
|
|
138
|
+
target="kg/m^3",
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
if std_column is not None and std_unit is not None:
|
|
142
|
+
deviations.append(
|
|
143
|
+
_number(
|
|
144
|
+
record[std_column],
|
|
145
|
+
row=row,
|
|
146
|
+
column=std_column,
|
|
147
|
+
unit=std_unit,
|
|
148
|
+
target="kg/m^3",
|
|
149
|
+
positive=True,
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
return Observations(
|
|
153
|
+
experiment_id=experiment_id,
|
|
154
|
+
species_name=species_name,
|
|
155
|
+
time_s=tuple(times),
|
|
156
|
+
concentration_kg_m3=tuple(concentrations),
|
|
157
|
+
source_sha256=hashlib.sha256(source).hexdigest(),
|
|
158
|
+
std_kg_m3=tuple(deviations) if std_column is not None else None,
|
|
159
|
+
)
|
sorbflow/io/parquet.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Optional Parquet export of outlet series and global mass-balance evidence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict
|
|
7
|
+
from importlib import import_module
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .._arrays import real_array
|
|
11
|
+
from ..solvers import SimulationResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def export_parquet(result: SimulationResult, destination: str | Path) -> Path:
|
|
15
|
+
"""Write a time-series Parquet file with units and reproducibility metadata.
|
|
16
|
+
|
|
17
|
+
Requires the optional ``parquet`` extra. This table contains the outlet (or
|
|
18
|
+
mixed batch liquid) and global mass balance, not full axial/radial profiles.
|
|
19
|
+
Use ``export_result`` for the complete JSON fields. All numeric columns are
|
|
20
|
+
float64 in SI; per-field metadata identifies units. File metadata records the
|
|
21
|
+
configuration, solver settings, diagnostics, run manifest and numerical hash.
|
|
22
|
+
|
|
23
|
+
Existing files are never overwritten, including under a creation race. If an
|
|
24
|
+
I/O failure occurs during writing, a partial new file may remain for inspection.
|
|
25
|
+
"""
|
|
26
|
+
if not isinstance(result, SimulationResult):
|
|
27
|
+
raise ValueError("result must be a SimulationResult")
|
|
28
|
+
target = Path(destination)
|
|
29
|
+
if target.exists():
|
|
30
|
+
raise FileExistsError(f"Output file already exists: {target}")
|
|
31
|
+
try:
|
|
32
|
+
arrow = import_module("pyarrow")
|
|
33
|
+
parquet = import_module("pyarrow.parquet")
|
|
34
|
+
except ImportError as exc:
|
|
35
|
+
raise ImportError("Install sorbflow[parquet] to export Parquet") from exc
|
|
36
|
+
|
|
37
|
+
columns = {
|
|
38
|
+
"time_s": (result.time_s, "s"),
|
|
39
|
+
"outlet_concentration_kg_m3": (result.outlet_concentration_kg_m3, "kg/m^3"),
|
|
40
|
+
"inventory_kg": (result.inventory_kg, "kg"),
|
|
41
|
+
"inlet_mass_kg": (result.inlet_mass_kg, "kg"),
|
|
42
|
+
"outlet_mass_kg": (result.outlet_mass_kg, "kg"),
|
|
43
|
+
"mass_residual_kg": (result.mass_residual_kg, "kg"),
|
|
44
|
+
}
|
|
45
|
+
fields = []
|
|
46
|
+
arrays = []
|
|
47
|
+
for name, (values, unit) in columns.items():
|
|
48
|
+
numeric = real_array(values, name)
|
|
49
|
+
if numeric.ndim != 1 or numeric.shape != result.time_s.shape:
|
|
50
|
+
raise ValueError(f"{name} must be a vector matching time_s")
|
|
51
|
+
fields.append(
|
|
52
|
+
arrow.field(
|
|
53
|
+
name,
|
|
54
|
+
arrow.float64(),
|
|
55
|
+
nullable=False,
|
|
56
|
+
metadata={b"unit": unit.encode("ascii")},
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
arrays.append(arrow.array(numeric, type=arrow.float64(), from_pandas=False))
|
|
60
|
+
|
|
61
|
+
metadata = {
|
|
62
|
+
b"sorbflow.export_schema_version": b"1",
|
|
63
|
+
b"sorbflow.export_scope": b"outlet_timeseries_and_global_mass_balance",
|
|
64
|
+
b"sorbflow.reactor": result.reactor.encode("ascii"),
|
|
65
|
+
b"sorbflow.result_kind": b"numerical_simulation",
|
|
66
|
+
b"sorbflow.config_json": result.config_json.encode("utf-8"),
|
|
67
|
+
b"sorbflow.solver_options_json": result.options_json.encode("utf-8"),
|
|
68
|
+
b"sorbflow.numerical_sha256": result.numerical_sha256.encode("ascii"),
|
|
69
|
+
b"sorbflow.manifest_json": result.manifest.to_json().encode("utf-8"),
|
|
70
|
+
b"sorbflow.diagnostics_json": json.dumps(
|
|
71
|
+
asdict(result.diagnostics), sort_keys=True, allow_nan=False
|
|
72
|
+
).encode("utf-8"),
|
|
73
|
+
}
|
|
74
|
+
schema = arrow.schema(fields, metadata=metadata)
|
|
75
|
+
table = arrow.Table.from_arrays(arrays, schema=schema)
|
|
76
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
with target.open("xb") as stream:
|
|
78
|
+
parquet.write_table(table, stream, compression="snappy", version="2.6", store_schema=True)
|
|
79
|
+
return target
|
sorbflow/io/results.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Portable result export without silently overwriting a previous simulation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ..solvers import SimulationResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def export_result(result: SimulationResult, destination: str | Path) -> Path:
|
|
14
|
+
"""Write full JSON, outlet CSV and file hashes to a new directory.
|
|
15
|
+
|
|
16
|
+
Existing directories are rejected, including empty ones, to preserve run identity.
|
|
17
|
+
CSV includes SI units in column names; JSON contains all axial fields and inputs.
|
|
18
|
+
"""
|
|
19
|
+
path = Path(destination)
|
|
20
|
+
path.mkdir(parents=True, exist_ok=False)
|
|
21
|
+
(path / "result.json").write_text(result.to_json(), encoding="utf-8")
|
|
22
|
+
with (path / "timeseries.csv").open("w", newline="", encoding="utf-8") as stream:
|
|
23
|
+
writer = csv.writer(stream)
|
|
24
|
+
writer.writerow(
|
|
25
|
+
[
|
|
26
|
+
"time_s",
|
|
27
|
+
"outlet_concentration_kg_m3",
|
|
28
|
+
"inventory_kg",
|
|
29
|
+
"inlet_mass_kg",
|
|
30
|
+
"outlet_mass_kg",
|
|
31
|
+
"mass_residual_kg",
|
|
32
|
+
]
|
|
33
|
+
)
|
|
34
|
+
writer.writerows(
|
|
35
|
+
zip(
|
|
36
|
+
result.time_s,
|
|
37
|
+
result.outlet_concentration_kg_m3,
|
|
38
|
+
result.inventory_kg,
|
|
39
|
+
result.inlet_mass_kg,
|
|
40
|
+
result.outlet_mass_kg,
|
|
41
|
+
result.mass_residual_kg,
|
|
42
|
+
strict=True,
|
|
43
|
+
)
|
|
44
|
+
)
|
|
45
|
+
hashes = {
|
|
46
|
+
name: hashlib.sha256((path / name).read_bytes()).hexdigest()
|
|
47
|
+
for name in ("result.json", "timeseries.csv")
|
|
48
|
+
}
|
|
49
|
+
(path / "files.sha256.json").write_text(json.dumps(hashes, indent=2), encoding="utf-8")
|
|
50
|
+
return path
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Conservative spherical FV surface diffusion and nonlinear film coupling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from .._arrays import FloatArray
|
|
10
|
+
from ..equilibrium import Isotherm
|
|
11
|
+
from ..equilibrium.isotherms import trial_loading
|
|
12
|
+
from ..solvers.integration import SimulationError
|
|
13
|
+
from ..units import finite_scalar
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class SphereGrid:
|
|
18
|
+
"""Uniform radial faces; exact shell volumes per unit solid angle."""
|
|
19
|
+
|
|
20
|
+
radius_m: float
|
|
21
|
+
cells: int
|
|
22
|
+
|
|
23
|
+
def __post_init__(self) -> None:
|
|
24
|
+
if finite_scalar(self.radius_m, "radius_m") <= 0:
|
|
25
|
+
raise ValueError("radius_m must be positive")
|
|
26
|
+
if type(self.cells) is not int or self.cells < 2:
|
|
27
|
+
raise ValueError("cells must be an integer >=2")
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def centers_m(self) -> FloatArray:
|
|
31
|
+
return np.asarray(
|
|
32
|
+
(np.arange(self.cells, dtype=np.float64) + 0.5) * self.radius_m / self.cells
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def faces_m(self) -> FloatArray:
|
|
37
|
+
return np.linspace(0, self.radius_m, self.cells + 1)
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def shell_volumes_m3(self) -> FloatArray:
|
|
41
|
+
return np.diff(self.faces_m**3) / 3
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def mean_weights(self) -> FloatArray:
|
|
45
|
+
volumes = self.shell_volumes_m3
|
|
46
|
+
return volumes / np.sum(volumes)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def diffusion_rhs(
|
|
50
|
+
loading: FloatArray,
|
|
51
|
+
surface_mass_flux: FloatArray,
|
|
52
|
+
*,
|
|
53
|
+
grid: SphereGrid,
|
|
54
|
+
diffusivity_m2_s: float,
|
|
55
|
+
particle_density_kg_m3: float,
|
|
56
|
+
) -> FloatArray:
|
|
57
|
+
"""q shape (axial cell, radial shell); boundary flux is positive inward."""
|
|
58
|
+
flux = np.zeros((loading.shape[0], grid.cells + 1))
|
|
59
|
+
flux[:, 1:-1] = (
|
|
60
|
+
grid.faces_m[1:-1] ** 2
|
|
61
|
+
* diffusivity_m2_s
|
|
62
|
+
* np.diff(loading, axis=1)
|
|
63
|
+
/ (grid.radius_m / grid.cells)
|
|
64
|
+
)
|
|
65
|
+
flux[:, -1] = grid.radius_m**2 * surface_mass_flux / particle_density_kg_m3
|
|
66
|
+
return np.asarray(np.diff(flux, axis=1) / grid.shell_volumes_m3)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def film_flux(
|
|
70
|
+
bulk: FloatArray,
|
|
71
|
+
outer_loading: FloatArray,
|
|
72
|
+
model: Isotherm,
|
|
73
|
+
*,
|
|
74
|
+
grid: SphereGrid,
|
|
75
|
+
diffusivity_m2_s: float,
|
|
76
|
+
particle_density_kg_m3: float,
|
|
77
|
+
film_coefficient_m_s: float,
|
|
78
|
+
) -> FloatArray:
|
|
79
|
+
"""Solve the implicit monotone surface concentration; no inverse isotherm needed.
|
|
80
|
+
|
|
81
|
+
Odd continuation is used exclusively for implicit solver trial states. The same
|
|
82
|
+
returned flux is used in both phases, including desorption.
|
|
83
|
+
"""
|
|
84
|
+
conductance = particle_density_kg_m3 * diffusivity_m2_s / (grid.radius_m / (2 * grid.cells))
|
|
85
|
+
target = film_coefficient_m_s * bulk + conductance * outer_loading
|
|
86
|
+
sign = np.sign(target)
|
|
87
|
+
absolute = np.abs(target)
|
|
88
|
+
low = np.zeros_like(bulk)
|
|
89
|
+
high = absolute / film_coefficient_m_s
|
|
90
|
+
bound = 512 * np.finfo(float).eps * np.maximum(absolute, np.finfo(float).tiny)
|
|
91
|
+
for _ in range(256):
|
|
92
|
+
mid = (low + high) / 2
|
|
93
|
+
estimate = film_coefficient_m_s * mid + conductance * model.loading(mid)
|
|
94
|
+
converged = np.abs(estimate - absolute) <= bound
|
|
95
|
+
if np.all(converged):
|
|
96
|
+
low, high = mid, mid
|
|
97
|
+
break
|
|
98
|
+
low = np.where(converged | (estimate < absolute), mid, low)
|
|
99
|
+
high = np.where(converged | (estimate >= absolute), mid, high)
|
|
100
|
+
surface = sign * (low + high) / 2
|
|
101
|
+
residual = film_coefficient_m_s * surface + conductance * trial_loading(model, surface) - target
|
|
102
|
+
if not np.all(np.isfinite(surface)) or np.any(np.abs(residual) > bound):
|
|
103
|
+
raise SimulationError("Film/surface equilibrium root did not converge")
|
|
104
|
+
surface_loading = trial_loading(model, surface)
|
|
105
|
+
film_side = film_coefficient_m_s * (bulk - surface)
|
|
106
|
+
solid_side = conductance * (surface_loading - outer_loading)
|
|
107
|
+
# Choose the expression with the smaller absolute cancellation/error scale.
|
|
108
|
+
# A shared but poorly conditioned film-side flux can conserve mass while being
|
|
109
|
+
# physically inaccurate when the film resistance tends to zero.
|
|
110
|
+
film_scale = film_coefficient_m_s * (np.abs(bulk) + np.abs(surface))
|
|
111
|
+
solid_scale = conductance * (np.abs(surface_loading) + np.abs(outer_loading))
|
|
112
|
+
return np.asarray(np.where(film_scale <= solid_scale, film_side, solid_side))
|