From 0eb743f92f69b6cb5d89095a470224cfd385294a Mon Sep 17 00:00:00 2001 From: Mathias Methlie Nilsen Date: Mon, 2 Nov 2026 14:19:44 +0100 Subject: [PATCH 1/2] Add weighted adjoint (H^T w) to the JutulDarcy wrapper New `weighted_adjoint` option: one adjoint solve per member returns the gradient of sum_i w_i d_i for given data weights (DataFrame or callable (forward_df, member)). With w = C_d^-1 (d_obs - d) this is minus the gradient of the data misfit, as needed by SVGD. The objective is cross-checked against sum(w d) before solving. Also: - Fix cumulative summary vectors (WOPT, ...) being 86400x too large in METRIC/FIELD (JutulDarcy integrates per-day rates over seconds). This changes the values returned for cumulative data types. - Detect LAB units. - Use isapprox for the report-time match in the rate objective. - Share perm-gradient and adjoint-storage setup between both adjoint modes. - Tests: agreement with per-datum sensitivities, linearity in callable weights, Stein's lemma check, and option validation. Co-Authored-By: Claude Opus 5.5 --- src/subsurface/multphaseflow/jutul_darcy.py | 317 ++++++++++++++++++-- tests/test_jutul_darcy.py | 227 ++++++++++++++ 2 files changed, 516 insertions(+), 28 deletions(-) diff --git a/src/subsurface/multphaseflow/jutul_darcy.py b/src/subsurface/multphaseflow/jutul_darcy.py index 52e03b7..9489431 100644 --- a/src/subsurface/multphaseflow/jutul_darcy.py +++ b/src/subsurface/multphaseflow/jutul_darcy.py @@ -16,6 +16,10 @@ deck makes other quantities depend on the permeability field: a COMPDAT connection factor left defaulted (well-index chain rule) and PERMY/PERMZ produced by ``COPY`` from PERMX. Both are detected from the deck by default. +* Weighted adjoints: ``H^T w`` for a weight per datum, in a single adjoint + solve per member regardless of the number of data. With + ``w = Cd^{-1} (d_obs - d_sim)`` this is the data-misfit term of the + log-posterior gradient used by e.g. Stein variational gradient descent. The wrapper communicates with Julia via :mod:`juliacall`. Heavy Julia state is created lazily inside worker processes so the class can be pickled for @@ -79,6 +83,14 @@ "WOPT", "WGPT", "WWPT", "WLPT", }) +#: Seconds per time unit of a rate in each unit system (Sm3/day in METRIC, +#: stb/day in FIELD, cc/hour in LAB). JutulDarcy's summary integrates rates +#: over seconds to get cumulative totals, so those come out too large by this +#: factor in any system other than SI. +RATE_TIME_UNIT_SECONDS: dict[str, int] = { + "si": 1, "metric": SECONDS_PER_DAY, "field": SECONDS_PER_DAY, "lab": 3_600, +} + VALID_OUTPUT_FORMATS: frozenset[str] = frozenset({"list", "dict", "dataframe"}) VALID_ADJOINT_MODES: frozenset[str] = frozenset({"sensitivities", "optimization"}) VALID_REPORT_TYPES: frozenset[str] = frozenset({"days", "dates"}) @@ -137,6 +149,12 @@ #: survives this comparison came from the Peaceman formula rather than the deck. WI_PEACEMAN_RTOL: float = 1e-10 +#: Tolerance in seconds for matching a ministep's end time to a report point. +#: Ministep times are floating-point cumulative sums and can miss the whole +#: second they belong to by a fraction of a second, while no ministep is +#: anywhere near this short. +STEP_TIME_TOL: float = 0.5 + #: Julia helpers that JutulDarcy does not expose itself. Defined once per Julia #: session by :func:`_ensure_julia_helpers`. #: @@ -163,6 +181,11 @@ #: One adjoint sweep against pre-built storage, stopping at `n_steps`. An #: objective that only fires at report step k has zero adjoint contribution #: from every later step, so sweeping them is wasted work. +#: +#: ``subsurface_weighted_well_objective`` +#: ``sum_i w_i * d_i`` over well data ``d_i`` as one sum objective, so its +#: gradient is ``H^T w`` from a single adjoint solve. Entries sharing a well +#: and quantity are grouped, so each ministep evaluates that quantity once. _JULIA_HELPERS: str = """ function subsurface_sensitivities_with_wells(case, result, obj) sens = Jutul.solve_adjoint_sensitivities(case, result, obj) @@ -286,6 +309,43 @@ end return (reservoir = grad, models = sens) end + +function subsurface_weighted_well_objective(wells, targets, is_rate, times, weights, tol) + groups = Dict{Tuple{Symbol, Symbol, Bool}, Tuple{Vector{Float64}, Vector{Float64}}}() + for (w, tgt, r, t, c) in zip(String.(wells), String.(targets), Bool.(collect(is_rate)), + Float64.(collect(times)), Float64.(collect(weights))) + ts, cs = get!(groups, (Symbol(w), Symbol(tgt), r), (Float64[], Float64[])) + push!(ts, t) + push!(cs, c) + end + terms = [ + (well = k[1], target = getfield(JutulDarcy, k[2]), is_rate = k[3], + times = v[1], weights = v[2]) + for (k, v) in groups + ] + + function weighted_well_objective(model, state, dt, step_info, forces) + t = step_info[:time] + obj = 0.0 + for term in terms + # A rate datum is the rate over the ministep ending at its report + # time; a cumulative datum integrates every ministep up to it. + c = 0.0 + for (tk, wk) in zip(term.times, term.weights) + hit = term.is_rate ? abs(t - tk) <= tol : t <= tk + tol + hit && (c += wk) + end + c == 0.0 && continue + ctrl = forces[:Facility].control[term.well] + sgn = ctrl isa JutulDarcy.ProducerControl ? -1.0 : 1.0 + q = JutulDarcy.compute_well_qoi(model, state, forces, term.well, term.target) + # Rates are reported in Sm3/day, cumulatives in Sm3. + obj += c * sgn * q * (term.is_rate ? si_unit(:day) : dt) + end + return obj + end + return weighted_well_objective +end """ @@ -1000,7 +1060,7 @@ def well_QOI_objective(wellID: str, phaseID: str, time: Iterable[float], obj = julia.seval( f""" function well_QOI_{i}(model, state, dt, step_info, forces) - if step_info[:time] != {sec} + if !isapprox(step_info[:time], {sec}; rtol=1e-9, atol=1e-6) return 0.0 end ctrl = forces[:Facility].control[Symbol("{wellID}")] @@ -1063,6 +1123,18 @@ class JutulDarcy: - ``adjoints`` : dict Objective/parameter spec; enables adjoint computation. + - ``weighted_adjoint`` : dict + ``{"parameters": [...]}``; enables the weighted adjoint ``H^T w`` + for the weights given by ``adjoint_weights``. Cannot be combined + with ``adjoints``. + + - ``adjoint_weights`` : pandas.DataFrame or callable + Weights for ``weighted_adjoint``, laid out like the forward + output (report points x datatypes; absent cells weigh zero). A + callable is called as ``adjoint_weights(forward_df, member)`` + after each forward run and returns such a frame, so weights may + depend on the simulated data. May also be set as an attribute. + - ``output_format`` : {"list", "dict", "dataframe"} Output container type. Default ``"dataframe"``. @@ -1136,13 +1208,25 @@ def __init__(self, options: dict): ) # ---- Adjoint configuration --------------------------------------- # + if "adjoints" in options and "weighted_adjoint" in options: + raise ValueError( + "'adjoints' and 'weighted_adjoint' are mutually exclusive" + ) + self.adjoint_info: dict[str, AdjointObjective] = {} + self.weighted_parameters: list[str] | None = None if "adjoints" in options: self.compute_adjoints = True self.adjoint_info = _process_adjoint_info(options["adjoints"]) self.eval_adjoint_funcs = options.get("eval_adjoint_funcs", False) + elif "weighted_adjoint" in options: + self.compute_adjoints = True + params = options["weighted_adjoint"]["parameters"] + self.weighted_parameters = [params] if isinstance(params, str) else list(params) + self.eval_adjoint_funcs = False else: self.compute_adjoints = False self.eval_adjoint_funcs = False + self.adjoint_weights = options.get("adjoint_weights") self.adjoint_funcs: pd.DataFrame | None = None # ---- Output / execution options ---------------------------------- # @@ -1175,6 +1259,8 @@ def __init__(self, options: dict): f"Invalid adjoint_mode '{self.adjoint_mode}'. " f"Must be one of {sorted(VALID_ADJOINT_MODES)}" ) + if self.weighted_parameters is not None and self.adjoint_mode != "sensitivities": + raise ValueError("'weighted_adjoint' requires adjoint_mode 'sensitivities'") self.optimization_targets = options.get("optimization_targets") # ---- PET compatibility attributes -------------------------------- # @@ -1205,6 +1291,10 @@ def __call__(self, inputs: list[dict] | dict | str): Same shape as above, but each result is a ``(forward, adjoint)`` tuple where ``adjoint`` is a :class:`pandas.DataFrame` with a ``(objective, parameter)`` MultiIndex on the columns. + Weighted-adjoint mode + As adjoint mode, but ``adjoint`` is a :class:`pandas.Series` of + full-grid gradients ``H^T w`` indexed by parameter, with the + weighted sum ``w^T d`` in ``adjoint.attrs["value"]``. """ # Normalise to a list so the parallel path is uniform. if isinstance(inputs, (dict, str)): @@ -1294,6 +1384,12 @@ def run_fwd_sim(self, input: dict | str, idn: int = 0, pyres = self.extract_datatypes(jlres, case, units, julia) output = self._format_output(pyres) + if self.weighted_parameters is not None: + adjoint = self._compute_weighted_adjoint( + case, jlres, pyres, units, actnum_vec, idn, julia + ) + return output, adjoint + if self.compute_adjoints: adjoints = self._compute_adjoints( case, jlres, pyres, units, actnum_vec, idn, julia @@ -1371,12 +1467,13 @@ def _detect_units(case, julia) -> str | Any: Returns ------- str - One of ``"metric"``, ``"si"``, ``"field"`` if specified. + One of ``"metric"``, ``"si"``, ``"field"``, ``"lab"`` if specified. Any ``julia.missing`` if no unit keyword is present. """ runspec = case.input_data["RUNSPEC"] - for key, name in (("METRIC", "metric"), ("SI", "si"), ("FIELD", "field")): + for key, name in (("METRIC", "metric"), ("SI", "si"), ("FIELD", "field"), + ("LAB", "lab")): if julia.haskey(runspec, key): return name return julia.missing @@ -1561,6 +1658,11 @@ def extract_datatypes(self, jlres, jlcase, units, julia) -> pd.DataFrame: wells = smry["VALUES"]["WELLS"] field = smry["VALUES"]["FIELD"] + # `summary_result` falls back to METRIC when the deck names no system. + cumulative_scale = RATE_TIME_UNIT_SECONDS[ + str(smry["UNIT_SYSTEM"]).lower() + ] + for datatype in self.datatype: if ":" in datatype: # Well-level datatype: ":" @@ -1585,6 +1687,9 @@ def extract_datatypes(self, jlres, jlcase, units, julia) -> pd.DataFrame: res[datatype] = np.array(field[datatype])[idx] attrs[datatype] = get_metric_unit(datatype) + if datatype.split(":")[0] in CUMULATIVE_KEYS: + res[datatype] = res[datatype] / cumulative_scale + df = pd.DataFrame(res, index=self.index[1]) df.index.name = self.index[0] df.attrs = attrs @@ -1667,37 +1772,17 @@ def _compute_adjoints(self, case, jlres, pyres, units, actnum_vec, # dWI/dK depends only on the case, so it is built once and contracted # with each objective's dJ/dWI below. - needs_perm = any( - "perm" in param.lower() - for obj in self.adjoint_info.values() - for param in obj.parameters + wi_jacobian, ncells, perm_copy = self._perm_gradient_context( + case, actnum_vec, + [p for obj in self.adjoint_info.values() for p in obj.parameters], + julia, ) - if needs_perm: - wi_jacobian, ncells = _well_index_perm_jacobian( - case, julia, self.well_index_from_perm - ) - perm_copy = _detect_copied_perm_axes( - case, actnum_vec, self.perm_copied, julia - ) - else: - wi_jacobian, ncells, perm_copy = {}, 0, None # Build the adjoint storage and the ministep expansion once per member. # `solve_adjoint_sensitivities` does both on every call, which is pure # repetition when a member has many objectives. `step_times` then lets # each objective stop its backward sweep at its own evaluation point. - step_times = None - if self.adjoint_mode == "sensitivities" and self.adjoint_reuse_storage: - julia.adj_packed = _suppress_julia( - julia, "subsurface_adjoint_packed(case, res)" - ) - julia.adj_storage = _suppress_julia( - julia, "subsurface_adjoint_storage(case)" - ) - step_times = np.asarray( - _suppress_julia(julia, "subsurface_packed_step_times(adj_packed)"), - dtype=float, - ) + step_times = self._prepare_adjoint_storage(julia) pbar = self._make_adjoint_pbar(idn) sim_times = np.array(jlres.time) # Unit: seconds @@ -1776,6 +1861,182 @@ def _compute_adjoints(self, case, jlres, pyres, units, actnum_vec, return adjoints + def _compute_weighted_adjoint(self, case, jlres, pyres, units, actnum_vec, + idn: int, julia) -> pd.Series: + """ + Compute ``H^T w``, the gradient of ``sum_i w_i d_i`` with ``w`` held fixed. + + ``H^T w`` is linear in ``w``, so weights computed from this member's + own forward run give the exact gradient of any function of the data + through them, in one adjoint solve. ``w = Cd^{-1} (d_obs - d)`` gives + the Gaussian log-likelihood gradient + ``-d/dx 1/2 (d_obs - d)^T Cd^{-1} (d_obs - d)``. + + Parameters + ---------- + case : Any + Julia case object. + jlres : Any + Julia simulation result. + pyres : pd.DataFrame + Forward-extracted results; passed to a callable ``adjoint_weights`` + and used to cross-check Jutul's evaluation of the weighted sum. + units : Any + Unit system identifier (stored in the returned ``attrs``). + actnum_vec : np.ndarray + Flat ACTNUM vector for full-grid embedding. + idn : int + Ensemble index, passed to a callable ``adjoint_weights``. + julia : juliacall.Main + Julia main module. + + Returns + ------- + pd.Series + Full-grid gradient per parameter in ``self.weighted_parameters``. + ``attrs["value"]`` is ``sum_i w_i d_i`` from the forward output. + + Raises + ------ + ValueError + If a weighted datatype is not a supported well quantity, or Jutul's + evaluation of the weighted sum disagrees with the forward output. + """ + weights = self._resolve_adjoint_weights(pyres, idn) + w = weights.to_numpy() + rows, cols = np.nonzero(w) + contributions = w[rows, cols] * pyres.to_numpy(dtype=np.float64)[rows, cols] + value = float(contributions.sum()) + + def _pack(grads: dict[str, np.ndarray]) -> pd.Series: + out = pd.Series(list(grads.values()), index=list(grads), + name="weighted_adjoint", dtype=object) + out.attrs = {"value": value, "units": units} + return out + + if not rows.size: + return _pack({p: np.zeros(actnum_vec.shape) + for p in self.weighted_parameters}) + + wells, targets, is_rate = [], [], [] + for datatype in weights.columns[cols]: + base, _, well = datatype.partition(":") + if not well or base not in PHASE_MAP: + raise ValueError( + f"No weighted adjoint for datatype '{datatype}'; supported " + f"are well data of type {sorted(PHASE_MAP)}" + ) + phase, rate = PHASE_MAP[base] + wells.append(well) + targets.append(RATE_ID_MAP[phase]) + is_rate.append(rate) + times = self.report_seconds[rows].astype(np.float64) + + julia.func = julia.subsurface_weighted_well_objective( + wells, targets, np.array(is_rate), times, w[rows, cols], STEP_TIME_TOL + ) + + # The weighted sum may cancel to near zero, so compare on the scale of + # its terms rather than of its value. + func_val = float(julia.Jutul.evaluate_objective(julia.func, case, jlres.result)) + if abs(func_val - value) > 1e-6 * np.abs(contributions).sum(): + raise ValueError( + f"Jutul evaluates the weighted sum to {func_val:.6e} but the " + f"forward output gives {value:.6e}; the adjoint objective does " + f"not reproduce the reported data" + ) + + step_times = self._prepare_adjoint_storage(julia) + n_steps = None + if step_times is not None: + # Nothing after the last weighted report point enters the sum. + n_steps = int(np.searchsorted( + step_times, times.max() + STEP_TIME_TOL, side="right" + )) + grad, well_sens = self._solve_adjoint(julia, n_steps=n_steps) + + wi_jacobian, ncells, perm_copy = self._perm_gradient_context( + case, actnum_vec, self.weighted_parameters, julia + ) + wi_chain_term = ( + _well_index_chain_term(wi_jacobian, well_sens, ncells, julia) + if wi_jacobian else None + ) + return _pack({ + p: _extract_adjoint(grad, case, p, actnum_vec, perm_copy, julia, + wi_chain_term=wi_chain_term) + for p in self.weighted_parameters + }) + + def _resolve_adjoint_weights(self, pyres: pd.DataFrame, idn: int) -> pd.DataFrame: + """ + Return this member's weights aligned with ``pyres``, zero where absent. + + Raises + ------ + ValueError + If no weights are configured, or they name report points or + datatypes the forward output does not have. + """ + weights = self.adjoint_weights + if weights is None: + raise ValueError( + "'weighted_adjoint' needs 'adjoint_weights' (a DataFrame or a " + "callable returning one)" + ) + if callable(weights): + weights = weights(pyres.copy(), idn) + weights = pd.DataFrame(weights) + + extra_cols = [c for c in weights.columns if c not in pyres.columns] + extra_rows = [r for r in weights.index if r not in pyres.index] + if extra_cols or extra_rows: + raise ValueError( + f"Adjoint weights name data the simulation does not report: " + f"datatypes {extra_cols}, report points {extra_rows}" + ) + weights = weights.reindex(index=pyres.index, columns=pyres.columns) + return weights.fillna(0.0).astype(np.float64) + + def _perm_gradient_context(self, case, actnum_vec: np.ndarray, + parameters: Iterable[str], julia): + """ + Build what permeability gradients need beyond the adjoint solve itself. + + Returns + ------- + tuple + ``(wi_jacobian, ncells, perm_copy)`` for + :func:`_well_index_chain_term` and :func:`_extract_adjoint`; empty + when none of ``parameters`` is a permeability. + """ + if not any("perm" in p.lower() for p in parameters): + return {}, 0, None + wi_jacobian, ncells = _well_index_perm_jacobian( + case, julia, self.well_index_from_perm + ) + perm_copy = _detect_copied_perm_axes(case, actnum_vec, self.perm_copied, julia) + return wi_jacobian, ncells, perm_copy + + def _prepare_adjoint_storage(self, julia) -> np.ndarray | None: + """ + Bind ``adj_packed`` / ``adj_storage`` in Julia for reuse across solves. + + Returns + ------- + np.ndarray or None + End time in seconds of every ministep, or ``None`` when storage + reuse is off or does not apply to the adjoint mode. + """ + if not (self.adjoint_mode == "sensitivities" and self.adjoint_reuse_storage): + return None + julia.adj_packed = _suppress_julia(julia, "subsurface_adjoint_packed(case, res)") + julia.adj_storage = _suppress_julia(julia, "subsurface_adjoint_storage(case)") + return np.asarray( + _suppress_julia(julia, "subsurface_packed_step_times(adj_packed)"), + dtype=float, + ) + def _solve_adjoint(self, julia, n_steps: int | None = None): """ Invoke the appropriate JutulDarcy adjoint solver for the current mode. diff --git a/tests/test_jutul_darcy.py b/tests/test_jutul_darcy.py index ce9c2dc..a7bee99 100644 --- a/tests/test_jutul_darcy.py +++ b/tests/test_jutul_darcy.py @@ -11,6 +11,7 @@ import os import shutil import numpy as np +import pandas as pd import pytest from subsurface.multphaseflow.jutul_darcy import JutulDarcy @@ -408,3 +409,229 @@ def test_copy_detection_per_direction( np.testing.assert_array_equal(spec.include, expected_include) np.testing.assert_allclose(spec.ratio, expected_ratio, rtol=1e-9) + + +# --------------------------------------------------------------------------- # +# Weighted adjoint (H^T w) +# --------------------------------------------------------------------------- # +#: Rates, an injector rate and cumulatives, so every objective branch is used. +WEIGHTED_DATA_TYPES = DATA_TYPES + ["WOPT:PRO2", "WWPT:PRO1"] + +#: Log-permeability amplitude of each Stein mode. Small enough that the +#: response is close to cubic over the sample, where the control variate and +#: antithetic pairs below leave little but gradient error. +STEIN_AMPLITUDE = 0.02 + +#: Antithetic pairs in the Stein ensemble (2 * pairs + 1 simulations). +STEIN_PAIRS = 24 + +#: Bound on |E[z f] - E[grad f]| relative to |E[grad f]|. The correct gradient +#: sits at ~1.5%: adaptive timestepping makes the simulated f jump slightly +#: where the ministep sequence changes, and Stein's lemma sees those jumps while +#: the adjoint, which differentiates a fixed ministep sequence, cannot. Leaving +#: out the well-index chain rule gives ~45%, ignoring PERMY/PERMZ ~145%. +STEIN_RTOL = 0.05 + + +def _weighted_options(options: dict, weights, **extra) -> dict: + """Base options with the weighted adjoint w.r.t. log-permeability.""" + return { + **options, + "datatype": WEIGHTED_DATA_TYPES, + "weighted_adjoint": {"parameters": ["log_permx"]}, + "adjoint_weights": weights, + **extra, + } + + +def _stein_basis() -> np.ndarray: + """ + Smooth log-permeability modes on the 10 x 10 x 2 TINY grid, (n_cell, 4). + + A uniform shift, an east-west trend, a bump around PRO2's perforations + (where the well-index chain rule acts) and a contrast between the layers + (which only the PERMZ part of the copied-permeability gradient sees). + """ + i, j, k = np.meshgrid(np.arange(NX), np.arange(NY), np.arange(2), indexing="ij") + i, j, k = (a.flatten(order="F") for a in (i, j, k)) + modes = np.stack([ + np.ones(i.size), + np.cos(np.pi * i / (NX - 1)), + np.exp(-((i - 4) ** 2 + (j - 9) ** 2) / 4.0), + np.where(k == 0, 1.0, -1.0), + ], axis=1) + return STEIN_AMPLITUDE * modes + + +class _MemberScaledWeights: + """Callable weights that are ``base * (member + 1)``, to see both arguments used.""" + + def __init__(self, base: pd.DataFrame): + self.base = base + + def __call__(self, forward: pd.DataFrame, member: int) -> pd.DataFrame: + assert list(forward.columns) == WEIGHTED_DATA_TYPES + return self.base * (member + 1) + + +@pytest.fixture(scope="module") +def base_forward(tmp_path_factory, options, tiny_folder): + """Forward output of the unperturbed TINY case for the weighted datatypes.""" + case_path = _copy_case_folder( + tmp_path_factory.mktemp("weighted_base"), tiny_folder, "TINY_BASE" + ) + return _run_case(case_path, {**options, "datatype": WEIGHTED_DATA_TYPES}) + + +@pytest.fixture(scope="module") +def random_weights(base_forward) -> pd.DataFrame: + """Signed weights with every datatype contributing on a comparable scale.""" + rng = np.random.default_rng(7) + raw = pd.DataFrame(rng.standard_normal(base_forward.shape), + index=base_forward.index, columns=base_forward.columns) + return raw / base_forward.abs().mean() + + +def test_cumulative_output_is_in_volume_units(base_forward): + """ + WOPT must be oil volume, i.e. roughly rate x elapsed days. JutulDarcy's + summary integrates per-day rates over seconds, which is 86400x too much. + """ + days = (REPORT_DATES[0] - datetime(2022, 1, 1)).days + first = base_forward.iloc[0] + ratio = first["WOPT:PRO2"] / (first["WOPR:PRO2"] * days) + assert 0.5 < ratio < 2.0, f"WOPT / (WOPR * days) = {ratio:.3g}" + + +def test_weighted_adjoint_matches_weighted_sum_of_sensitivities( + tmp_path, options, tiny_folder, random_weights +): + """One weighted solve equals sum_i w_i * grad d_i from one solve per datum.""" + case_path = _copy_case_folder(tmp_path, tiny_folder, "TINY_WEIGHTED") + _, weighted = _run_case(case_path, _weighted_options(options, random_weights)) + + adjoints: dict[str, dict] = {} + for datatype in WEIGHTED_DATA_TYPES: + base, well = datatype.split(":") + spec = adjoints.setdefault( + base, {"wellID": [], "steps": "all", "parameters": ["log_permx"]} + ) + spec["wellID"].append(well) + _, per_datum = _run_case(case_path, { + **options, "datatype": WEIGHTED_DATA_TYPES, "adjoints": adjoints, + }) + + expected = sum( + random_weights.loc[t, d] * per_datum.loc[t, (d, "log_permx")] + for t in random_weights.index + for d in WEIGHTED_DATA_TYPES + ) + # Jutul's adjoint linear solver is iterative, so the two paths agree to + # its tolerance rather than to rounding. + np.testing.assert_allclose(weighted["log_permx"], expected, + rtol=1e-3, atol=1e-3 * np.abs(expected).max()) + + +def test_weighted_adjoint_is_linear_in_callable_weights( + tmp_path, options, tiny_folder, random_weights +): + """A callable gets each member's index, and H^T w scales with w.""" + case_path = _copy_case_folder(tmp_path, tiny_folder, "TINY_CALLABLE") + log_permx = np.log(np.load(case_path / "PERMX.npy")) + simulator = JutulDarcy(_weighted_options( + options, _MemberScaledWeights(random_weights), parallel=2 + )) + with _working_directory(case_path): + _, (first, second) = simulator( + [{"log_permx": log_permx.copy()}, {"log_permx": log_permx.copy()}] + ) + + assert second.attrs["value"] == pytest.approx(2 * first.attrs["value"]) + np.testing.assert_allclose(second["log_permx"], 2 * first["log_permx"], + rtol=1e-3, atol=1e-3 * np.abs(first["log_permx"]).max()) + + +def test_weighted_adjoint_satisfies_steins_lemma( + tmp_path, options, tiny_folder, random_weights +): + """ + Stein's lemma: for ``z ~ N(0, I)`` and ``f(z) = L(x0 + B z)``, + ``E[z f(z)] = E[grad_z f(z)] = E[B^T grad_x L]``. The left side needs only + forward values, the right side only adjoint gradients, so their agreement + checks the gradient without finite differences and without assuming f is + linear over the sample. + + Two exact variance reductions make a small ensemble enough: antithetic + pairs ``+-z`` (the even part of f and the odd part of its gradient cancel), + and the control variate ``z^T a0`` with ``a0 = B^T grad L(x0)``, which + removes the same mean from both sides because ``E[z z^T a0] = a0``. + """ + case_path = _copy_case_folder(tmp_path, tiny_folder, "TINY_STEIN") + x0 = np.log(np.load(case_path / "PERMX.npy")) + basis = _stein_basis() + half = np.random.default_rng(42).standard_normal((STEIN_PAIRS, basis.shape[1])) + z = np.vstack([half, -half]) + members = x0 + z @ basis.T + # The template caps log-permeability at 6, beyond which the gradient + # would describe a field the deck never sees. + assert members.max() < 6.0 + + simulator = JutulDarcy(_weighted_options( + options, random_weights, parallel=min(4, os.cpu_count() or 1) + )) + with _working_directory(case_path): + _, gradients = simulator( + [{"log_permx": x0.copy()}] + [{"log_permx": x} for x in members] + ) + + f = np.array([g.attrs["value"] for g in gradients]) + grad_z = np.array([basis.T @ g["log_permx"] for g in gradients]) + f0, a0 = f[0], grad_z[0] + n = STEIN_PAIRS + f_odd = (f[1:n + 1] - f[n + 1:]) / 2 + grad_even = (grad_z[1:n + 1] + grad_z[n + 1:]) / 2 + + # Per pair: z (f_odd - z^T a0) - (grad_even - a0), whose mean is zero. + residual = half * (f_odd - half @ a0)[:, None] - (grad_even - a0) + mean = residual.mean(axis=0) + std_err = residual.std(axis=0, ddof=1) / np.sqrt(n) + scale = np.linalg.norm(grad_z[1:].mean(axis=0)) + + assert np.linalg.norm(std_err) < 0.02 * scale, ( + "Stein estimate too noisy to judge the gradient" + ) + assert np.linalg.norm(mean) < STEIN_RTOL * scale, ( + f"E[z f] - E[grad f] = {mean} (std. err. {std_err}) against " + f"|E[grad f]| = {scale:.4g}" + ) + + +def test_weighted_adjoint_rejects_weights_for_unreported_data(options, random_weights): + """Weights naming a datatype or report point the run lacks are an error.""" + simulator = JutulDarcy(_weighted_options(options, random_weights)) + forward = random_weights * 0.0 + simulator.adjoint_weights = random_weights.assign(**{"WOPR:NOPE": 1.0}) + with pytest.raises(ValueError, match="WOPR:NOPE"): + simulator._resolve_adjoint_weights(forward, 0) + + simulator.adjoint_weights = random_weights.iloc[:2].copy() + simulator.adjoint_weights.index = [datetime(1999, 1, 1), REPORT_DATES[1]] + with pytest.raises(ValueError, match="1999"): + simulator._resolve_adjoint_weights(forward, 0) + + simulator.adjoint_weights = random_weights[["WOPR:PRO1"]] + resolved = simulator._resolve_adjoint_weights(forward, 0) + assert list(resolved.columns) == WEIGHTED_DATA_TYPES + assert (resolved.drop(columns="WOPR:PRO1") == 0.0).all().all() + + +def test_weighted_adjoint_option_validation(options): + """Only one adjoint flavour at a time, and only on the sensitivities path.""" + weighted = {"parameters": ["log_permx"]} + with pytest.raises(ValueError, match="mutually exclusive"): + JutulDarcy({**options, "weighted_adjoint": weighted, + "adjoints": {"WOPR": {"wellID": "PRO1", "steps": "all", + "parameters": ["permx"]}}}) + with pytest.raises(ValueError, match="sensitivities"): + JutulDarcy({**options, "weighted_adjoint": weighted, + "adjoint_mode": "optimization"}) From 63537e7f9f42eddc713f0478c161655b835bccb8 Mon Sep 17 00:00:00 2001 From: Kristian Fossum Date: Thu, 26 Nov 2026 09:06:45 +0100 Subject: [PATCH 2/2] feat: add weighted JutulDarcy adjoints for PET --- README.md | 29 ++++ src/subsurface/multphaseflow/jutul_darcy.py | 162 +++++++++++++++----- src/subsurface/multphaseflow/vjp.py | 23 +++ tests/test_jutul_vjp.py | 28 ++++ 4 files changed, 203 insertions(+), 39 deletions(-) create mode 100644 src/subsurface/multphaseflow/vjp.py create mode 100644 tests/test_jutul_vjp.py diff --git a/README.md b/README.md index 759c90f..77ec925 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,35 @@ Clone the repository and install it in editable mode by running python3 -m pip install -e . ``` +## PET LowRankGN: weighted JutulDarcy adjoints + +Pass the existing `subsurface.multphaseflow.jutul_darcy.JutulDarcy(options)` +to PET. Use a Mako `runfile`, `adjoint_mode="sensitivities"` (the default), +and omit `adjoints`. Ordinary forecasts then return just predictions. The +existing `adjoints` configuration remains available for standalone +per-observation gradients. + +`run_vjp(state, weights)` accepts PET's report-by-datatype frame. An +observed cell contains the k coefficients of that datum, a missing cell +is `None`. It runs the centre once per call, shares its ministeps and +adjoint storage across the columns, and returns `{name: array(k, n)}` in +the coordinates of each state field. There is no cross-call cache. The +wrapper checks each weighted objective against the direct forward summary. + +Supported observations are scalar `WOPR`, `WWPR` and `WGPR` well rates in +Sm³/day on exact report steps of a METRIC deck. Supported controls are +direct `poro` (fraction), `permx`, `permy`, `permz` (mD) and `log_permx` +etc. (natural log of mD). Use Cartesian deck order, full grid or processed +active cells. The permeability gradient includes the wrapper's existing +well-index and copied-axis chain rules. Specify `perm_copied=False` for +independent axes or `True` for three identical copies when the deck fields +alone are ambiguous. Inputs must render directly: clipping outside bounds, +fault factors, and other template dependencies need their own chain rule. + +With the wrapper's Julia environment active, run +`python -m pytest -q tests/test_jutul_vjp.py` for a two-objective, +two-well directional check on the bundled TINY case. + ## Examples 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/jutul_darcy.py b/src/subsurface/multphaseflow/jutul_darcy.py index 52e03b7..99109d2 100644 --- a/src/subsurface/multphaseflow/jutul_darcy.py +++ b/src/subsurface/multphaseflow/jutul_darcy.py @@ -34,10 +34,12 @@ from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path +from tempfile import TemporaryDirectory from typing import Any, Iterable from mako.template import Template from p_tqdm import p_map from tqdm import tqdm +from .vjp import scalar_seeds __author__ = ["Mathias Methlie Nilsen"] # With help from "Claude Opus 4.7" __all__ = ["JutulDarcy"] @@ -239,6 +241,30 @@ ) end +function subsurface_rate_sum(seconds, wells, kinds, coefficients) + terms = Dict{Int, Vector{Tuple{Symbol, String, Float64}}}() + for (t, w, k, c) in zip(seconds, wells, kinds, coefficients) + iszero(c) && continue + push!(get!(terms, Int(t), Tuple{Symbol, String, Float64}[]), + (Symbol(string(w)), string(k), Float64(c))) + end + return function (model, state, dt, step_info, forces) + t = step_info[:time] + target = round(Int, t) + abs(t - target) <= 1e-5 && haskey(terms, target) || return 0.0 + total = 0.0 + controls = forces[:Facility].control + for (well, kind, c) in terms[target] + haskey(controls, well) || continue + controls[well] isa JutulDarcy.ProducerControl || continue + phase = kind == "WOPR" ? SurfaceOilRateTarget : + kind == "WWPR" ? SurfaceWaterRateTarget : SurfaceGasRateTarget + total -= c * 86400 * JutulDarcy.compute_well_qoi(model, state, forces, well, phase) + end + return total + end +end + function subsurface_packed_step_times(packed) ps = Jutul.AdjointPackedResult(packed.states, packed.dt, packed.forces) return [ps[i].step_info[:time] for i in 1:length(ps)] @@ -1261,51 +1287,109 @@ def run_fwd_sim(self, input: dict | str, idn: int = 0, ------- Same as :meth:`__call__` for a single member. """ - # Julia is imported lazily inside the worker so it picks up the - # process-local thread/state. Importing at module scope would break - # multiprocessing's fork/spawn semantics. - from juliacall import Main as julia - julia.seval("using JutulDarcy, Jutul") - if self.compute_adjoints: - _ensure_julia_helpers(julia) - folder = Path(f"En_{idn}") folder.mkdir(exist_ok=False) - try: - # Stage the deck (render template or copy file). - datafile = self._stage_input(input, folder, idn) - - # All Julia file I/O must happen relative to the deck location. - with _chdir(folder): - case = self._setup_case(datafile, julia) - julia.case = case # expose to Julia-side eval'd expressions - - units = self._detect_units(case, julia) - actnum_vec = self._extract_actnum(case, julia) - - # Forward solve. `output_substates=True` keeps intermediate - # states needed for adjoint reconstruction. - jlres = julia.simulate_reservoir( - case, info_level=-1, output_substates=True - ) - julia.res = jlres - - pyres = self.extract_datatypes(jlres, case, units, julia) - output = self._format_output(pyres) - - if self.compute_adjoints: - adjoints = self._compute_adjoints( - case, jlres, pyres, units, actnum_vec, idn, julia - ) - return output, adjoints - - return output + return self._simulate(input, idn, folder) finally: - # Always clean up, even on failure, to keep the workspace tidy. if delete_folder and folder.exists(): shutil.rmtree(folder, ignore_errors=True) + def run_vjp(self, state, weights): + """Return one PET-state gradient per weighted sum of metric production rates.""" + if self.compute_adjoints or self.adjoint_mode != "sensitivities": + raise ValueError("Use sensitivities mode without ensemble 'adjoints' for PET VJPs") + cells, seeds = scalar_seeds(weights, self.report, self.datatype) + for _, key in cells: + kind, _, well = key.partition(":") + if not well or kind not in {"WOPR", "WWPR", "WGPR"}: + raise ValueError(f"Unsupported production rate: {key}") + valid = {"poro", "permx", "permy", "permz", "log_permx", "log_permy", "log_permz"} + if not state or set(state) - valid or not self.makofile: + raise ValueError("VJP needs a Mako deck with direct porosity or (log-)permeability fields") + if len({name.removeprefix("log_") for name in state}) != len(state): + raise ValueError("Only one PET variable may control a deck field") + with TemporaryDirectory(prefix="vjp_", dir=".") as folder: + return self._simulate(dict(state), 0, Path(folder), (cells, seeds)) + + def _simulate(self, input, idn, folder, vjp=None): + # Julia is imported lazily inside the worker so it picks up the + # process-local thread/state. Importing at module scope would break + # multiprocessing's fork/spawn semantics. + from juliacall import Main as julia + # Julia 1.11+ requires bindings to exist before PythonCall can assign them. + julia.seval("using JutulDarcy, Jutul; global case, res, grad_case, adj_packed, adj_storage, func") + if self.compute_adjoints or vjp is not None: + _ensure_julia_helpers(julia) + + datafile = self._stage_input(input.copy() if isinstance(input, dict) else input, folder, idn) + with _chdir(folder): + case = self._setup_case(datafile, julia) + julia.case = case + units = self._detect_units(case, julia) + actnum_vec = self._extract_actnum(case, julia) + jlres = julia.simulate_reservoir(case, info_level=-1, output_substates=True) + julia.res = jlres + pyres = self.extract_datatypes(jlres, case, units, julia) + if vjp is not None: + if units != "metric": + raise ValueError("Rate VJPs require a METRIC deck") + return self._rate_vjp(input, *vjp, case, jlres, pyres, actnum_vec, julia) + output = self._format_output(pyres) + if self.compute_adjoints: + return output, self._compute_adjoints(case, jlres, pyres, units, actnum_vec, idn, julia) + return output + + def _rate_vjp(self, state, cells, seeds, case, res, summary, actnum, jl): + active = actnum == 1 + md = jl.seval("si_unit(:milli)*si_unit(:darcy)") + for name, x in state.items(): + keyword = name.removeprefix("log_").upper() + field = np.asarray(case.input_data["GRID"][keyword]).ravel(order="F")[active] + if keyword != "PORO": + field = field / md + expected = np.exp(x) if name.startswith("log_") else np.asarray(x) + if expected.shape == active.shape: + expected = expected[active] + if (expected.shape != field.shape or not np.all(expected > 0) + or not np.allclose(field, expected, rtol=3e-5, atol=0)): + raise ValueError(f"{name} must render directly in Cartesian order (check units and clipping)") + times = dict(zip(self.report, self.report_seconds)) + seconds = [int(times[label]) for label, _ in cells] + kinds, wells = zip(*(key.split(":") for _, key in cells)) + values = np.asarray([summary.at[label, key] for label, key in cells]) + packed = jl.subsurface_adjoint_packed(case, res) + storage = jl.subsurface_adjoint_storage(case) + packed_times = np.asarray(jl.subsurface_packed_step_times(packed)) + if any(np.count_nonzero(abs(packed_times - t) <= 1e-5) != 1 for t in set(seconds)): + raise ValueError("VJP requires one matching simulator step per report time") + jac, nc = _well_index_perm_jacobian(case, jl, self.well_index_from_perm) if any( + "perm" in name for name in state) else ({}, 0) + copied = (_detect_copied_perm_axes(case, actnum, self.perm_copied, jl) + if any(k.endswith("permx") for k in state) else None) + if copied and any(name.endswith(axis) for axis, tied in zip(("permy", "permz"), copied.include[1:]) + if tied for name in state): + raise ValueError("A copied axis cannot also be an independent permeability control") + out = {name: np.zeros((seeds.shape[1], np.size(x))) for name, x in state.items()} + for j, column in enumerate(seeds.T): + if not column.any(): + continue + obj = jl.subsurface_rate_sum(seconds, list(wells), list(kinds), column) + actual = jl.Jutul.evaluate_objective(obj, case, res.result) + if not np.isclose(actual, column @ values): + raise ValueError("Weighted adjoint objective differs from the forward summary") + sens = jl.subsurface_sensitivities_reuse(case, storage, packed, obj, len(packed_times)) + wi = _well_index_chain_term(jac, sens.models, nc, jl) if jac else None + for name, x in state.items(): + g = _extract_adjoint(sens.reservoir, case, name, actnum, + copied if name.endswith("permx") else None, jl, wi_chain_term=wi) + if np.size(x) != len(g): + g = g[actnum == 1] + if g.shape != np.shape(x) or not np.isfinite(g).all(): + raise ValueError(f"Invalid adjoint shape or nonfinite values for {name}") + out[name][j] = g + return out + # ---------------------------------------------------------------- # # Setup helpers # ---------------------------------------------------------------- # @@ -1890,4 +1974,4 @@ def _make_adjoint_pbar(self, idn: int): dynamic_ncols=False, colour="#713996", **opts, - ) \ No newline at end of file + ) 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_jutul_vjp.py b/tests/test_jutul_vjp.py new file mode 100644 index 0000000..c6e2fc0 --- /dev/null +++ b/tests/test_jutul_vjp.py @@ -0,0 +1,28 @@ +import numpy as np +import pandas as pd + +from test_jutul_darcy import REPORT_DATES, _copy_case_folder, _tiny_folder +from subsurface.multphaseflow.jutul_darcy import JutulDarcy + + +def test_weighted_rates_match_forward_difference(tmp_path, monkeypatch): + case = _copy_case_folder(tmp_path, _tiny_folder(), "tiny") + monkeypatch.chdir(case) + sim = JutulDarcy({"runfile": "RUNFILE.mako", "reportpoint": REPORT_DATES, "reporttype": "dates", + "datatype": ["WOPR:PRO2", "WWPR:PRO1"], "perm_copied": True}) + x = np.log(np.load("PERMX.npy")) + direction = np.zeros_like(x) + direction[94] = 1 + assert x[94] + .01 < 6 # differentiating the interior of this clipped template + labels = [REPORT_DATES[-1], REPORT_DATES[2]] + weights = pd.DataFrame({"WWPR:PRO1": [None, np.array([.2, -.7])], + "WOPR:PRO2": [np.array([1., .5]), None]}, index=labels) + g = sim.run_vjp({"log_permx": x}, weights)["log_permx"] + + def f(y): + frame = sim.run_fwd_sim({"log_permx": y}) + return frame.at[labels[0], "WOPR:PRO2"] * np.array([1., .5]) + frame.at[labels[1], "WWPR:PRO1"] * np.array([.2, -.7]) + + fd = (f(x + .01*direction) - f(x - .01*direction)) / .02 + assert np.linalg.norm(fd) > 1e-4 + np.testing.assert_allclose(g @ direction, fd, rtol=.05, atol=1e-4)