The Du et al. (2025) refinery planning benchmark#

W. Du, C. Wang, C. Fan et al., “A production planning benchmark for real-world refinery-petrochemical complexes”, arXiv:2503.22057 (2025), publishes a refinery topology with crude data, prices, product specifications and a delta-base planning model. difflow_refinery.benchmarks.du2025 implements its Case 1 as published (#530): two swing-cut crude units, 20 fixed-yield units, 5 delta-base units, 32 mixers, 61 splitters and 12 blenders. They are assembled into one differentiable JAX model.

This notebook:

  1. loads the data and builds the model;

  2. checks the published optimum against it: every equation, every limit, and the profit;

  3. re-solves the model locally with pounce;

  4. reads the binding capacities off the multipliers;

  5. differentiates a delta-base unit, which is the Jacobian that later work compares against nonlinear units.

The data are not shipped with difflow, because the paper is CC BY-NC-SA and the data repository has no license file. du2025.fetch() downloads them. Without network access, the notebook falls back to the tiny synthetic case used by the tests, which has the same format and none of the benchmark’s numbers.

import jax
import jax.numpy as jnp
import numpy as np
from pathlib import Path

from difflow_refinery.benchmarks import du2025
from difflow_refinery.benchmarks.du2025 import blocks

jax.config.update("jax_enable_x64", True)

try:
    case = du2025.find_case(1) or du2025.fetch() / "case1"
    REAL = True
except Exception as exc:                 # offline: the synthetic test case
    print("benchmark data unavailable:", exc)
    case, REAL = Path("../tests/refinery/du2025_mini/case1"), False

data = du2025.load_case(case)
model = du2025.build_model(data)
print(f"{'Case 1' if REAL else 'synthetic case'}: {model.n} variables, "
      f"{model.eq.n_rows} equations, {model.ineq.n_rows} inequalities")
Case 1: 1850 variables, 1621 equations, 81 inequalities

The published optimum#

The paper reports a profit of 34,167,968 for Case 1, and BARON and ANTIGONE agree on it. The solution itself is a GAMS .gdx file. load_solution reads it through gams.transfer (pip install gamspy-base 'gamsapi[transfer]'), or reads a JSON export of it (du2025.export_solution_json).

The model reproduces the published point only after four rules that the paper does not state are added. They were read from the bounds stored with the solution. One of them makes an untraced property that some equation references into a free variable. Those free variables can take unphysical values at the optimum, so do not read plant data from them.

sol = None
for name in ("solution_baron.json", "solution_baron.gdx"):
    try:
        sol = du2025.load_solution(case / name)
        break
    except (FileNotFoundError, ImportError) as exc:
        print(f"{name}: {type(exc).__name__}")

if sol is not None:
    x_pub = model.x_from_solution(sol)
    print("violations at the published point:", model.violations(x_pub))
    print(f"profit {float(model.profit(x_pub)):,.2f}  (paper: {du2025.CASE1_PUBLISHED_PROFIT:,.0f})")
    print(f"{len(model.untracked)} untraced properties are free variables, e.g.",
          model.untracked[:3])
violations at the published point: {'eq': 8.460807876531362e-08, 'ineq': 5.684341886080802e-14, 'bounds': 0.0}
profit 34,167,967.96  (paper: 34,167,968)
21 untraced properties are free variables, e.g. (('s6', 'Q0'), ('s170', 'Q37'), ('s170', 'Q17'))

A local solve#

With denominators cleared, every equation is at most bilinear. The model stores itself as sparse polynomial coefficients, so its Jacobian sparsity pattern is exact and needs no probing. solve_local hands the model to pounce. Pooling makes the problem nonconvex, so a local solve finds a local optimum. Here it starts at the published point, or at a point built from the blocks on the synthetic case.

x0 = x_pub if sol is not None else np.clip(np.ones(model.n), model.lower, model.upper)
xs, info = du2025.solve_local(model, x0, options=du2025.WARM_START_OPTIONS)
print(info["status_msg"], f"profit {info['profit']:,.2f}", model.violations(xs))
 INFO pounce_algorithm::conv_check::opt_error: refusing an acceptable-level termination: the error has been inside the acceptable band for the whole streak but is still moving across it, so the streak has not flattened; continuing (acceptable_progress_kappa=0 disables) nlp_err=2.4259931959439344e-7 obj=-34.16796870628019 acceptable_tol=1e-6 window=15 kappa=0.1
Solved_To_Acceptable_Level profit 34,167,968.71 {'eq': 1.4585274588085895e-07, 'ineq': 9.990442251250897e-09, 'bounds': 1.0899458757762659e-07}

Which limits bind#

The constraint multipliers give the marginal profit of each inequality, in the solver’s scaled units, which are millions per unit. The largest ones show which capacities and specifications limit the plan.

mult = np.asarray(info["mult_g"])[model.eq.n_rows:] / du2025.model.PROFIT_SCALE
g = np.asarray(model.ineq(xs))
order = np.argsort(-np.abs(mult))[:8]
for i in order:
    print(f"{str(model.ineq.names[i]):40s} slack {-g[i]:9.2e}   marginal profit {abs(mult[i]):12,.0f}")
('25', 'ccap6', 'min')                   slack -9.99e-09   marginal profit    1,046,306
('25', 'ccap5', 'min')                   slack -9.99e-09   marginal profit      723,099
('26', 'ccap2', 'min')                   slack -9.98e-09   marginal profit      498,245
('25', 'ccap10', 'max')                  slack -9.96e-09   marginal profit      236,159
('25', 'ccap19', 'max')                  slack -9.95e-09   marginal profit      186,911
('25', 'ccap13', 'max')                  slack -9.93e-09   marginal profit      135,397
('25', 'ccap4', 'min')                   slack -9.93e-09   marginal profit      133,641
('16', 'Umix21', 'm126', 'Q169', 'max')  slack -9.85e-09   marginal profit       66,083

Differentiating a delta-base unit#

A delta-base unit shifts its yields linearly with the feed properties (Eq. 9) and renormalizes them (Eq. 10). Its Jacobian with respect to the feed properties at the base point is the published delta vector delta / Del, scaled by the feed. #533 compares this Jacobian with the AD Jacobian of a nonlinear unit. Here it is Upd0 (a diesel hydrotreater), batch m22, with its feed at the base properties.

if REAL:
    u, m = "Upd0", "m22"
    ins = [s for (uu, mm, s) in data.sets["IM"] if (uu, mm) == (u, m)]
    outs = [s for (uu, mm, s) in data.sets["OM"] if (uu, mm) == (u, m)]
    qs = [q for (uu, mm, s, q) in data.sets["DBSQ"] if (uu, mm) == (u, m)]
else:
    u, m, ins, outs, qs = "Upd0", "m2", ["s2"], ["s6", "s7"], ["Q0"]
P = data.param
gam = lambda ss: jnp.array([P("gamma").get((u, m, s), 0.0) for s in ss])
dlt = lambda ss: jnp.array([[P("delta").get((u, m, s, q), 0.0) for q in qs] for s in ss])
base = jnp.array([P("B")[(u, m, q)] for q in qs])
step = jnp.array([P("Del")[(u, m, q)] for q in qs])
feeds = gam(ins)                    # feed in its base proportions, 1 t of the main feed

def yields(props):
    out, _ = blocks.delta_base(feeds, gam(ins), gam(outs), props, base, dlt(ins), dlt(outs), step)
    return out

J = jax.jacobian(yields)(base)
print("properties:", qs)
for s, row, d in zip(outs, np.asarray(J), np.asarray(dlt(outs) / step)):
    print(f"{s:6s} dF/dFQ {np.round(row, 6)}   delta/Del {np.round(d, 6)}")
properties: ['Q0', 'Q168']
s140   dF/dFQ [ 1.088e-03 -1.000e-06]   delta/Del [0.00109 0.     ]
s227   dF/dFQ [-7.62e-04 -1.10e-05]   delta/Del [-7.6e-04 -1.0e-05]
s91    dF/dFQ [-3.27e-04  5.20e-05]   delta/Del [-0.0002   0.00013]
s126   dF/dFQ [-0. -0.]   delta/Del [0. 0.]

Property data and crude assays (#532)#

The benchmark names its properties Q0-Q169. du2025.properties identifies the ones it uses and records, for each, a confidence and the evidence. Its crudes are given only as cut yields and cut properties. du2025.assays.fit_tbp reconstructs a TBP and a gravity curve for every crude. To do that, it fits the crude unit’s anonymized cut temperatures jointly over all crudes, so that each crude’s Watson K varies smoothly from cut to cut. A prior on typical cut points sets the temperature scale.

from difflow_refinery.benchmarks.du2025.properties import PROPERTY_MAP, describe
from difflow_refinery.benchmarks.du2025.assays import crude_assay, fit_tbp
from difflow_refinery.assay import characterize
import warnings

for q in ("Q168", "Q0", "Q21", "Q25", "Q51", "Q45"):
    print(describe(q))

fit = fit_tbp(data)
for unit, s in fit.summary().items():
    print(unit, {k: round(v, 4) for k, v in s.items()})
print("UCDU0 cut points (C):", (fit.cut_points[fit.tables[0].unit] - 273.15).round(0))
Q168: specific gravity (-, high)
Q0: sulfur (wt%, high)
Q21: Conradson carbon residue (wt%, high)
Q25: nickel + vanadium (wppm, high)
Q51: olefins (vol%, high)
Q45: unidentified (not weight-blended) (-, unknown)
UCDU0 {'max_yield_err': 0.0003, 'max_sg_err': 0.0, 'yield_within_tol': 1.0, 'sg_within_tol': 1.0, 'k_rms': 0.0484}
UCDU1 {'max_yield_err': 0.1356, 'max_sg_err': 0.1635, 'yield_within_tol': 0.6967, 'sg_within_tol': 0.4533, 'k_rms': 0.1314}
UCDU0 cut points (C): [ 93. 103. 140. 152. 226. 256. 268. 285. 363. 491. 513. 526.]

The reference unit’s cuts are reproduced. The second unit’s are not, because in this data set the two units describe the same crude differently (see the docs). The reconstructed assay characterizes into one pseudo-component per benchmark cut. Sulfur, nitrogen and CCR come from the benchmark, and PNA and hydrogen from difflow’s correlations.

t = fit.tables[0]
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    char = characterize(crude_assay(fit, 0), cut_points=fit.cut_points[t.unit], composition=True)
k = len(t.cuts) - 1
print("cut    yield   SG     S wt%   N wppm   CCR wt%  aromatics")
for j in range(k):
    print(f"{t.cuts[j]:6s} {float(char.mass_fraction[j]):.4f} {float(char.SG[j]):.4f} "
          f"{100 * float(char.sulfur[j]):6.3f} {1e6 * float(char.nitrogen[j]):8.0f} "
          f"{100 * float(char.ccr[j]):7.3f}  {float(char.composition.hc_type[j, 2]):.3f}")
cut    yield   SG     S wt%   N wppm   CCR wt%  aromatics
s310   0.1395 0.6972  0.082        6   0.013  0.132
s327   0.0267 0.7747  0.161       22   0.013  0.249
s157   0.0616 0.7928  0.215       35   0.013  0.275
s329   0.0223 0.8114  0.292       49   0.013  0.308
s169   0.1007 0.8395  0.658       72   0.013  0.367
s122   0.0319 0.8674  1.477      103   0.013  0.426
s290   0.0289 0.8797  1.862      114   0.013  0.431
s331   0.0286 0.8864  2.036      176   0.017  0.398
s296   0.1680 0.9073  2.565      456   0.018  0.196
s298   0.2044 0.9363  3.214      949   0.019  0.255
s300   0.0084 0.9575  3.689     1313   0.019  0.267
s333   0.0121 0.9656  3.839     1402   0.028  0.282

The crude units as swing-cut blocks (#531)#

In build_model the swing fractions phi are fixed parameters. difflow_refinery.swing_cut turns a crude unit into a block whose decisions are the crude rates and phi. With the published values, it reproduces the crude unit’s outlets. The published formulation gives a swing cut constant properties. Letting them vary linearly across the cut shows what that simplification costs.

from difflow_refinery.swing_cut import swing_cut_block, swing_property_error
from difflow_refinery.benchmarks.du2025.crude import cut_table, published_rates

if REAL and sol is not None:
    table, phi = cut_table(data, "UCDU0")
    rates = published_rates(table, "UCDU0", sol)
    F, q = swing_cut_block(table, jnp.asarray(rates), jnp.asarray(phi))
    err = max(abs(float(F[i]) - sol["FVO"].get((p, "1"), 0.0)) for i, p in enumerate(table.products))
    print(f"max outlet flow error vs the published solution: {err:.1e}")
    J = jax.jacfwd(lambda ph: swing_cut_block(table, jnp.asarray(rates), ph)[0])(jnp.asarray(phi))
    print("dF/dphi shape", J.shape)
    for k, (p, c) in enumerate(table.swings):
        _, e = swing_property_error(table, jnp.asarray(rates), jnp.asarray(phi), k, table.spg)
        print(f"swing {c:5s} -> {p:5s}: max |SG(varying) - SG(constant)| = {np.abs(e).max():.4f}")
max outlet flow error vs the published solution: 1.8e-15
dF/dphi shape (10, 9)
swing s290  -> s122 : max |SG(varying) - SG(constant)| = 0.0034
swing s303  -> s0   : max |SG(varying) - SG(constant)| = 0.0115
swing s303  -> s169 : max |SG(varying) - SG(constant)| = 0.0117
swing s310  -> s0   : max |SG(varying) - SG(constant)| = 0.0220
swing s327  -> s157 : max |SG(varying) - SG(constant)| = 0.0025
swing s329  -> s157 : max |SG(varying) - SG(constant)| = 0.0005
swing s329  -> s169 : max |SG(varying) - SG(constant)| = 0.0004
swing s331  -> s296 : max |SG(varying) - SG(constant)| = 0.0002
swing s333  -> s300 : max |SG(varying) - SG(constant)| = 0.0058

Fixed-yield blocks, and which unit to model next (#537)#

The deasphalter, aromatics extraction, gas fractionation and MTBE units have no mechanistic model. fixed_yield_block represents each as a block of base yields and property transfers. Which one is worth a mechanistic model? The envelope theorem gives the optimal profit’s sensitivity to every outlet yield straight from the local solve’s multipliers.

from difflow_refinery.benchmarks.du2025.units import FIXED_YIELD_UNITS, fixed_yield_block, stream_from_solution
from difflow_refinery.benchmarks.du2025.calibration import yield_sensitivity

if REAL and sol is not None:
    blk = fixed_yield_block(data, "Upf19")
    print(blk.name, "outlets", blk.outlets, "loss", round(blk.loss, 4))
    sens = yield_sensitivity(model, xs, info["mult_g"], list(FIXED_YIELD_UNITS))
    for u, s in sorted(sens.items(), key=lambda kv: -kv[1]["per_wt_pct"]):
        print(f"{u:6s} {FIXED_YIELD_UNITS[u]:38s} profit per 1 wt% yield shift {s['per_wt_pct']:12,.0f}")
Upf19.m52 outlets {'s164': 0.26, 's201': 0.73} loss 0.01
Upf13  aromatics extraction (reformate)       profit per 1 wt% yield shift      858,683
Upf12  aromatics extraction (purchased feed)  profit per 1 wt% yield shift      136,680
Upf6   gas fractionation                      profit per 1 wt% yield shift      107,009
Upf5   gas fractionation                      profit per 1 wt% yield shift       98,927
Upf10  MTBE / C4                              profit per 1 wt% yield shift       46,671
Upf19  solvent deasphalter                    profit per 1 wt% yield shift        9,115

At the base point the two columns differ only by the renormalization of Eq. 10. That term moves every outlet when the inlet coefficients move too, as they do for the hydrogen co-feed. When the published unit is replaced by a nonlinear model, J is the quantity to compare.

See the docs, “The Du et al. (2025) planning benchmark”, in docs/unit-operations-refinery.md.