diff --git a/README.md b/README.md index 759c90f..dc63c6b 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,50 @@ Clone the repository and install it in editable mode by running python3 -m pip install -e . ``` +## JutulDarcy weighted adjoints for PET (LowRankGN and SVGD) + +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. + +For SVGD, set `weighted_adjoint={"parameters": ["log_permx"]}` instead. +PET sets `sim.adjoint_weights` to a callable `(forward_frame, member_index)` +returning one scalar weight per observed cell (missing weights are zero). +`run_fwd_sim` returns `(output, gradient_series)` from that member's live +trajectory, with no second forward solve. Match the gradient coordinate +to the state: `permx` differentiates mD, `log_permx` its natural logarithm. + +Both entry points support METRIC well observations on report steps: `WOPR`, +`WWPR`, `WGPR`, `WLPR`, `WWIR` (Sm³/day) and `WOPT`, `WWPT`, `WGPT`, +`WLPT` (Sm³). The batched VJP's 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. + +**Forward summary unit change:** field and well surface totals (including +`WWIT` and `FLPT`) are now converted from SI volumes. Previously JutulDarcy +0.3.11's METRIC/FIELD cumulative outputs were 86,400 times too large. Rates +are reported per day for METRIC/FIELD, per hour for LAB, and per second for +SI. Do not rescale PET observations or gradients to compensate for the old +output. Recheck any prior workaround before comparing stored forecasts. + +With the wrapper's Julia environment active, run `python -m pytest -q +tests/test_jutul_darcy.py tests/test_jutul_vjp.py` for both derivative +paths, the directional finite difference and the SI-volume regression. + ## 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..7b85e4c 100644 --- a/src/subsurface/multphaseflow/jutul_darcy.py +++ b/src/subsurface/multphaseflow/jutul_darcy.py @@ -5,7 +5,7 @@ JutulDarcy reservoir simulations from a single configuration dictionary. It supports: -* Single or ensemble forward simulations (parallel via :mod:`p_tqdm`). +* Single or ensemble forward simulations (parallel in spawned worker processes). * Input through either a static ``.DATA`` file or a Mako-templated ``.mako`` file rendered per ensemble member. * Flexible result extraction (field and per-well summary keywords) with @@ -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 @@ -34,10 +38,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 multiprocess import get_context from tqdm import tqdm +from .vjp import scalar_seeds __author__ = ["Mathias Methlie Nilsen"] # With help from "Claude Opus 4.7" __all__ = ["JutulDarcy"] @@ -73,11 +79,9 @@ "ascii": "-◼", } -#: Summary keywords whose values are cumulative (totals), as opposed to rates. -CUMULATIVE_KEYS: frozenset[str] = frozenset({ - "FOPT", "FGPT", "FWPT", "FWLT", "FWIT", - "WOPT", "WGPT", "WWPT", "WLPT", -}) +# Phase production/injection rates and totals in JutulDarcy's summary_key_lookup. +SURFACE_KEYS = {f"{scope}{phase}{flow}{kind}" for scope in "FW" for phase in "OWGL" + for flow in "PI" for kind in "RT"} VALID_OUTPUT_FORMATS: frozenset[str] = frozenset({"list", "dict", "dataframe"}) VALID_ADJOINT_MODES: frozenset[str] = frozenset({"sensitivities", "optimization"}) @@ -137,6 +141,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 +173,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 +301,46 @@ end return (reservoir = grad, models = sens) end + +function subsurface_weighted_well_objective(wells, targets, is_rate, injectors, times, weights, tol) + groups = Dict{Tuple{Symbol, Symbol, Bool, Bool}, Tuple{Vector{Float64}, Vector{Float64}}}() + for (w, tgt, r, inj, t, c) in zip(String.(wells), String.(targets), Bool.(collect(is_rate)), Bool.(collect(injectors)), + Float64.(collect(times)), Float64.(collect(weights))) + ts, cs = get!(groups, (Symbol(w), Symbol(tgt), r, inj), (Float64[], Float64[])) + push!(ts, t) + push!(cs, c) + end + terms = [ + (well = k[1], target = getfield(JutulDarcy, k[2]), is_rate = k[3], injector = k[4], + 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 + controls = forces[:Facility].control + haskey(controls, term.well) || continue + ctrl = controls[term.well] + (term.injector ? ctrl isa JutulDarcy.InjectorControl : ctrl isa JutulDarcy.ProducerControl) || continue + sgn = term.injector ? 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 +1055,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 +1118,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 +1203,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 +1254,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 +1286,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)): @@ -1214,27 +1299,23 @@ def __call__(self, inputs: list[dict] | dict | str): self._cleanup_simulation_folders() n = len(inputs) - outputs = p_map( - self.run_fwd_sim, - list(inputs), - list(range(n)), - num_cpus=self.parallel, - unit="sim", - desc="Simulations", - leave=False, - **PBAR_OPTS, - ) + if n == 1: + return self.run_fwd_sim(inputs[0], 0) + if self.parallel == 1: + outputs = [self.run_fwd_sim(member, i) for i, member in enumerate(inputs)] + else: + # Forking after a previous run inherits a live Julia runtime and its threads. + with get_context("spawn").Pool(min(n, self.parallel)) as pool: + outputs = pool.starmap(self.run_fwd_sim, zip(inputs, range(n))) # In adjoint mode each worker returns a (result, adjoint) tuple; split # them out so callers see two parallel collections rather than a list # of tuples. if self.compute_adjoints: results, adjoints = zip(*outputs) - if n == 1: - return results[0], adjoints[0] return list(results), list(adjoints) - return outputs[0] if n == 1 else outputs + return outputs # ---------------------------------------------------------------- # # Per-member forward simulation @@ -1261,50 +1342,84 @@ def run_fwd_sim(self, input: dict | str, idn: int = 0, ------- Same as :meth:`__call__` for a single member. """ + folder = Path(f"En_{idn}") + folder.mkdir(exist_ok=False) + try: + return self._simulate(input, idn, folder) + finally: + 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 well observations.""" + 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) + 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.seval("using JutulDarcy, Jutul") - if self.compute_adjoints: + # 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) - 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 + 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 or self.weighted_parameters is not None: + if isinstance(units, str) and units != "metric": + raise ValueError("Weighted adjoints require a METRIC deck") + if vjp is not None: + self._validate_vjp_state(input, case, actnum_vec, julia) + return self._weighted_products(case, jlres, pyres, actnum_vec, julia, + list(input), *vjp, state=input) + weights = self._resolve_adjoint_weights(pyres, idn) + r, c = np.nonzero(weights.to_numpy()) + cells = list(zip(weights.index[r], weights.columns[c])) + seeds = weights.to_numpy()[r, c, None] + products = self._weighted_products(case, jlres, pyres, actnum_vec, julia, + self.weighted_parameters, cells, seeds) + adjoint = pd.Series({p: g[0] for p, g in products.items()}, name="weighted_adjoint", dtype=object) + adjoint.attrs = {"value": float(seeds[:, 0] @ pyres.to_numpy()[r, c]), "units": "metric"} + return self._format_output(pyres), adjoint + output = self._format_output(pyres) + if self.compute_adjoints: + return output, self._compute_adjoints(case, jlres, pyres, units, actnum_vec, idn, julia) + return output - 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 + @staticmethod + def _validate_vjp_state(state, case, actnum, jl): + """The deck must actually contain the PET coordinates being differentiated.""" + 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)") - return output - finally: - # Always clean up, even on failure, to keep the workspace tidy. - if delete_folder and folder.exists(): - shutil.rmtree(folder, ignore_errors=True) # ---------------------------------------------------------------- # # Setup helpers @@ -1371,12 +1486,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 @@ -1507,8 +1623,16 @@ def extract_datatypes(self, jlres, jlcase, units, julia) -> pd.DataFrame: ValueError If a requested datatype or well is missing from the results. """ - jl_units = julia.Symbol(units) if isinstance(units, str) else units - smry = julia.JutulDarcy.summary_result(jlcase, jlres, jl_units) + # Read surface quantities in SI: non-SI summaries in JutulDarcy 0.3.11 + # accumulate per-day rates against seconds, including in LAB decks. + system = units if isinstance(units, str) else "metric" + keys = {key.split(":")[0] for key in self.datatype} + smry = julia.JutulDarcy.summary_result(jlcase, jlres, julia.Symbol(system if keys - SURFACE_KEYS else "si")) + surface = smry + if keys & SURFACE_KEYS: + deck = julia.JutulDarcy.GeoEnergyIO.InputParser.DeckUnitSystem(julia.Symbol(system)) + if keys - SURFACE_KEYS and system != "si": + surface = julia.JutulDarcy.summary_result(jlcase, jlres, julia.Symbol("si")) # JutulDarcy builds its time vector as a floating-point cumulative sum # over adaptive ministeps (`output_substates=True` keeps every one of @@ -1558,10 +1682,10 @@ def extract_datatypes(self, jlres, jlcase, units, julia) -> pd.DataFrame: res: dict[str, np.ndarray] = {} attrs: dict[str, str] = {} - wells = smry["VALUES"]["WELLS"] - field = smry["VALUES"]["FIELD"] - for datatype in self.datatype: + key = datatype.split(":")[0] + values = (surface if key in SURFACE_KEYS else smry)["VALUES"] + wells, field = values["WELLS"], values["FIELD"] if ":" in datatype: # Well-level datatype: ":" baseID, wellID = datatype.split(":") @@ -1585,6 +1709,15 @@ def extract_datatypes(self, jlres, jlcase, units, julia) -> pd.DataFrame: res[datatype] = np.array(field[datatype])[idx] attrs[datatype] = get_metric_unit(datatype) + if key in SURFACE_KEYS: + gas = key[1] == "G" + volume = deck.gas_volume_surface if gas else deck.liquid_volume_surface + rate = key.endswith("R") + res[datatype] *= (deck.time if rate else 1.0) / volume + unit = {"si": "m3", "metric": "Sm3", "field": "Mscf" if gas else "stb", "lab": "cm3"}[system] + period = {"si": "s", "metric": "day", "field": "day", "lab": "h"}[system] + attrs[datatype] = f"{unit}/{period}" if rate else unit + df = pd.DataFrame(res, index=self.index[1]) df.index.name = self.index[0] df.attrs = attrs @@ -1667,37 +1800,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 +1889,125 @@ def _compute_adjoints(self, case, jlres, pyres, units, actnum_vec, return adjoints + def _weighted_products(self, case, res, summary, actnum, jl, parameters, cells, seeds, state=None): + """Differentiate the columns of labelled seeds on one live METRIC trajectory.""" + active = actnum == 1 + out = {p: np.zeros((seeds.shape[1], np.size(state[p]) if state is not None else len(actnum))) + for p in parameters} + if not np.isfinite(seeds).all(): + raise ValueError("Weighted adjoint coefficients must be finite") + if not seeds.any(): + return out + report_times = dict(zip(self.report, self.report_seconds)) + times, wells, targets, rates, injectors, values = [], [], [], [], [], [] + for label, key in cells: + kind, _, well = key.partition(":") + if not well or kind not in PHASE_MAP: + raise ValueError(f"No weighted adjoint for {key!r}; supported well data: {sorted(PHASE_MAP)}") + phase, rate = PHASE_MAP[kind] + times.append(report_times[label]) + wells.append(well) + targets.append(RATE_ID_MAP[phase]) + rates.append(rate) + injectors.append(kind[2] == "I") + values.append(summary.at[label, key]) + step_times = self._prepare_adjoint_storage(jl) + if step_times is not None and any(np.count_nonzero(abs(step_times - t) <= STEP_TIME_TOL) != 1 for t in set(times)): + raise ValueError("Weighted adjoints require one matching simulator step per report time") + jac, nc, copied = self._perm_gradient_context(case, actnum, parameters, jl) + if state is not None and copied and any(p.endswith(axis) for axis, tied in zip(("permy", "permz"), copied.include[1:]) + if tied for p in state): + raise ValueError("A copied axis cannot also be an independent permeability control") + for j, column in enumerate(seeds.T): + if not column.any(): + continue + jl.func = jl.subsurface_weighted_well_objective(wells, targets, rates, injectors, times, column, STEP_TIME_TOL) + contributions = column * values + actual = float(jl.Jutul.evaluate_objective(jl.func, case, res.result)) + if not np.isfinite(actual) or not np.isclose(actual, contributions.sum(), rtol=0, atol=1e-6 * np.abs(contributions).sum()): + raise ValueError("Weighted adjoint objective does not reproduce the reported data") + stop = max(t for t, w in zip(times, column) if w) + n_steps = None if step_times is None else int(np.searchsorted(step_times, stop + STEP_TIME_TOL, side="right")) + grad, well = self._solve_adjoint(jl, n_steps=n_steps) + wi = _well_index_chain_term(jac, well, nc, jl) if jac else None + for p in parameters: + g = _extract_adjoint(grad, case, p, actnum, copied if p.endswith("permx") else None, jl, wi_chain_term=wi) + if state is not None and np.size(state[p]) != len(g): + g = g[active] + if g.shape != out[p][j].shape or not np.isfinite(g).all(): + raise ValueError(f"Invalid adjoint shape or nonfinite values for {p}") + out[p][j] = g + return out + + 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. @@ -1890,4 +2122,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_darcy.py b/tests/test_jutul_darcy.py index ce9c2dc..3bab151 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,246 @@ 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_surface_units_against_si_on_the_same_trajectory(tmp_path, options, tiny_folder, monkeypatch): + case_dir = _copy_case_folder(tmp_path, tiny_folder, "units") + monkeypatch.chdir(case_dir) + keys = ["WOPT:PRO2", "WWIT:INJ1", "FLPT", "FGPT", "WOPR:PRO2"] + sim = JutulDarcy({**options, "datatype": keys}) + extract = sim.extract_datatypes + + def check(result, case, units, jl): + summary = jl.JutulDarcy.summary_result(case, result, jl.Symbol("si")) + si = summary["VALUES"] + times = np.rint(np.array(summary["TIME"].seconds)).astype(int) + report = [np.flatnonzero(times == (date - datetime(2022, 1, 1)).total_seconds()).item() + for date in REPORT_DATES] + expected = np.column_stack([np.array(si["WELLS"][well][key] if well else si["FIELD"][key]) + for key, _, well in (k.partition(":") for k in keys)])[report] + assert (expected[-1] > 0).all() + for system, liquid, gas, period in [("si", 1, 1, 1), ("metric", 1, 1, 86400), + ("lab", 1e-6, 1e-6, 3600), + ("field", 0.158987294928, 28.316846592, 86400)]: + frame = extract(result, case, system, jl) + np.testing.assert_allclose(frame.to_numpy(), expected / [liquid, liquid, liquid, gas, liquid / period], + rtol=1e-6) + return frame + + monkeypatch.setattr(sim, "extract_datatypes", check) + sim.run_fwd_sim({"log_permx": np.log(np.load("PERMX.npy"))}) + + +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"}) diff --git a/tests/test_jutul_vjp.py b/tests/test_jutul_vjp.py new file mode 100644 index 0000000..7a8013b --- /dev/null +++ b/tests/test_jutul_vjp.py @@ -0,0 +1,38 @@ +import numpy as np +import pandas as pd +from unittest.mock import patch + +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) + with patch.object(sim, "_setup_case", wraps=sim._setup_case) as setup: + g = sim.run_vjp({"log_permx": x}, weights)["log_permx"] + assert setup.call_count == 1 + single = weights.map(lambda cell: cell[0] if cell is not None else np.nan) + forecast = JutulDarcy({"runfile": "RUNFILE.mako", "reportpoint": REPORT_DATES, "reporttype": "dates", + "datatype": sim.datatype, "perm_copied": True, + "weighted_adjoint": {"parameters": ["log_permx"]}}) + forecast.adjoint_weights = lambda output, i: single.loc[output.index.intersection(single.index)] + _, gradient = forecast.run_fwd_sim({"log_permx": x}) + np.testing.assert_allclose(gradient["log_permx"], g[0], rtol=1e-6, atol=1e-7) + + 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)