From 9b3d536dadc5ef468ab9d3b28cd23513a8b34238 Mon Sep 17 00:00:00 2001 From: Kristian Fossum Date: Thu, 26 Nov 2026 09:06:45 +0100 Subject: [PATCH 1/5] feat: add weighted OPM Flow adjoints for PET --- README.md | 40 ++++++ src/subsurface/multphaseflow/opm_adjoint.py | 128 ++++++++++++++++++++ src/subsurface/multphaseflow/vjp.py | 23 ++++ tests/test_flow_vjp.py | 48 ++++++++ 4 files changed, 239 insertions(+) create mode 100644 src/subsurface/multphaseflow/opm_adjoint.py create mode 100644 src/subsurface/multphaseflow/vjp.py create mode 100644 tests/test_flow_vjp.py diff --git a/README.md b/README.md index 759c90f..2cd773f 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,46 @@ python3 -m pip install -e . ``` ## Examples +### PET LowRankGN: weighted Flow adjoints + +Use `subsurface.multphaseflow.opm_adjoint.FlowAdjoint(options)` in place of +`flow(options)`. Give it the usual Flow options plus `adjoint_executable` (an +absolute executable path or command on PATH; default `flow_adjoint`). Use the +`adjoint-hooks` build of [opm-simulators](https://github.com/hnil/opm-simulators/tree/adjoint-hooks) +and the [`linw` build of opm-adjoint](https://github.com/KriFos1/opm-adjoint/tree/feat/matchw-linw-objectives); +stock Flow cannot replay weighted objectives. No Python dependency is added. + +After `setup_fwd_run()`, `run_vjp(state, weights)` renders the centre once, +records a trajectory, and replays it serially for each nonzero seed column. +`weights` is PET's report-by-datatype frame: each observed cell holds a +length-k vector; `None` cells are skipped. Each returned `grad[name][j]` is +the derivative of the j-th weighted summary with respect to `state[name]`. +Forward members never record an archive. The temporary archive needs enough +disk for all substeps and is removed after the batch. + +- Use scalar `WOPR`, `WWPR` or `WGPR` for **producing wells** in Sm³/day. + Supply exact midnight reports isolated from other substep ends by more + than six hours (`linw`'s date-matching window). The wrapper checks each + objective against the recorded summary. Turn off summary thinning. +- Use serial METRIC decks writing `INIT`, with independent `poro` (fraction), + `permx`, `permy`, `permz` (mD), or `log_permx` etc. (natural log of mD). + One vector entry per active cell in Flow order. Direct fields must not + control any other property. For permeability, use **fixed connection + factors**: the backend differentiates face transmissibilities, not a + permeability-derived well index. Copied axes, fault multipliers, nonlinear + Mako transforms, changing active sets and multisegment wells are outside + this adapter. Do not change a model's wells just to make it pass. +- The same executable and solver flags drive both predictions and adjoints. + Use converged forward tolerances and check a directional derivative when + moving to a new deck; matching objective values checks units and timing, + not the accuracy of the backend derivative. + +Run the identity- and mixed-seed directional derivative test with `FLOW_ADJOINT` pointing to +the executable and `OPM_ADJOINT_CASE` to `MODEL_1D_DEBUG/inputfiles` from +[`hnil/opm-tests`, `add_adjoint_tests`](https://github.com/hnil/opm-tests/tree/add_adjoint_tests): +`python -m pytest -q tests/test_flow_vjp.py` (with PET on the Python path). + +### Forward Flow example The example demonstrates usage of [OPM-flow](https://opm-project.org/). To reproduce, ensure that OPM-flow is installed and in the path. The full noteboox is [here](https://github.com/Python-Ensemble-Toolbox/SimulatorWrap/tree/main/Example), we employ the [3Spot example](https://github.com/Python-Ensemble-Toolbox/Examples/tree/main/3Spot) as a template for this example. All files are Example folder. diff --git a/src/subsurface/multphaseflow/opm_adjoint.py b/src/subsurface/multphaseflow/opm_adjoint.py new file mode 100644 index 0000000..f7cb325 --- /dev/null +++ b/src/subsurface/multphaseflow/opm_adjoint.py @@ -0,0 +1,128 @@ +"""Serial PET wrapper for Flow builds with adjoint record/replay and the linw objective.""" + +from contextlib import closing +from datetime import timedelta +from pathlib import Path +import re +import shlex +import subprocess +from tempfile import TemporaryDirectory + +import numpy as np +import pandas as pd +from resdata.summary import Summary +from resdata.resfile import ResdataFile + +from .opm import flow +from .vjp import scalar_seeds + + +class FlowAdjoint(flow): + """Use the same Flow executable, deck renderer and flags for predictions and VJPs.""" + + def __init__(self, input_file): + super().__init__(input_file) + self.executable = input_file.get("adjoint_executable", "flow_adjoint") + if self.options["mpi"] or self.options["mpiarray"] or input_file.get("hpc") or self.upscale: + raise ValueError("FlowAdjoint supports serial, non-upscaled decks only") + self.flags = shlex.split(self.options["sim_flag"]) + if any(f.startswith(("--adjoint-", "--output-dir", "--enable-storage-cache")) for f in self.flags): + raise ValueError("FlowAdjoint owns archive, output and storage-cache flags") + if self.options["parsing-strictness"]: + self.flags.append("--parsing-strictness=" + self.options["parsing-strictness"]) + + def _flow(self, deck, output, *flags): + output.mkdir(exist_ok=True) + with (output / "flow.log").open("w+") as log: + result = subprocess.run([self.executable, str(deck), f"--output-dir={output}", + *self.flags, "--enable-storage-cache=false", *flags], + stdout=log, stderr=subprocess.STDOUT, timeout=self.options.get("sim_limit")) + if result.returncode: + log.seek(0, 2) + log.seek(max(0, log.tell() - 2000)) + raise RuntimeError(f"flow_adjoint exited {result.returncode}: {log.read()}") + + def call_sim(self, folder, wait_for_proc=False): + folder = Path(folder).resolve() + try: + self._flow(folder / (self.file + ".DATA"), folder) + except (RuntimeError, subprocess.TimeoutExpired): + return False + return True + + def run_vjp(self, state, weights): + cells, seeds = scalar_seeds(weights, self.true_order[1], self.all_data_types) + supported = {"poro", "permx", "permy", "permz", "log_permx", "log_permy", "log_permz"} + if not state or set(state) - supported: + raise ValueError(f"Expected direct active-cell fields from {sorted(supported)}, got {list(state)}") + if len({key.removeprefix("log_") for key in state}) != len(state): + raise ValueError("Only one PET variable may control a deck field") + phases = {"WOPR": "oil", "WWPR": "water", "WGPR": "gas"} + for _, key in cells: + kind, _, well = key.partition(":") + if kind.upper() not in phases or not re.fullmatch(r"[\w.-]+", well): + raise ValueError(f"Unsupported production rate: {key}") + gradients = {key: np.zeros((seeds.shape[1], np.size(x))) for key, x in state.items()} + with TemporaryDirectory(prefix="vjp_", dir=".") as tmp: + root = Path(tmp).resolve() + self._runMako(str(root) + "/", dict(state, member=0, level=self.level)) + deck = root / (self.file + ".DATA") + archive = f"--adjoint-file={root / 'archive'}" + self._flow(deck, root, archive, "--adjoint-save=true") + with closing(ResdataFile(str(root / (self.file + ".INIT")))) as init: + for key, x in state.items(): + field = key.removeprefix("log_").upper() + expected = np.exp(x) if key.startswith("log_") else np.asarray(x) + actual = np.asarray(init[field][0]) + if (expected.shape != actual.shape or not np.all(expected > 0) + or not np.allclose(actual, expected, rtol=2e-5, atol=0)): + raise ValueError(f"{key} must render directly in active-cell order (check units and clipping)") + summary = Summary(str(root / self.file)) + dates = pd.DatetimeIndex(summary.dates) + steps = root / "archive" / "adjoint" / "substep" + if sum(dates > summary.start_time) != len(list(steps.iterdir())): + raise ValueError("linw requires a summary for every recorded substep; check summary thinning") + key_map = {k.upper(): k for k in summary.keys()} + rows, values = [], [] + for label, key in cells: + key = key_map[key.upper()] + date = (pd.Timestamp(summary.start_time) + timedelta(days=float(label)) + if self.true_order[0] == "days" else pd.Timestamp(label)) + if date != date.normalize() or date not in dates or np.sum(abs(dates - date) <= pd.Timedelta(hours=6)) != 1: + raise ValueError(f"linw needs an isolated midnight report at {date} (±6 hour lookup)") + if summary.unit(key).upper() != "SM3/DAY": + raise ValueError(f"Expected metric surface rate for {key}, got {summary.unit(key)}") + values.append(summary.iget(key, dates.get_loc(date))) + kind, well = key.split(":") + rows.append(f"{date:%Y-%m-%d} {well} {phases[kind]}") + for j, column in enumerate(seeds.T): + if not column.any(): + continue + objective = root / "weights.txt" + objective.write_text("".join(f"{row} {-86400*w:.17g}\n" for row, w in zip(rows, column) if w)) + with TemporaryDirectory(dir=root) as replay: + out = Path(replay) + self._flow(deck, out, archive, "--adjoint-mode=gradient", f"--adjoint-objective=linw:{objective}") + prefix = out / (self.file + ".ADJOINT_GRADIENTS_PV.txt") + with prefix.open() as f: + actual = float(f.readline().split("J = ")[1].split(")")[0]) + # UNSMRY is single precision: scale roundoff by the terms before cancellation. + if not np.isclose(actual, column @ values, rtol=2e-5, + atol=1e-8 + 1e-7 * (abs(column) @ np.abs(values))): + raise ValueError("linw replay does not match the weighted forward summary") + perm = np.loadtxt(out / (self.file + ".ADJOINT_GRADIENTS_PERM.txt"), ndmin=2) + for name, x in state.items(): + x = np.asarray(x) + if perm.shape != (len(x), 3): + raise ValueError(f"{name} must follow Flow's serial active-cell order") + if name == "poro": + g = np.loadtxt(prefix, ndmin=1) / x + else: + axes = "xyz".index(name[-1]) + g = perm[:, axes] * 9.869233e-16 + if name.startswith("log_"): + g *= np.exp(x) + if not np.isfinite(g).all(): + raise ValueError(f"Nonfinite replay gradient for {name}") + gradients[name][j] = g + return gradients diff --git a/src/subsurface/multphaseflow/vjp.py b/src/subsurface/multphaseflow/vjp.py new file mode 100644 index 0000000..311673d --- /dev/null +++ b/src/subsurface/multphaseflow/vjp.py @@ -0,0 +1,23 @@ +"""PET's labelled seeds for scalar simulator summaries; columns are independent objectives.""" + +import numpy as np + + +def scalar_seeds(weights, reports, datatypes): + if not weights.index.is_unique or not weights.columns.is_unique: + raise ValueError("VJP report and datatype labels must be unique") + cells, vectors = [], [] + for label, row in weights.iterrows(): + for key, value in row.items(): + if value is None: + continue + if label not in reports or key not in datatypes: + raise ValueError(f"Unknown VJP observation {(label, key)}") + vector = np.atleast_1d(np.asarray(value, dtype=float)) + if vector.ndim != 1 or not vector.size or not np.isfinite(vector).all(): + raise ValueError(f"Expected finite scalar-observation seeds at {(label, key)}") + cells.append((label, key)) + vectors.append(vector) + if not cells: + raise ValueError("VJP needs at least one observed cell") + return cells, np.stack(vectors) diff --git a/tests/test_flow_vjp.py b/tests/test_flow_vjp.py new file mode 100644 index 0000000..2865665 --- /dev/null +++ b/tests/test_flow_vjp.py @@ -0,0 +1,48 @@ +"""Integration: point OPM_ADJOINT_CASE at MODEL_1D_DEBUG/inputfiles from opm-tests-adjoint.""" + +import os +from pathlib import Path +import re + +import numpy as np +import pandas as pd +import pytest + +from subsurface.multphaseflow.opm_adjoint import FlowAdjoint +from misc.structures.layout import DataLayout + + +@pytest.mark.skipif(not os.environ.get("OPM_ADJOINT_CASE"), reason="requires adjoint-enabled Flow and debug deck") +def test_weighted_producer_rate_matches_forward_directional_difference(tmp_path, monkeypatch): + source = Path(os.environ["OPM_ADJOINT_CASE"]).resolve() + deck = (source / "MODEL_1D_DEBUG.DATA").read_text() + deck = re.sub(r"INCLUDE\s+(\w+\.txt)\s*/", lambda m: (source / m[1]).read_text(), deck) + deck = re.sub(r"(?ms)^PERMX\s.*?/", "PERMX\n${' '.join(map(str, permx))} /", deck) + deck = re.sub(r"(?ms)^PORO\s.*?/", "PORO\n${' '.join(map(str, poro))} /", deck) + deck = re.sub(r"(?ms)^TSTEP\s.*?/", "TSTEP\n 2 2 /", deck) + # The exported MRST fixture uses -1 for a missing VFP table; Flow expects 0. + deck = deck.replace("1* -1 1*/", "1* 0 1*/").replace("1* -1 1*", "1* 0 1*") + monkeypatch.chdir(tmp_path) + Path("TEST.mako").write_text(deck) + sim = FlowAdjoint({"runfile": "TEST", "datatype": ["wopr:prod"], "reporttype": "days", "reportpoint": [2, 4], + "adjoint_executable": os.environ.get("FLOW_ADJOINT", "flow_adjoint"), + "simoptions": {"sim_flag": "--enable-adaptive-time-stepping=false --tolerance-cnv=1e-7"}}) + sim.setup_fwd_run() + x, d = np.full(3, 100.), np.array([.2, 1., -.3]) + w = np.array([[1., 0., -.5], [0., 1., 1.]]) # two Jacobian rows and a projected row + layout = DataLayout.from_frame(pd.DataFrame({"wopr:prod": [0., 0.]}, index=[2, 4])) + p = np.full(3, .1) + g = sim.run_vjp({"permx": x, "poro": p}, layout.to_frame(w)) + + def forward(y, z): + records = sim.run_fwd_sim({"permx": y, "poro": z}, 0) + return np.array([r["wopr:prod"] for r in records]) @ w + + delta = .2 + fd = (forward(x + delta*d, p) - forward(x - delta*d, p)) / (2*delta) + assert np.linalg.norm(fd) > 1e-5 + np.testing.assert_allclose(g["permx"] @ d, fd, rtol=.02, atol=1e-5) + delta = .0002 + fd = (forward(x, p + delta*d) - forward(x, p - delta*d)) / (2*delta) + assert np.linalg.norm(fd) > 1e-5 + np.testing.assert_allclose(g["poro"] @ d, fd, rtol=.02, atol=1e-5) From 5306079e7df8671cc07a71cdac3cbbfb69016497 Mon Sep 17 00:00:00 2001 From: Kristian Fossum Date: Thu, 26 Nov 2026 21:22:14 +0100 Subject: [PATCH 2/5] feat: drive OPM adjoints through opm-adjoint's JSON objectives FlowAdjoint.run_vjp now targets the official OPM/opm-adjoint flow_adjoint instead of a fork with the linw objective. Each weight column is written as a JSON objective (--adjoint-config) with one rate term per observed value, active on the substep that ends on its report, and the gradients are read from the ADJOINT_GRADIENTS_{PORO,PERM}.csv files and their JSON sidecar. A rate term carries the substep length as a factor. The summary stores time in single precision, so each batch adds one objective- only replay with unit weights that gives the lengths in double precision; the summary time differences then check units, sign and timing. Reports no longer have to be at midnight, and state vectors may be given per active cell or per grid cell. Connection factors that follow the permeability and multisegment wells are left to opm-adjoint. The run_vjp(state, weights) contract is unchanged. --- README.md | 47 ++++--- src/subsurface/multphaseflow/opm_adjoint.py | 145 +++++++++++++------- tests/test_flow_vjp.py | 18 +-- 3 files changed, 133 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 2cd773f..f58a3ab 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,10 @@ python3 -m pip install -e . Use `subsurface.multphaseflow.opm_adjoint.FlowAdjoint(options)` in place of `flow(options)`. Give it the usual Flow options plus `adjoint_executable` (an -absolute executable path or command on PATH; default `flow_adjoint`). Use the -`adjoint-hooks` build of [opm-simulators](https://github.com/hnil/opm-simulators/tree/adjoint-hooks) -and the [`linw` build of opm-adjoint](https://github.com/KriFos1/opm-adjoint/tree/feat/matchw-linw-objectives); -stock Flow cannot replay weighted objectives. No Python dependency is added. +absolute executable path or command on PATH; default `flow_adjoint`), the +executable of [OPM/opm-adjoint](https://github.com/OPM/opm-adjoint) built +against the official OPM modules. Stock `flow` has no adjoint. No Python +dependency is added. After `setup_fwd_run()`, `run_vjp(state, weights)` renders the centre once, records a trajectory, and replays it serially for each nonzero seed column. @@ -26,27 +26,38 @@ the derivative of the j-th weighted summary with respect to `state[name]`. Forward members never record an archive. The temporary archive needs enough disk for all substeps and is removed after the batch. -- Use scalar `WOPR`, `WWPR` or `WGPR` for **producing wells** in Sm³/day. - Supply exact midnight reports isolated from other substep ends by more - than six hours (`linw`'s date-matching window). The wrapper checks each +The weighted sums are handed to `flow_adjoint` as a JSON objective +(`--adjoint-config`): one `rate` term per observed value, active on the +substep that ends on its report. Gradients are read from the +`ADJOINT_GRADIENTS_{PORO,PERM}.csv` files and their JSON sidecar. Each batch +adds one objective-only replay, which fixes the substep lengths the terms +need. + +- Use scalar `WOPR`, `WWPR` or `WGPR` for **producing wells** in Sm³/day. A + report may be any time a simulator step ends on; the wrapper checks the objective against the recorded summary. Turn off summary thinning. - Use serial METRIC decks writing `INIT`, with independent `poro` (fraction), - `permx`, `permy`, `permz` (mD), or `log_permx` etc. (natural log of mD). - One vector entry per active cell in Flow order. Direct fields must not - control any other property. For permeability, use **fixed connection - factors**: the backend differentiates face transmissibilities, not a - permeability-derived well index. Copied axes, fault multipliers, nonlinear - Mako transforms, changing active sets and multisegment wells are outside - this adapter. Do not change a model's wells just to make it pass. + `permx`, `permy`, `permz` (mD), or `log_permx` etc. (natural log of mD), one + value per active cell or per grid cell in natural order. The gradient has + the shape of the state; inactive cells get zero. Direct fields must not + control any other property: copied axes, fault multipliers and nonlinear + Mako transforms need their own chain rule. +- Connection factors computed from the permeability and multisegment wells + are differentiated by opm-adjoint. Two cases need changes that are not in + its master yet: + [OPM/opm-adjoint#2](https://github.com/OPM/opm-adjoint/pull/2) for exact + gradients with producers on RESV control, and + [OPM/opm-adjoint#3](https://github.com/OPM/opm-adjoint/pull/3) for wells + that the schedule defines after the first report step. - The same executable and solver flags drive both predictions and adjoints. Use converged forward tolerances and check a directional derivative when moving to a new deck; matching objective values checks units and timing, not the accuracy of the backend derivative. -Run the identity- and mixed-seed directional derivative test with `FLOW_ADJOINT` pointing to -the executable and `OPM_ADJOINT_CASE` to `MODEL_1D_DEBUG/inputfiles` from -[`hnil/opm-tests`, `add_adjoint_tests`](https://github.com/hnil/opm-tests/tree/add_adjoint_tests): -`python -m pytest -q tests/test_flow_vjp.py` (with PET on the Python path). +Run the directional derivative tests with `FLOW_ADJOINT` pointing to the +executable and `OPM_ADJOINT_CASE` to `doc/tutorials/MODEL_1D_DEBUG` of +opm-adjoint: `python -m pytest -q tests/test_flow_vjp.py` (with PET on the +Python path). ### Forward Flow example The example demonstrates usage of [OPM-flow](https://opm-project.org/). To reproduce, ensure that OPM-flow is installed and in the path. The full noteboox is [here](https://github.com/Python-Ensemble-Toolbox/SimulatorWrap/tree/main/Example), we employ the [3Spot example](https://github.com/Python-Ensemble-Toolbox/Examples/tree/main/3Spot) as a template for this example. All files are Example folder. diff --git a/src/subsurface/multphaseflow/opm_adjoint.py b/src/subsurface/multphaseflow/opm_adjoint.py index f7cb325..8a6c457 100644 --- a/src/subsurface/multphaseflow/opm_adjoint.py +++ b/src/subsurface/multphaseflow/opm_adjoint.py @@ -1,7 +1,7 @@ -"""Serial PET wrapper for Flow builds with adjoint record/replay and the linw objective.""" +"""Serial PET wrapper for OPM Flow with opm-adjoint: forecasts, and weighted adjoints through its JSON objectives.""" from contextlib import closing -from datetime import timedelta +import json from pathlib import Path import re import shlex @@ -16,6 +16,9 @@ from .opm import flow from .vjp import scalar_seeds +PHASES = {"WOPR": "oil", "WWPR": "water", "WGPR": "gas"} +FIELDS = {"poro", "permx", "permy", "permz", "log_permx", "log_permy", "log_permz"} + class FlowAdjoint(flow): """Use the same Flow executable, deck renderer and flags for predictions and VJPs.""" @@ -51,16 +54,15 @@ def call_sim(self, folder, wait_for_proc=False): return True def run_vjp(self, state, weights): + """Gradients of weighted sums of producer rates: ``{name: (k, n)}`` for the ``k`` weight columns.""" cells, seeds = scalar_seeds(weights, self.true_order[1], self.all_data_types) - supported = {"poro", "permx", "permy", "permz", "log_permx", "log_permy", "log_permz"} - if not state or set(state) - supported: - raise ValueError(f"Expected direct active-cell fields from {sorted(supported)}, got {list(state)}") + if not state or set(state) - FIELDS: + raise ValueError(f"Expected direct cell fields from {sorted(FIELDS)}, got {list(state)}") if len({key.removeprefix("log_") for key in state}) != len(state): raise ValueError("Only one PET variable may control a deck field") - phases = {"WOPR": "oil", "WWPR": "water", "WGPR": "gas"} for _, key in cells: kind, _, well = key.partition(":") - if kind.upper() not in phases or not re.fullmatch(r"[\w.-]+", well): + if kind.upper() not in PHASES or not re.fullmatch(r"[\w.-]+", well): raise ValueError(f"Unsupported production rate: {key}") gradients = {key: np.zeros((seeds.shape[1], np.size(x))) for key, x in state.items()} with TemporaryDirectory(prefix="vjp_", dir=".") as tmp: @@ -69,60 +71,103 @@ def run_vjp(self, state, weights): deck = root / (self.file + ".DATA") archive = f"--adjoint-file={root / 'archive'}" self._flow(deck, root, archive, "--adjoint-save=true") - with closing(ResdataFile(str(root / (self.file + ".INIT")))) as init: - for key, x in state.items(): - field = key.removeprefix("log_").upper() - expected = np.exp(x) if key.startswith("log_") else np.asarray(x) - actual = np.asarray(init[field][0]) - if (expected.shape != actual.shape or not np.all(expected > 0) - or not np.allclose(actual, expected, rtol=2e-5, atol=0)): - raise ValueError(f"{key} must render directly in active-cell order (check units and clipping)") summary = Summary(str(root / self.file)) - dates = pd.DatetimeIndex(summary.dates) - steps = root / "archive" / "adjoint" / "substep" - if sum(dates > summary.start_time) != len(list(steps.iterdir())): - raise ValueError("linw requires a summary for every recorded substep; check summary thinning") + days = np.asarray(summary.days, dtype=float) + days = days[days > 0] + if len(days) != len(list((root / "archive" / "adjoint" / "substep").iterdir())): + raise ValueError("Expected one summary row per recorded substep; check summary thinning") key_map = {k.upper(): k for k in summary.keys()} - rows, values = [], [] + start = pd.Timestamp(summary.start_time) + terms, rates, steps = [], [], [] for label, key in cells: key = key_map[key.upper()] - date = (pd.Timestamp(summary.start_time) + timedelta(days=float(label)) - if self.true_order[0] == "days" else pd.Timestamp(label)) - if date != date.normalize() or date not in dates or np.sum(abs(dates - date) <= pd.Timedelta(hours=6)) != 1: - raise ValueError(f"linw needs an isolated midnight report at {date} (±6 hour lookup)") if summary.unit(key).upper() != "SM3/DAY": raise ValueError(f"Expected metric surface rate for {key}, got {summary.unit(key)}") - values.append(summary.iget(key, dates.get_loc(date))) + time = (float(label) if self.true_order[0] == "days" + else (pd.Timestamp(label) - start) / pd.Timedelta(days=1)) + i = int(np.argmin(abs(days - time))) + step = days[i] - (days[i - 1] if i else 0.0) + after = days[i + 1] - days[i] if i + 1 < len(days) else step + # Summary times are single precision: the window must be resolved by them. + if abs(days[i] - time) > 1e-3 or min(step, after) < 16 * np.spacing(np.float32(days[i])): + raise ValueError(f"No simulator step ends on the report at {label}") kind, well = key.split(":") - rows.append(f"{date:%Y-%m-%d} {well} {phases[kind]}") + # A term is active on the substep whose end lies in its window. + terms.append({"kind": "rate", "wells": [well], "phase": PHASES[kind], + "window_days": [days[i] - step / 2, days[i] + after / 2]}) + rates.append(summary.numpy_vector(key)[len(summary.days) - len(days) + i]) + steps.append((i, step * 86400.0)) + rates = np.asarray(rates, dtype=float) + + # A rate term is weight * dt * q, with q the internal rate (m3/s, negative for a + # producer). Its unit-weight value gives dt of each report's substep in double + # precision; the summary's time differences only check it. + values = self._objective_terms(deck, root, archive, terms) + seconds = {} + for (i, step), value, rate in zip(steps, values, rates): + if rate: + seconds.setdefault(i, []).append(-86400.0 * value / rate) + resolution = 86400.0 * 2 * np.spacing(np.float32(days[-1])) + for i, estimates in seconds.items(): + step = next(step for j, step in steps if j == i) + if not np.allclose(estimates, step, rtol=1e-3, atol=resolution): + raise ValueError("Rate objectives do not match the forward summary (units, sign or timing)") + seconds[i] = float(np.median(estimates)) + unit = np.array([-86400.0 / seconds.get(i, step) for i, step in steps]) + + with closing(ResdataFile(str(root / (self.file + ".INIT")))) as init: + cells_total = int(np.prod(init["INTEHEAD"][0][8:11])) + deck_fields = {key: np.asarray(init[key.removeprefix("log_").upper()][0]) for key in state} + for j, column in enumerate(seeds.T): if not column.any(): continue - objective = root / "weights.txt" - objective.write_text("".join(f"{row} {-86400*w:.17g}\n" for row, w in zip(rows, column) if w)) + config = root / "objective.json" + config.write_text(json.dumps({"schema_version": 1, "objective": {"terms": [ + dict(term, weight=w * u) for term, w, u in zip(terms, column, unit) if w]}})) with TemporaryDirectory(dir=root) as replay: out = Path(replay) - self._flow(deck, out, archive, "--adjoint-mode=gradient", f"--adjoint-objective=linw:{objective}") - prefix = out / (self.file + ".ADJOINT_GRADIENTS_PV.txt") - with prefix.open() as f: - actual = float(f.readline().split("J = ")[1].split(")")[0]) + self._flow(deck, out, archive, "--adjoint-mode=gradient", f"--adjoint-config={config}") + prefix = str(out / self.file) + ".ADJOINT_GRADIENTS" + actual = json.loads(Path(prefix + ".json").read_text())["objective"]["value"] # UNSMRY is single precision: scale roundoff by the terms before cancellation. - if not np.isclose(actual, column @ values, rtol=2e-5, - atol=1e-8 + 1e-7 * (abs(column) @ np.abs(values))): - raise ValueError("linw replay does not match the weighted forward summary") - perm = np.loadtxt(out / (self.file + ".ADJOINT_GRADIENTS_PERM.txt"), ndmin=2) - for name, x in state.items(): - x = np.asarray(x) - if perm.shape != (len(x), 3): - raise ValueError(f"{name} must follow Flow's serial active-cell order") - if name == "poro": - g = np.loadtxt(prefix, ndmin=1) / x - else: - axes = "xyz".index(name[-1]) - g = perm[:, axes] * 9.869233e-16 - if name.startswith("log_"): - g *= np.exp(x) - if not np.isfinite(g).all(): - raise ValueError(f"Nonfinite replay gradient for {name}") - gradients[name][j] = g + if not np.isclose(actual, column @ rates, rtol=2e-5, + atol=1e-8 + 1e-6 * (abs(column) @ abs(rates))): + raise ValueError("Replayed objective does not match the weighted forward summary") + poro = np.loadtxt(prefix + "_PORO.csv", delimiter=",", skiprows=1, ndmin=2) + perm = np.loadtxt(prefix + "_PERM.csv", delimiter=",", skiprows=1, ndmin=2) + order = np.argsort(poro[:, 0]) + active = poro[order, 0].astype(int) + if not np.array_equal(active, np.sort(perm[:, 0]).astype(int)): + raise ValueError("Porosity and permeability gradients cover different cells") + poro, perm = poro[order, 1], perm[np.argsort(perm[:, 0]), 1:] * 9.869233e-16 + for name, x in state.items(): + x = np.asarray(x, dtype=float) + if x.size not in (len(active), cells_total): + raise ValueError(f"{name} must have one value per active cell or per grid cell") + at = active if x.size == cells_total else slice(None) + expected = np.exp(x[at]) if name.startswith("log_") else x[at] + if (expected.shape != deck_fields[name].shape or not np.all(expected > 0) + or not np.allclose(deck_fields[name], expected, rtol=2e-5, atol=0)): + raise ValueError(f"{name} must render directly in grid order (check units and clipping)") + g = poro / expected if name == "poro" else perm[:, "xyz".index(name[-1])] + if name.startswith("log_"): + g = g * expected + if not np.isfinite(g).all(): + raise ValueError(f"Nonfinite replay gradient for {name}") + gradients[name][j, at] = g return gradients + + def _objective_terms(self, deck, root, archive, terms): + """Values of unit-weight objective ``terms`` on the recorded trajectory.""" + config = root / "terms.json" + config.write_text(json.dumps({"schema_version": 1, "objective": {"terms": terms}})) + with TemporaryDirectory(dir=root) as replay: + self._flow(deck, Path(replay), archive, "--adjoint-mode=objective", f"--adjoint-config={config}") + log = (Path(replay) / "flow.log").read_text() + values = re.findall(r"Adjoint objective term\s+\d+\s+\S+\s+J_term = (\S+)", log) + if len(terms) == 1: # the tool lists the terms only when there are several + values = re.findall(r"Adjoint objective J = (\S+)", log) + if len(values) != len(terms): + raise RuntimeError("Could not read the objective terms from the flow_adjoint log") + return np.array(values, dtype=float) diff --git a/tests/test_flow_vjp.py b/tests/test_flow_vjp.py index 2865665..f37f95a 100644 --- a/tests/test_flow_vjp.py +++ b/tests/test_flow_vjp.py @@ -1,4 +1,4 @@ -"""Integration: point OPM_ADJOINT_CASE at MODEL_1D_DEBUG/inputfiles from opm-tests-adjoint.""" +"""Integration: point OPM_ADJOINT_CASE at doc/tutorials/MODEL_1D_DEBUG of OPM/opm-adjoint.""" import os from pathlib import Path @@ -12,25 +12,25 @@ from misc.structures.layout import DataLayout -@pytest.mark.skipif(not os.environ.get("OPM_ADJOINT_CASE"), reason="requires adjoint-enabled Flow and debug deck") -def test_weighted_producer_rate_matches_forward_directional_difference(tmp_path, monkeypatch): +# Fixed steps: one substep per report. Adaptive steps: several, of which the last one carries the datum. +@pytest.mark.skipif(not os.environ.get("OPM_ADJOINT_CASE"), reason="requires flow_adjoint and its tutorial deck") +@pytest.mark.parametrize("steps,flags", [((2, 4), "--enable-adaptive-time-stepping=false"), ((40, 80), "")]) +def test_weighted_producer_rate_matches_forward_directional_difference(tmp_path, monkeypatch, steps, flags): source = Path(os.environ["OPM_ADJOINT_CASE"]).resolve() deck = (source / "MODEL_1D_DEBUG.DATA").read_text() deck = re.sub(r"INCLUDE\s+(\w+\.txt)\s*/", lambda m: (source / m[1]).read_text(), deck) deck = re.sub(r"(?ms)^PERMX\s.*?/", "PERMX\n${' '.join(map(str, permx))} /", deck) deck = re.sub(r"(?ms)^PORO\s.*?/", "PORO\n${' '.join(map(str, poro))} /", deck) - deck = re.sub(r"(?ms)^TSTEP\s.*?/", "TSTEP\n 2 2 /", deck) - # The exported MRST fixture uses -1 for a missing VFP table; Flow expects 0. - deck = deck.replace("1* -1 1*/", "1* 0 1*/").replace("1* -1 1*", "1* 0 1*") + deck = re.sub(r"(?ms)^TSTEP\s.*?/", f"TSTEP\n {steps[0]} {steps[1] - steps[0]} /", deck) monkeypatch.chdir(tmp_path) Path("TEST.mako").write_text(deck) - sim = FlowAdjoint({"runfile": "TEST", "datatype": ["wopr:prod"], "reporttype": "days", "reportpoint": [2, 4], + sim = FlowAdjoint({"runfile": "TEST", "datatype": ["wopr:prod"], "reporttype": "days", "reportpoint": list(steps), "adjoint_executable": os.environ.get("FLOW_ADJOINT", "flow_adjoint"), - "simoptions": {"sim_flag": "--enable-adaptive-time-stepping=false --tolerance-cnv=1e-7"}}) + "simoptions": {"sim_flag": f"{flags} --tolerance-cnv=1e-7 --tolerance-mb=1e-9"}}) sim.setup_fwd_run() x, d = np.full(3, 100.), np.array([.2, 1., -.3]) w = np.array([[1., 0., -.5], [0., 1., 1.]]) # two Jacobian rows and a projected row - layout = DataLayout.from_frame(pd.DataFrame({"wopr:prod": [0., 0.]}, index=[2, 4])) + layout = DataLayout.from_frame(pd.DataFrame({"wopr:prod": [0., 0.]}, index=list(steps))) p = np.full(3, .1) g = sim.run_vjp({"permx": x, "poro": p}, layout.to_frame(w)) From abbc2bac39383662669904b9dd3f43a604c80b24 Mon Sep 17 00:00:00 2001 From: Kristian Fossum Date: Fri, 27 Nov 2026 10:04:28 +0100 Subject: [PATCH 3/5] feat: let the user choose opm-adjoint's linear solver FlowAdjoint refused every --adjoint- flag in sim_flag, so the solver of the transposed systems could not be chosen. On a 2,500-cell deck the default iterative solver stopped short of its tolerance for a single-datum objective and aborted the sweep; the direct solver (--adjoint-linear-solver=umfpack) did not. Only the flags the wrapper sets itself are refused now: the archive, mode, objective, output and storage-cache flags. --- README.md | 3 +++ src/subsurface/multphaseflow/opm_adjoint.py | 8 ++++++-- tests/test_flow_vjp.py | 8 ++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f58a3ab..cdfba6e 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,9 @@ need. [OPM/opm-adjoint#3](https://github.com/OPM/opm-adjoint/pull/3) for wells that the schedule defines after the first report step. - The same executable and solver flags drive both predictions and adjoints. + opm-adjoint's own solver flags, such as `--adjoint-linear-solver=umfpack`, + go in `sim_flag` with the others; the wrapper sets the archive, mode, + objective and output flags itself and refuses them there. Use converged forward tolerances and check a directional derivative when moving to a new deck; matching objective values checks units and timing, not the accuracy of the backend derivative. diff --git a/src/subsurface/multphaseflow/opm_adjoint.py b/src/subsurface/multphaseflow/opm_adjoint.py index 8a6c457..df6e611 100644 --- a/src/subsurface/multphaseflow/opm_adjoint.py +++ b/src/subsurface/multphaseflow/opm_adjoint.py @@ -18,6 +18,10 @@ PHASES = {"WOPR": "oil", "WWPR": "water", "WGPR": "gas"} FIELDS = {"poro", "permx", "permy", "permz", "log_permx", "log_permy", "log_permz"} +# Flags the wrapper sets itself; the adjoint's solver settings (--adjoint-linear-solver...) remain the user's. +OWNED_FLAGS = ("--adjoint-file", "--adjoint-save", "--adjoint-mode", "--adjoint-config", "--adjoint-objective", + "--output-dir", "--enable-storage-cache") + class FlowAdjoint(flow): @@ -29,8 +33,8 @@ def __init__(self, input_file): if self.options["mpi"] or self.options["mpiarray"] or input_file.get("hpc") or self.upscale: raise ValueError("FlowAdjoint supports serial, non-upscaled decks only") self.flags = shlex.split(self.options["sim_flag"]) - if any(f.startswith(("--adjoint-", "--output-dir", "--enable-storage-cache")) for f in self.flags): - raise ValueError("FlowAdjoint owns archive, output and storage-cache flags") + if any(f.startswith(OWNED_FLAGS) for f in self.flags): + raise ValueError("FlowAdjoint owns the archive, mode, objective, output and storage-cache flags") if self.options["parsing-strictness"]: self.flags.append("--parsing-strictness=" + self.options["parsing-strictness"]) diff --git a/tests/test_flow_vjp.py b/tests/test_flow_vjp.py index f37f95a..36b3000 100644 --- a/tests/test_flow_vjp.py +++ b/tests/test_flow_vjp.py @@ -46,3 +46,11 @@ def forward(y, z): fd = (forward(x, p + delta*d) - forward(x, p - delta*d)) / (2*delta) assert np.linalg.norm(fd) > 1e-5 np.testing.assert_allclose(g["poro"] @ d, fd, rtol=.02, atol=1e-5) + + +def test_the_solver_of_the_adjoint_is_the_users_choice_and_the_run_mode_is_not(): + options = {"runfile": "TEST", "datatype": ["wopr:prod"], "reporttype": "days", "reportpoint": [2, 4]} + sim = FlowAdjoint({**options, "simoptions": {"sim_flag": "--adjoint-linear-solver=umfpack"}}) + assert "--adjoint-linear-solver=umfpack" in sim.flags + with pytest.raises(ValueError, match="FlowAdjoint owns"): + FlowAdjoint({**options, "simoptions": {"sim_flag": "--adjoint-mode=gradient"}}) From e9c0a878843438a9375d3cbfcb0262d3bd33cdb4 Mon Sep 17 00:00:00 2001 From: Kristian Fossum Date: Fri, 27 Nov 2026 10:05:09 +0100 Subject: [PATCH 4/5] feat: check that the OPM adjoint resolves every chain-rule term run_vjp returned the sensitivity to the field a state variable is written to, and nothing told whether the deck moved anything else with it. A deck with COPY PERMX PERMY lost the y part of the gradient without an error, and the replayed objective still matched. FlowAdjoint.check_chain_rule(state, weights=None) perturbs each variable, renders the deck again and lets Flow read it without simulating. The rendered text may differ only in the keyword of the variable's own field, and Flow's INIT arrays only in that field, in what Flow derives from it, and in permeability axes tied to it by a constant factor. run_vjp adds the tied axes to the gradient, runs the check before its first batch and raises on anything else. Connection factors left for Flow to compute are reported as approximate. With weights, the gradients are also compared with central differences of the weighted sums along an alternating and a uniform direction at two step sizes, through template and simulator. A mismatch raises; rows the step sizes disagree on are marked inconclusive with a warning. vjp.weighted_sums and vjp.finite_difference_check hold the part that does not depend on the simulator. --- README.md | 32 +++- src/subsurface/multphaseflow/opm_adjoint.py | 166 +++++++++++++++++++- src/subsurface/multphaseflow/vjp.py | 45 ++++++ tests/test_flow_vjp.py | 50 +++++- 4 files changed, 284 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index cdfba6e..c59a562 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,12 @@ need. - Use serial METRIC decks writing `INIT`, with independent `poro` (fraction), `permx`, `permy`, `permz` (mD), or `log_permx` etc. (natural log of mD), one value per active cell or per grid cell in natural order. The gradient has - the shape of the state; inactive cells get zero. Direct fields must not - control any other property: copied axes, fault multipliers and nonlinear - Mako transforms need their own chain rule. + the shape of the state; inactive cells get zero. A permeability axis the + deck ties to the variable's field by a constant factor (`COPY`, `MULTIPLY`) + is found and added to its gradient. Anything else that moves with the + state is refused: another keyword the template writes from it, a clipped + or otherwise transformed field, an array Flow derives from it that + opm-adjoint does not differentiate. - Connection factors computed from the permeability and multisegment wells are differentiated by opm-adjoint. Two cases need changes that are not in its master yet: @@ -54,8 +57,27 @@ need. go in `sim_flag` with the others; the wrapper sets the archive, mode, objective and output flags itself and refuses them there. Use converged forward tolerances and check a directional derivative when - moving to a new deck; matching objective values checks units and timing, - not the accuracy of the backend derivative. + moving to a new deck (below); matching objective values checks units and + timing, not the accuracy of the backend derivative. + +`check_chain_rule(state, weights=None)` tells whether the derivative resolves +every term of the chain rule from the state to the weighted sums. It perturbs +each variable, renders the deck again and lets Flow read it without +simulating, then compares the rendered text and Flow's `INIT` arrays with the +unperturbed ones. `run_vjp` runs this part itself before its first batch, and +raises on a term it would miss. The returned report lists the tied axes +(`ties`), the arrays Flow derives (`derived`) and what opm-adjoint +differentiates approximately (`approximate`: connection factors left for Flow +to compute from the permeability, of which it keeps the Kh term). + +With `weights`, the gradients are also compared with central differences of +the weighted sums along an alternating and a uniform direction, at two step +sizes: four simulations per variable and direction. This is the check that +reaches dependencies inside Flow which its `INIT` arrays do not show. A +mismatch raises. A row with `ok = None` could not be judged because the +finite differences change too much with the step: the simulated rates are +not smooth in the state, which adaptive time stepping and loose solver +tolerances cause; fixed steps and tight tolerances make it conclusive. Run the directional derivative tests with `FLOW_ADJOINT` pointing to the executable and `OPM_ADJOINT_CASE` to `doc/tutorials/MODEL_1D_DEBUG` of diff --git a/src/subsurface/multphaseflow/opm_adjoint.py b/src/subsurface/multphaseflow/opm_adjoint.py index df6e611..25b1a7e 100644 --- a/src/subsurface/multphaseflow/opm_adjoint.py +++ b/src/subsurface/multphaseflow/opm_adjoint.py @@ -7,6 +7,7 @@ import shlex import subprocess from tempfile import TemporaryDirectory +import warnings import numpy as np import pandas as pd @@ -14,16 +15,19 @@ from resdata.resfile import ResdataFile from .opm import flow -from .vjp import scalar_seeds +from .vjp import finite_difference_check, scalar_seeds, weighted_sums PHASES = {"WOPR": "oil", "WWPR": "water", "WGPR": "gas"} FIELDS = {"poro", "permx", "permy", "permz", "log_permx", "log_permy", "log_permz"} +# INIT arrays Flow computes from a field; opm-adjoint carries their derivatives itself. +DERIVED = {"PORO": {"PORV"}, "PERMX": {"TRANX", "TRANY", "TRANZ"}, "PERMY": {"TRANX", "TRANY", "TRANZ"}, + "PERMZ": {"TRANX", "TRANY", "TRANZ"}} +HEADERS = {"INTEHEAD", "LOGIHEAD", "DOUBHEAD"} # Flags the wrapper sets itself; the adjoint's solver settings (--adjoint-linear-solver...) remain the user's. OWNED_FLAGS = ("--adjoint-file", "--adjoint-save", "--adjoint-mode", "--adjoint-config", "--adjoint-objective", "--output-dir", "--enable-storage-cache") - class FlowAdjoint(flow): """Use the same Flow executable, deck renderer and flags for predictions and VJPs.""" @@ -37,6 +41,7 @@ def __init__(self, input_file): raise ValueError("FlowAdjoint owns the archive, mode, objective, output and storage-cache flags") if self.options["parsing-strictness"]: self.flags.append("--parsing-strictness=" + self.options["parsing-strictness"]) + self.chain_rule = None # the report of check_chain_rule, once it has run def _flow(self, deck, output, *flags): output.mkdir(exist_ok=True) @@ -68,6 +73,8 @@ def run_vjp(self, state, weights): kind, _, well = key.partition(":") if kind.upper() not in PHASES or not re.fullmatch(r"[\w.-]+", well): raise ValueError(f"Unsupported production rate: {key}") + if self.chain_rule is None or set(self.chain_rule["ties"]) != set(state): + self.check_chain_rule(state) gradients = {key: np.zeros((seeds.shape[1], np.size(x))) for key, x in state.items()} with TemporaryDirectory(prefix="vjp_", dir=".") as tmp: root = Path(tmp).resolve() @@ -154,7 +161,11 @@ def run_vjp(self, state, weights): if (expected.shape != deck_fields[name].shape or not np.all(expected > 0) or not np.allclose(deck_fields[name], expected, rtol=2e-5, atol=0)): raise ValueError(f"{name} must render directly in grid order (check units and clipping)") - g = poro / expected if name == "poro" else perm[:, "xyz".index(name[-1])] + if name == "poro": + g = poro / expected + else: # the deck may tie other axes to this one: PERMb = factor * PERMa + g = perm[:, "xyz".index(name[-1])] + sum( + factor * perm[:, "xyz".index(axis)] for axis, factor in self.chain_rule["ties"][name].items()) if name.startswith("log_"): g = g * expected if not np.isfinite(g).all(): @@ -175,3 +186,152 @@ def _objective_terms(self, deck, root, archive, terms): if len(values) != len(terms): raise RuntimeError("Could not read the objective terms from the flow_adjoint log") return np.array(values, dtype=float) + + # ------------------------------------------------------------------ + # Does the derivative resolve every term of the chain rule? + # ------------------------------------------------------------------ + def check_chain_rule(self, state, weights=None, step=1e-2, rtol=0.05, seed=0): + """Find everything in the deck that moves with ``state``, and say whether ``run_vjp`` differentiates it. + + Each state variable is perturbed, the deck rendered again and read by Flow without simulating. The + rendered text may differ only inside the keyword of the variable's own field, and the grid arrays Flow + reports only in that field, in what Flow derives from it, and in permeability axes the deck ties to it + by a constant factor (``COPY``/``MULTIPLY``), which ``run_vjp`` then adds. Anything else is a term the + derivative lacks, and raises. Connection factors left for Flow to compute from the permeability are + listed as ``approximate``: opm-adjoint keeps their leading term. + + With ``weights`` (as for ``run_vjp``) the gradients are also compared with central differences of the + weighted sums through template and simulator: the check of the whole chain, at four simulations per + variable and direction. A mismatch raises; the rows are in the returned report. + """ + if not state or set(state) - FIELDS: + raise ValueError(f"Expected direct cell fields from {sorted(FIELDS)}, got {list(state)}") + rng = np.random.default_rng(seed) + report = {"ties": {}, "derived": {}, "approximate": [], "unresolved": [], "finite_difference": []} + base_text, base, _, wells = self._dry_run(state) + if wells and any(name != "poro" for name in state): + report["approximate"].append( + f"connection factors of {wells} follow the permeability; opm-adjoint differentiates the " + "leading (Kh) term only") + for name, x in state.items(): + x = np.asarray(x, dtype=float) + target = name.removeprefix("log_").upper() + sign = rng.choice([-1.0, 1.0], size=x.shape) + moved = x + 1e-3 * sign if name.startswith("log_") else x * (1 + 1e-3 * sign) + text, arrays, cells, _ = self._dry_run({**state, name: moved}) + lines, base_lines = text.splitlines(), base_text.splitlines() + if len(lines) != len(base_lines): + report["unresolved"].append(f"{name} changes the layout of the rendered deck") + else: + keywords = _keyword_of_lines(base_lines) + touched = {keywords[i] for i, (a, b) in enumerate(zip(lines, base_lines)) if a != b} + for keyword in sorted(touched - {target}): + report["unresolved"].append(f"the template writes {keyword} from {name}") + changed = {key for key in base if key not in arrays or not np.array_equal(arrays[key], base[key])} + if target not in changed: + report["unresolved"].append(f"{name} does not reach {target} in the deck Flow reads") + continue + active = arrays[target] != base[target] + expected = np.exp(moved) if name.startswith("log_") else moved + if expected.size != base[target].size: # one value per grid cell + expected = expected[cells] + if not np.allclose(arrays[target], expected, rtol=2e-5, atol=0): + report["unresolved"].append( + f"{target} is not {name} itself in {int(np.sum(~np.isclose(arrays[target], expected, rtol=2e-5, atol=0)))} " + "cells (clipping or another transform)") + ties = {} + for axis in "xyz": + other = "PERM" + axis.upper() + if target.startswith("PERM") and other != target and other in changed: + factor = float(np.median(base[other][active] / base[target][active])) + tied = all(np.allclose(a[other], factor * a[target], rtol=1e-5, atol=0) for a in (base, arrays)) + if tied and not {other.lower(), "log_" + other.lower()} & set(state): + ties[axis] = factor + else: + report["unresolved"].append(f"{other} follows {name}, but not by a constant factor of its own") + report["ties"][name] = ties + allowed = {target} | DERIVED[target] | {"PERM" + axis.upper() for axis in ties} + report["derived"][name] = sorted(changed & (allowed - {target})) + for key in sorted(changed - allowed): + report["unresolved"].append(f"{key} follows {name}") + if report["unresolved"]: + raise ValueError("run_vjp would miss part of the chain rule: " + "; ".join(report["unresolved"])) + for note in report["approximate"]: + warnings.warn(note, stacklevel=2) + self.chain_rule = report + if weights is not None: + cells, seeds = scalar_seeds(weights, self.true_order[1], self.all_data_types) + member = iter(range(10**6)) + + def forward(x): + records = self.run_fwd_sim({key: np.array(value, dtype=float) for key, value in x.items()}, next(member)) + return weighted_sums(records, self.true_order[1], cells, seeds) + + gradients = self.run_vjp({key: np.array(value, dtype=float) for key, value in state.items()}, weights) + report["finite_difference"] = finite_difference_check(forward, gradients, state, forward(state), step, rtol, seed) + failed = [row for row in report["finite_difference"] if row["ok"] is False] + if failed: + raise ValueError(f"Gradients differ from finite differences beyond {rtol:g}: {failed[:4]}") + if any(row["ok"] is None for row in report["finite_difference"]): + warnings.warn("The finite differences change too much with the step to judge some gradients: the " + "simulated rates are not smooth in the state. Tighten the solver tolerances or fix " + "the time steps (rows with ok=None in the report).", stacklevel=2) + return report + + def _dry_run(self, state): + """Render ``state`` and let Flow read the deck without simulating. + + Returns the deck text, its INIT arrays, the active cells, and the wells whose connection factors Flow + computes from the permeability. The deck sits where a member's deck does, so relative includes resolve. + """ + with TemporaryDirectory(prefix="audit_", dir=".") as tmp: + folder = Path(tmp).resolve() + self._runMako(str(folder) + "/", dict({key: np.array(value, dtype=float) for key, value in state.items()}, + member=0, level=self.level)) + deck = folder / (self.file + ".DATA") + self._flow(deck, folder, "--enable-dry-run=true") + with closing(ResdataFile(str(folder / (self.file + ".INIT")))) as init: + arrays = {key: np.asarray(init[key][0]).copy() for key in dict.fromkeys(init.keys()) if key not in HEADERS} + with closing(ResdataFile(str(folder / (self.file + ".EGRID")))) as grid: + cells = np.asarray(grid["ACTNUM"][0]) != 0 if grid.has_kw("ACTNUM") else slice(None) + return deck.read_text(), arrays, cells, _connection_factors_from_permeability(deck) + + +def _keyword_of_lines(lines): + """The deck keyword each line belongs to.""" + current, out = "", [] + for line in lines: + if re.fullmatch(r"[A-Z][A-Z0-9_]{1,7}", line.strip()): + current = line.strip() + out.append(current) + return out + + +def _connection_factors_from_permeability(deck): + """Wells with a COMPDAT connection whose transmissibility factor (item 8) and Kh (item 10) are both defaulted.""" + wells, seen = set(), set() + + def scan(path): + if path in seen or not path.is_file(): + return + seen.add(path) + keyword = "" + text = re.sub(r"--.*", "", path.read_text(errors="replace")) + for include in re.findall(r"(?m)^\s*INCLUDE\s*\n\s*'?([^'/\s][^'\n]*?)'?\s*/", text): + scan((path.parent / include.strip()).resolve()) + for line in text.splitlines(): + stripped = line.strip() + if re.fullmatch(r"[A-Z][A-Z0-9_]{1,7}", stripped): + keyword = stripped + elif keyword in ("COMPDAT", "COMPDATL") and stripped and stripped != "/": + items = [] + for token in stripped.split("/")[0].split(): + repeat = re.fullmatch(r"(\d+)\*", token) + items += ["*"] * int(repeat[1]) if repeat else [token] + items += ["*"] * (14 - len(items)) + offset = 1 if keyword == "COMPDATL" else 0 + if items[7 + offset] == "*" and items[9 + offset] == "*": + wells.add(items[0].strip("'")) + + scan(Path(deck).resolve()) + return sorted(wells) diff --git a/src/subsurface/multphaseflow/vjp.py b/src/subsurface/multphaseflow/vjp.py index 311673d..12cdfe2 100644 --- a/src/subsurface/multphaseflow/vjp.py +++ b/src/subsurface/multphaseflow/vjp.py @@ -21,3 +21,48 @@ def scalar_seeds(weights, reports, datatypes): if not cells: raise ValueError("VJP needs at least one observed cell") return cells, np.stack(vectors) + + +def weighted_sums(prediction, reports, cells, seeds): + """The weighted sums of ``scalar_seeds`` cells in a wrapper's forward output (a frame, or records per report).""" + values = [] + for label, key in cells: + if hasattr(prediction, "at"): + values.append(prediction.at[label, key]) + else: + values.append(prediction[list(reports).index(label)][key]) + return np.array([float(np.ravel(v)[0]) for v in values]) @ seeds + + +def finite_difference_check(forward, gradients, state, sums, step=1e-2, rtol=0.05, seed=0): + """Compare ``gradients`` with central differences of the weighted sums along random directions. + + ``forward(state)`` returns the sums, ``(k,)``; ``gradients[name]`` is ``(k, n)``. Each state variable is + perturbed along a +-1 direction (every entry moves, also those next to wells) and along a uniform shift, + additively for ``log_`` variables and relative to its value otherwise. Two step sizes separate the error of + the difference quotient from a derivative that is missing a term. Returns one row per variable, direction + and sum; ``ok`` is ``False`` for a mismatch and ``None`` where the two step sizes disagree too much to tell. + """ + rng = np.random.default_rng(seed) + rows = [] + for name, x in state.items(): + x = np.asarray(x, dtype=float) + scale = np.ones_like(x) if name.startswith("log_") else x + for kind, pattern in (("alternating", rng.choice([-1.0, 1.0], size=x.shape)), ("uniform", np.ones_like(x))): + direction = pattern * scale + quotients = [] + for h in (step, step / 2): + plus = forward({**state, name: x + h * direction}) + minus = forward({**state, name: x - h * direction}) + quotients.append((np.asarray(plus) - np.asarray(minus)) / (2 * h)) + adjoint = np.asarray(gradients[name]) @ direction + for j, (coarse, fine, value) in enumerate(zip(*quotients, adjoint)): + spread = abs(coarse - fine) + tolerance = rtol * max(abs(fine), abs(value)) + ok = bool(abs(value - fine) <= tolerance + 2 * spread) + if spread > tolerance: + ok = None if ok else False + rows.append({"variable": name, "direction": kind, "sum": j, "adjoint": float(value), + "finite_difference": float(fine), "step_spread": float(spread), + "base": float(sums[j]), "ok": ok}) + return rows diff --git a/tests/test_flow_vjp.py b/tests/test_flow_vjp.py index 36b3000..3c25513 100644 --- a/tests/test_flow_vjp.py +++ b/tests/test_flow_vjp.py @@ -8,7 +8,7 @@ import pandas as pd import pytest -from subsurface.multphaseflow.opm_adjoint import FlowAdjoint +from subsurface.multphaseflow.opm_adjoint import FlowAdjoint, _connection_factors_from_permeability from misc.structures.layout import DataLayout @@ -54,3 +54,51 @@ def test_the_solver_of_the_adjoint_is_the_users_choice_and_the_run_mode_is_not() assert "--adjoint-linear-solver=umfpack" in sim.flags with pytest.raises(ValueError, match="FlowAdjoint owns"): FlowAdjoint({**options, "simoptions": {"sim_flag": "--adjoint-mode=gradient"}}) + + +PERMX = "PERMX\n${' '.join(map(str, permx))} /" + + +def tutorial_template(steps=(2, 4), flags="--enable-adaptive-time-stepping=false", **blocks): + """The tutorial deck as a Mako template, with the given keyword blocks replaced.""" + source = Path(os.environ["OPM_ADJOINT_CASE"]).resolve() + deck = (source / "MODEL_1D_DEBUG.DATA").read_text() + deck = re.sub(r"INCLUDE\s+(\w+\.txt)\s*/", lambda m: (source / m[1]).read_text(), deck) + deck = re.sub(r"(?ms)^TSTEP\s.*?/", f"TSTEP\n {steps[0]} {steps[1] - steps[0]} /", deck) + for keyword, block in blocks.items(): + deck = re.sub(rf"(?ms)^{keyword}\s.*?/", lambda _: block, deck) + Path("TEST.mako").write_text(deck) + sim = FlowAdjoint({"runfile": "TEST", "datatype": ["wopr:prod"], "reporttype": "days", "reportpoint": list(steps), + "adjoint_executable": os.environ.get("FLOW_ADJOINT", "flow_adjoint"), + "simoptions": {"sim_flag": f"{flags} --tolerance-cnv=1e-7 --tolerance-mb=1e-9"}}) + sim.setup_fwd_run() + layout = DataLayout.from_frame(pd.DataFrame({"wopr:prod": [0., 0.]}, index=list(steps))) + return sim, layout.to_frame(np.array([[1.], [.5]])) + + +@pytest.mark.skipif(not os.environ.get("OPM_ADJOINT_CASE"), reason="requires flow_adjoint and its tutorial deck") +def test_an_axis_the_deck_copies_is_found_and_differentiated(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + # The flow is along x, which the state reaches only through the deck's COPY + sim, weights = tutorial_template(PERMY="PERMY\n${' '.join(map(str, permy))} /\nCOPY\n PERMY PERMX /\n/\nMULTIPLY\n PERMX 0.5 /\n/", + PERMX="") + report = sim.check_chain_rule({"permy": np.full(3, 200.)}, weights) + assert report["ties"] == {"permy": {"x": 0.5}} and report["approximate"] == [] + rows = report["finite_difference"] + assert len(rows) == 2 and all(row["ok"] for row in rows) and all(abs(row["adjoint"]) > 1e-6 for row in rows) + + +@pytest.mark.skipif(not os.environ.get("OPM_ADJOINT_CASE"), reason="requires flow_adjoint and its tutorial deck") +def test_a_field_the_template_computes_from_the_state_is_refused(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + sim, weights = tutorial_template(PERMX=PERMX, + PORO="PORO\n${' '.join(str(0.1 + 1e-4 * k) for k in permx)} /") + with pytest.raises(ValueError, match="template writes PORO from permx"): + sim.run_vjp({"permx": np.full(3, 100.)}, weights) + + +def test_defaulted_connection_factors_are_found_through_includes(tmp_path): + (tmp_path / "wells.inc").write_text("COMPDAT\n 'P1' 1 1 1 1 OPEN 2* 0.25 /\n 'P2' 2 1 1 1 OPEN 1* 5.3 0.25 /\n" + " 'P3' 3 1 1 1 OPEN 2* 0.25 120.0 /\n/\n") + (tmp_path / "CASE.DATA").write_text("SCHEDULE\nINCLUDE\n 'wells.inc' /\n") + assert _connection_factors_from_permeability(tmp_path / "CASE.DATA") == ["P1"] From 1b2b4ffda2e03df205133011d56e22a028e9fd52 Mon Sep 17 00:00:00 2001 From: Kristian Fossum Date: Fri, 27 Nov 2026 10:05:16 +0100 Subject: [PATCH 5/5] fix: record every substep when the deck has RPTONLY run_vjp takes the substep lengths from the summary of its recorded run. A deck with RPTONLY writes the summary at report steps only, so with several substeps per report the run was refused. The keyword is commented out in the deck of the recorded run; forecasts are unchanged. --- README.md | 3 ++- src/subsurface/multphaseflow/opm_adjoint.py | 2 ++ tests/test_flow_vjp.py | 15 ++++++++++++++- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c59a562..cc6618b 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,8 @@ need. - Use scalar `WOPR`, `WWPR` or `WGPR` for **producing wells** in Sm³/day. A report may be any time a simulator step ends on; the wrapper checks the - objective against the recorded summary. Turn off summary thinning. + objective against the recorded summary, which must hold every simulator + step: `RPTONLY` in the deck is switched off for the recorded run. - Use serial METRIC decks writing `INIT`, with independent `poro` (fraction), `permx`, `permy`, `permz` (mD), or `log_permx` etc. (natural log of mD), one value per active cell or per grid cell in natural order. The gradient has diff --git a/src/subsurface/multphaseflow/opm_adjoint.py b/src/subsurface/multphaseflow/opm_adjoint.py index 25b1a7e..f683f78 100644 --- a/src/subsurface/multphaseflow/opm_adjoint.py +++ b/src/subsurface/multphaseflow/opm_adjoint.py @@ -80,6 +80,8 @@ def run_vjp(self, state, weights): root = Path(tmp).resolve() self._runMako(str(root) + "/", dict(state, member=0, level=self.level)) deck = root / (self.file + ".DATA") + # The substep lengths come from the summary, which RPTONLY would thin to the report steps + deck.write_text(re.sub(r"(?m)^[ \t]*RPTONLY[ \t]*$", "-- RPTONLY", deck.read_text())) archive = f"--adjoint-file={root / 'archive'}" self._flow(deck, root, archive, "--adjoint-save=true") summary = Summary(str(root / self.file)) diff --git a/tests/test_flow_vjp.py b/tests/test_flow_vjp.py index 3c25513..229457a 100644 --- a/tests/test_flow_vjp.py +++ b/tests/test_flow_vjp.py @@ -59,12 +59,14 @@ def test_the_solver_of_the_adjoint_is_the_users_choice_and_the_run_mode_is_not() PERMX = "PERMX\n${' '.join(map(str, permx))} /" -def tutorial_template(steps=(2, 4), flags="--enable-adaptive-time-stepping=false", **blocks): +def tutorial_template(steps=(2, 4), flags="--enable-adaptive-time-stepping=false", report_steps_only=False, **blocks): """The tutorial deck as a Mako template, with the given keyword blocks replaced.""" source = Path(os.environ["OPM_ADJOINT_CASE"]).resolve() deck = (source / "MODEL_1D_DEBUG.DATA").read_text() deck = re.sub(r"INCLUDE\s+(\w+\.txt)\s*/", lambda m: (source / m[1]).read_text(), deck) deck = re.sub(r"(?ms)^TSTEP\s.*?/", f"TSTEP\n {steps[0]} {steps[1] - steps[0]} /", deck) + if report_steps_only: + deck = deck.replace("SUMMARY\n", "SUMMARY\nRPTONLY\n", 1) for keyword, block in blocks.items(): deck = re.sub(rf"(?ms)^{keyword}\s.*?/", lambda _: block, deck) Path("TEST.mako").write_text(deck) @@ -102,3 +104,14 @@ def test_defaulted_connection_factors_are_found_through_includes(tmp_path): " 'P3' 3 1 1 1 OPEN 2* 0.25 120.0 /\n/\n") (tmp_path / "CASE.DATA").write_text("SCHEDULE\nINCLUDE\n 'wells.inc' /\n") assert _connection_factors_from_permeability(tmp_path / "CASE.DATA") == ["P1"] + + +@pytest.mark.skipif(not os.environ.get("OPM_ADJOINT_CASE"), reason="requires flow_adjoint and its tutorial deck") +def test_a_deck_that_reports_the_summary_at_report_steps_only_gives_the_same_gradient(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + gradients = [] + for report_steps_only in (False, True): # adaptive steps: several substeps per report + sim, weights = tutorial_template((40, 80), "", report_steps_only, PERMX=PERMX) + gradients.append(sim.run_vjp({"permx": np.full(3, 100.)}, weights)["permx"]) + assert np.abs(gradients[0]).max() > 0 + np.testing.assert_allclose(gradients[1], gradients[0], rtol=1e-9)