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,327 @@
|
|
|
1
|
+
"""Experimental known-sigma Gaussian profiles on an explicit physical grid.
|
|
2
|
+
|
|
3
|
+
Finite multi-start searches and asymptotic cutoffs never establish global
|
|
4
|
+
identifiability. See docs/profile_likelihood.md for the observation contract.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable, Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from numpy.typing import ArrayLike
|
|
15
|
+
from scipy.optimize import least_squares
|
|
16
|
+
from scipy.stats import chi2
|
|
17
|
+
|
|
18
|
+
from .._arrays import FloatArray, real_array
|
|
19
|
+
from ..units import finite_scalar, quantity
|
|
20
|
+
|
|
21
|
+
WeightedResidual = Callable[[FloatArray], ArrayLike]
|
|
22
|
+
EdgeStatus = Literal["REJECTED", "GRID_TRUNCATED", "BOUND_LIMITED", "UNAVAILABLE"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class ProfileParameter:
|
|
27
|
+
"""Positive physical coordinate; unit metadata never converts magnitudes."""
|
|
28
|
+
|
|
29
|
+
name: str
|
|
30
|
+
unit: str
|
|
31
|
+
lower: float
|
|
32
|
+
upper: float
|
|
33
|
+
|
|
34
|
+
def __post_init__(self) -> None:
|
|
35
|
+
if not isinstance(self.name, str) or not self.name.strip():
|
|
36
|
+
raise ValueError("Parameter name must be nonempty")
|
|
37
|
+
quantity(1.0, self.unit)
|
|
38
|
+
lower = finite_scalar(self.lower, "lower")
|
|
39
|
+
upper = finite_scalar(self.upper, "upper")
|
|
40
|
+
if not 0 < lower < upper or not np.log(lower) < np.log(upper):
|
|
41
|
+
raise ValueError("Bounds must satisfy 0 < lower < upper in log coordinates")
|
|
42
|
+
object.__setattr__(self, "lower", lower)
|
|
43
|
+
object.__setattr__(self, "upper", upper)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True, slots=True)
|
|
47
|
+
class ProfileTrial:
|
|
48
|
+
"""One attempted optimization, including failed and budget-skipped starts."""
|
|
49
|
+
|
|
50
|
+
start: tuple[float, ...]
|
|
51
|
+
parameters: tuple[float, ...] | None
|
|
52
|
+
chi2: float | None
|
|
53
|
+
success: bool
|
|
54
|
+
status: str
|
|
55
|
+
message: str
|
|
56
|
+
callback_calls: int
|
|
57
|
+
bound_parameters: tuple[str, ...]
|
|
58
|
+
lowest_evaluated_chi2: float | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True, slots=True)
|
|
62
|
+
class ProfilePoint:
|
|
63
|
+
value: float
|
|
64
|
+
trials: tuple[ProfileTrial, ...]
|
|
65
|
+
parameters: tuple[float, ...] | None
|
|
66
|
+
chi2: float | None
|
|
67
|
+
delta_chi2: float | None
|
|
68
|
+
accepted: bool | None
|
|
69
|
+
bound_limited: bool
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True, slots=True)
|
|
73
|
+
class GaussianProfile:
|
|
74
|
+
"""Grid evidence only: accepted_grid is not a continuous confidence interval."""
|
|
75
|
+
|
|
76
|
+
parameters: tuple[ProfileParameter, ...]
|
|
77
|
+
parameter_name: str
|
|
78
|
+
confidence: float
|
|
79
|
+
cutoff: float
|
|
80
|
+
baseline_trials: tuple[ProfileTrial, ...]
|
|
81
|
+
baseline_parameters: tuple[float, ...] | None
|
|
82
|
+
baseline_chi2: float | None
|
|
83
|
+
points: tuple[ProfilePoint, ...]
|
|
84
|
+
accepted_grid: tuple[float, ...]
|
|
85
|
+
edge_status: tuple[EdgeStatus, EdgeStatus]
|
|
86
|
+
callback_calls: int
|
|
87
|
+
budget_exhausted: bool
|
|
88
|
+
baseline_inconsistent: bool
|
|
89
|
+
status: str
|
|
90
|
+
edge_diagnostics: tuple[str, str] = ("UNAVAILABLE", "UNAVAILABLE")
|
|
91
|
+
requested_grid: tuple[float, ...] = ()
|
|
92
|
+
bound_log_tolerance: float = 1e-7
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class _BudgetExhausted(RuntimeError):
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class _Evaluator:
|
|
101
|
+
callback: WeightedResidual
|
|
102
|
+
limit: int | None
|
|
103
|
+
calls: int = 0
|
|
104
|
+
size: int | None = None
|
|
105
|
+
exhausted: bool = False
|
|
106
|
+
lowest_chi2: float | None = None
|
|
107
|
+
|
|
108
|
+
def __call__(self, values: FloatArray) -> FloatArray:
|
|
109
|
+
if self.limit is not None and self.calls >= self.limit:
|
|
110
|
+
self.exhausted = True
|
|
111
|
+
raise _BudgetExhausted("Global callback budget exhausted")
|
|
112
|
+
readonly = np.array(values, dtype=np.float64, copy=True)
|
|
113
|
+
readonly.setflags(write=False)
|
|
114
|
+
self.calls += 1
|
|
115
|
+
residual = real_array(self.callback(readonly), "weighted residual")
|
|
116
|
+
if residual.ndim != 1 or not residual.size:
|
|
117
|
+
raise ValueError("Weighted residual must be a nonempty 1D vector")
|
|
118
|
+
if self.size is not None and residual.size != self.size:
|
|
119
|
+
raise ValueError("Weighted residual length changed")
|
|
120
|
+
self.size = residual.size
|
|
121
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
122
|
+
score = float(np.dot(residual, residual))
|
|
123
|
+
if np.isfinite(score):
|
|
124
|
+
self.lowest_chi2 = score if self.lowest_chi2 is None else min(self.lowest_chi2, score)
|
|
125
|
+
return residual
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _bounds_at(
|
|
129
|
+
values: FloatArray, specs: tuple[ProfileParameter, ...], tolerance: float,
|
|
130
|
+
) -> tuple[str, ...]:
|
|
131
|
+
return tuple(spec.name for value, spec in zip(values, specs, strict=True)
|
|
132
|
+
if abs(np.log(value) - np.log(spec.lower)) <= tolerance
|
|
133
|
+
or abs(np.log(value) - np.log(spec.upper)) <= tolerance)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _trial(
|
|
137
|
+
evaluate: _Evaluator,
|
|
138
|
+
specs: tuple[ProfileParameter, ...],
|
|
139
|
+
start: FloatArray,
|
|
140
|
+
max_nfev: int,
|
|
141
|
+
fixed: tuple[int, float] | None,
|
|
142
|
+
bound_log_tolerance: float,
|
|
143
|
+
) -> ProfileTrial:
|
|
144
|
+
initial = start.copy()
|
|
145
|
+
if fixed is not None:
|
|
146
|
+
initial[fixed[0]] = fixed[1]
|
|
147
|
+
indices = [i for i in range(len(specs)) if fixed is None or i != fixed[0]]
|
|
148
|
+
lower = np.array([specs[i].lower for i in indices])
|
|
149
|
+
upper = np.array([specs[i].upper for i in indices])
|
|
150
|
+
count = evaluate.calls
|
|
151
|
+
last_values: FloatArray | None = None
|
|
152
|
+
last_chi2: float | None = None
|
|
153
|
+
lowest_chi2: float | None = None
|
|
154
|
+
active_names: tuple[str, ...] = ()
|
|
155
|
+
|
|
156
|
+
def residual(log_values: FloatArray) -> FloatArray:
|
|
157
|
+
nonlocal last_values, last_chi2, lowest_chi2
|
|
158
|
+
values = initial.copy()
|
|
159
|
+
values[indices] = np.clip(np.exp(log_values), lower, upper)
|
|
160
|
+
r = evaluate(values)
|
|
161
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
162
|
+
objective = float(np.dot(r, r))
|
|
163
|
+
if not np.isfinite(objective):
|
|
164
|
+
raise ValueError("Sum of squared residuals is not finite")
|
|
165
|
+
last_values, last_chi2 = values, objective
|
|
166
|
+
lowest_chi2 = objective if lowest_chi2 is None else min(lowest_chi2, objective)
|
|
167
|
+
return r
|
|
168
|
+
|
|
169
|
+
try:
|
|
170
|
+
if indices:
|
|
171
|
+
fitted = least_squares(
|
|
172
|
+
residual, np.log(initial[indices]), bounds=(np.log(lower), np.log(upper)),
|
|
173
|
+
jac="3-point", max_nfev=max_nfev, ftol=1e-10, xtol=1e-10, gtol=1e-10,
|
|
174
|
+
)
|
|
175
|
+
values = initial.copy()
|
|
176
|
+
values[indices] = np.clip(np.exp(fitted.x), lower, upper)
|
|
177
|
+
objective = float(np.dot(fitted.fun, fitted.fun))
|
|
178
|
+
success = bool(fitted.success)
|
|
179
|
+
active_names = tuple(specs[i].name for i, mask in zip(
|
|
180
|
+
indices, fitted.active_mask, strict=True) if mask != 0)
|
|
181
|
+
status, message = ("CONVERGED" if success else "OPTIMIZER_FAILED"), str(fitted.message)
|
|
182
|
+
else:
|
|
183
|
+
residual(np.empty(0))
|
|
184
|
+
assert last_chi2 is not None
|
|
185
|
+
values, objective = initial, last_chi2
|
|
186
|
+
success, status, message = True, "EVALUATED", "No nuisance parameters"
|
|
187
|
+
except Exception as exc:
|
|
188
|
+
return ProfileTrial(
|
|
189
|
+
tuple(initial), None if last_values is None else tuple(last_values), last_chi2,
|
|
190
|
+
False, "BUDGET_EXHAUSTED" if isinstance(exc, _BudgetExhausted) else "ERROR",
|
|
191
|
+
f"{type(exc).__name__}: {exc}", evaluate.calls - count,
|
|
192
|
+
() if last_values is None else _bounds_at(last_values, specs, bound_log_tolerance),
|
|
193
|
+
lowest_chi2,
|
|
194
|
+
)
|
|
195
|
+
return ProfileTrial(tuple(initial), tuple(values), objective, success, status, message,
|
|
196
|
+
evaluate.calls - count,
|
|
197
|
+
tuple(dict.fromkeys((
|
|
198
|
+
*_bounds_at(values, specs, bound_log_tolerance), *active_names))),
|
|
199
|
+
lowest_chi2)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _best(trials: tuple[ProfileTrial, ...]) -> ProfileTrial | None:
|
|
203
|
+
valid = [trial for trial in trials if trial.success and trial.chi2 is not None]
|
|
204
|
+
return min(
|
|
205
|
+
valid, key=lambda trial: trial.chi2 if trial.chi2 is not None else np.inf,
|
|
206
|
+
) if valid else None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def profile_gaussian_known_sigma(
|
|
210
|
+
weighted_residual: WeightedResidual,
|
|
211
|
+
parameters: Sequence[ProfileParameter],
|
|
212
|
+
starts: ArrayLike,
|
|
213
|
+
*,
|
|
214
|
+
parameter: str,
|
|
215
|
+
grid: ArrayLike,
|
|
216
|
+
confidence: float = 0.95,
|
|
217
|
+
max_nfev: int = 200,
|
|
218
|
+
max_callback_calls: int | None = None,
|
|
219
|
+
baseline_tolerance: float = 1e-6,
|
|
220
|
+
bound_log_tolerance: float = 1e-7,
|
|
221
|
+
) -> GaussianProfile:
|
|
222
|
+
"""Reoptimize nuisance on a supplied grid, recording every multi-start attempt.
|
|
223
|
+
|
|
224
|
+
Errors in configuration raise ValueError; evaluator/optimizer errors are
|
|
225
|
+
retained as trials. The hard budget counts actual callback invocations, not
|
|
226
|
+
scipy nfev or physical solves inside the callback. Sigma must be known.
|
|
227
|
+
"""
|
|
228
|
+
specs = tuple(parameters)
|
|
229
|
+
if not specs or not all(isinstance(spec, ProfileParameter) for spec in specs):
|
|
230
|
+
raise ValueError("parameters must contain ProfileParameter instances")
|
|
231
|
+
names = tuple(spec.name for spec in specs)
|
|
232
|
+
if len(set(names)) != len(names) or parameter not in names:
|
|
233
|
+
raise ValueError("Names must be unique and parameter must be present")
|
|
234
|
+
if not callable(weighted_residual):
|
|
235
|
+
raise ValueError("weighted_residual must be callable")
|
|
236
|
+
confidence = finite_scalar(confidence, "confidence")
|
|
237
|
+
tolerance = finite_scalar(baseline_tolerance, "baseline_tolerance")
|
|
238
|
+
bound_log_tolerance = finite_scalar(bound_log_tolerance, "bound_log_tolerance")
|
|
239
|
+
if bound_log_tolerance < 0:
|
|
240
|
+
raise ValueError("bound_log_tolerance must be nonnegative")
|
|
241
|
+
if not 0 < confidence < 1 or tolerance < 0:
|
|
242
|
+
raise ValueError("Require 0 < confidence < 1 and nonnegative baseline_tolerance")
|
|
243
|
+
if type(max_nfev) is not int or max_nfev < 1:
|
|
244
|
+
raise ValueError("max_nfev must be a positive integer")
|
|
245
|
+
if max_callback_calls is not None and (
|
|
246
|
+
type(max_callback_calls) is not int or max_callback_calls < 1
|
|
247
|
+
):
|
|
248
|
+
raise ValueError("max_callback_calls must be a positive integer or None")
|
|
249
|
+
initial = real_array(starts, "starts")
|
|
250
|
+
lower = np.array([spec.lower for spec in specs])
|
|
251
|
+
upper = np.array([spec.upper for spec in specs])
|
|
252
|
+
if initial.ndim != 2 or initial.shape[1] != len(specs) or not initial.shape[0]:
|
|
253
|
+
raise ValueError("starts must have shape (n_starts, n_parameters), n_starts > 0")
|
|
254
|
+
if np.any(initial < lower) or np.any(initial > upper):
|
|
255
|
+
raise ValueError("starts must lie inside physical bounds")
|
|
256
|
+
index = names.index(parameter)
|
|
257
|
+
values = real_array(grid, "grid")
|
|
258
|
+
if values.ndim != 1 or not values.size or np.any(np.diff(values) <= 0):
|
|
259
|
+
raise ValueError("grid must be a nonempty strictly increasing 1D vector")
|
|
260
|
+
requested_grid = tuple(float(value) for value in values)
|
|
261
|
+
values = values.copy()
|
|
262
|
+
# Canonicalize endpoint roundoff only; do not use the proximity diagnostic tolerance.
|
|
263
|
+
for bound in (lower[index], upper[index]):
|
|
264
|
+
rounding = 4 * abs(np.spacing(bound))
|
|
265
|
+
values[np.abs(values - bound) <= rounding] = bound
|
|
266
|
+
if np.any(np.diff(values) <= 0):
|
|
267
|
+
raise ValueError("grid has duplicate points after endpoint rounding")
|
|
268
|
+
if np.any(values < lower[index]) or np.any(values > upper[index]):
|
|
269
|
+
raise ValueError("grid must lie inside physical bounds")
|
|
270
|
+
|
|
271
|
+
evaluate = _Evaluator(weighted_residual, max_callback_calls)
|
|
272
|
+
baseline_trials = tuple(
|
|
273
|
+
_trial(evaluate, specs, start, max_nfev, None, bound_log_tolerance)
|
|
274
|
+
for start in initial
|
|
275
|
+
)
|
|
276
|
+
baseline = _best(baseline_trials)
|
|
277
|
+
profiled: list[tuple[float, tuple[ProfileTrial, ...], ProfileTrial | None]] = []
|
|
278
|
+
for value in values:
|
|
279
|
+
trials = (() if baseline is None else tuple(
|
|
280
|
+
_trial(evaluate, specs, start, max_nfev, (index, float(value)), bound_log_tolerance)
|
|
281
|
+
for start in initial
|
|
282
|
+
))
|
|
283
|
+
profiled.append((float(value), trials, _best(trials)))
|
|
284
|
+
reference = None if baseline is None else baseline.chi2
|
|
285
|
+
inconsistent = (reference is not None and evaluate.lowest_chi2 is not None
|
|
286
|
+
and evaluate.lowest_chi2 < reference - tolerance)
|
|
287
|
+
cutoff = float(chi2.ppf(confidence, 1))
|
|
288
|
+
points: list[ProfilePoint] = []
|
|
289
|
+
for value, trials, best in profiled:
|
|
290
|
+
score = None if best is None else best.chi2
|
|
291
|
+
delta = None if score is None or reference is None else score - reference
|
|
292
|
+
accepted = None if delta is None or inconsistent else delta <= cutoff
|
|
293
|
+
at_bound = value in (specs[index].lower, specs[index].upper)
|
|
294
|
+
nuisance_bound = best is not None and any(
|
|
295
|
+
name != parameter for name in best.bound_parameters
|
|
296
|
+
)
|
|
297
|
+
points.append(ProfilePoint(value, trials, None if best is None else best.parameters,
|
|
298
|
+
score, delta, accepted, at_bound or nuisance_bound))
|
|
299
|
+
|
|
300
|
+
def edge(point: ProfilePoint, physical_bound: float) -> EdgeStatus:
|
|
301
|
+
if point.accepted is None:
|
|
302
|
+
return "UNAVAILABLE"
|
|
303
|
+
if not point.accepted:
|
|
304
|
+
return "REJECTED"
|
|
305
|
+
return "BOUND_LIMITED" if point.value == physical_bound else "GRID_TRUNCATED"
|
|
306
|
+
|
|
307
|
+
status = ("BASELINE_INCONSISTENT" if inconsistent else
|
|
308
|
+
"BUDGET_EXHAUSTED" if evaluate.exhausted else
|
|
309
|
+
"BASELINE_FAILED" if baseline is None else
|
|
310
|
+
"INCOMPLETE" if any(point.chi2 is None for point in points) else "COMPLETE")
|
|
311
|
+
|
|
312
|
+
def diagnostic(point: ProfilePoint, physical_bound: float) -> str:
|
|
313
|
+
coarse = edge(point, physical_bound)
|
|
314
|
+
best = _best(point.trials)
|
|
315
|
+
nuisance = best is not None and any(name != parameter for name in best.bound_parameters)
|
|
316
|
+
return f"{coarse}_WITH_NUISANCE_BOUND_EVIDENCE" if nuisance else coarse
|
|
317
|
+
|
|
318
|
+
return GaussianProfile(
|
|
319
|
+
specs, parameter, confidence, cutoff, baseline_trials,
|
|
320
|
+
None if baseline is None else baseline.parameters, reference, tuple(points),
|
|
321
|
+
tuple(point.value for point in points if point.accepted),
|
|
322
|
+
(edge(points[0], float(lower[index])), edge(points[-1], float(upper[index]))),
|
|
323
|
+
evaluate.calls, evaluate.exhausted,
|
|
324
|
+
inconsistent, status,
|
|
325
|
+
(diagnostic(points[0], float(lower[index])),
|
|
326
|
+
diagnostic(points[-1], float(upper[index]))), requested_grid, bound_log_tolerance,
|
|
327
|
+
)
|
sorbflow/cli.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Command-line interface for independent batch and column LDF simulations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from .io import export_result
|
|
12
|
+
from .reactors import simulate_batch, simulate_column
|
|
13
|
+
from .schemas import BatchConfig, SimulationConfig
|
|
14
|
+
from .solvers import SimulationError, SolverOptions
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv: list[str] | None = None) -> int:
|
|
18
|
+
parser = argparse.ArgumentParser(description="SorbFlow — aqueous LDF simulations in SI")
|
|
19
|
+
parser.add_argument("reactor", choices=("batch", "column"))
|
|
20
|
+
parser.add_argument("config", type=Path, help="Versioned JSON configuration")
|
|
21
|
+
parser.add_argument("--output", required=True, type=Path, help="New output directory")
|
|
22
|
+
parser.add_argument("--method", choices=("BDF", "Radau"), default="BDF")
|
|
23
|
+
parser.add_argument("--cells", type=int, default=100)
|
|
24
|
+
parser.add_argument("--radial-cells", type=int, default=20)
|
|
25
|
+
parser.add_argument("--samples", type=int, default=201)
|
|
26
|
+
parser.add_argument("--rtol", type=float, default=1e-7)
|
|
27
|
+
parser.add_argument("--code-revision", default="uncommitted")
|
|
28
|
+
args = parser.parse_args(argv)
|
|
29
|
+
try:
|
|
30
|
+
if args.samples < 2:
|
|
31
|
+
raise ValueError("--samples must be >=2")
|
|
32
|
+
if args.output.exists():
|
|
33
|
+
raise FileExistsError(f"Output directory already exists: {args.output}")
|
|
34
|
+
options = SolverOptions(
|
|
35
|
+
method=args.method,
|
|
36
|
+
axial_cells=args.cells,
|
|
37
|
+
radial_cells=args.radial_cells,
|
|
38
|
+
rtol=args.rtol,
|
|
39
|
+
)
|
|
40
|
+
payload = args.config.read_text(encoding="utf-8-sig")
|
|
41
|
+
if args.reactor == "batch":
|
|
42
|
+
batch_config = BatchConfig.from_json(payload)
|
|
43
|
+
result = simulate_batch(
|
|
44
|
+
batch_config,
|
|
45
|
+
options=options,
|
|
46
|
+
code_revision=args.code_revision,
|
|
47
|
+
time_s=np.linspace(0, batch_config.duration_s, args.samples),
|
|
48
|
+
)
|
|
49
|
+
else:
|
|
50
|
+
column_config = SimulationConfig.from_json(payload)
|
|
51
|
+
result = simulate_column(
|
|
52
|
+
column_config,
|
|
53
|
+
options=options,
|
|
54
|
+
code_revision=args.code_revision,
|
|
55
|
+
time_s=np.linspace(0, column_config.operation.duration_s, args.samples),
|
|
56
|
+
)
|
|
57
|
+
export_result(result, args.output)
|
|
58
|
+
except (OSError, ValueError, SimulationError, NotImplementedError) as exc:
|
|
59
|
+
print(f"SorbFlow error: {exc}", file=sys.stderr)
|
|
60
|
+
return 2
|
|
61
|
+
print(f"Saved {result.reactor} simulation to {args.output}")
|
|
62
|
+
print(f"Mass residual max: {result.diagnostics.max_abs_mass_residual_kg:.6g} kg")
|
|
63
|
+
print("Numerical checks passed (mass balance and state constraints).")
|
|
64
|
+
return 0
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Process geometry and hydraulic calculations; no mechanical certification."""
|
|
2
|
+
|
|
3
|
+
from .cad import export_dxf
|
|
4
|
+
from .hydraulics import CostBasis, HydraulicDesign, cost_estimate, hydraulics
|
|
5
|
+
|
|
6
|
+
__all__ = ["CostBasis", "HydraulicDesign", "cost_estimate", "hydraulics", "export_dxf"]
|
sorbflow/design/cad.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Neutral process-envelope DXF export; no CAD runtime in the scientific core."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from ..schemas import Bed
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def export_dxf(bed: Bed, path: str | Path) -> Path:
|
|
9
|
+
"""Export a cylindrical bed envelope: elevation and plan in meters.
|
|
10
|
+
|
|
11
|
+
This contains process geometry, not wall thickness, vessel heads, connections,
|
|
12
|
+
pressure-vessel calculations or a fabrication drawing. STEP requires a future
|
|
13
|
+
optional CAD adapter. Existing files are never overwritten.
|
|
14
|
+
"""
|
|
15
|
+
pairs: list[tuple[int, str | float | int]] = [
|
|
16
|
+
(0, "SECTION"),
|
|
17
|
+
(2, "HEADER"),
|
|
18
|
+
(9, "$ACADVER"),
|
|
19
|
+
(1, "AC1015"),
|
|
20
|
+
(9, "$INSUNITS"),
|
|
21
|
+
(70, 6),
|
|
22
|
+
(0, "ENDSEC"),
|
|
23
|
+
(0, "SECTION"),
|
|
24
|
+
(2, "ENTITIES"),
|
|
25
|
+
]
|
|
26
|
+
d, length = bed.diameter_m, bed.length_m
|
|
27
|
+
corners = ((0, 0), (d, 0), (d, length), (0, length))
|
|
28
|
+
for i in range(4):
|
|
29
|
+
a, b = corners[i], corners[(i + 1) % 4]
|
|
30
|
+
pairs.extend(
|
|
31
|
+
[
|
|
32
|
+
(0, "LINE"),
|
|
33
|
+
(8, "PROCESS_ENVELOPE"),
|
|
34
|
+
(10, a[0]),
|
|
35
|
+
(20, a[1]),
|
|
36
|
+
(30, 0),
|
|
37
|
+
(11, b[0]),
|
|
38
|
+
(21, b[1]),
|
|
39
|
+
(31, 0),
|
|
40
|
+
]
|
|
41
|
+
)
|
|
42
|
+
pairs.extend(
|
|
43
|
+
[
|
|
44
|
+
(0, "CIRCLE"),
|
|
45
|
+
(8, "PROCESS_ENVELOPE"),
|
|
46
|
+
(10, 2 * d),
|
|
47
|
+
(20, d / 2),
|
|
48
|
+
(30, 0),
|
|
49
|
+
(40, d / 2),
|
|
50
|
+
(0, "TEXT"),
|
|
51
|
+
(8, "NOTES"),
|
|
52
|
+
(10, 0),
|
|
53
|
+
(20, -d / 4),
|
|
54
|
+
(30, 0),
|
|
55
|
+
(40, d / 12),
|
|
56
|
+
(1, "PROCESS ENVELOPE - METERS - NOT A FABRICATION DRAWING"),
|
|
57
|
+
(0, "ENDSEC"),
|
|
58
|
+
(0, "EOF"),
|
|
59
|
+
]
|
|
60
|
+
)
|
|
61
|
+
target = Path(path)
|
|
62
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
with target.open("x", encoding="ascii", newline="\n") as stream:
|
|
64
|
+
stream.write("".join(f"{code}\n{value}\n" for code, value in pairs))
|
|
65
|
+
return target
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""SI hydraulic design for uniform spherical-particle liquid beds."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from ..schemas import Bed
|
|
8
|
+
from ..units import finite_scalar
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _positive(value: object, name: str) -> float:
|
|
12
|
+
number = finite_scalar(value, name)
|
|
13
|
+
if number <= 0:
|
|
14
|
+
raise ValueError(f"{name} must be positive")
|
|
15
|
+
return number
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class HydraulicDesign:
|
|
20
|
+
bed_volume_m3: float
|
|
21
|
+
dry_adsorbent_mass_kg: float
|
|
22
|
+
superficial_velocity_m_s: float
|
|
23
|
+
ebct_s: float
|
|
24
|
+
liquid_residence_s: float
|
|
25
|
+
pressure_drop_pa: float
|
|
26
|
+
pump_power_w: float
|
|
27
|
+
particle_reynolds: float
|
|
28
|
+
pump_efficiency: float
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def hydraulics(
|
|
32
|
+
bed: Bed,
|
|
33
|
+
*,
|
|
34
|
+
flow_m3_s: float,
|
|
35
|
+
fluid_density_kg_m3: float,
|
|
36
|
+
viscosity_pa_s: float,
|
|
37
|
+
pump_efficiency: float = 1.0,
|
|
38
|
+
) -> HydraulicDesign:
|
|
39
|
+
"""Ergun pressure drop for a fixed uniform bed, including viscous/inertial terms.
|
|
40
|
+
|
|
41
|
+
Fluid properties are supplied, never inferred from a contaminant name. Particle
|
|
42
|
+
shape, wall effects, swelling, fouling and support losses are excluded.
|
|
43
|
+
"""
|
|
44
|
+
flow = _positive(flow_m3_s, "flow_m3_s")
|
|
45
|
+
rho = _positive(fluid_density_kg_m3, "fluid_density_kg_m3")
|
|
46
|
+
mu = _positive(viscosity_pa_s, "viscosity_pa_s")
|
|
47
|
+
efficiency = _positive(pump_efficiency, "pump_efficiency")
|
|
48
|
+
if efficiency > 1:
|
|
49
|
+
raise ValueError("pump_efficiency cannot exceed one")
|
|
50
|
+
volume = bed.volume_m3
|
|
51
|
+
speed = flow / (volume / bed.length_m)
|
|
52
|
+
eps, dp = bed.porosity, bed.particle_diameter_m
|
|
53
|
+
gradient = 150 * mu * (1 - eps) ** 2 * speed / (eps**3 * dp**2)
|
|
54
|
+
gradient += 1.75 * rho * (1 - eps) * speed**2 / (eps**3 * dp)
|
|
55
|
+
drop = finite_scalar(gradient * bed.length_m, "pressure_drop_pa")
|
|
56
|
+
return HydraulicDesign(
|
|
57
|
+
volume,
|
|
58
|
+
volume * bed.bulk_density_kg_m3,
|
|
59
|
+
speed,
|
|
60
|
+
volume / flow,
|
|
61
|
+
eps * volume / flow,
|
|
62
|
+
drop,
|
|
63
|
+
flow * drop / efficiency,
|
|
64
|
+
rho * speed * dp / mu,
|
|
65
|
+
efficiency,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
70
|
+
class CostBasis:
|
|
71
|
+
"""Caller-provided prices; no exchange-rate or market-price assumptions."""
|
|
72
|
+
|
|
73
|
+
currency: str
|
|
74
|
+
base_year: int
|
|
75
|
+
adsorbent_per_kg: float
|
|
76
|
+
electricity_per_kwh: float
|
|
77
|
+
|
|
78
|
+
def __post_init__(self) -> None:
|
|
79
|
+
if not isinstance(self.currency, str) or not self.currency.strip():
|
|
80
|
+
raise ValueError("currency must be explicit")
|
|
81
|
+
if type(self.base_year) is not int or not 1900 <= self.base_year <= 9999:
|
|
82
|
+
raise ValueError("base_year must be an explicit integer year")
|
|
83
|
+
for name in ("adsorbent_per_kg", "electricity_per_kwh"):
|
|
84
|
+
if finite_scalar(getattr(self, name), name) < 0:
|
|
85
|
+
raise ValueError(f"{name} must be nonnegative")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def cost_estimate(design: HydraulicDesign, prices: CostBasis, *, service_time_s: float) -> float:
|
|
89
|
+
"""Adsorbent plus pumping electricity in the stated currency/base year.
|
|
90
|
+
|
|
91
|
+
Excludes vessel CAPEX, labor, pretreatment, regeneration/disposal, financing and
|
|
92
|
+
replacement schedules. It is not an economic lifecycle model.
|
|
93
|
+
"""
|
|
94
|
+
duration = _positive(service_time_s, "service_time_s")
|
|
95
|
+
energy_kwh = design.pump_power_w * duration / 3.6e6
|
|
96
|
+
return (
|
|
97
|
+
design.dry_adsorbent_mass_kg * prices.adsorbent_per_kg
|
|
98
|
+
+ energy_kwh * prices.electricity_per_kwh
|
|
99
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Mass-based equilibrium API, independent of transport and reactor geometry."""
|
|
2
|
+
|
|
3
|
+
from .isotherms import (
|
|
4
|
+
FreundlichIsotherm,
|
|
5
|
+
Isotherm,
|
|
6
|
+
LangmuirIsotherm,
|
|
7
|
+
LinearIsotherm,
|
|
8
|
+
isotherm_from_parameters,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"Isotherm",
|
|
13
|
+
"LangmuirIsotherm",
|
|
14
|
+
"FreundlichIsotherm",
|
|
15
|
+
"LinearIsotherm",
|
|
16
|
+
"isotherm_from_parameters",
|
|
17
|
+
]
|