Skip to content

Check that the JutulDarcy adjoint resolves every chain-rule term - #23

Merged
KriFos1 merged 11 commits into
Python-Ensemble-Toolbox:mainfrom
KriFos1:feature/jutul-chain-rule-check
Nov 27, 2026
Merged

KriFos1 merged 11 commits into
Python-Ensemble-Toolbox:mainfrom
KriFos1:feature/jutul-chain-rule-check

Conversation

@KriFos1

@KriFos1 KriFos1 commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Builds on #21 (JutulDarcy weighted adjoints) and #22 (the same check for the OPM wrapper, itself on #19). Until those are merged the diff here also shows their commits. The commits of this PR are the merge adb17f4, bec39e1 and c4db316.

Why

The JutulDarcy wrapper adds two chain-rule terms to a permeability gradient: the axes a deck COPY ties to PERMX, and the well indices JutulDarcy computes from the permeability. Both are detected from the parsed fields. Nothing told when the detection missed one, or when a deck moved something else with the state. For a uniform PERMX the copy cannot be detected at all: the wrapper warns and returns a gradient without the y and z parts.

Public API

  • New: JutulDarcy.check_chain_rule(state, weights=None, step=1e-2, rtol=0.05, seed=0), with the call and the report of FlowAdjoint.check_chain_rule (Check that the OPM adjoint resolves every chain-rule term #22): ties, derived, approximate, unresolved, finite_difference. It raises ValueError on an unresolved term or a gradient that differs from finite differences.
    • Structural part: each variable is perturbed, the deck rendered again and set up by JutulDarcy without simulating. The rendered text and every numeric array of the two cases are compared: data domains, parameters and initial state of all models. Only the variable's own field may move, the reservoir parameters JutulDarcy computes from it, the axes perm_copied adds and the well indices well_index_from_perm differentiates.
    • It raises in both directions: on a term the wrapper would miss, and on a term the options add for an axis or a well index that does not move.
    • With weights: central differences of the weighted sums along an alternating and a uniform direction at two step sizes, four simulations per variable and direction.
  • Changed: JutulDarcy.run_vjp(state, weights). Same signature and return value. It runs the structural check before its first batch (one extra case setup, plus one per state variable; no simulation) and raises on an unresolved term. A deck for which it returned an incomplete gradient is now refused.
  • New attribute: JutulDarcy.chain_rule, the last report (None before the first check).
  • New in subsurface.multphaseflow.vjp: keywords_changed(base_text, text), the comparison of two rendered decks, moved out of opm_adjoint.py so both wrappers use it. FlowAdjoint behaves as in Check that the OPM adjoint resolves every chain-rule term #22.
  • New Julia helper subsurface_case_arrays(case) in the wrapper's helper block.
  • README: the JutulDarcy section describes the check.

run_fwd_sim, the adjoints and the weighted_adjoint paths are unchanged.

Changed test

test_weighted_rates_match_forward_difference asserts one case setup per run_vjp call. It now calls check_chain_rule first, since the first run_vjp would otherwise set up the extra cases of the check.

Verification

JutulDarcy 0.4.1 / Jutul 0.5.9, on the Example/TINY deck (COPY of PERMX into PERMY and PERMZ, defaulted connection factors):

  • tests/test_jutul_vjp.py: 7 passed. tests/test_jutul_darcy.py with tests/test_import.py: all passed in a run of 23 tests that held the first six of these seven.
  • tests/test_flow_vjp.py (OPM/opm-adjoint master a02f844): 7 passed, also on the refactor commit alone.
  • The check finds PERMY and PERMZ tied to log_permx by the factor 1, with transmissibilities and well indices derived. Gradient and finite differences: 864.25 against 860.53 (alternating direction) and 384.25 against 374.45 (uniform direction).
  • Refused before anything is simulated: perm_copied=False, well_index_from_perm=False, well_index_from_perm=True on a schedule with explicit connection factors, a template that writes PERMY from the state, and a uniform PERMX until perm_copied=True is set.
  • With the structural part bypassed, the finite differences still catch a missing term: 406 against 861 with the copies off, 157 against 861 with the well indices off.
  • Cost on this deck, once Julia has compiled: 0.3 s for the structural part.

Not exercised: a porosity state, decks with inactive cells, and independent permy/permz states. The JutulDarcy tests were run on the last commit only. The wrapper decides the copied axes at each state, so a check passed at a heterogeneous state does not cover a later uniform one. The repository has no CI.

MathiasMNilsen and others added 11 commits November 26, 2026 08:48
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 <noreply@anthropic.com>
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.
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.
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.
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.
…rule-check

The JutulDarcy chain-rule check uses the finite-difference helpers that
branch adds to vjp.py. Both branches added vjp.py with the same
scalar_seeds; the conflict is resolved to the version with the helpers.
Which keywords of a rendered deck differ between two states does not
depend on the simulator. vjp.keywords_changed replaces the helper in
opm_adjoint.py, so the JutulDarcy wrapper can use the same comparison.
The wrapper adds two chain-rule terms to a permeability gradient, the
axes a deck COPY ties to PERMX and the well indices JutulDarcy computes
from the permeability. Both are detected from the parsed fields, and
nothing told when the detection missed one or when a deck moved
something else with the state. For a uniform PERMX the copy cannot be
detected at all, and the gradient silently lost the y and z parts.

JutulDarcy.check_chain_rule(state, weights=None) perturbs each
variable, renders the deck again and lets JutulDarcy set the case up
without simulating. It compares the rendered text and every numeric
array of the two cases: data domains, parameters and initial state of
all models. Only the variable's own field may move, the reservoir
parameters JutulDarcy computes from it, the axes perm_copied adds and
the well indices well_index_from_perm differentiates. It raises on a
term the wrapper would miss, and on a term the options add for an axis
or a well index that does not move. run_vjp runs it before its first
batch.

With weights, the gradients are also compared with central
differences of the weighted sums, with the helpers the OPM wrapper
uses.

The test of one case setup per run_vjp call runs the check first.
@KriFos1
KriFos1 marked this pull request as ready for review November 27, 2026 09:59
@KriFos1
KriFos1 merged commit 22738e0 into Python-Ensemble-Toolbox:main Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants