urson 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.
urson/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ # SPDX-FileCopyrightText: 2026 ETH Zurich
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Finite element simulator for coupled fluid flow and heat transport in geologic reservoirs."""
5
+
6
+ from importlib.metadata import version
7
+
8
+ from .api import UrsonModel
9
+
10
+ __all__ = ["UrsonModel"]
11
+ __version__ = version("urson")
urson/__main__.py ADDED
@@ -0,0 +1,72 @@
1
+ # SPDX-FileCopyrightText: 2026 ETH Zurich
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Entry point for running the simulator as a module.
5
+
6
+ Run a simulation:
7
+ uv run -m urson some-config-name
8
+
9
+ Run the test suite:
10
+ uv run -m urson --test
11
+ """
12
+
13
+ import argparse
14
+ from pathlib import Path
15
+
16
+
17
+ def main() -> None:
18
+ """Run the URSON reservoir simulator."""
19
+ parser = argparse.ArgumentParser(
20
+ prog="urson",
21
+ description="URSON - Underground Reservoir Simulator with Open-source Numerics",
22
+ )
23
+ parser.add_argument(
24
+ "config",
25
+ nargs="?",
26
+ help="Name of the config file in CONFIG_DIR, with or without .yaml (e.g. config_example)",
27
+ )
28
+ parser.add_argument(
29
+ "--config-dir",
30
+ type=Path,
31
+ default=None,
32
+ help="Directory containing the config file (default: <repo_root>/config/)",
33
+ )
34
+ parser.add_argument(
35
+ "--verbosity",
36
+ choices=["quiet", "lite", "full"],
37
+ default="full",
38
+ help="Console output: none, one line per timestep attempt, or full detail (default: full)",
39
+ )
40
+ parser.add_argument(
41
+ "--quiet",
42
+ action="store_true",
43
+ help="Suppress simulation output (same as --verbosity quiet)",
44
+ )
45
+ parser.add_argument(
46
+ "--test",
47
+ action="store_true",
48
+ help="Run the test suite instead of a simulation",
49
+ )
50
+
51
+ args = parser.parse_args()
52
+
53
+ if args.test:
54
+ import sys
55
+
56
+ import pytest
57
+
58
+ sys.exit(pytest.main(["tests"]))
59
+ elif args.config:
60
+ from urson.subsurface import main as run_sim
61
+
62
+ run_sim(
63
+ config_name=args.config,
64
+ config_dir=args.config_dir,
65
+ verbosity="quiet" if args.quiet else args.verbosity,
66
+ )
67
+ else:
68
+ parser.print_help()
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
urson/api.py ADDED
@@ -0,0 +1,266 @@
1
+ # SPDX-FileCopyrightText: 2026 ETH Zurich
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Coupling API: an external simulator drives URSON one coupling step at a time.
5
+
6
+ Each `solve` advances a trial state from the last accepted state; `get_fresh` accepts the
7
+ trial once the external coupling iteration has converged.
8
+ """
9
+
10
+ import warnings
11
+ from dataclasses import dataclass, replace
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+
17
+ from .logging_utils import RunLogger
18
+ from .postprocessing import WellProfile, postprocessing, prepare_output_directory, well_profiles
19
+ from .preprocessing import preprocessing
20
+ from .subsurface import (
21
+ StepStats,
22
+ Verbosity,
23
+ _load_wb,
24
+ _rollover,
25
+ _snapshot_wb,
26
+ advance,
27
+ check_verbosity,
28
+ initialize_simulation,
29
+ load_state,
30
+ snapshot_state,
31
+ )
32
+
33
+ # Coupling input used by each external BC type
34
+ _INPUT_KEY = {"pressure": "p", "flux": "q", "temperature": "T"}
35
+ _INPUT_KEYS = ("p", "T", "q")
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class _ExternalField:
40
+ """One BC field set through the API, and how its coupling input is converted."""
41
+
42
+ label: str
43
+ group_index: int # index into BC_config
44
+ field: str # "hydraulics" or "thermal"
45
+ input_key: str # "p", "T" or "q"
46
+ measure: float # group length/area (node count without flux weights), converts q in kg/s to flux
47
+
48
+
49
+ def _external_fields(BC_config: list[dict[str, Any]]) -> list[_ExternalField]:
50
+ """Describe every external field; types are read before any wellbore constraint switching."""
51
+ fields = []
52
+ for i, group in enumerate(BC_config):
53
+ if "flux_weight_matrix" in group:
54
+ measure = float(np.sum(group["flux_weight_matrix"] @ np.ones(len(group["nodes"]))))
55
+ else:
56
+ measure = float(len(group["nodes"]))
57
+ for field in ("hydraulics", "thermal"):
58
+ spec = group.get(field, {})
59
+ if spec.get("external", False):
60
+ fields.append(_ExternalField(group["label"], i, field, _INPUT_KEY[spec["type"]], measure))
61
+ return fields
62
+
63
+
64
+ class UrsonModel:
65
+ """A URSON simulation advanced by an external solver through trial coupling steps."""
66
+
67
+ def __init__(
68
+ self,
69
+ config_name: str,
70
+ t_start: float,
71
+ config_dir: Path | None = None,
72
+ verbosity: Verbosity = "full",
73
+ ) -> None:
74
+ """Preprocess, assign initial conditions at t_start and write output frame 0."""
75
+ # Full detail goes through the usual verbose flag; lite only adds the per-step line
76
+ check_verbosity(verbosity)
77
+ self.verbose = verbosity == "full"
78
+ self._progress = verbosity == "lite"
79
+ with RunLogger() as run_logger:
80
+ if self.verbose:
81
+ print("URSON - UNDERGROUND RESERVOIR SIMULATOR WITH OPEN-SOURCE NUMERICS (coupling API) \n")
82
+ print("Initializing simulation " + config_name + "\n")
83
+
84
+ # Load config and mesh
85
+ config, mesh = preprocessing(config_name, config_dir, self.verbose)
86
+ controls = config["simulation"]
87
+ controls["config_name"] = config["config_name"]
88
+ controls["config_dir"] = config["config_dir"]
89
+ controls["t_start"] = t_start # the coupling sets the start time
90
+
91
+ # Mirror output to run.log; later calls append to it
92
+ self._output_log = bool(controls["output_log"])
93
+ self._log_dir = prepare_output_directory(controls)
94
+ if self._output_log:
95
+ run_logger.attach_file(self._log_dir)
96
+
97
+ # The initial condition is the current state, with no trial pending
98
+ self._setup, self._current = initialize_simulation(config, mesh, t_start, self.verbose)
99
+ self._external = _external_fields(self._setup.BC_config)
100
+ self._labels = sorted({ext.label for ext in self._external})
101
+ self._trial = self._current
102
+ self._trial_pending = False
103
+ # Last accepted step before its history shift, for well profiles; statistics of the last solve
104
+ self._accepted = self._current
105
+ self.solve_stats = StepStats()
106
+
107
+ def solve(
108
+ self, t_start: float, t_end: float, bcs: dict[str, dict[str, float]]
109
+ ) -> dict[str, dict[str, Any]]:
110
+ """Advance a trial state from the current state at t_start to exactly t_end."""
111
+ with RunLogger() as run_logger:
112
+ self._resume_log(run_logger)
113
+
114
+ # The coupling step must start from the current state
115
+ current = self._current
116
+ if not np.isclose(t_start, current.t, rtol=1.0e-12, atol=0.0):
117
+ raise ValueError(
118
+ f"t_start = {t_start:.9e} does not match the current state at t = {current.t:.9e}."
119
+ )
120
+ if t_end <= current.t:
121
+ raise ValueError(f"t_end = {t_end:.9e} must be after t_start = {current.t:.9e}.")
122
+
123
+ # Write this step's external BC tables onto the current wellbore flags
124
+ self._check_bcs(bcs)
125
+ BC_config = self._setup.BC_config
126
+ _load_wb(BC_config, current.wb_flags)
127
+ self._apply_external_bcs(current.t, t_end, bcs, current.ext_values)
128
+ inputs = {label: {key: float(bcs[label][key]) for key in _INPUT_KEYS} for label in self._labels}
129
+ start = replace(current, wb_flags=_snapshot_wb(BC_config), ext_values=inputs)
130
+
131
+ # Advance a trial from the current state; a failed solve leaves no trial pending
132
+ self._trial_pending = False
133
+ self.solve_stats = StepStats()
134
+ self._trial, self.solve_stats = advance(
135
+ self._setup, start, t_end, self.verbose, progress=self._progress
136
+ )
137
+ self._trial_pending = True
138
+
139
+ # Report each external group at t_end
140
+ return self._boundary_values(self._trial.primary_variables)
141
+
142
+ def get_fresh(self) -> None:
143
+ """Accept the trial state as the current state and write its output."""
144
+ if not self._trial_pending:
145
+ raise RuntimeError("No trial state to accept: call solve before each get_fresh.")
146
+
147
+ with RunLogger() as run_logger:
148
+ self._resume_log(run_logger)
149
+ setup = self._setup
150
+ trial = self._trial
151
+
152
+ # Write output at the end of the coupling step
153
+ primary_variables = load_state(trial, setup.BC_config)
154
+ n_out = trial.n_out + 1
155
+ postprocessing(
156
+ n_out,
157
+ setup.mesh,
158
+ setup.controls,
159
+ setup.material,
160
+ setup.BC_config,
161
+ primary_variables,
162
+ trial.t,
163
+ trial.dt_hist[1:4],
164
+ self.verbose,
165
+ )
166
+
167
+ # Shift the time history and accept the trial as the current state
168
+ _rollover(primary_variables, setup.BC_config, setup.controls["wellbore_check"])
169
+ self._current = snapshot_state(
170
+ trial.t,
171
+ trial.n_step,
172
+ n_out,
173
+ trial.dt_hist,
174
+ primary_variables,
175
+ setup.BC_config,
176
+ trial.ext_values,
177
+ )
178
+ self._accepted = trial
179
+ self._trial_pending = False
180
+
181
+ def well_profiles(self) -> list[WellProfile]:
182
+ """Pressure, temperature and flow along each well: the pending trial, else the last accepted step."""
183
+ if "well_mesh" not in self._setup.mesh:
184
+ raise ValueError("This model has no wells.")
185
+ state = self._trial if self._trial_pending else self._accepted
186
+ setup = self._setup
187
+ return well_profiles(
188
+ setup.mesh, setup.controls, setup.material, state.primary_variables, state.dt_hist[1:4]
189
+ )
190
+
191
+ def _resume_log(self, run_logger: RunLogger) -> None:
192
+ """Append this call's output to run.log, when logging is on."""
193
+ if self._output_log:
194
+ run_logger.attach_file(self._log_dir, mode="a")
195
+
196
+ def _check_bcs(self, bcs: dict[str, dict[str, float]]) -> None:
197
+ """Every external label, and only those, with finite p, T and q."""
198
+ missing = sorted(set(self._labels) - set(bcs))
199
+ unknown = sorted(set(bcs) - set(self._labels))
200
+ if missing or unknown:
201
+ raise ValueError(f"Boundary condition labels missing: {missing}; not external: {unknown}.")
202
+ for label in self._labels:
203
+ absent = [key for key in _INPUT_KEYS if key not in bcs[label]]
204
+ if absent:
205
+ raise ValueError(f"Boundary conditions for '{label}' lack {absent}.")
206
+ if not np.all(np.isfinite([bcs[label][key] for key in _INPUT_KEYS])):
207
+ raise ValueError(f"Boundary conditions for '{label}' are not finite: {bcs[label]}.")
208
+
209
+ def _apply_external_bcs(
210
+ self,
211
+ t_start: float,
212
+ t_end: float,
213
+ bcs: dict[str, dict[str, float]],
214
+ previous: dict[str, dict[str, float]],
215
+ ) -> None:
216
+ """Write each external field as a two-point table over [t_start, t_end]."""
217
+ BC_config = self._setup.BC_config
218
+ for ext in self._external:
219
+ spec = BC_config[ext.group_index][ext.field]
220
+ value_end = self._input_value(ext, bcs)
221
+ # Linear interpolation starts from the last accepted input; the first step is stepwise
222
+ if spec["interpolation"] == "linear" and previous:
223
+ value_start = self._input_value(ext, previous)
224
+ else:
225
+ value_start = value_end
226
+ table = [[t_start, t_end], [value_start, value_end]]
227
+
228
+ if "constraints" in spec:
229
+ # Wellbore group: keep the flux target while pressure-limited
230
+ spec["function_flux"], spec["values_flux"] = "table", table
231
+ if spec["curr_BC"] == "flux":
232
+ spec["function"], spec["values"] = "table", table
233
+ else:
234
+ spec["function"], spec["values"] = "table", table
235
+
236
+ def _input_value(self, ext: _ExternalField, bcs: dict[str, dict[str, float]]) -> float:
237
+ """Coupling input for one field; a flow rate in kg/s becomes a flux over the group."""
238
+ value = float(bcs[ext.label][ext.input_key])
239
+ if ext.input_key == "q":
240
+ return value / ext.measure
241
+ return value
242
+
243
+ def _boundary_values(self, primary_variables: dict[str, Any]) -> dict[str, dict[str, Any]]:
244
+ """Mean p and T, summed q (kg/s, positive inflow) and hydraulic mode of each external group."""
245
+ BC_config = self._setup.BC_config
246
+ group_indices = {ext.label: ext.group_index for ext in self._external}
247
+ results = {}
248
+ for label in self._labels:
249
+ group = BC_config[group_indices[label]]
250
+ nodes = np.asarray(group["nodes"])
251
+ q = float(np.sum(primary_variables["q"][nodes, 0]))
252
+ hydraulics = group.get("hydraulics", {})
253
+ results[label] = {
254
+ "p": float(np.mean(primary_variables["p"][nodes, 0])),
255
+ "T": float(np.mean(primary_variables["T"][nodes, 0])),
256
+ "q": q,
257
+ "mode": hydraulics.get("type", "none"),
258
+ }
259
+
260
+ # A fixed temperature only makes sense where fluid flows in
261
+ thermal = group.get("thermal", {})
262
+ if thermal.get("external", False) and q < 0:
263
+ warnings.warn(
264
+ f"'{label}' fixes temperature while fluid flows out (q = {q:.3e} kg/s).", stacklevel=3
265
+ )
266
+ return results
urson/logging_utils.py ADDED
@@ -0,0 +1,61 @@
1
+ # SPDX-FileCopyrightText: 2026 ETH Zurich
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Mirror simulation stdout to a run.log file in the output directory, in addition to the console."""
5
+
6
+ import io
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import IO, Any
10
+
11
+
12
+ class _Tee(io.TextIOBase):
13
+ """Write-only stream that duplicates writes to multiple underlying streams."""
14
+
15
+ def __init__(self, *streams: IO[str]) -> None:
16
+ self._streams = streams
17
+
18
+ def write(self, data: str) -> int:
19
+ for stream in self._streams:
20
+ stream.write(data)
21
+ return len(data)
22
+
23
+ def flush(self) -> None:
24
+ for stream in self._streams:
25
+ stream.flush()
26
+
27
+
28
+ class RunLogger:
29
+ """Buffers stdout until the output directory is known, then optionally mirrors it to run.log.
30
+
31
+ Console output (gated by `verbose` at each print site, as before) is always passed
32
+ through untouched. Everything printed before `attach_file()` is called is buffered so
33
+ it can still be written to the log file once the output directory is resolved from
34
+ the config.
35
+ """
36
+
37
+ def __init__(self) -> None:
38
+ """Create a logger with nothing attached yet; call as a context manager to activate it."""
39
+ self._buffer = io.StringIO()
40
+ self._file: IO[str] | None = None
41
+ self._old_stdout: IO[str] | None = None
42
+
43
+ def __enter__(self) -> "RunLogger":
44
+ """Start buffering stdout, still passing it through to the console."""
45
+ self._old_stdout = sys.stdout
46
+ sys.stdout = _Tee(self._old_stdout, self._buffer)
47
+ return self
48
+
49
+ def attach_file(self, output_directory: str, filename: str = "run.log", mode: str = "w") -> None:
50
+ """Start mirroring stdout to `filename` in `output_directory`, including anything buffered so far."""
51
+ self._file = open(Path(output_directory) / filename, mode) # noqa: SIM115 (kept open for the run)
52
+ self._file.write(self._buffer.getvalue())
53
+ self._file.flush()
54
+ assert self._old_stdout is not None
55
+ sys.stdout = _Tee(self._old_stdout, self._file)
56
+
57
+ def __exit__(self, *exc_info: Any) -> None:
58
+ """Restore stdout and close the log file, if one was attached."""
59
+ sys.stdout = self._old_stdout
60
+ if self._file is not None:
61
+ self._file.close()