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,174 @@
1
+ """Experimental SI observation operators; no interpolation or fitted transport.
2
+
3
+ An upstream bed-output shift is valid only for a compatible time-invariant bed
4
+ with initial equilibrium/history. This module cannot establish that physics.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Callable, Sequence
9
+ from dataclasses import dataclass
10
+ from typing import Literal
11
+
12
+ from .units import finite_scalar
13
+
14
+ ScalarSignal = Callable[[float], float]
15
+
16
+
17
+ def _positive(value: float, name: str) -> float:
18
+ result = finite_scalar(value, name)
19
+ if result <= 0:
20
+ raise ValueError(f"{name} must be positive")
21
+ return result
22
+
23
+
24
+ def _delay(value: float) -> float:
25
+ result = finite_scalar(value, "delay_s")
26
+ if result < 0:
27
+ raise ValueError("delay_s must be nonnegative")
28
+ return result
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class LiquidSegment:
33
+ """Separate upstream segment; only ideal plug delay and identity implemented."""
34
+
35
+ volume_m3: float
36
+ position: Literal["upstream"] = "upstream"
37
+ model: Literal["plug", "none"] = "plug"
38
+
39
+ def __post_init__(self) -> None:
40
+ volume = finite_scalar(self.volume_m3, "volume_m3")
41
+ if volume < 0 or self.position != "upstream" or self.model not in ("plug", "none"):
42
+ raise ValueError("Require nonnegative volume, upstream position and plug/none model")
43
+ object.__setattr__(self, "volume_m3", volume)
44
+
45
+ def residence_time(self, flow_m3_s: float) -> float:
46
+ """V/Q for the plug model; identity deliberately applies no segment."""
47
+ flow = _positive(flow_m3_s, "flow_m3_s")
48
+ return (finite_scalar(self.volume_m3 / flow, "residence_time")
49
+ if self.model == "plug" else 0.)
50
+
51
+
52
+ @dataclass(frozen=True, slots=True)
53
+ class CollectionWindow:
54
+ """Collection bounds and independently declared integrated liquid volume."""
55
+
56
+ start_s: float
57
+ end_s: float
58
+ volume_m3: float
59
+
60
+ def __post_init__(self) -> None:
61
+ start = finite_scalar(self.start_s, "start_s")
62
+ end = finite_scalar(self.end_s, "end_s")
63
+ volume = _positive(self.volume_m3, "volume_m3")
64
+ if end <= start:
65
+ raise ValueError("Collection window must have positive duration")
66
+ object.__setattr__(self, "start_s", start)
67
+ object.__setattr__(self, "end_s", end)
68
+ object.__setattr__(self, "volume_m3", volume)
69
+
70
+ @property
71
+ def flags(self) -> tuple[str, ...]:
72
+ return ("WINDOW_STARTS_BEFORE_T0",) if self.start_s < 0 else ()
73
+
74
+
75
+ def collection_window(
76
+ time_s: float, volume_m3: float, flow_m3_s: float,
77
+ rule: Literal["mid", "start", "end"] = "mid",
78
+ ) -> CollectionWindow:
79
+ """Constant-Q window; instantaneous observations are deliberately separate."""
80
+ time = finite_scalar(time_s, "time_s")
81
+ duration = finite_scalar(_positive(volume_m3, "volume_m3") /
82
+ _positive(flow_m3_s, "flow_m3_s"), "duration_s")
83
+ if rule not in ("mid", "start", "end"):
84
+ raise ValueError("rule must be mid, start or end; instant is a separate operator")
85
+ left = time - {"start": 0., "mid": .5, "end": 1.}[rule] * duration
86
+ return CollectionWindow(left, left + duration, volume_m3)
87
+
88
+
89
+ @dataclass(frozen=True, slots=True)
90
+ class SampledSignal:
91
+ """Exact sample lookup; missing solver endpoints are errors, never interpolated."""
92
+
93
+ times_s: Sequence[float]
94
+ values: Sequence[float]
95
+
96
+ def __post_init__(self) -> None:
97
+ try:
98
+ times = tuple(finite_scalar(v, "times_s") for v in self.times_s)
99
+ values = tuple(finite_scalar(v, "values") for v in self.values)
100
+ except TypeError as exc:
101
+ raise ValueError("Sample arrays must be one-dimensional sequences") from exc
102
+ if not times or len(times) != len(values):
103
+ raise ValueError("Nonempty matching sample arrays required")
104
+ if any(b <= a for a, b in zip(times, times[1:], strict=False)):
105
+ raise ValueError("Sample times must strictly increase")
106
+ object.__setattr__(self, "times_s", times)
107
+ object.__setattr__(self, "values", values)
108
+
109
+ def __call__(self, time_s: float) -> float:
110
+ time = finite_scalar(time_s, "time_s")
111
+ for sampled_time, value in zip(self.times_s, self.values, strict=True):
112
+ if time == sampled_time:
113
+ return value
114
+ raise ValueError(f"Missing exact sample endpoint: {time}; request it from the solver")
115
+
116
+
117
+ def _shifted_value(
118
+ signal: ScalarSignal, time_s: float, delay_s: float, initially_at_rest: bool,
119
+ history: ScalarSignal | None,
120
+ ) -> float:
121
+ if type(initially_at_rest) is not bool:
122
+ raise ValueError("initially_at_rest must be an explicit boolean")
123
+ if not callable(signal) or (history is not None and not callable(history)):
124
+ raise ValueError("signal and optional history must be callable")
125
+ time = finite_scalar(time_s, "time_s")
126
+ delay = _delay(delay_s)
127
+ shifted = finite_scalar(time - delay, "shifted_time_s")
128
+ if shifted < 0:
129
+ if history is not None:
130
+ return finite_scalar(history(shifted), "history value")
131
+ if initially_at_rest:
132
+ return 0.
133
+ raise ValueError("Negative time requires explicit history or initially_at_rest")
134
+ return finite_scalar(signal(shifted), "signal value")
135
+
136
+
137
+ def plug_delay(
138
+ signal: ScalarSignal, time_s: float, delay_s: float, *,
139
+ initially_at_rest: bool = False, history: ScalarSignal | None = None,
140
+ ) -> float:
141
+ """Delay a prescribed signal; history covers negative times.
142
+
143
+ A nonzero history is allowed. Using this as an upstream bed-output substitution
144
+ additionally requires time invariance and a compatible initial equilibrium;
145
+ those conditions cannot be inferred from this callable.
146
+ """
147
+ return _shifted_value(signal, time_s, delay_s, initially_at_rest, history)
148
+
149
+
150
+ def fraction_average(
151
+ cumulative_mass: ScalarSignal, window: CollectionWindow, *, delay_s: float = 0.,
152
+ initially_at_rest: bool = False, mass_history: ScalarSignal | None = None,
153
+ ) -> float:
154
+ """(M(b-delay)-M(a-delay))/V; endpoint numerical error is retained.
155
+
156
+ M is cumulative solute mass in kg. An additive mass origin cancels. V is actual
157
+ collected volume, not automatically a container capacity. Nonzero delay assumes
158
+ constant Q when shifting bed cumulative mass. For variable Q, use delay_s=0
159
+ with M already integrating the correctly delayed concentration against Q(t),
160
+ and supply the integrated volume. Negative history is explicit; windows are
161
+ never clipped or renormalized. The caller must establish physical validity of
162
+ any upstream-bed substitution (time invariance and compatible initial state).
163
+ initially_at_rest supplies zero prehistory, requiring a consistent zero origin
164
+ of M; otherwise supply mass_history with the same additive origin as M.
165
+ """
166
+ if not isinstance(window, CollectionWindow):
167
+ raise ValueError("window must be CollectionWindow")
168
+ if not callable(cumulative_mass):
169
+ raise ValueError("cumulative_mass must be callable")
170
+ left = _shifted_value(cumulative_mass, window.start_s, delay_s,
171
+ initially_at_rest, mass_history)
172
+ right = _shifted_value(cumulative_mass, window.end_s, delay_s,
173
+ initially_at_rest, mass_history)
174
+ return finite_scalar((right - left) / window.volume_m3, "fraction concentration")
@@ -0,0 +1,5 @@
1
+ """Optional multiobjective orchestration with explicit constraints."""
2
+
3
+ from .nsga2 import Evaluation, OptimizationError, ParetoResult, nsga2
4
+
5
+ __all__ = ["Evaluation", "OptimizationError", "ParetoResult", "nsga2"]
@@ -0,0 +1,161 @@
1
+ """Optional NSGA-II orchestration; the evolutionary engine is pymoo, not FAST."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from importlib.metadata import version
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ from numpy.typing import ArrayLike
13
+
14
+ from .._arrays import FloatArray, real_array
15
+
16
+
17
+ class OptimizationError(RuntimeError):
18
+ """No valid feasible solution, or an invalid objective evaluation."""
19
+
20
+
21
+ @dataclass(frozen=True, slots=True, kw_only=True)
22
+ class Evaluation:
23
+ """All objectives are minimized; normalized inequality constraints satisfy g<=0."""
24
+
25
+ objectives: ArrayLike
26
+ constraints: ArrayLike = ()
27
+
28
+
29
+ @dataclass(frozen=True, slots=True, kw_only=True)
30
+ class ParetoResult:
31
+ decisions_si: FloatArray
32
+ objectives_si: FloatArray
33
+ normalized_constraints: FloatArray
34
+ evaluations: int
35
+ seed: int
36
+ specification_json: str
37
+
38
+ def __post_init__(self) -> None:
39
+ for name in ("decisions_si", "objectives_si", "normalized_constraints"):
40
+ array = np.array(getattr(self, name), dtype=np.float64, copy=True)
41
+ array.setflags(write=False)
42
+ object.__setattr__(self, name, array)
43
+
44
+
45
+ def nsga2(
46
+ evaluate: Callable[[FloatArray], Evaluation],
47
+ lower_bounds_si: ArrayLike,
48
+ upper_bounds_si: ArrayLike,
49
+ *,
50
+ objective_units: tuple[str, ...],
51
+ variable_units: tuple[str, ...],
52
+ problem_id: str,
53
+ seed: int,
54
+ n_constraints: int = 0,
55
+ population_size: int = 80,
56
+ generations: int = 100,
57
+ ) -> ParetoResult:
58
+ """Find a feasible nondominated approximation and re-evaluate every returned point.
59
+
60
+ Requires the optional 'optimize' extra. User supplies units, SI bounds, all
61
+ objectives to minimize, and scaled g<=0 constraints. Use a frozen common set
62
+ of uncertainty scenarios for robust objectives. No global optimum is certified.
63
+ problem_id must reference the versioned evaluator and all fixed physical inputs.
64
+ """
65
+ low, high = (
66
+ real_array(lower_bounds_si, "lower bounds"),
67
+ real_array(upper_bounds_si, "upper bounds"),
68
+ )
69
+ if low.ndim != 1 or not low.size or low.shape != high.shape or np.any(high <= low):
70
+ raise ValueError("Matched nonempty bounds with upper>lower are required")
71
+ if len(variable_units) != low.size or len(objective_units) < 2:
72
+ raise ValueError("Units must name every variable and at least two objectives")
73
+ if any(
74
+ not isinstance(unit, str) or not unit.strip()
75
+ for unit in (*variable_units, *objective_units)
76
+ ):
77
+ raise ValueError("Units must be nonempty strings")
78
+ for name, value, minimum in (
79
+ ("population_size", population_size, 4),
80
+ ("generations", generations, 2),
81
+ ("n_constraints", n_constraints, 0),
82
+ ):
83
+ if type(value) is not int or value < minimum:
84
+ raise ValueError(f"{name} must be an integer >={minimum}")
85
+ if type(seed) is not int or not 0 <= seed < 2**32:
86
+ raise ValueError("seed must be an unsigned 32-bit integer")
87
+ if not isinstance(problem_id, str) or not problem_id.strip():
88
+ raise ValueError("problem_id must identify the versioned physical problem")
89
+ try:
90
+ from pymoo.algorithms.moo.nsga2 import NSGA2
91
+ from pymoo.core.problem import ElementwiseProblem
92
+ from pymoo.optimize import minimize
93
+ except ImportError as exc:
94
+ raise ImportError("Install sorbflow[optimize] to use NSGA-II") from exc
95
+
96
+ def checked(x: FloatArray) -> tuple[FloatArray, FloatArray]:
97
+ output = evaluate(x.copy())
98
+ if not isinstance(output, Evaluation):
99
+ raise OptimizationError("Evaluator must return Evaluation")
100
+ f = real_array(output.objectives, "objectives")
101
+ g = real_array(output.constraints, "constraints")
102
+ if f.shape != (len(objective_units),) or g.shape != (n_constraints,):
103
+ raise OptimizationError("Objective or constraint shape does not match the problem")
104
+ return f, g
105
+
106
+ class Problem(ElementwiseProblem): # type: ignore[misc]
107
+ def __init__(self) -> None:
108
+ super().__init__(
109
+ n_var=low.size,
110
+ n_obj=len(objective_units),
111
+ n_ieq_constr=n_constraints,
112
+ xl=low,
113
+ xu=high,
114
+ )
115
+
116
+ def _evaluate(self, x: FloatArray, out: dict[str, Any], *args: Any, **kwargs: Any) -> None:
117
+ f, g = checked(x)
118
+ out["F"], out["G"] = f, g
119
+
120
+ result = minimize(
121
+ Problem(),
122
+ NSGA2(pop_size=population_size, eliminate_duplicates=True),
123
+ ("n_gen", generations),
124
+ seed=seed,
125
+ verbose=False,
126
+ )
127
+ if result.X is None or result.F is None:
128
+ raise OptimizationError("No feasible nondominated solutions were found")
129
+ decisions = real_array(np.atleast_2d(result.X), "Pareto decisions")
130
+ verified = [checked(x) for x in decisions]
131
+ objectives = np.stack([v[0] for v in verified])
132
+ constraints = np.stack([v[1] for v in verified])
133
+ if np.any(decisions < low) or np.any(decisions > high) or np.any(constraints > 0):
134
+ raise OptimizationError("Returned Pareto points fail physical constraints or bounds")
135
+ if not np.allclose(objectives, result.F, rtol=1e-10, atol=1e-12):
136
+ raise OptimizationError("Evaluator is not repeatable; freeze uncertainty scenarios")
137
+ specification = json.dumps(
138
+ {
139
+ "problem_id": problem_id,
140
+ "seed": seed,
141
+ "algorithm": "pymoo.NSGA2",
142
+ "pymoo_version": version("pymoo"),
143
+ "population_size": population_size,
144
+ "generations": generations,
145
+ "lower_bounds_si": low.tolist(),
146
+ "upper_bounds_si": high.tolist(),
147
+ "variable_units": variable_units,
148
+ "objective_units": objective_units,
149
+ "n_constraints": n_constraints,
150
+ },
151
+ sort_keys=True,
152
+ allow_nan=False,
153
+ )
154
+ return ParetoResult(
155
+ decisions_si=decisions,
156
+ objectives_si=objectives,
157
+ normalized_constraints=constraints,
158
+ evaluations=int(result.algorithm.evaluator.n_eval) + len(verified),
159
+ seed=seed,
160
+ specification_json=specification,
161
+ )
sorbflow/optimize.py ADDED
@@ -0,0 +1,5 @@
1
+ """Public multiobjective API. The NSGA-II engine is an optional dependency."""
2
+
3
+ from .optimization.nsga2 import Evaluation, OptimizationError, ParetoResult, nsga2
4
+
5
+ __all__ = ["Evaluation", "OptimizationError", "ParetoResult", "nsga2"]
sorbflow/py.typed ADDED
File without changes
@@ -0,0 +1,6 @@
1
+ """Single-solute aqueous LDF reactor implementations."""
2
+
3
+ from .batch import simulate_batch
4
+ from .column import simulate_column
5
+
6
+ __all__ = ["simulate_batch", "simulate_column"]
@@ -0,0 +1,58 @@
1
+ """Sparse derivative of the existing upwind finite-volume LDF column equations."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ from scipy.sparse import csc_matrix
6
+
7
+ from .._arrays import FloatArray
8
+ from ..equilibrium import isotherm_from_parameters
9
+ from ..schemas import LDF, Langmuir, Linear, SimulationConfig
10
+ from ..units import finite_scalar
11
+
12
+
13
+ class LDFColumnJacobian:
14
+ """Precomputed CSC structure; no change to fluxes, states or boundary conditions.
15
+
16
+ State order is c[0:N], q[0:N], inlet mass, outlet mass. For the odd extension
17
+ used by trial_loading, its slope is q_star_prime(abs(c)), also at zero for
18
+ the supported Langmuir and Linear models. Freundlich is intentionally absent.
19
+ """
20
+
21
+ def __init__(self, config: SimulationConfig, cells: int) -> None:
22
+ if (not isinstance(config, SimulationConfig)
23
+ or not isinstance(config.kinetics, LDF)
24
+ or not isinstance(config.equilibrium, (Langmuir, Linear))):
25
+ raise ValueError("Analytic Jacobian supports LDF with Langmuir or Linear only")
26
+ if type(cells) is not int or cells < 2:
27
+ raise ValueError("cells must be an integer >=2")
28
+ bed, operation = config.bed, config.operation
29
+ self.cells = cells
30
+ self.rate = config.kinetics.rate_s_inv
31
+ self.model = isotherm_from_parameters(config.equilibrium)
32
+ self.rho_over_epsilon = bed.bulk_density_kg_m3 / bed.porosity
33
+ dz = bed.length_m / cells
34
+ area = finite_scalar(bed.volume_m3 / bed.length_m, "cross-sectional area")
35
+ v = finite_scalar(operation.flow_m3_s / area, "superficial velocity")
36
+ epsilon, dispersion = bed.porosity, operation.axial_dispersion_m2_s
37
+ i = np.arange(cells)
38
+ rows = np.concatenate((i[1:], i, i[:-1], i, cells+i, cells+i, [2*cells+1]))
39
+ cols = np.concatenate((i[:-1], i, i[1:], cells+i, i, cells+i, [cells-1]))
40
+ self.order = np.lexsort((rows, cols))
41
+ self.rows = rows[self.order]
42
+ self.indptr = np.concatenate(([0], np.cumsum(np.bincount(cols, minlength=2*cells+2))))
43
+ self.sub = np.full(cells-1, (v + epsilon*dispersion/dz)/(epsilon*dz))
44
+ self.sup = np.full(cells-1, dispersion/dz**2)
45
+ incoming = np.where(i >= 1, -epsilon*dispersion/dz, 0.)
46
+ outgoing = np.where(i+1 < cells, v + epsilon*dispersion/dz, v)
47
+ self.transport = (incoming-outgoing)/(epsilon*dz)
48
+ self.cq = np.full(cells, self.rho_over_epsilon*self.rate)
49
+ self.qq = np.full(cells, -self.rate)
50
+ self.mass = np.array([operation.flow_m3_s])
51
+
52
+ def __call__(self, _time: float, state: FloatArray) -> csc_matrix:
53
+ slope = self.model.derivative(np.abs(state[:self.cells]))
54
+ diag = self.transport - self.rho_over_epsilon*self.rate*slope
55
+ data = np.concatenate((self.sub, diag, self.sup, self.cq,
56
+ self.rate*slope, self.qq, self.mass))
57
+ return csc_matrix((data[self.order], self.rows, self.indptr),
58
+ shape=(2*self.cells+2, 2*self.cells+2))
@@ -0,0 +1,87 @@
1
+ """Closed batch balance with a shared, conservative LDF mass source."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from numpy.typing import ArrayLike
7
+
8
+ from .._arrays import FloatArray
9
+ from ..equilibrium import isotherm_from_parameters
10
+ from ..equilibrium.isotherms import trial_loading
11
+ from ..schemas import BatchConfig
12
+ from ..solvers.integration import integrate
13
+ from ..solvers.options import SolverOptions, sample_times
14
+ from ..solvers.results import SimulationResult, check_physics, result_metadata
15
+ from ..units import finite_scalar
16
+
17
+
18
+ def simulate_batch(
19
+ config: BatchConfig,
20
+ *,
21
+ time_s: ArrayLike | None = None,
22
+ options: SolverOptions | None = None,
23
+ code_revision: str = "uncommitted",
24
+ ) -> SimulationResult:
25
+ """Integrate c and q for a closed, single-solute, isothermal batch.
26
+
27
+ Tolerances use physical SI units. Internal accepted states are checked for
28
+ nonnegativity and mass conservation before any success result is returned.
29
+ """
30
+ if not isinstance(config, BatchConfig):
31
+ raise ValueError("config must be a BatchConfig")
32
+ settings = SolverOptions() if options is None else options
33
+ if not isinstance(settings, SolverOptions):
34
+ raise ValueError("options must be SolverOptions")
35
+ times = sample_times(config.duration_s, time_s)
36
+ options_json, fingerprint, manifest = result_metadata(
37
+ config.to_json(), times, settings, "batch", code_revision
38
+ )
39
+ model = isotherm_from_parameters(config.equilibrium)
40
+ ratio = finite_scalar(config.adsorbent_mass_kg / config.liquid_volume_m3, "mass/volume")
41
+ initial = np.array([config.initial_concentration_kg_m3, config.initial_loading_kg_kg])
42
+ initial_mass = finite_scalar(
43
+ config.liquid_volume_m3 * initial[0] + config.adsorbent_mass_kg * initial[1], "initial_mass"
44
+ )
45
+
46
+ def rhs(_time: float, state: FloatArray) -> FloatArray:
47
+ source = config.kinetics.rate_s_inv * (trial_loading(model, state[:1])[0] - state[1])
48
+ return np.array([-ratio * source, source])
49
+
50
+ solution = integrate(
51
+ rhs,
52
+ initial,
53
+ times,
54
+ np.array([settings.atol_concentration_kg_m3, settings.atol_loading_kg_kg]),
55
+ settings,
56
+ )
57
+ checked = solution.checkpoints
58
+ inventory_checked = config.liquid_volume_m3 * checked[0] + config.adsorbent_mass_kg * checked[1]
59
+ diagnostics = check_physics(
60
+ checked[0],
61
+ checked[1],
62
+ inventory_checked,
63
+ np.zeros(checked.shape[1]),
64
+ np.zeros(checked.shape[1]),
65
+ initial_mass,
66
+ settings,
67
+ solution,
68
+ )
69
+ c, q = solution.samples
70
+ inventory = config.liquid_volume_m3 * c + config.adsorbent_mass_kg * q
71
+ zeros = np.zeros(times.size)
72
+ return SimulationResult(
73
+ reactor="batch",
74
+ time_s=times,
75
+ concentration_kg_m3=c[:, None],
76
+ loading_kg_kg=q[:, None],
77
+ inventory_kg=inventory,
78
+ inlet_mass_kg=zeros,
79
+ outlet_mass_kg=zeros,
80
+ mass_residual_kg=inventory - initial_mass,
81
+ z_m=None,
82
+ config_json=config.to_json(),
83
+ options_json=options_json,
84
+ numerical_sha256=fingerprint,
85
+ manifest=manifest,
86
+ diagnostics=diagnostics,
87
+ )
@@ -0,0 +1,151 @@
1
+ """Conservative method-of-lines fixed-bed LDF model, independent of FAST."""
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 ..equilibrium.isotherms import trial_loading
12
+ from ..schemas import LDF, Langmuir, Linear, SimulationConfig
13
+ from ..solvers.integration import integrate, integrate_streaming
14
+ from ..solvers.options import SolverOptions, sample_times
15
+ from ..solvers.results import SimulationResult, StreamingPhysics, check_physics, result_metadata
16
+ from ..units import finite_scalar
17
+ from ._ldf_jacobian import LDFColumnJacobian
18
+
19
+
20
+ def _jacobian_pattern(cells: int) -> csc_matrix:
21
+ rows: list[int] = []
22
+ cols: list[int] = []
23
+ for i in range(cells):
24
+ for j in range(max(0, i - 1), min(cells, i + 2)):
25
+ rows.append(i)
26
+ cols.append(j)
27
+ rows.extend((i, cells + i, cells + i))
28
+ cols.extend((cells + i, i, cells + i))
29
+ rows.append(2 * cells + 1)
30
+ cols.append(cells - 1)
31
+ return csc_matrix((np.ones(len(rows)), (rows, cols)), shape=(2 * cells + 2, 2 * cells + 2))
32
+
33
+
34
+ def simulate_column(
35
+ config: SimulationConfig,
36
+ *,
37
+ time_s: ArrayLike | None = None,
38
+ options: SolverOptions | None = None,
39
+ code_revision: str = "uncommitted",
40
+ ) -> SimulationResult:
41
+ """Solve a uniform aqueous column using upwind FV, dispersion and LDF.
42
+
43
+ Constant positive flow/inlet, dry mass basis, one solute and fixed T only.
44
+ HSDM dispatches to its radial solver; it is never replaced by LDF.
45
+ """
46
+ if not isinstance(config, SimulationConfig):
47
+ raise ValueError("config must be a SimulationConfig")
48
+ settings = SolverOptions() if options is None else options
49
+ if not isinstance(settings, SolverOptions):
50
+ raise ValueError("options must be SolverOptions")
51
+ if settings.jacobian == "analytic" and (
52
+ not isinstance(config.kinetics, LDF)
53
+ or not isinstance(config.equilibrium, (Langmuir, Linear))
54
+ ):
55
+ raise ValueError("Analytic Jacobian supports only LDF with Langmuir or Linear")
56
+ if settings.history == "streaming" and not isinstance(config.kinetics, LDF):
57
+ raise ValueError("Streaming history supports LDF columns only")
58
+ if not isinstance(config.kinetics, LDF):
59
+ from .hsdm import simulate_hsdm_column
60
+
61
+ return simulate_hsdm_column(
62
+ config, time_s=time_s, options=options, code_revision=code_revision
63
+ )
64
+ times = sample_times(config.operation.duration_s, time_s)
65
+ options_json, fingerprint, manifest = result_metadata(
66
+ config.to_json(), times, settings, "column", code_revision
67
+ )
68
+ bed, op = config.bed, config.operation
69
+ cells = settings.axial_cells
70
+ dz = bed.length_m / cells
71
+ area = finite_scalar(bed.volume_m3 / bed.length_m, "cross-sectional area")
72
+ velocity = finite_scalar(op.flow_m3_s / area, "superficial velocity")
73
+ epsilon, rho_b = bed.porosity, bed.bulk_density_kg_m3
74
+ model = isotherm_from_parameters(config.equilibrium)
75
+ rate = config.kinetics.rate_s_inv
76
+ initial = np.concatenate(
77
+ (
78
+ np.full(cells, op.initial_concentration_kg_m3),
79
+ np.full(cells, op.initial_loading_kg_kg),
80
+ np.zeros(2),
81
+ )
82
+ )
83
+ initial_mass = finite_scalar(
84
+ bed.volume_m3
85
+ * (epsilon * op.initial_concentration_kg_m3 + rho_b * op.initial_loading_kg_kg),
86
+ "initial mass",
87
+ )
88
+
89
+ def rhs(_time: float, state: FloatArray) -> FloatArray:
90
+ c, q = state[:cells], state[cells : 2 * cells]
91
+ source = rate * (trial_loading(model, c) - q)
92
+ flux = np.empty(cells + 1)
93
+ flux[0] = velocity * op.inlet_concentration_kg_m3
94
+ flux[1:cells] = velocity * c[:-1] - epsilon * op.axial_dispersion_m2_s * np.diff(c) / dz
95
+ flux[cells] = velocity * c[-1]
96
+ dc = -np.diff(flux) / (epsilon * dz) - (rho_b / epsilon) * source
97
+ return np.concatenate(
98
+ (dc, source, [op.flow_m3_s * op.inlet_concentration_kg_m3, op.flow_m3_s * c[-1]])
99
+ )
100
+
101
+ atol = np.concatenate(
102
+ (
103
+ np.full(cells, settings.atol_concentration_kg_m3),
104
+ np.full(cells, settings.atol_loading_kg_kg),
105
+ np.full(2, settings.atol_mass_kg),
106
+ )
107
+ )
108
+ jac = LDFColumnJacobian(config, cells) if settings.jacobian == "analytic" else None
109
+
110
+ def inventory(states: FloatArray) -> FloatArray:
111
+ return np.asarray(
112
+ area
113
+ * dz
114
+ * (
115
+ epsilon * np.sum(states[:cells], axis=0)
116
+ + rho_b * np.sum(states[cells : 2 * cells], axis=0)
117
+ )
118
+ )
119
+
120
+ if settings.history == "streaming":
121
+ physics = StreamingPhysics(cells=cells, area=area, dz=dz, epsilon=epsilon,
122
+ rho_b=rho_b, initial_mass=initial_mass, options=settings, n_states=initial.size)
123
+ streamed = integrate_streaming(rhs, initial, times, atol, settings,
124
+ _jacobian_pattern(cells), jac=jac, on_state=physics.push_state)
125
+ sampled = streamed.samples
126
+ physics.push_block(sampled, [("sample", i, float(t)) for i, t in enumerate(times)])
127
+ diagnostics = physics.finalize(streamed.nfev, streamed.njev, streamed.nlu,
128
+ streamed.accepted_steps)
129
+ else:
130
+ solution = integrate(rhs, initial, times, atol, settings, _jacobian_pattern(cells), jac=jac)
131
+ checked = solution.checkpoints
132
+ diagnostics = check_physics(checked[:cells], checked[cells:2*cells], inventory(checked),
133
+ checked[-2], checked[-1], initial_mass, settings, solution)
134
+ sampled = solution.samples
135
+ mass = inventory(sampled)
136
+ return SimulationResult(
137
+ reactor="column",
138
+ time_s=times,
139
+ concentration_kg_m3=sampled[:cells].T,
140
+ loading_kg_kg=sampled[cells : 2 * cells].T,
141
+ inventory_kg=mass,
142
+ inlet_mass_kg=sampled[-2],
143
+ outlet_mass_kg=sampled[-1],
144
+ mass_residual_kg=mass - initial_mass - sampled[-2] + sampled[-1],
145
+ z_m=np.asarray((np.arange(cells, dtype=np.float64) + 0.5) * dz),
146
+ config_json=config.to_json(),
147
+ options_json=options_json,
148
+ numerical_sha256=fingerprint,
149
+ manifest=manifest,
150
+ diagnostics=diagnostics,
151
+ )