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
@@ -0,0 +1,167 @@
1
+ """Aqueous HSDM column: axial FV, spherical radial FV and finite film resistance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from numpy.typing import ArrayLike
7
+ from scipy.sparse import csc_matrix
8
+
9
+ from .._arrays import FloatArray
10
+ from ..equilibrium import isotherm_from_parameters
11
+ from ..kinetics.sphere import SphereGrid, diffusion_rhs, film_flux
12
+ from ..schemas import HSDM, SimulationConfig
13
+ from ..solvers.integration import integrate
14
+ from ..solvers.options import SolverOptions, sample_times
15
+ from ..solvers.results import SimulationResult, check_physics, result_metadata
16
+ from ..units import finite_scalar
17
+
18
+
19
+ def _pattern(axial: int, radial: int) -> csc_matrix:
20
+ rows: list[int] = []
21
+ cols: list[int] = []
22
+ for i in range(axial):
23
+ for j in range(max(0, i - 1), min(axial, i + 2)):
24
+ rows.append(i)
25
+ cols.append(j)
26
+ rows.append(i)
27
+ cols.append(axial + (i + 1) * radial - 1)
28
+ for r in range(radial):
29
+ index = axial + i * radial + r
30
+ for k in range(max(0, r - 1), min(radial, r + 2)):
31
+ rows.append(index)
32
+ cols.append(axial + i * radial + k)
33
+ if r == radial - 1:
34
+ rows.append(index)
35
+ cols.append(i)
36
+ states = axial * (radial + 1) + 2
37
+ rows.append(states - 1)
38
+ cols.append(axial - 1)
39
+ return csc_matrix((np.ones(len(rows)), (rows, cols)), shape=(states, states))
40
+
41
+
42
+ def simulate_hsdm_column(
43
+ config: SimulationConfig,
44
+ *,
45
+ time_s: ArrayLike | None = None,
46
+ options: SolverOptions | None = None,
47
+ code_revision: str = "uncommitted",
48
+ ) -> SimulationResult:
49
+ """Solve spherical surface diffusion coupled to an aqueous column and a film.
50
+
51
+ Particle liquid storage is excluded by the HSDM assumption. A single particle
52
+ size, dry-mass density and fixed T apply. Internal and sampled states are checked.
53
+ """
54
+ if not isinstance(config.kinetics, HSDM):
55
+ raise ValueError("HSDM parameter contract is required")
56
+ settings = SolverOptions() if options is None else options
57
+ if not isinstance(settings, SolverOptions):
58
+ raise ValueError("options must be SolverOptions")
59
+ times = sample_times(config.operation.duration_s, time_s)
60
+ options_json, fingerprint, manifest = result_metadata(
61
+ config.to_json(), times, settings, "column", code_revision
62
+ )
63
+ bed, op, kinetics = config.bed, config.operation, config.kinetics
64
+ n, nr = settings.axial_cells, settings.radial_cells
65
+ grid = SphereGrid(bed.particle_diameter_m / 2, nr)
66
+ dz = bed.length_m / n
67
+ area = finite_scalar(bed.volume_m3 / bed.length_m, "cross-sectional area")
68
+ velocity = finite_scalar(op.flow_m3_s / area, "superficial velocity")
69
+ eps, rho = bed.porosity, bed.particle_density_kg_m3
70
+ specific_area = 3 * (1 - eps) / grid.radius_m
71
+ model = isotherm_from_parameters(config.equilibrium)
72
+ initial = np.concatenate(
73
+ (
74
+ np.full(n, op.initial_concentration_kg_m3),
75
+ np.full(n * nr, op.initial_loading_kg_kg),
76
+ np.zeros(2),
77
+ )
78
+ )
79
+ initial_mass = finite_scalar(
80
+ bed.volume_m3
81
+ * (
82
+ eps * op.initial_concentration_kg_m3 + bed.bulk_density_kg_m3 * op.initial_loading_kg_kg
83
+ ),
84
+ "initial mass",
85
+ )
86
+
87
+ def rhs(_time: float, state: FloatArray) -> FloatArray:
88
+ c, q = state[:n], state[n:-2].reshape(n, nr)
89
+ transfer = film_flux(
90
+ c,
91
+ q[:, -1],
92
+ model,
93
+ grid=grid,
94
+ diffusivity_m2_s=kinetics.surface_diffusivity_m2_s,
95
+ particle_density_kg_m3=rho,
96
+ film_coefficient_m_s=kinetics.film_coefficient_m_s,
97
+ )
98
+ dq = diffusion_rhs(
99
+ q,
100
+ transfer,
101
+ grid=grid,
102
+ diffusivity_m2_s=kinetics.surface_diffusivity_m2_s,
103
+ particle_density_kg_m3=rho,
104
+ )
105
+ flux = np.empty(n + 1)
106
+ flux[0] = velocity * op.inlet_concentration_kg_m3
107
+ flux[1:n] = velocity * c[:-1] - eps * op.axial_dispersion_m2_s * np.diff(c) / dz
108
+ flux[-1] = velocity * c[-1]
109
+ dc = (-np.diff(flux) / dz - specific_area * transfer) / eps
110
+ return np.concatenate(
111
+ (dc, dq.ravel(), [op.flow_m3_s * op.inlet_concentration_kg_m3, op.flow_m3_s * c[-1]])
112
+ )
113
+
114
+ atol = np.concatenate(
115
+ (
116
+ np.full(n, settings.atol_concentration_kg_m3),
117
+ np.full(n * nr, settings.atol_loading_kg_kg),
118
+ np.full(2, settings.atol_mass_kg),
119
+ )
120
+ )
121
+ solution = integrate(rhs, initial, times, atol, settings, _pattern(n, nr))
122
+
123
+ def average(states: FloatArray) -> FloatArray:
124
+ q = states[n:-2].reshape(n, nr, states.shape[1])
125
+ return np.asarray(np.einsum("irt,r->it", q, grid.mean_weights))
126
+
127
+ def inventory(states: FloatArray) -> FloatArray:
128
+ return np.asarray(
129
+ area
130
+ * dz
131
+ * (
132
+ eps * np.sum(states[:n], axis=0)
133
+ + bed.bulk_density_kg_m3 * np.sum(average(states), axis=0)
134
+ )
135
+ )
136
+
137
+ checked = solution.checkpoints
138
+ diagnostics = check_physics(
139
+ checked[:n],
140
+ checked[n:-2],
141
+ inventory(checked),
142
+ checked[-2],
143
+ checked[-1],
144
+ initial_mass,
145
+ settings,
146
+ solution,
147
+ )
148
+ sampled = solution.samples
149
+ mass = inventory(sampled)
150
+ return SimulationResult(
151
+ reactor="column",
152
+ time_s=times,
153
+ concentration_kg_m3=sampled[:n].T,
154
+ loading_kg_kg=average(sampled).T,
155
+ inventory_kg=mass,
156
+ inlet_mass_kg=sampled[-2],
157
+ outlet_mass_kg=sampled[-1],
158
+ mass_residual_kg=mass - initial_mass - sampled[-2] + sampled[-1],
159
+ z_m=np.asarray((np.arange(n, dtype=np.float64) + 0.5) * dz),
160
+ radial_loading_kg_kg=sampled[n:-2].T.reshape(times.size, n, nr),
161
+ r_m=grid.centers_m,
162
+ config_json=config.to_json(),
163
+ options_json=options_json,
164
+ numerical_sha256=fingerprint,
165
+ manifest=manifest,
166
+ diagnostics=diagnostics,
167
+ )
sorbflow/schemas.py ADDED
@@ -0,0 +1,496 @@
1
+ """Immutable schema v1. Direct constructor fields are explicitly in SI units.
2
+
3
+ These data contracts describe proposed models; they do not evaluate isotherms,
4
+ integrate equations or certify physical validity outside their stated domain.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import math
12
+ import re
13
+ from dataclasses import asdict, dataclass, field, fields
14
+ from datetime import datetime
15
+ from typing import Any, Literal, TypeVar
16
+ from uuid import UUID
17
+
18
+ import pint
19
+
20
+ from .units import finite_scalar, to_si
21
+
22
+
23
+ def _number(obj: object, name: str, *, positive: bool = False) -> None:
24
+ value = finite_scalar(getattr(obj, name), name)
25
+ if value < 0 or (positive and value == 0):
26
+ raise ValueError(f"{name} must be {'positive' if positive else 'nonnegative'}")
27
+ object.__setattr__(obj, name, value)
28
+
29
+
30
+ def _text(value: object, name: str) -> None:
31
+ if not isinstance(value, str) or not value.strip():
32
+ raise ValueError(f"{name} must be a nonempty string")
33
+
34
+
35
+ def _instance(value: object, cls: type | tuple[type, ...], name: str) -> None:
36
+ if not isinstance(value, cls):
37
+ raise ValueError(f"Invalid {name} type")
38
+
39
+
40
+ def _sha(value: object, name: str) -> None:
41
+ if not isinstance(value, str) or re.fullmatch(r"[0-9a-f]{64}", value) is None:
42
+ raise ValueError(f"{name} must be a lowercase SHA-256 hex digest")
43
+
44
+
45
+ def _canonical(data: object) -> str:
46
+ return json.dumps(data, sort_keys=True, separators=(",", ":"), allow_nan=False)
47
+
48
+
49
+ def _json_object(payload: str) -> dict[str, Any]:
50
+ def unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
51
+ result: dict[str, Any] = {}
52
+ for key, value in pairs:
53
+ if key in result:
54
+ raise ValueError(f"Duplicate JSON field: {key}")
55
+ result[key] = value
56
+ return result
57
+
58
+ data = json.loads(payload, object_pairs_hook=unique)
59
+ if not isinstance(data, dict):
60
+ raise ValueError("Configuration must be a JSON object")
61
+ return data
62
+
63
+
64
+ @dataclass(frozen=True, slots=True, kw_only=True)
65
+ class Species:
66
+ """Solute identity; mass basis is kg of this solute, never inferred ppm."""
67
+
68
+ name: str
69
+ molar_mass_kg_mol: float | None = None
70
+
71
+ def __post_init__(self) -> None:
72
+ _text(self.name, "name")
73
+ if self.molar_mass_kg_mol is not None:
74
+ _number(self, "molar_mass_kg_mol", positive=True)
75
+
76
+
77
+ @dataclass(frozen=True, slots=True, kw_only=True)
78
+ class BlendComponent:
79
+ """One arbitrary adsorbent component, expressed as a dry mass fraction."""
80
+
81
+ material_id: str
82
+ dry_mass_fraction: float
83
+
84
+ def __post_init__(self) -> None:
85
+ _text(self.material_id, "material_id")
86
+ _number(self, "dry_mass_fraction", positive=True)
87
+ if self.dry_mass_fraction > 1:
88
+ raise ValueError("dry_mass_fraction cannot exceed one")
89
+
90
+
91
+ @dataclass(frozen=True, slots=True, kw_only=True)
92
+ class AdsorbentBlend:
93
+ """Recipe metadata only; no mixing law for equilibrium/kinetics is assumed."""
94
+
95
+ name: str
96
+ components: tuple[BlendComponent, ...]
97
+
98
+ def __post_init__(self) -> None:
99
+ _text(self.name, "name")
100
+ if not isinstance(self.components, (tuple, list)) or not self.components:
101
+ raise ValueError("components must be a nonempty sequence")
102
+ for component in self.components:
103
+ _instance(component, BlendComponent, "component")
104
+ ids = [c.material_id for c in self.components]
105
+ if len(set(ids)) != len(ids):
106
+ raise ValueError("Blend material identifiers must be unique")
107
+ if not math.isclose(
108
+ sum(c.dry_mass_fraction for c in self.components), 1, abs_tol=1e-9, rel_tol=0
109
+ ):
110
+ raise ValueError("Dry mass fractions must sum to one")
111
+ object.__setattr__(self, "components", tuple(self.components))
112
+
113
+ def to_json(self) -> str:
114
+ """Serialize recipe provenance; supply fitted properties separately."""
115
+ return _canonical(asdict(self))
116
+
117
+
118
+ @dataclass(frozen=True, slots=True, kw_only=True)
119
+ class Bed:
120
+ """Uniform cylindrical bed. Density is dry mass/apparent particle volume."""
121
+
122
+ length_m: float
123
+ diameter_m: float
124
+ particle_diameter_m: float
125
+ porosity: float
126
+ particle_density_kg_m3: float
127
+ material: str
128
+ mass_basis: Literal["dry"] = "dry"
129
+
130
+ def __post_init__(self) -> None:
131
+ for name in ("length_m", "diameter_m", "particle_diameter_m", "particle_density_kg_m3"):
132
+ _number(self, name, positive=True)
133
+ _number(self, "porosity", positive=True)
134
+ if self.porosity >= 1:
135
+ raise ValueError("porosity must lie strictly between zero and one")
136
+ _text(self.material, "material")
137
+ if self.mass_basis != "dry":
138
+ raise ValueError("Schema v1 supports dry adsorbent mass only")
139
+ if self.particle_diameter_m >= min(self.length_m, self.diameter_m):
140
+ raise ValueError("Particle diameter must be smaller than bed dimensions")
141
+
142
+ @classmethod
143
+ def from_quantities(
144
+ cls,
145
+ *,
146
+ length: pint.Quantity[Any],
147
+ diameter: pint.Quantity[Any],
148
+ particle_diameter: pint.Quantity[Any],
149
+ porosity: float,
150
+ particle_density: pint.Quantity[Any],
151
+ material: str,
152
+ ) -> Bed:
153
+ """Normalize dimensional inputs to SI; porosity is a scalar fraction."""
154
+ return cls(
155
+ length_m=to_si(length, "m"),
156
+ diameter_m=to_si(diameter, "m"),
157
+ particle_diameter_m=to_si(particle_diameter, "m"),
158
+ porosity=porosity,
159
+ particle_density_kg_m3=to_si(particle_density, "kg/m^3"),
160
+ material=material,
161
+ )
162
+
163
+ @property
164
+ def bulk_density_kg_m3(self) -> float:
165
+ """Dry mass per total bed volume."""
166
+ return (1 - self.porosity) * self.particle_density_kg_m3
167
+
168
+ @property
169
+ def volume_m3(self) -> float:
170
+ """Total bed volume, including interparticle voids."""
171
+ return math.pi * self.diameter_m**2 * self.length_m / 4
172
+
173
+
174
+ @dataclass(frozen=True, slots=True, kw_only=True)
175
+ class Operation:
176
+ """Constant inlet/flow, uniform initial fields, no thermal equation."""
177
+
178
+ flow_m3_s: float
179
+ inlet_concentration_kg_m3: float
180
+ duration_s: float
181
+ temperature_k: float = 298.15
182
+ axial_dispersion_m2_s: float = 0.0
183
+ initial_concentration_kg_m3: float = 0.0
184
+ initial_loading_kg_kg: float = 0.0
185
+
186
+ def __post_init__(self) -> None:
187
+ for name in ("flow_m3_s", "duration_s", "temperature_k"):
188
+ _number(self, name, positive=True)
189
+ for name in (
190
+ "inlet_concentration_kg_m3",
191
+ "axial_dispersion_m2_s",
192
+ "initial_concentration_kg_m3",
193
+ "initial_loading_kg_kg",
194
+ ):
195
+ _number(self, name)
196
+
197
+ @classmethod
198
+ def from_quantities(
199
+ cls,
200
+ *,
201
+ flow: pint.Quantity[Any],
202
+ inlet_concentration: pint.Quantity[Any],
203
+ duration: pint.Quantity[Any],
204
+ temperature: pint.Quantity[Any],
205
+ ) -> Operation:
206
+ """Construct the common clean-bed case using explicit dimensional inputs."""
207
+ return cls(
208
+ flow_m3_s=to_si(flow, "m^3/s"),
209
+ inlet_concentration_kg_m3=to_si(inlet_concentration, "kg/m^3"),
210
+ duration_s=to_si(duration, "s"),
211
+ temperature_k=to_si(temperature, "K"),
212
+ )
213
+
214
+
215
+ @dataclass(frozen=True, slots=True, kw_only=True)
216
+ class Langmuir:
217
+ """Parameter contract only: q*=qmax*b*c/(1+b*c), dry mass basis."""
218
+
219
+ qmax_kg_kg: float
220
+ affinity_m3_kg: float
221
+ kind: Literal["langmuir"] = field(default="langmuir", init=False)
222
+
223
+ def __post_init__(self) -> None:
224
+ _number(self, "qmax_kg_kg", positive=True)
225
+ _number(self, "affinity_m3_kg", positive=True)
226
+
227
+
228
+ @dataclass(frozen=True, slots=True, kw_only=True)
229
+ class Freundlich:
230
+ """Normalized contract q*=q_ref*(c/c_ref)**exponent, no hidden units of K_F."""
231
+
232
+ q_ref_kg_kg: float
233
+ c_ref_kg_m3: float
234
+ exponent: float
235
+ kind: Literal["freundlich"] = field(default="freundlich", init=False)
236
+
237
+ def __post_init__(self) -> None:
238
+ for name in ("q_ref_kg_kg", "c_ref_kg_m3", "exponent"):
239
+ _number(self, name, positive=True)
240
+
241
+
242
+ @dataclass(frozen=True, slots=True, kw_only=True)
243
+ class Linear:
244
+ """Linear equilibrium q*=K*c; K=0 is the nonadsorbing tracer reference."""
245
+
246
+ distribution_m3_kg: float
247
+ kind: Literal["linear"] = field(default="linear", init=False)
248
+
249
+ def __post_init__(self) -> None:
250
+ _number(self, "distribution_m3_kg")
251
+
252
+
253
+ @dataclass(frozen=True, slots=True, kw_only=True)
254
+ class LDF:
255
+ """Effective overall rate. It must not be interpreted as film coefficient."""
256
+
257
+ rate_s_inv: float
258
+ kind: Literal["ldf"] = field(default="ldf", init=False)
259
+
260
+ def __post_init__(self) -> None:
261
+ _number(self, "rate_s_inv", positive=True)
262
+
263
+
264
+ @dataclass(frozen=True, slots=True, kw_only=True)
265
+ class HSDM:
266
+ """Future surface diffusion plus film parameter contract; no solver attached."""
267
+
268
+ surface_diffusivity_m2_s: float
269
+ film_coefficient_m_s: float
270
+ kind: Literal["hsdm"] = field(default="hsdm", init=False)
271
+
272
+ def __post_init__(self) -> None:
273
+ _number(self, "surface_diffusivity_m2_s", positive=True)
274
+ _number(self, "film_coefficient_m_s", positive=True)
275
+
276
+
277
+ T = TypeVar("T")
278
+
279
+
280
+ def _construct(cls: type[T], data: object) -> T:
281
+ if not isinstance(data, dict):
282
+ raise ValueError(f"{cls.__name__} must be an object")
283
+ allowed = {f.name for f in fields(cls) if f.init} # type: ignore[arg-type]
284
+ if set(data) - allowed:
285
+ raise ValueError(f"Unknown {cls.__name__} fields: {set(data) - allowed}")
286
+ try:
287
+ return cls(**data)
288
+ except TypeError as exc:
289
+ raise ValueError(f"Invalid {cls.__name__} fields") from exc
290
+
291
+
292
+ def _model(data: object, options: dict[str, type[Any]]) -> Any:
293
+ if not isinstance(data, dict) or not isinstance(data.get("kind"), str):
294
+ raise ValueError("Model requires a string kind discriminator")
295
+ kind = data["kind"]
296
+ if kind not in options:
297
+ raise ValueError(f"Unknown model kind: {kind}")
298
+ return _construct(options[kind], {k: v for k, v in data.items() if k != "kind"})
299
+
300
+
301
+ @dataclass(frozen=True, slots=True, kw_only=True)
302
+ class SimulationConfig:
303
+ """Single-species schema v1; deterministic JSON is the public persistence form."""
304
+
305
+ species: Species
306
+ bed: Bed
307
+ operation: Operation
308
+ equilibrium: Langmuir | Freundlich | Linear
309
+ kinetics: LDF | HSDM
310
+ schema_version: int = 1
311
+
312
+ def __post_init__(self) -> None:
313
+ if type(self.schema_version) is not int or self.schema_version != 1:
314
+ raise ValueError("Only integer schema_version=1 is supported")
315
+ for value, cls, name in (
316
+ (self.species, Species, "species"),
317
+ (self.bed, Bed, "bed"),
318
+ (self.operation, Operation, "operation"),
319
+ (self.equilibrium, (Langmuir, Freundlich, Linear), "equilibrium"),
320
+ (self.kinetics, (LDF, HSDM), "kinetics"),
321
+ ):
322
+ _instance(value, cls, name)
323
+ if isinstance(self.equilibrium, Langmuir):
324
+ if self.operation.initial_loading_kg_kg > self.equilibrium.qmax_kg_kg:
325
+ raise ValueError("Initial loading exceeds Langmuir capacity")
326
+
327
+ def to_json(self) -> str:
328
+ """Serialize SI data with stable key order, without NaN or Infinity."""
329
+ return _canonical(asdict(self))
330
+
331
+ @property
332
+ def sha256(self) -> str:
333
+ """Configuration content hash, excluding run timestamps and identifiers."""
334
+ return hashlib.sha256(self.to_json().encode("utf-8")).hexdigest()
335
+
336
+ @classmethod
337
+ def from_json(cls, payload: str) -> SimulationConfig:
338
+ """Load strict version-1 JSON; reject unknown fields and model kinds."""
339
+
340
+ data = _json_object(payload)
341
+ expected = {f.name for f in fields(cls)}
342
+ if set(data) != expected:
343
+ raise ValueError("Configuration fields must match schema v1 exactly")
344
+ return cls(
345
+ species=_construct(Species, data["species"]),
346
+ bed=_construct(Bed, data["bed"]),
347
+ operation=_construct(Operation, data["operation"]),
348
+ equilibrium=_model(
349
+ data["equilibrium"],
350
+ {"langmuir": Langmuir, "freundlich": Freundlich, "linear": Linear},
351
+ ),
352
+ kinetics=_model(data["kinetics"], {"ldf": LDF, "hsdm": HSDM}),
353
+ schema_version=data["schema_version"],
354
+ )
355
+
356
+
357
+ @dataclass(frozen=True, slots=True, kw_only=True)
358
+ class BatchConfig:
359
+ """Closed, perfectly mixed liquid plus dry adsorbent; all fields are SI."""
360
+
361
+ species: Species
362
+ material: str
363
+ liquid_volume_m3: float
364
+ adsorbent_mass_kg: float
365
+ duration_s: float
366
+ initial_concentration_kg_m3: float
367
+ initial_loading_kg_kg: float
368
+ equilibrium: Langmuir | Freundlich | Linear
369
+ kinetics: LDF
370
+ temperature_k: float = 298.15
371
+ schema_version: int = 1
372
+
373
+ def __post_init__(self) -> None:
374
+ _instance(self.species, Species, "species")
375
+ _instance(self.equilibrium, (Langmuir, Freundlich, Linear), "equilibrium")
376
+ _instance(self.kinetics, LDF, "kinetics")
377
+ _text(self.material, "material")
378
+ for name in ("liquid_volume_m3", "adsorbent_mass_kg", "duration_s", "temperature_k"):
379
+ _number(self, name, positive=True)
380
+ for name in ("initial_concentration_kg_m3", "initial_loading_kg_kg"):
381
+ _number(self, name)
382
+ if type(self.schema_version) is not int or self.schema_version != 1:
383
+ raise ValueError("Only integer schema_version=1 is supported")
384
+ if isinstance(self.equilibrium, Langmuir):
385
+ if self.initial_loading_kg_kg > self.equilibrium.qmax_kg_kg:
386
+ raise ValueError("Initial loading exceeds Langmuir capacity")
387
+
388
+ def to_json(self) -> str:
389
+ """Canonical SI problem description, independent of numerical options."""
390
+ return _canonical(asdict(self))
391
+
392
+ @property
393
+ def sha256(self) -> str:
394
+ """SHA-256 of the canonical physical configuration."""
395
+ return hashlib.sha256(self.to_json().encode("utf-8")).hexdigest()
396
+
397
+ @classmethod
398
+ def from_json(cls, payload: str) -> BatchConfig:
399
+ """Read strict batch schema v1, without dropping unknown data."""
400
+ data = _json_object(payload)
401
+ if set(data) != {f.name for f in fields(cls)}:
402
+ raise ValueError("Batch fields must match schema v1 exactly")
403
+ data["species"] = _construct(Species, data["species"])
404
+ data["equilibrium"] = _model(
405
+ data["equilibrium"], {"langmuir": Langmuir, "freundlich": Freundlich, "linear": Linear}
406
+ )
407
+ data["kinetics"] = _model(data["kinetics"], {"ldf": LDF})
408
+ return cls(**data)
409
+
410
+
411
+ @dataclass(frozen=True, slots=True, kw_only=True)
412
+ class Observations:
413
+ """One outlet series; standard deviations refer to concentration measurements.
414
+
415
+ Replicates use separate series. Censored observations need a future schema.
416
+ """
417
+
418
+ experiment_id: str
419
+ species_name: str
420
+ time_s: tuple[float, ...]
421
+ concentration_kg_m3: tuple[float, ...]
422
+ source_sha256: str
423
+ std_kg_m3: tuple[float, ...] | None = None
424
+
425
+ def __post_init__(self) -> None:
426
+ _text(self.experiment_id, "experiment_id")
427
+ _text(self.species_name, "species_name")
428
+ _sha(self.source_sha256, "source_sha256")
429
+ for name in ("time_s", "concentration_kg_m3", "std_kg_m3"):
430
+ values = getattr(self, name)
431
+ if name == "std_kg_m3" and values is None:
432
+ continue
433
+ if not isinstance(values, (tuple, list)):
434
+ raise ValueError(f"{name} must be a sequence")
435
+ normalized = tuple(finite_scalar(v, name) for v in values)
436
+ if any(v < 0 or (name == "std_kg_m3" and v == 0) for v in normalized):
437
+ raise ValueError(f"Invalid {name} range")
438
+ object.__setattr__(self, name, normalized)
439
+ if not self.time_s or len(self.time_s) != len(self.concentration_kg_m3):
440
+ raise ValueError("Nonempty matching time and concentration arrays are required")
441
+ if any(b <= a for a, b in zip(self.time_s, self.time_s[1:], strict=False)):
442
+ raise ValueError("Observation times must strictly increase")
443
+ if self.std_kg_m3 is not None and len(self.std_kg_m3) != len(self.time_s):
444
+ raise ValueError("Standard deviations must match observations")
445
+
446
+
447
+ @dataclass(frozen=True, slots=True, kw_only=True)
448
+ class RunManifest:
449
+ """Manual provenance contract; creation does not execute a simulation."""
450
+
451
+ run_id: str
452
+ created_utc: str
453
+ config_sha256: str
454
+ code_revision: str
455
+ python_version: str
456
+ package_versions: tuple[str, ...]
457
+ seed: int
458
+ input_sha256: tuple[str, ...] = ()
459
+
460
+ def __post_init__(self) -> None:
461
+ _text(self.run_id, "run_id")
462
+ UUID(self.run_id)
463
+ _text(self.created_utc, "created_utc")
464
+ timestamp = datetime.fromisoformat(self.created_utc)
465
+ offset = timestamp.utcoffset()
466
+ if offset is None or offset.total_seconds() != 0:
467
+ raise ValueError("created_utc must include UTC timezone")
468
+ _sha(self.config_sha256, "config_sha256")
469
+ if not isinstance(self.code_revision, str) or (
470
+ self.code_revision != "uncommitted"
471
+ and re.fullmatch(r"[0-9a-f]{7,40}", self.code_revision) is None
472
+ ):
473
+ raise ValueError("code_revision must be a Git hash or 'uncommitted'")
474
+ _text(self.python_version, "python_version")
475
+ if type(self.seed) is not int or self.seed < 0 or self.seed >= 2**64:
476
+ raise ValueError("seed must be an unsigned 64-bit integer")
477
+ for name in ("package_versions", "input_sha256"):
478
+ values = getattr(self, name)
479
+ if not isinstance(values, (tuple, list)):
480
+ raise ValueError(f"{name} must be a sequence")
481
+ for value in values:
482
+ if name == "input_sha256":
483
+ _sha(value, name)
484
+ else:
485
+ _text(value, name)
486
+ if re.fullmatch(r"[A-Za-z0-9_.-]+==[^\s=]+", value) is None:
487
+ raise ValueError("Package versions require name==version")
488
+ if len(set(values)) != len(values):
489
+ raise ValueError(f"Duplicate {name} entries")
490
+ object.__setattr__(self, name, tuple(sorted(values)))
491
+ if not self.package_versions:
492
+ raise ValueError("package_versions must not be empty")
493
+
494
+ def to_json(self) -> str:
495
+ """Return canonical run metadata, suitable for archival."""
496
+ return _canonical(asdict(self))
sorbflow/simulate.py ADDED
@@ -0,0 +1,6 @@
1
+ """Public simulation facade for batch reactors and LDF/HSDM fixed-bed columns."""
2
+
3
+ from .reactors import simulate_batch as batch
4
+ from .reactors import simulate_column as column
5
+
6
+ __all__ = ["batch", "column"]
@@ -0,0 +1,7 @@
1
+ """Numerical options, failures and result contracts."""
2
+
3
+ from .integration import SimulationError
4
+ from .options import SolverOptions
5
+ from .results import SimulationResult, SolverDiagnostics
6
+
7
+ __all__ = ["SimulationError", "SolverOptions", "SimulationResult", "SolverDiagnostics"]