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.
Files changed (56) hide show
  1. sorbflow/__init__.py +41 -0
  2. sorbflow/__main__.py +5 -0
  3. sorbflow/_arrays.py +40 -0
  4. sorbflow/_version.py +3 -0
  5. sorbflow/adapters/__init__.py +1 -0
  6. sorbflow/calibration/__init__.py +5 -0
  7. sorbflow/calibration/batch_objective.py +118 -0
  8. sorbflow/calibration/least_squares.py +207 -0
  9. sorbflow/calibration/measurements.py +49 -0
  10. sorbflow/calibration/profile.py +327 -0
  11. sorbflow/cli.py +64 -0
  12. sorbflow/design/__init__.py +6 -0
  13. sorbflow/design/cad.py +65 -0
  14. sorbflow/design/hydraulics.py +99 -0
  15. sorbflow/equilibrium/__init__.py +17 -0
  16. sorbflow/equilibrium/isotherms.py +117 -0
  17. sorbflow/fit.py +7 -0
  18. sorbflow/io/__init__.py +7 -0
  19. sorbflow/io/experimental.py +159 -0
  20. sorbflow/io/parquet.py +79 -0
  21. sorbflow/io/results.py +50 -0
  22. sorbflow/kinetics/__init__.py +5 -0
  23. sorbflow/kinetics/sphere.py +112 -0
  24. sorbflow/observation.py +174 -0
  25. sorbflow/optimization/__init__.py +5 -0
  26. sorbflow/optimization/nsga2.py +161 -0
  27. sorbflow/optimize.py +5 -0
  28. sorbflow/py.typed +0 -0
  29. sorbflow/reactors/__init__.py +6 -0
  30. sorbflow/reactors/_ldf_jacobian.py +58 -0
  31. sorbflow/reactors/batch.py +87 -0
  32. sorbflow/reactors/column.py +151 -0
  33. sorbflow/reactors/hsdm.py +167 -0
  34. sorbflow/schemas.py +496 -0
  35. sorbflow/simulate.py +6 -0
  36. sorbflow/solvers/__init__.py +7 -0
  37. sorbflow/solvers/integration.py +152 -0
  38. sorbflow/solvers/options.py +74 -0
  39. sorbflow/solvers/results.py +318 -0
  40. sorbflow/uncertainty/__init__.py +5 -0
  41. sorbflow/uncertainty/monte_carlo.py +129 -0
  42. sorbflow/units.py +53 -0
  43. sorbflow/validate/__init__.py +35 -0
  44. sorbflow/web/__init__.py +5 -0
  45. sorbflow/web/__main__.py +6 -0
  46. sorbflow/web/app.py +278 -0
  47. sorbflow/web/config.py +213 -0
  48. sorbflow/web/server.py +302 -0
  49. sorbflow/web/ui.py +50 -0
  50. sorbflow-0.3.0.dist-info/METADATA +121 -0
  51. sorbflow-0.3.0.dist-info/RECORD +56 -0
  52. sorbflow-0.3.0.dist-info/WHEEL +5 -0
  53. sorbflow-0.3.0.dist-info/entry_points.txt +2 -0
  54. sorbflow-0.3.0.dist-info/licenses/LICENSE +202 -0
  55. sorbflow-0.3.0.dist-info/licenses/NOTICE +12 -0
  56. sorbflow-0.3.0.dist-info/top_level.txt +1 -0
sorbflow/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """SorbFlow: configurable aqueous adsorption modelling for batch reactors and fixed beds."""
2
+
3
+ from ._version import VERSION as __version__
4
+ from .schemas import (
5
+ HSDM,
6
+ LDF,
7
+ AdsorbentBlend,
8
+ BatchConfig,
9
+ Bed,
10
+ BlendComponent,
11
+ Freundlich,
12
+ Langmuir,
13
+ Linear,
14
+ Observations,
15
+ Operation,
16
+ RunManifest,
17
+ SimulationConfig,
18
+ Species,
19
+ )
20
+ from .units import UnitError, quantity, to_si
21
+
22
+ __all__ = [
23
+ "__version__",
24
+ "HSDM",
25
+ "LDF",
26
+ "AdsorbentBlend",
27
+ "BatchConfig",
28
+ "Bed",
29
+ "BlendComponent",
30
+ "Freundlich",
31
+ "Langmuir",
32
+ "Linear",
33
+ "Observations",
34
+ "Operation",
35
+ "RunManifest",
36
+ "SimulationConfig",
37
+ "Species",
38
+ "UnitError",
39
+ "quantity",
40
+ "to_si",
41
+ ]
sorbflow/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Run the same CLI using python -m sorbflow."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
sorbflow/_arrays.py ADDED
@@ -0,0 +1,40 @@
1
+ """Shared finite real array checks; no physical units are inferred here."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from numpy.typing import ArrayLike, NDArray
7
+
8
+ FloatArray = NDArray[np.float64]
9
+
10
+
11
+ def _contains_boolean(value: object) -> bool:
12
+ # Inspect containers before NumPy can turn mixed bool/float inputs into floats.
13
+ if isinstance(value, (bool, np.bool_)):
14
+ return True
15
+ if isinstance(value, np.ndarray):
16
+ return bool(value.dtype.kind == "b")
17
+ if isinstance(value, (list, tuple)):
18
+ return any(_contains_boolean(item) for item in value)
19
+ return False
20
+
21
+
22
+ def real_array(value: ArrayLike, name: str) -> FloatArray:
23
+ """Copy numeric input, preserving shape, rejecting booleans/complex/NaN."""
24
+ if _contains_boolean(value):
25
+ raise ValueError(f"{name} must contain real numbers, not booleans")
26
+ raw = np.asarray(value)
27
+ if raw.dtype.kind not in "iuf":
28
+ raise ValueError(f"{name} must contain real numbers")
29
+ result = np.array(raw, dtype=np.float64, copy=True)
30
+ if not np.all(np.isfinite(result)):
31
+ raise ValueError(f"{name} must be finite")
32
+ return result
33
+
34
+
35
+ def nonnegative_array(value: ArrayLike, name: str) -> FloatArray:
36
+ """Require nonnegative physical values, including scalar (zero-D) input."""
37
+ result = real_array(value, name)
38
+ if np.any(result < 0):
39
+ raise ValueError(f"{name} must be nonnegative")
40
+ return result
sorbflow/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Single source version for runtime provenance."""
2
+
3
+ VERSION = "0.3.0"
@@ -0,0 +1 @@
1
+ """Reserved extension namespace. No algorithms implemented in the foundation release."""
@@ -0,0 +1,5 @@
1
+ """Least-squares fitting with local SVD identifiability diagnostics."""
2
+
3
+ from .least_squares import FitError, FitResult, fit_batch_rate, fit_isotherm
4
+
5
+ __all__ = ["FitError", "FitResult", "fit_batch_rate", "fit_isotherm"]
@@ -0,0 +1,118 @@
1
+ """Known-sigma multi-experiment objective using the existing linear batch solver."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass, replace
7
+ from threading import Lock
8
+
9
+ import numpy as np
10
+ from numpy.typing import ArrayLike
11
+
12
+ from .._arrays import FloatArray
13
+ from ..reactors.batch import simulate_batch
14
+ from ..schemas import LDF, BatchConfig, Linear, Observations
15
+ from ..solvers import SolverOptions
16
+ from ..units import finite_scalar
17
+ from .measurements import SignedGaussianMeasurements
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class BatchExperiment:
22
+ """One declared experiment with known measurement sigma and SI quantities."""
23
+
24
+ config: BatchConfig
25
+ observations: Observations | SignedGaussianMeasurements
26
+
27
+ def __post_init__(self) -> None:
28
+ if (not isinstance(self.config, BatchConfig)
29
+ or not isinstance(self.observations, (Observations, SignedGaussianMeasurements))):
30
+ raise ValueError("BatchExperiment requires BatchConfig and supported measurements")
31
+ if (not isinstance(self.config.equilibrium, Linear)
32
+ or not isinstance(self.config.kinetics, LDF)):
33
+ raise ValueError("This objective supports only linear equilibrium and LDF")
34
+ if self.observations.species_name != self.config.species.name:
35
+ raise ValueError("Observation and model species differ")
36
+ if self.observations.std_kg_m3 is None:
37
+ raise ValueError("Known positive measurement standard deviations are required")
38
+ if self.observations.time_s[-1] > self.config.duration_s:
39
+ raise ValueError("Observation times exceed the configured experiment duration")
40
+
41
+
42
+ class LinearBatchObjective:
43
+ """Whitened residual for shared positive K and k across declared independent batches.
44
+
45
+ Known c0/q0, mass, volume and fixed common temperature are assumed. This
46
+ callback does not fit nuisance quantities or validate experiment independence.
47
+ """
48
+
49
+ parameter_names = ("distribution_m3_kg", "rate_s_inv")
50
+ parameter_units = ("m^3/kg", "1/s")
51
+
52
+ def __init__(
53
+ self, experiments: Sequence[BatchExperiment], *, options: SolverOptions | None = None,
54
+ code_revision: str = "uncommitted",
55
+ ) -> None:
56
+ items = tuple(experiments)
57
+ if not items or not all(isinstance(item, BatchExperiment) for item in items):
58
+ raise ValueError("At least one BatchExperiment is required")
59
+ reference = items[0].config
60
+ identities = [item.observations.experiment_id for item in items]
61
+ if len(set(identities)) != len(identities):
62
+ raise ValueError("Experiment IDs must be unique")
63
+ for item in items:
64
+ config = item.config
65
+ if (config.material != reference.material or config.species != reference.species
66
+ or config.temperature_k != reference.temperature_k):
67
+ raise ValueError("Shared parameters require common material/species/temperature")
68
+ settings = SolverOptions(rtol=1e-9, atol_concentration_kg_m3=1e-13,
69
+ atol_loading_kg_kg=1e-14) if options is None else options
70
+ if not isinstance(settings, SolverOptions):
71
+ raise ValueError("options must be SolverOptions")
72
+ if not isinstance(code_revision, str) or (code_revision != "uncommitted"
73
+ and re.fullmatch(r"[0-9a-f]{7,40}", code_revision) is None):
74
+ raise ValueError("code_revision must be a Git hash or uncommitted")
75
+ self._experiments = items
76
+ self._options = settings
77
+ self._code_revision = code_revision
78
+ self._physical_solves = 0
79
+ self._lock = Lock()
80
+
81
+ @property
82
+ def experiments(self) -> tuple[BatchExperiment, ...]:
83
+ return self._experiments
84
+
85
+ @property
86
+ def physical_solves(self) -> int:
87
+ with self._lock:
88
+ return self._physical_solves
89
+
90
+ @property
91
+ def input_hashes(self) -> tuple[tuple[str, str, str], ...]:
92
+ """(experiment ID, original configuration SHA, declared observation source SHA)."""
93
+ return tuple((item.observations.experiment_id, item.config.sha256,
94
+ item.observations.source_sha256) for item in self._experiments)
95
+
96
+ def __call__(self, parameters: ArrayLike) -> FloatArray:
97
+ raw = np.asarray(parameters, dtype=object)
98
+ if raw.ndim != 1 or raw.shape != (2,):
99
+ raise ValueError("Expected [K_m3_kg, k_LDF_s_inv]")
100
+ values = tuple(finite_scalar(value, "parameter") for value in raw)
101
+ if any(value <= 0 for value in values):
102
+ raise ValueError("K and k_LDF must be strictly positive")
103
+ distribution, rate = values
104
+ residuals = []
105
+ for item in self._experiments:
106
+ config = replace(item.config, equilibrium=Linear(distribution_m3_kg=distribution),
107
+ kinetics=LDF(rate_s_inv=rate))
108
+ observed_times = np.asarray(item.observations.time_s)
109
+ times = np.unique(np.concatenate(([0.0], observed_times, [config.duration_s])))
110
+ with self._lock:
111
+ self._physical_solves += 1
112
+ result = simulate_batch(config, time_s=times, options=self._options,
113
+ code_revision=self._code_revision)
114
+ measured = np.asarray(item.observations.concentration_kg_m3)
115
+ sigma = np.asarray(item.observations.std_kg_m3)
116
+ positions = np.searchsorted(times, observed_times)
117
+ residuals.append((result.outlet_concentration_kg_m3[positions] - measured) / sigma)
118
+ return np.concatenate(residuals)
@@ -0,0 +1,207 @@
1
+ """Initial inverse workflows with explicit local identifiability diagnostics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass, replace
7
+
8
+ import numpy as np
9
+ from numpy.typing import ArrayLike
10
+ from scipy.optimize import least_squares
11
+
12
+ from .._arrays import FloatArray, nonnegative_array
13
+ from ..equilibrium import isotherm_from_parameters
14
+ from ..reactors.batch import simulate_batch
15
+ from ..schemas import LDF, BatchConfig, Freundlich, Langmuir, Linear, Observations
16
+ from ..solvers import SolverOptions
17
+
18
+ Parameters = Langmuir | Freundlich | Linear | LDF
19
+
20
+
21
+ class FitError(RuntimeError):
22
+ """The inverse problem did not converge or left the numerical model domain."""
23
+
24
+
25
+ @dataclass(frozen=True, slots=True, kw_only=True)
26
+ class FitResult:
27
+ """Local least-squares evidence, never a declaration of global identifiability.
28
+
29
+ Covariance is in log-parameter coordinates. With known measurement sigma it
30
+ assumes that error model; otherwise residual variance is estimated from DOF.
31
+ """
32
+
33
+ parameters: Parameters
34
+ parameter_names: tuple[str, ...]
35
+ predicted: FloatArray
36
+ residuals: FloatArray
37
+ singular_values: FloatArray
38
+ covariance_log_parameters: FloatArray | None
39
+ jacobian_rank: int
40
+ jacobian_condition: float
41
+ locally_identifiable: bool
42
+ nfev: int
43
+
44
+ def __post_init__(self) -> None:
45
+ for name in ("predicted", "residuals", "singular_values", "covariance_log_parameters"):
46
+ array = getattr(self, name)
47
+ if array is not None:
48
+ value = np.array(array, dtype=np.float64, copy=True)
49
+ value.setflags(write=False)
50
+ object.__setattr__(self, name, value)
51
+
52
+
53
+ def _fit(
54
+ measured: FloatArray,
55
+ initial: FloatArray,
56
+ names: tuple[str, ...],
57
+ build: Callable[[FloatArray], Parameters],
58
+ predict: Callable[[Parameters], FloatArray],
59
+ std: ArrayLike | None,
60
+ max_nfev: int,
61
+ diff_step: float | None = None,
62
+ ) -> FitResult:
63
+ if type(max_nfev) is not int or max_nfev < 1:
64
+ raise ValueError("max_nfev must be a positive integer")
65
+ if measured.ndim != 1 or measured.size <= initial.size:
66
+ raise ValueError("More observations than fitted parameters are required")
67
+ if np.any(initial <= 0):
68
+ raise ValueError("Fitted parameters must start strictly positive")
69
+ if std is None:
70
+ sigma = np.full_like(measured, max(float(np.max(np.abs(measured))), 1e-30))
71
+ else:
72
+ sigma = nonnegative_array(std, "standard deviation")
73
+ if sigma.shape != measured.shape or np.any(sigma == 0):
74
+ raise ValueError("Positive standard deviations must match measurements")
75
+
76
+ def residual(log_parameters: FloatArray) -> FloatArray:
77
+ with np.errstate(over="raise", invalid="raise"):
78
+ parameters = build(np.exp(log_parameters))
79
+ return np.asarray((predict(parameters) - measured) / sigma)
80
+
81
+ try:
82
+ fitted = least_squares(
83
+ residual,
84
+ np.log(initial),
85
+ method="trf",
86
+ jac="3-point",
87
+ x_scale="jac",
88
+ diff_step=None if diff_step is None else np.asarray(diff_step),
89
+ max_nfev=max_nfev,
90
+ ftol=1e-10,
91
+ xtol=1e-10,
92
+ gtol=1e-10,
93
+ )
94
+ except (ValueError, FloatingPointError, OverflowError) as exc:
95
+ raise FitError(f"Fit left the supported numerical domain: {exc}") from exc
96
+ if not fitted.success:
97
+ raise FitError(f"Fit did not converge: {fitted.message}")
98
+ parameters = build(np.exp(fitted.x))
99
+ predicted = predict(parameters)
100
+ jacobian = np.asarray(fitted.jac)
101
+ _, singular, vt = np.linalg.svd(jacobian, full_matrices=False)
102
+ threshold = np.finfo(float).eps * max(jacobian.shape) * singular[0]
103
+ rank = int(np.sum(singular > threshold))
104
+ condition = float(singular[0] / singular[-1]) if singular[-1] > 0 else float("inf")
105
+ identified = rank == initial.size and condition <= 1e8
106
+ covariance = None
107
+ if identified:
108
+ covariance = (vt.T / singular**2) @ vt
109
+ if std is None:
110
+ covariance *= float(np.dot(fitted.fun, fitted.fun) / (measured.size - initial.size))
111
+ return FitResult(
112
+ parameters=parameters,
113
+ parameter_names=names,
114
+ predicted=predicted,
115
+ residuals=predicted - measured,
116
+ singular_values=singular,
117
+ covariance_log_parameters=covariance,
118
+ jacobian_rank=rank,
119
+ jacobian_condition=condition,
120
+ locally_identifiable=identified,
121
+ nfev=fitted.nfev,
122
+ )
123
+
124
+
125
+ def fit_isotherm(
126
+ concentration_kg_m3: ArrayLike,
127
+ loading_kg_kg: ArrayLike,
128
+ initial: Langmuir | Freundlich | Linear,
129
+ *,
130
+ std_loading_kg_kg: ArrayLike | None = None,
131
+ max_nfev: int = 1000,
132
+ ) -> FitResult:
133
+ """Fit one equilibrium model at a fixed, common experimental temperature.
134
+
135
+ All values are SI. Concentration error, censoring, mixtures and thermal effects
136
+ are not handled here. Freundlich c_ref stays fixed to avoid redundant parameters.
137
+ """
138
+ c = nonnegative_array(concentration_kg_m3, "concentration_kg_m3")
139
+ q = nonnegative_array(loading_kg_kg, "loading_kg_kg")
140
+ if c.ndim != 1 or c.shape != q.shape or c.size == 0:
141
+ raise ValueError("Matched one-dimensional equilibrium data are required")
142
+ names: tuple[str, ...]
143
+ if isinstance(initial, Langmuir):
144
+ values = np.array([initial.qmax_kg_kg, initial.affinity_m3_kg])
145
+ names = ("qmax_kg_kg", "affinity_m3_kg")
146
+
147
+ def build(values: FloatArray) -> Parameters:
148
+ return Langmuir(qmax_kg_kg=float(values[0]), affinity_m3_kg=float(values[1]))
149
+ elif isinstance(initial, Freundlich):
150
+ reference = initial.c_ref_kg_m3
151
+ values = np.array([initial.q_ref_kg_kg, initial.exponent])
152
+ names = ("q_ref_kg_kg", "exponent")
153
+
154
+ def build(values: FloatArray) -> Parameters:
155
+ return Freundlich(
156
+ q_ref_kg_kg=float(values[0]), exponent=float(values[1]), c_ref_kg_m3=reference
157
+ )
158
+ elif isinstance(initial, Linear):
159
+ values = np.array([initial.distribution_m3_kg])
160
+ names = ("distribution_m3_kg",)
161
+
162
+ def build(values: FloatArray) -> Parameters:
163
+ return Linear(distribution_m3_kg=float(values[0]))
164
+ else:
165
+ raise ValueError("Unsupported equilibrium model")
166
+
167
+ def predict(parameters: Parameters) -> FloatArray:
168
+ if isinstance(parameters, LDF):
169
+ raise ValueError("An equilibrium model is required")
170
+ return isotherm_from_parameters(parameters).loading(c)
171
+
172
+ return _fit(q, values, names, build, predict, std_loading_kg_kg, max_nfev)
173
+
174
+
175
+ def fit_batch_rate(
176
+ config: BatchConfig, observations: Observations, *, max_nfev: int = 100
177
+ ) -> FitResult:
178
+ """Estimate only k_LDF with all other physical parameters treated as known.
179
+
180
+ This does not identify separate film and surface diffusion coefficients.
181
+ Observations must include zero and the full configured simulation duration.
182
+ """
183
+ if observations.species_name != config.species.name:
184
+ raise ValueError("Observation species does not match the problem")
185
+ times = np.asarray(observations.time_s)
186
+ measured = np.asarray(observations.concentration_kg_m3)
187
+ options = SolverOptions(rtol=1e-9, atol_concentration_kg_m3=1e-13, atol_loading_kg_kg=1e-15)
188
+
189
+ def build(values: FloatArray) -> Parameters:
190
+ return LDF(rate_s_inv=float(values[0]))
191
+
192
+ def predict(parameters: Parameters) -> FloatArray:
193
+ if not isinstance(parameters, LDF):
194
+ raise ValueError("LDF rate parameters required")
195
+ result = simulate_batch(replace(config, kinetics=parameters), time_s=times, options=options)
196
+ return result.outlet_concentration_kg_m3
197
+
198
+ return _fit(
199
+ measured,
200
+ np.array([config.kinetics.rate_s_inv]),
201
+ ("rate_s_inv",),
202
+ build,
203
+ predict,
204
+ observations.std_kg_m3,
205
+ max_nfev,
206
+ diff_step=1e-4,
207
+ )
@@ -0,0 +1,49 @@
1
+ """Experimental signed observations for a fixed, diagonal Gaussian error model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+
8
+ from ..units import finite_scalar
9
+
10
+
11
+ @dataclass(frozen=True, slots=True, kw_only=True)
12
+ class SignedGaussianMeasurements:
13
+ """Finite measurements in SI; signed values are distinct from physical states.
14
+
15
+ The model is y = c + sigma*z with known, positive, fixed diagonal sigma.
16
+ Values are retained without clipping, censoring or resampling. Construction
17
+ does not establish normality or independence of the experimental errors.
18
+ """
19
+
20
+ experiment_id: str
21
+ species_name: str
22
+ time_s: tuple[float, ...]
23
+ concentration_kg_m3: tuple[float, ...]
24
+ source_sha256: str
25
+ std_kg_m3: tuple[float, ...]
26
+
27
+ def __post_init__(self) -> None:
28
+ for name in ("experiment_id", "species_name"):
29
+ value = getattr(self, name)
30
+ if not isinstance(value, str) or not value.strip():
31
+ raise ValueError(f"{name} must be nonempty text")
32
+ if (not isinstance(self.source_sha256, str)
33
+ or re.fullmatch(r"[0-9a-f]{64}", self.source_sha256) is None):
34
+ raise ValueError("source_sha256 must be a lowercase SHA-256 hex digest")
35
+ for name in ("time_s", "concentration_kg_m3", "std_kg_m3"):
36
+ values = getattr(self, name)
37
+ if not isinstance(values, (tuple, list)):
38
+ raise ValueError(f"{name} must be a sequence")
39
+ normalized = tuple(finite_scalar(value, name) for value in values)
40
+ if name == "time_s" and any(value < 0 for value in normalized):
41
+ raise ValueError("Measurement times must be nonnegative")
42
+ if name == "std_kg_m3" and any(value <= 0 for value in normalized):
43
+ raise ValueError("Known standard deviations must be positive")
44
+ object.__setattr__(self, name, normalized)
45
+ if (not self.time_s or len(self.time_s) != len(self.concentration_kg_m3)
46
+ or len(self.time_s) != len(self.std_kg_m3)):
47
+ raise ValueError("Nonempty matching time, measurement and sigma arrays are required")
48
+ if any(b <= a for a, b in zip(self.time_s, self.time_s[1:], strict=False)):
49
+ raise ValueError("Measurement times must strictly increase")