Repository navigation
Conversation
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
marked this pull request as ready for review
November 27, 2026 09:59
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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,bec39e1andc4db316.Why
The JutulDarcy wrapper adds two chain-rule terms to a permeability gradient: the axes a deck
COPYties 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
JutulDarcy.check_chain_rule(state, weights=None, step=1e-2, rtol=0.05, seed=0), with the call and the report ofFlowAdjoint.check_chain_rule(Check that the OPM adjoint resolves every chain-rule term #22):ties,derived,approximate,unresolved,finite_difference. It raisesValueErroron an unresolved term or a gradient that differs from finite differences.perm_copiedadds and the well indiceswell_index_from_permdifferentiates.weights: central differences of the weighted sums along an alternating and a uniform direction at two step sizes, four simulations per variable and direction.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.JutulDarcy.chain_rule, the last report (Nonebefore the first check).subsurface.multphaseflow.vjp:keywords_changed(base_text, text), the comparison of two rendered decks, moved out ofopm_adjoint.pyso both wrappers use it.FlowAdjointbehaves as in Check that the OPM adjoint resolves every chain-rule term #22.subsurface_case_arrays(case)in the wrapper's helper block.run_fwd_sim, theadjointsand theweighted_adjointpaths are unchanged.Changed test
test_weighted_rates_match_forward_differenceasserts one case setup perrun_vjpcall. It now callscheck_chain_rulefirst, since the firstrun_vjpwould otherwise set up the extra cases of the check.Verification
JutulDarcy 0.4.1 / Jutul 0.5.9, on the
Example/TINYdeck (COPYof PERMX into PERMY and PERMZ, defaulted connection factors):tests/test_jutul_vjp.py: 7 passed.tests/test_jutul_darcy.pywithtests/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.log_permxby 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).perm_copied=False,well_index_from_perm=False,well_index_from_perm=Trueon a schedule with explicit connection factors, a template that writes PERMY from the state, and a uniform PERMX untilperm_copied=Trueis set.Not exercised: a porosity state, decks with inactive cells, and independent
permy/permzstates. 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.