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
sorbflow/units.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Scalar unit boundary: explicit physical units in, finite SI magnitudes out."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from numbers import Real
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import pint
|
|
10
|
+
|
|
11
|
+
_REGISTRY: pint.UnitRegistry[Any] = pint.UnitRegistry()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class UnitError(ValueError):
|
|
15
|
+
"""A value has missing, unknown or incompatible physical units."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def finite_scalar(value: object, name: str) -> float:
|
|
19
|
+
"""Reject booleans, non-real values, arrays and non-finite magnitudes."""
|
|
20
|
+
if isinstance(value, bool) or not isinstance(value, Real):
|
|
21
|
+
raise ValueError(f"{name} must be a finite real scalar")
|
|
22
|
+
result = float(value)
|
|
23
|
+
if not math.isfinite(result):
|
|
24
|
+
raise ValueError(f"{name} must be finite")
|
|
25
|
+
return result
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def quantity(value: float, unit: str) -> pint.Quantity[Any]:
|
|
29
|
+
"""Create a finite scalar quantity, including offset units such as degC.
|
|
30
|
+
|
|
31
|
+
This is the public quantity factory. No mutable registry is exposed.
|
|
32
|
+
"""
|
|
33
|
+
magnitude = finite_scalar(value, "value")
|
|
34
|
+
if not isinstance(unit, str) or not unit.strip():
|
|
35
|
+
raise UnitError("unit must be an explicit nonempty unit string")
|
|
36
|
+
try:
|
|
37
|
+
return _REGISTRY.Quantity(magnitude, unit)
|
|
38
|
+
except (pint.UndefinedUnitError, ValueError, TypeError) as exc:
|
|
39
|
+
raise UnitError(f"Invalid unit: {unit}") from exc
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def to_si(value: pint.Quantity[Any], target_unit: str) -> float:
|
|
43
|
+
"""Convert a scalar quantity to a caller-declared SI unit.
|
|
44
|
+
|
|
45
|
+
The function does not infer chemical species, dry/wet basis, ppm or molar mass.
|
|
46
|
+
"""
|
|
47
|
+
if not isinstance(value, pint.Quantity):
|
|
48
|
+
raise UnitError("A quantity with explicit units is required")
|
|
49
|
+
try:
|
|
50
|
+
converted = value.to(target_unit)
|
|
51
|
+
except (pint.DimensionalityError, pint.UndefinedUnitError) as exc:
|
|
52
|
+
raise UnitError(f"Expected units compatible with {target_unit}") from exc
|
|
53
|
+
return finite_scalar(converted.magnitude, "magnitude")
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Numerical diagnostics: mass balance and state checks of simulation results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from ..solvers import SimulationResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True)
|
|
14
|
+
class MassBalanceReport:
|
|
15
|
+
max_absolute_residual_kg: float
|
|
16
|
+
max_scaled_residual: float
|
|
17
|
+
passed: bool
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def mass_balance(result: SimulationResult) -> MassBalanceReport:
|
|
21
|
+
"""Recompute mass closure from exported time samples; internal checks are separate."""
|
|
22
|
+
settings = json.loads(result.options_json)
|
|
23
|
+
residual = (
|
|
24
|
+
result.inventory_kg - result.inventory_kg[0] - result.inlet_mass_kg + result.outlet_mass_kg
|
|
25
|
+
)
|
|
26
|
+
scale = np.maximum(
|
|
27
|
+
np.maximum(result.inventory_kg[0], result.inlet_mass_kg), settings["mass_reference_kg"]
|
|
28
|
+
)
|
|
29
|
+
passed = bool(
|
|
30
|
+
np.all(np.abs(residual) <= settings["atol_mass_kg"] + settings["mass_rtol"] * scale)
|
|
31
|
+
and np.all(np.abs(residual) / scale <= settings["mass_rtol"])
|
|
32
|
+
)
|
|
33
|
+
return MassBalanceReport(
|
|
34
|
+
float(np.max(np.abs(residual))), float(np.max(np.abs(residual) / scale)), passed
|
|
35
|
+
)
|
sorbflow/web/__init__.py
ADDED
sorbflow/web/__main__.py
ADDED
sorbflow/web/app.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""Bounded local jobs, with an isolated process per simulation and immutable outputs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import multiprocessing
|
|
7
|
+
import re
|
|
8
|
+
import secrets
|
|
9
|
+
import stat
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
import traceback
|
|
13
|
+
from dataclasses import asdict, dataclass
|
|
14
|
+
from datetime import UTC, datetime
|
|
15
|
+
from multiprocessing.process import BaseProcess
|
|
16
|
+
from multiprocessing.queues import Queue
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from queue import Empty
|
|
19
|
+
from typing import Any, Literal
|
|
20
|
+
from uuid import uuid4
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
from ..io import export_result
|
|
25
|
+
from ..schemas import BatchConfig, SimulationConfig
|
|
26
|
+
from ..simulate import batch, column
|
|
27
|
+
from .config import MAX_JOBS, SCIENTIFIC_STATUS, RequestSpec
|
|
28
|
+
|
|
29
|
+
_JOB_ID = re.compile(r"[0-9a-f]{32}\Z")
|
|
30
|
+
_FILES = {
|
|
31
|
+
"result.json": "results/result.json",
|
|
32
|
+
"timeseries.csv": "results/timeseries.csv",
|
|
33
|
+
"files.sha256.json": "results/files.sha256.json",
|
|
34
|
+
"input.json": "job_input.json",
|
|
35
|
+
"summary.json": "web_summary.json",
|
|
36
|
+
"job.log": "job.log",
|
|
37
|
+
}
|
|
38
|
+
_RESULT_FILES = {"result.json", "timeseries.csv", "files.sha256.json"}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BusyError(RuntimeError):
|
|
42
|
+
"""The local UI's concurrency or session limit has been reached."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _now() -> str:
|
|
46
|
+
return datetime.now(UTC).isoformat()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def guarded_output_root(path: str | Path) -> Path:
|
|
50
|
+
"""Reject protected names and reparse points before creating any run directories."""
|
|
51
|
+
absolute = Path(path).absolute()
|
|
52
|
+
protected = {".git", "src", "datasets_benchmark_pyfast"}
|
|
53
|
+
if any(part.casefold() in protected for part in absolute.parts):
|
|
54
|
+
raise ValueError("GUI outputs must be outside src, .git and raw dataset directories")
|
|
55
|
+
for candidate in (absolute, *absolute.parents):
|
|
56
|
+
if candidate.is_symlink():
|
|
57
|
+
raise ValueError("Linked output paths are not supported")
|
|
58
|
+
if candidate.exists():
|
|
59
|
+
attributes = getattr(candidate.lstat(), "st_file_attributes", 0)
|
|
60
|
+
if attributes & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400):
|
|
61
|
+
raise ValueError("Reparse-point output paths are not supported")
|
|
62
|
+
if absolute.exists() and not absolute.is_dir():
|
|
63
|
+
raise ValueError("Output root must be a directory")
|
|
64
|
+
return absolute.resolve()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _worker(spec: RequestSpec, job_folder: str, channel: Queue[dict[str, Any]]) -> None:
|
|
68
|
+
"""Only package APIs and validated data are invoked; never shell commands or user code."""
|
|
69
|
+
try:
|
|
70
|
+
times = np.linspace(0, spec.duration_s, spec.samples)
|
|
71
|
+
if spec.reactor == "batch":
|
|
72
|
+
result = batch(
|
|
73
|
+
BatchConfig.from_json(spec.config_json), time_s=times, options=spec.options
|
|
74
|
+
)
|
|
75
|
+
else:
|
|
76
|
+
result = column(
|
|
77
|
+
SimulationConfig.from_json(spec.config_json), time_s=times, options=spec.options
|
|
78
|
+
)
|
|
79
|
+
folder = guarded_output_root(Path(job_folder).parent) / Path(job_folder).name
|
|
80
|
+
if folder.is_symlink() or folder.resolve().parent != guarded_output_root(folder.parent):
|
|
81
|
+
raise ValueError("Invalid job output directory")
|
|
82
|
+
export_result(result, folder / "results")
|
|
83
|
+
channel.put(
|
|
84
|
+
{
|
|
85
|
+
"ok": True,
|
|
86
|
+
"numerical_sha256": result.numerical_sha256,
|
|
87
|
+
"preview": {
|
|
88
|
+
"time_s": result.time_s.tolist(),
|
|
89
|
+
"outlet_concentration_kg_m3": result.outlet_concentration_kg_m3.tolist(),
|
|
90
|
+
},
|
|
91
|
+
"diagnostics": asdict(result.diagnostics),
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
channel.put({"ok": False, "error": str(exc)[:600], "trace": traceback.format_exc()[-6000:]})
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(slots=True)
|
|
99
|
+
class Job:
|
|
100
|
+
id: str
|
|
101
|
+
reactor: str
|
|
102
|
+
config_sha256: str
|
|
103
|
+
created_utc: str
|
|
104
|
+
status: Literal["queued", "running", "succeeded", "failed", "timed_out"] = "queued"
|
|
105
|
+
finished_utc: str | None = None
|
|
106
|
+
numerical_sha256: str | None = None
|
|
107
|
+
error: str | None = None
|
|
108
|
+
preview: dict[str, Any] | None = None
|
|
109
|
+
diagnostics: dict[str, Any] | None = None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class WebApplication:
|
|
113
|
+
"""One active simulation and at most 50 retained job records per server session.
|
|
114
|
+
|
|
115
|
+
A worker has a hard wall-clock limit. Only that UI-owned process is terminated
|
|
116
|
+
on timeout/shutdown; no process discovery or intervention in other simulations.
|
|
117
|
+
This is a local application, not a multi-user production service.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
def __init__(self, output_root: str | Path, *, job_timeout_s: float = 30.0) -> None:
|
|
121
|
+
if isinstance(job_timeout_s, bool) or not 0 < job_timeout_s <= 120:
|
|
122
|
+
raise ValueError("job_timeout_s must lie within (0,120]")
|
|
123
|
+
self.output_root = guarded_output_root(output_root)
|
|
124
|
+
self.job_timeout_s = float(job_timeout_s)
|
|
125
|
+
self.token = secrets.token_urlsafe(32)
|
|
126
|
+
self.nonce = secrets.token_urlsafe(24)
|
|
127
|
+
self.port = 0
|
|
128
|
+
self._lock = threading.Lock()
|
|
129
|
+
self._jobs: dict[str, Job] = {}
|
|
130
|
+
self._active = False
|
|
131
|
+
self._closed = False
|
|
132
|
+
self._process: BaseProcess | None = None
|
|
133
|
+
self._thread: threading.Thread | None = None
|
|
134
|
+
|
|
135
|
+
def submit(self, spec: RequestSpec) -> dict[str, Any]:
|
|
136
|
+
with self._lock:
|
|
137
|
+
if self._closed or self._active or len(self._jobs) >= MAX_JOBS:
|
|
138
|
+
raise BusyError("One simulation at a time; maximum 50 jobs per session")
|
|
139
|
+
root = guarded_output_root(self.output_root)
|
|
140
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
141
|
+
job = Job(uuid4().hex, spec.reactor, spec.config_sha256, _now())
|
|
142
|
+
folder = root / job.id
|
|
143
|
+
folder.mkdir(exist_ok=False)
|
|
144
|
+
with (folder / "job_input.json").open("x", encoding="utf-8") as stream:
|
|
145
|
+
stream.write(spec.input_json())
|
|
146
|
+
self._jobs[job.id] = job
|
|
147
|
+
self._active = True
|
|
148
|
+
self._thread = threading.Thread(target=self._run, args=(job.id, spec), daemon=True)
|
|
149
|
+
self._thread.start()
|
|
150
|
+
return asdict(job)
|
|
151
|
+
|
|
152
|
+
def _run(self, job_id: str, spec: RequestSpec) -> None:
|
|
153
|
+
context = multiprocessing.get_context("spawn")
|
|
154
|
+
channel: Queue[dict[str, Any]] = context.Queue()
|
|
155
|
+
folder = self.output_root / job_id
|
|
156
|
+
process = context.Process(target=_worker, args=(spec, str(folder), channel), daemon=True)
|
|
157
|
+
status: Literal["succeeded", "failed", "timed_out"] = "failed"
|
|
158
|
+
response: dict[str, Any] = {}
|
|
159
|
+
log = ""
|
|
160
|
+
try:
|
|
161
|
+
with self._lock:
|
|
162
|
+
if self._closed:
|
|
163
|
+
raise RuntimeError("Local server closed before simulation started")
|
|
164
|
+
self._jobs[job_id].status = "running"
|
|
165
|
+
self._process = process
|
|
166
|
+
process.start()
|
|
167
|
+
deadline = time.monotonic() + self.job_timeout_s
|
|
168
|
+
received = False
|
|
169
|
+
# Drain the queue before join: a child's feeder may otherwise block its
|
|
170
|
+
# exit when the preview exceeds the OS pipe buffer (notably on Linux).
|
|
171
|
+
while time.monotonic() < deadline:
|
|
172
|
+
try:
|
|
173
|
+
response = channel.get(timeout=min(0.25, deadline - time.monotonic()))
|
|
174
|
+
received = True
|
|
175
|
+
break
|
|
176
|
+
except Empty:
|
|
177
|
+
if not process.is_alive():
|
|
178
|
+
raise RuntimeError(
|
|
179
|
+
f"Simulation worker exited without a result ({process.exitcode})"
|
|
180
|
+
) from None
|
|
181
|
+
if received:
|
|
182
|
+
process.join(max(0, deadline - time.monotonic()))
|
|
183
|
+
if response.get("ok") is True:
|
|
184
|
+
status = "succeeded"
|
|
185
|
+
if not received or process.is_alive():
|
|
186
|
+
process.terminate()
|
|
187
|
+
process.join(5)
|
|
188
|
+
status = "timed_out"
|
|
189
|
+
response = {"error": "Simulation exceeded the local GUI wall-clock limit"}
|
|
190
|
+
log = (
|
|
191
|
+
"Numerical simulation completed. "
|
|
192
|
+
if status == "succeeded"
|
|
193
|
+
else "Simulation failed. "
|
|
194
|
+
)
|
|
195
|
+
log += SCIENTIFIC_STATUS + "\n" + str(response.get("trace", response.get("error", "")))
|
|
196
|
+
except Exception as exc:
|
|
197
|
+
response = {"error": str(exc)[:600]}
|
|
198
|
+
log = traceback.format_exc()
|
|
199
|
+
finally:
|
|
200
|
+
with self._lock:
|
|
201
|
+
self._process = None
|
|
202
|
+
if process.pid is not None:
|
|
203
|
+
if process.is_alive():
|
|
204
|
+
process.terminate()
|
|
205
|
+
process.join(5)
|
|
206
|
+
process.close()
|
|
207
|
+
channel.close()
|
|
208
|
+
try:
|
|
209
|
+
guarded_output_root(folder)
|
|
210
|
+
with (folder / "job.log").open("x", encoding="utf-8") as stream:
|
|
211
|
+
stream.write(log)
|
|
212
|
+
summary = {
|
|
213
|
+
"id": job_id,
|
|
214
|
+
"status": status,
|
|
215
|
+
"scientific_status": SCIENTIFIC_STATUS,
|
|
216
|
+
"config_sha256": spec.config_sha256,
|
|
217
|
+
"numerical_sha256": response.get("numerical_sha256"),
|
|
218
|
+
"error": response.get("error"),
|
|
219
|
+
"diagnostics": response.get("diagnostics"),
|
|
220
|
+
}
|
|
221
|
+
with (folder / "web_summary.json").open("x", encoding="utf-8") as stream:
|
|
222
|
+
json.dump(summary, stream, ensure_ascii=False, allow_nan=False, indent=2)
|
|
223
|
+
except (OSError, ValueError) as exc:
|
|
224
|
+
status = "failed"
|
|
225
|
+
response["error"] = f"Could not persist local job record: {type(exc).__name__}"
|
|
226
|
+
with self._lock:
|
|
227
|
+
job = self._jobs[job_id]
|
|
228
|
+
job.status, job.finished_utc = status, _now()
|
|
229
|
+
job.error = response.get("error")
|
|
230
|
+
job.preview, job.diagnostics = response.get("preview"), response.get("diagnostics")
|
|
231
|
+
job.numerical_sha256 = response.get("numerical_sha256")
|
|
232
|
+
self._process = None
|
|
233
|
+
self._active = False
|
|
234
|
+
|
|
235
|
+
def get(self, job_id: str) -> dict[str, Any]:
|
|
236
|
+
if _JOB_ID.fullmatch(job_id) is None:
|
|
237
|
+
raise KeyError("Unknown job")
|
|
238
|
+
with self._lock:
|
|
239
|
+
if job_id not in self._jobs:
|
|
240
|
+
raise KeyError("Unknown job")
|
|
241
|
+
return asdict(self._jobs[job_id])
|
|
242
|
+
|
|
243
|
+
def jobs(self) -> list[dict[str, Any]]:
|
|
244
|
+
with self._lock:
|
|
245
|
+
return [
|
|
246
|
+
{
|
|
247
|
+
"id": job.id,
|
|
248
|
+
"status": job.status,
|
|
249
|
+
"reactor": job.reactor,
|
|
250
|
+
"created_utc": job.created_utc,
|
|
251
|
+
}
|
|
252
|
+
for job in reversed(list(self._jobs.values()))
|
|
253
|
+
]
|
|
254
|
+
|
|
255
|
+
def download(self, job_id: str, name: str) -> bytes:
|
|
256
|
+
job = self.get(job_id)
|
|
257
|
+
if name not in _FILES or (name in _RESULT_FILES and job["status"] != "succeeded"):
|
|
258
|
+
raise KeyError("File is not available")
|
|
259
|
+
folder = guarded_output_root(self.output_root / job_id)
|
|
260
|
+
file = folder / _FILES[name]
|
|
261
|
+
guarded_output_root(file.parent)
|
|
262
|
+
if file.is_symlink() or not file.is_file() or file.stat().st_size > 10 * 1024 * 1024:
|
|
263
|
+
raise KeyError("File is not available")
|
|
264
|
+
if getattr(file.lstat(), "st_file_attributes", 0) & 0x400:
|
|
265
|
+
raise KeyError("Linked files are not available")
|
|
266
|
+
data = file.read_bytes()
|
|
267
|
+
if len(data) > 10 * 1024 * 1024:
|
|
268
|
+
raise KeyError("File exceeds local download limit")
|
|
269
|
+
return data
|
|
270
|
+
|
|
271
|
+
def close(self) -> None:
|
|
272
|
+
with self._lock:
|
|
273
|
+
self._closed = True
|
|
274
|
+
process, thread = self._process, self._thread
|
|
275
|
+
if process is not None and process.is_alive():
|
|
276
|
+
process.terminate()
|
|
277
|
+
if thread is not None:
|
|
278
|
+
thread.join(7)
|
sorbflow/web/config.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Strict browser input boundary and deliberately bounded local-GUI defaults."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
from ..schemas import (
|
|
10
|
+
HSDM,
|
|
11
|
+
LDF,
|
|
12
|
+
BatchConfig,
|
|
13
|
+
Bed,
|
|
14
|
+
Freundlich,
|
|
15
|
+
Langmuir,
|
|
16
|
+
Linear,
|
|
17
|
+
Operation,
|
|
18
|
+
SimulationConfig,
|
|
19
|
+
Species,
|
|
20
|
+
)
|
|
21
|
+
from ..solvers import SolverOptions
|
|
22
|
+
|
|
23
|
+
MAX_REQUEST_BYTES = 65536
|
|
24
|
+
MAX_SAMPLES = 401
|
|
25
|
+
MAX_AXIAL_CELLS = 64
|
|
26
|
+
MAX_RADIAL_CELLS = 12
|
|
27
|
+
MAX_DURATION_S = 172800.0
|
|
28
|
+
MAX_JOBS = 50
|
|
29
|
+
SCIENTIFIC_STATUS = (
|
|
30
|
+
"SorbFlow: simulación numérica de adsorción con unidades SI, "
|
|
31
|
+
"balance de masa verificado y resultados trazables."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def strict_object(payload: str) -> dict[str, Any]:
|
|
36
|
+
"""Reject duplicate keys, non-objects and nonstandard NaN/Infinity literals."""
|
|
37
|
+
|
|
38
|
+
def unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
39
|
+
values: dict[str, Any] = {}
|
|
40
|
+
for key, value in pairs:
|
|
41
|
+
if key in values:
|
|
42
|
+
raise ValueError(f"Duplicate JSON key: {key}")
|
|
43
|
+
values[key] = value
|
|
44
|
+
return values
|
|
45
|
+
|
|
46
|
+
def invalid_constant(value: str) -> None:
|
|
47
|
+
raise ValueError(f"Nonfinite JSON literal: {value}")
|
|
48
|
+
|
|
49
|
+
result = json.loads(payload, object_pairs_hook=unique, parse_constant=invalid_constant)
|
|
50
|
+
if not isinstance(result, dict):
|
|
51
|
+
raise ValueError("A JSON object is required")
|
|
52
|
+
return result
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _range(value: float, name: str, low: float, high: float) -> None:
|
|
56
|
+
if not low <= value <= high:
|
|
57
|
+
raise ValueError(f"Local GUI limit: {name} must lie within [{low}, {high}] in SI")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class RequestSpec:
|
|
62
|
+
reactor: Literal["batch", "column"]
|
|
63
|
+
config_json: str
|
|
64
|
+
config_sha256: str
|
|
65
|
+
duration_s: float
|
|
66
|
+
options: SolverOptions
|
|
67
|
+
samples: int
|
|
68
|
+
|
|
69
|
+
def input_json(self) -> str:
|
|
70
|
+
return json.dumps(
|
|
71
|
+
{
|
|
72
|
+
"reactor": self.reactor,
|
|
73
|
+
"config": json.loads(self.config_json),
|
|
74
|
+
"solver_options": asdict(self.options),
|
|
75
|
+
"samples": self.samples,
|
|
76
|
+
"config_sha256": self.config_sha256,
|
|
77
|
+
},
|
|
78
|
+
sort_keys=True,
|
|
79
|
+
allow_nan=False,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def parse_request(data: dict[str, Any]) -> RequestSpec:
|
|
84
|
+
"""Use the package's existing strict schemas; GUI caps are not physical validation."""
|
|
85
|
+
allowed = {"reactor", "config_json", "options", "samples"}
|
|
86
|
+
if set(data) - allowed or not {"reactor", "config_json"} <= set(data):
|
|
87
|
+
raise ValueError("Allowed request fields: reactor, config_json, options, samples")
|
|
88
|
+
reactor, payload = data["reactor"], data["config_json"]
|
|
89
|
+
if reactor not in ("batch", "column") or not isinstance(payload, str):
|
|
90
|
+
raise ValueError("reactor must be batch/column and config_json must be JSON text")
|
|
91
|
+
if len(payload.encode("utf-8")) > MAX_REQUEST_BYTES:
|
|
92
|
+
raise ValueError("Configuration exceeds local GUI size limit")
|
|
93
|
+
# Validate the embedded JSON independently so its duplicate/nonfinite literals survive.
|
|
94
|
+
strict_object(payload)
|
|
95
|
+
config: BatchConfig | SimulationConfig
|
|
96
|
+
if reactor == "batch":
|
|
97
|
+
config = BatchConfig.from_json(payload)
|
|
98
|
+
duration = config.duration_s
|
|
99
|
+
c0, q0 = config.initial_concentration_kg_m3, config.initial_loading_kg_kg
|
|
100
|
+
temperature = config.temperature_k
|
|
101
|
+
_range(config.liquid_volume_m3, "liquid_volume_m3", 1e-9, 10)
|
|
102
|
+
_range(config.adsorbent_mass_kg, "adsorbent_mass_kg", 1e-9, 1e5)
|
|
103
|
+
_range(config.adsorbent_mass_kg / config.liquid_volume_m3, "mass/volume", 1e-9, 1e6)
|
|
104
|
+
material = config.material
|
|
105
|
+
else:
|
|
106
|
+
config = SimulationConfig.from_json(payload)
|
|
107
|
+
op, bed = config.operation, config.bed
|
|
108
|
+
duration, temperature = op.duration_s, op.temperature_k
|
|
109
|
+
c0, q0 = op.initial_concentration_kg_m3, op.initial_loading_kg_kg
|
|
110
|
+
_range(op.inlet_concentration_kg_m3, "inlet_concentration_kg_m3", 0, 1000)
|
|
111
|
+
_range(op.flow_m3_s, "flow_m3_s", 1e-12, 1e-2)
|
|
112
|
+
_range(op.axial_dispersion_m2_s, "axial_dispersion_m2_s", 0, 1)
|
|
113
|
+
_range(bed.length_m, "length_m", 1e-4, 10)
|
|
114
|
+
_range(bed.diameter_m, "diameter_m", 1e-3, 2)
|
|
115
|
+
_range(bed.particle_diameter_m, "particle_diameter_m", 1e-5, 0.1)
|
|
116
|
+
_range(bed.porosity, "porosity", 0.05, 0.95)
|
|
117
|
+
_range(bed.particle_density_kg_m3, "particle_density_kg_m3", 1, 1e4)
|
|
118
|
+
material = bed.material
|
|
119
|
+
if len(config.species.name) > 200 or len(material) > 200:
|
|
120
|
+
raise ValueError("Species/material labels may contain at most 200 characters")
|
|
121
|
+
_range(duration, "duration_s", 1e-6, MAX_DURATION_S)
|
|
122
|
+
_range(temperature, "temperature_k", 250, 400)
|
|
123
|
+
_range(c0, "initial_concentration_kg_m3", 0, 1000)
|
|
124
|
+
_range(q0, "initial_loading_kg_kg", 0, 10)
|
|
125
|
+
equilibrium = config.equilibrium
|
|
126
|
+
if isinstance(equilibrium, Langmuir):
|
|
127
|
+
_range(equilibrium.qmax_kg_kg, "qmax_kg_kg", 1e-12, 10)
|
|
128
|
+
_range(equilibrium.affinity_m3_kg, "affinity_m3_kg", 1e-12, 1e9)
|
|
129
|
+
elif isinstance(equilibrium, Freundlich):
|
|
130
|
+
_range(equilibrium.q_ref_kg_kg, "q_ref_kg_kg", 1e-12, 10)
|
|
131
|
+
_range(equilibrium.c_ref_kg_m3, "c_ref_kg_m3", 1e-12, 1000)
|
|
132
|
+
_range(equilibrium.exponent, "exponent", 0.2, 3)
|
|
133
|
+
elif isinstance(equilibrium, Linear):
|
|
134
|
+
_range(equilibrium.distribution_m3_kg, "distribution_m3_kg", 0, 1e6)
|
|
135
|
+
kinetics = config.kinetics
|
|
136
|
+
if isinstance(kinetics, LDF):
|
|
137
|
+
_range(kinetics.rate_s_inv, "rate_s_inv", 1e-8, 10)
|
|
138
|
+
else:
|
|
139
|
+
_range(kinetics.surface_diffusivity_m2_s, "surface_diffusivity_m2_s", 1e-16, 1e-8)
|
|
140
|
+
_range(kinetics.film_coefficient_m_s, "film_coefficient_m_s", 1e-9, 1e-3)
|
|
141
|
+
options_data = data.get("options", {})
|
|
142
|
+
if not isinstance(options_data, dict) or set(options_data) - {
|
|
143
|
+
"method",
|
|
144
|
+
"axial_cells",
|
|
145
|
+
"radial_cells",
|
|
146
|
+
"rtol",
|
|
147
|
+
}:
|
|
148
|
+
raise ValueError("GUI options allow only method, axial_cells, radial_cells, rtol")
|
|
149
|
+
defaults: dict[str, Any] = {"axial_cells": 40, "radial_cells": 8, "rtol": 1e-6}
|
|
150
|
+
options = SolverOptions(**(defaults | options_data))
|
|
151
|
+
if options.axial_cells > MAX_AXIAL_CELLS or options.radial_cells > MAX_RADIAL_CELLS:
|
|
152
|
+
raise ValueError("Local GUI grid limit: axial<=64 and radial<=12")
|
|
153
|
+
_range(options.rtol, "rtol", 1e-9, 1e-3)
|
|
154
|
+
samples = data.get("samples", 201)
|
|
155
|
+
if type(samples) is not int or not 2 <= samples <= MAX_SAMPLES:
|
|
156
|
+
raise ValueError("samples must be an integer within [2,401]")
|
|
157
|
+
return RequestSpec(reactor, config.to_json(), config.sha256, duration, options, samples)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def examples() -> list[dict[str, str]]:
|
|
161
|
+
"""Self-contained synthetic examples; no filesystem paths or experimental claims."""
|
|
162
|
+
batch = BatchConfig(
|
|
163
|
+
species=Species(name="Soluto sintético"),
|
|
164
|
+
material="Adsorbente sintético",
|
|
165
|
+
liquid_volume_m3=0.001,
|
|
166
|
+
adsorbent_mass_kg=0.002,
|
|
167
|
+
duration_s=300,
|
|
168
|
+
initial_concentration_kg_m3=0.01,
|
|
169
|
+
initial_loading_kg_kg=0,
|
|
170
|
+
equilibrium=Linear(distribution_m3_kg=0.5),
|
|
171
|
+
kinetics=LDF(rate_s_inv=0.02),
|
|
172
|
+
)
|
|
173
|
+
column = SimulationConfig(
|
|
174
|
+
species=Species(name="Soluto sintético"),
|
|
175
|
+
bed=Bed(
|
|
176
|
+
length_m=0.1,
|
|
177
|
+
diameter_m=0.01,
|
|
178
|
+
particle_diameter_m=0.0002,
|
|
179
|
+
porosity=0.4,
|
|
180
|
+
particle_density_kg_m3=1000,
|
|
181
|
+
material="Adsorbente sintético",
|
|
182
|
+
),
|
|
183
|
+
operation=Operation(flow_m3_s=1e-7, inlet_concentration_kg_m3=0.01, duration_s=1000),
|
|
184
|
+
equilibrium=Langmuir(qmax_kg_kg=0.001, affinity_m3_kg=10),
|
|
185
|
+
kinetics=LDF(rate_s_inv=0.02),
|
|
186
|
+
)
|
|
187
|
+
hsdm = SimulationConfig(
|
|
188
|
+
species=column.species,
|
|
189
|
+
bed=column.bed,
|
|
190
|
+
operation=column.operation,
|
|
191
|
+
equilibrium=column.equilibrium,
|
|
192
|
+
kinetics=HSDM(surface_diffusivity_m2_s=1e-11, film_coefficient_m_s=1e-5),
|
|
193
|
+
)
|
|
194
|
+
return [
|
|
195
|
+
{
|
|
196
|
+
"id": "batch_linear",
|
|
197
|
+
"label": "Batch LDF · referencia lineal",
|
|
198
|
+
"reactor": "batch",
|
|
199
|
+
"config_json": batch.to_json(),
|
|
200
|
+
},
|
|
201
|
+
{
|
|
202
|
+
"id": "column_ldf",
|
|
203
|
+
"label": "Columna LDF · Langmuir",
|
|
204
|
+
"reactor": "column",
|
|
205
|
+
"config_json": column.to_json(),
|
|
206
|
+
},
|
|
207
|
+
{
|
|
208
|
+
"id": "column_hsdm",
|
|
209
|
+
"label": "Columna HSDM · película externa",
|
|
210
|
+
"reactor": "column",
|
|
211
|
+
"config_json": hsdm.to_json(),
|
|
212
|
+
},
|
|
213
|
+
]
|