Repository navigation
Highlights
- Breaking: the browser editor now ships as
difflow-appwith the difflow book.difflow.guiis renameddifflow.workspace, anddifflow.publishis removed (sweep,SweepAxisandSweepResultlive indifflow.sweepsand are still exported fromdifflow). - New: an interactive flowsheet debugger (
difflow.debug,difflow debug, and MCP tools), feedback control (difflow.control: PI(D) and linear MPC), and model-discrimination / c-optimal experiment design. - Fixed: Fisher confidence intervals were too narrow by √2 (#512), plus planner, monitoring, reconciliation, stochastic and dynamic-CSTR fixes (#513–#519). The notebooks now run on jax 0.11 (#525).
Full details from CHANGELOG.md:
Breaking
- The browser editor moved out of difflow, to the app that comes with the difflow book. difflow is the
open engine; the editor (canvas, inspector, results, planning, console, assistant, and the debugger's
Debug and Trace panels), its server, its frontend and the staticpublishpage are nowdifflow-app,
which registers itself as adifflow.appsentry point.difflow guiand the agent tool
open_in_editorrun it when it is installed and say where it comes from when it is not; a bare
difflowprints usage without it. The session engine stays open and is renameddifflow.gui->
difflow.workspace(FlowsheetSession, edit, boilerplate, console, context, docs, docs_index,
doclinks, examples, layout, planning, sensitivity, and the newtopology); the agent and MCP tools are
unchanged.difflow.publishis gone:sweep,SweepAxisandSweepResultare indifflow.sweeps(and
still exported fromdifflow); the HTML page is the app's. The docs search index is
src/difflow/workspace/data/docs-index.json, rebuilt withmake docs-index(CI checks it); the
gui-build/gui-test/guimake targets, the editor's CI job and thedifflow-guiscript are removed.
Added
-
Example notebook
examples/69_flowsheet_debugger.ipynb. The flowsheet debugger on a recycle loop: stepping
by unit and tear iteration, breakpoints on a unit, a condition and an event,on_errorfinding the unit where a
NaN is born (in the tear-guessing pass),set tear, record and replay, and what-ifs on a loop with two steady
states (including Anderson converging to the unstable middle one);DebugRunnerand the JSON protocol. -
An interactive debugger for flowsheet solves. New
difflow.debug(docs/debugger.md) anddifflow debug plant.py|plant.json. Pauses a sequential-modular solve atsolve_start,before_unit/after_unit(each
unit call, tagged by phase:init,solve,probe,final,sequential),unit_error,iteration(the
tear map and its residual),after_accelandterminated; steps by tear iteration (step), by unit
(next) or by checkpoint (stepi). Breakpoints by iteration, before a unit, on a condition
(break if residual>1e3 && iter>5) or on an event (nonfinitewhere a NaN is born,inner_unconverged,
residual_rise,unit_error);printstreams, units, the tear table (x,g(x),|g - x|per field)
and the history;watch,diagnose,save, andinteract(Python with the pause in scope).
on_error=Truestops only post mortem. One engine, three front ends: a readline REPL, thedifflow-dbg/1
JSON protocol (a self-describinghello, pause/result events with request ids) andDebugRunner, which
runs the solve on a worker thread for a server or an agent. Detached it costs one thread-local read per
checkpoint; attached it only reads, andquitraisesDebugQuit. Design and the editor/agent phases in
plans/debugger.org, after pounce's and discopt's debuggers.
set tear STREAM.FIELD VALUE(at aniterationorafter_accelpause) changes the guess the next pass
runs on; edits are listed in theterminatedevent andFlowsheet.last_solve_debug_edits.
debug.record(fs, solve_kwargs)solves once through every checkpoint and returns adifflow-trace/1
trace (summarize,state_atandcompareread it). A what-if replays the recorded solve with one
tear value set at a frame (record(..., edits=, baseline=)): a replay, not a fresh solve, so the
accelerator keeps its history; frames before the edit are checked against the recording (diverged_at),
andcomparesays whether the two runs reached the same answer.FlowsheetSession(now
difflow.workspace) carries a live debugger for front ends that cannot block on a prompt: a long poll
(debug_start|command|wait|pause|stop, 20 s per call) overDebugRunner, which gainedstateand
pause(), plusdebug_record/debug_whatif, refusing a recording of a since-changed flowsheet; the
solve runs on a copy. (The book's browser editor puts its Debug and Trace panels on these.)
For agents,difflow mcpserves the same debugger:debug_guide(the contract and the handshake),
debug_start,debug_command,debug_wait,debug_pause,debug_state,debug_stop, over the
session'sFlowsheetSession.debug_*methods; thefix_convergenceprompt uses them. Record and what-if
for agents:debug_record(a per-iteration summary: frame, residual, largest tear entry, events, regime),
debug_trace_frame(one frame with every stream's value there) anddebug_whatif(the replay compared
with the recording,same_answerflagging a second steady state);difflow.debug.record.summarize,
state_atandcompare. Recording and replay now run on a copy of the flowsheet. -
Model-discrimination and c-optimal experiment design (issue 520).
difflow.estimation.design_discrimination(models, thetas, candidates, n, criterion='HR')chooses the
candidate runs that best tell rival models apart, each model at its own fitted parameters:'HR'
(Hunter-Reiner, the squared prediction differences over the model pairs weighted by1/sigma^2; additive,
so the best run replicated) or'BF'(Buzzi-Ferraris, the difference against the measurement and both
models' prediction variances, fromcovariances=or theexisting=runs; greedy on the set). It returns a
DiscriminationResultwith every candidate's score, per model pair, and each model's predictions over the
pool (onevmapper model).design_experiments(..., criterion='C', quantity=g)is c-optimal design: it
minimizesc^T FIM^-1 c, the predicted variance of a derived quantityg(theta)(c = jax.grad(g)at
theta, orquantity=cdirectly);design_criterion(fim, 'C', c=...)gives the value and
DesignResult.cthe gradient.CRITERIAnow includes'C'. -
Feedback control: PI(D) and linear MPC (issue 520). New
difflow.control(docs/control.md).
PIDController(also indifflow.dynamic) is a dynamic unit for aDynamicFlowsheet: parallel PI(D) with
derivative on the filtered measurement, output limits and back-calculation anti-windup (tracking time
constanttau_T,inffor none), reverse/direct action; gains, setpoint and limits are constants,f(t),
f(t, args)or (setpoint) a port, read per call fromparams, sojax.gradthroughsimulatetunes the
loop. Its output is a signal stream whoseTcarriesu;DynamicCSTRnow takesduty,UAorTcfrom
such a port and declares that its outlet does not read it (output_dependencies/partial_outputs), so a
controller measuring the outlet closes the loop without an algebraic loop (DynamicFlowsheetaccepts
output_dependencies(inlet_ports)as a method).LinearMPC(from_modellinearizes aStateSpaceModelby
autodiff) solves the input-bounded receding-horizon QP exactly withbox_qp(primal-dual active set, JAX),
offset-free through an output bias;run_mpcruns the closed loop against any JAX plant as onelax.scan.
StateSpaceModel.from_flowsheetmakes aDynamicFlowsheeta model fordifflow.mheand the MPC (input as
the flowsheet'sargs,thetaas itsparams), andDynamicFlowsheetResult.stream_historyreturns a
stream over the trajectory.
Fixed
-
make notebooksinstalls what the notebooks import, and they run on jax 0.11. The notebook rule ran under
plainuv run, which installs no extras, so every notebook that imports tabulate, asdex, gaspype or pounce
died withModuleNotFoundError; it now runs with theexamples,solversandgaspypeextras and
pounce-solver[jax]. jax 0.11 removedjax.core.get_opaque_trace_stateandjax.core.Effect, which flax
0.12.2 still called, andxla_pmap_p, which numpyro 0.20 (under gpjax) still imported: flax is floored at
0.12.9 on Python >= 3.12 and numpyro at 0.21.0.pandasjoins theexamplesextra. Every notebook is
re-executed (#525). -
difflow.particlesexportsDRAG_METHODS. It was missing from__all__, so
from difflow.particles import *raisedNameErroron it (#525). -
The bastnasite example cuts between Ce and Pr. Its extraction pH (1.05) was tuned on the REE circuit model
before the organic-flow, loading-capacity and scrub-recycle fixes; on the corrected model it sent 86 % of the
Pr to the raffinate and net income never changed sign over the scale sweep. At pH 1.20 the closed loop
recovers 99.7 % Pr and 100 % Nd and rejects 99.95 % Ce. The purity ceiling now counts only the elements
between the extraction and strip cuts (Dy and Y stay on the solvent), and the prose no longer says a third
of the Pr is lost whatever the scrub does: Pr is placed by stages, at the cost of recycle inventory (#525). -
The debugger's
p historyanddiagnoseread a history mid-solve by its observed rate ("falling, about
x0.039 per iteration", or creeping, rising, oscillating) instead of applying the verdict meant for a finished
solve, which called a residual falling fast after three iterations "creeping". -
Fisher confidence intervals were too narrow by sqrt(2) (issue 512).
fisher_confidence_intervals/Estimator.confidence_intervalscomputeds^2 H^-1from the Hessian of the
sum of squares, which has no 1/2, soH = 2 J^T Jand every standard error was 1/sqrt(2) of the textbook
s^2 (J^T J)^-1. The covariance now depends on the objective:'sse'givess^2 (J^T J)^-1(2 s^2 H^-1),
'wsse'treats the declared uncertainties as known and gives(J^T W J)^-1(nos^2; the same covariance
predicted_covariancepredicts), and'nll'givesH^-1.fisher_confidence_intervalstakes a new
objective='sse'argument;Estimator.confidence_intervalsandsummarypass theirs through. Standard errors
and intervals from earlier versions grow by sqrt(2) on'sse'; on'wsse'and'nll'bysqrt(2/s^2)and
sqrt(1/s^2). -
apply_backoffmargins were not kept by the planner (issue 513). The LP rows used
Spec.effective_rhs, but the trust-region acceptance test, the merit andPlanResult.violationsscored
each step against the statedrhs, so accepted steps ate into the back-off and the plan drifted back to
the nominal constraint. All of them now measure againsteffective_rhs(as does the merit that
plan_sensitivitydifferentiates).Spec.violation(values, stated=True),
DeltaBasePlanner.violations(values, stated=True)and the newPlanResult.stated_violationsreport the
stated limits. -
PlanResult.plan_sensitivityread the planner's current specs (issue 514). The active set and KKT
system were built fromresult.plannerat call time; a planner is shared, so after
planner.specs = apply_backoff(...)and a re-solve, an earlier result's sensitivities were silently
taken against the new specs (Ch 28 of the unit-ops book: d(profit*)/d ln k1 5180 instead of 2819). A
PlanResultnow keepssolved_with, aDeltaBasePlanner.snapshot()taken at the solve (specs,
prices, theta, modifiers, penalty, options), withspecs,prices,thetaandscore()on the
result;plan_sensitivity,stated_violations,DeltaVectorSet.from_resultanddraw_trust_region
read it. -
Block.from_flowsheetwithoutu0refused call-keyword levers (issue 515). A lever that is a key
of the unit'sUnit.params(e.g. a CSTR'sT_spec) can be set by_apply_params, but the defaultu0
was looked up only among the operation'sParamsfields and raisedKeyError. It now reads the value
through the newFlowsheet._param_value, the read side of_apply_paramswith the same lookup order. -
Two specs on one variable hid each other's violation (issue 515).
Spec.namedefaults to the
variable name, and violations, the penalty charge and the LP's elastic slack columns are keyed by it, so
with a>=and a<=on one variable (hard tank-level bounds) only the last survived. From a start
below the lower bound,res.violationsread 0, restoration judged the start feasible, and the loop ran
tomax_iter. The planner (andbuild_lp) now extend colliding default names with the operator and
limit ("tank.level>=0"), viadifflow.planning.lp.unique_spec_names; duplicate names chosen by the
caller raiseValueError. Such a run now restores, or endsrestoration_failedwith the violation
reported. -
MonitorResult.diagnoseread fouling as an instrument fault;track_parametersleaked a meter bias
into the parameter (issue 516). With two equations (an exchanger's energy balance and itsUArate
equation) fouling moves both outlet temperatures together and the measurement test blames the same
sensor every day, so drift was diagnosed "instrument fault ... on Th_out".monitorand
track_parametersnow also reconcile each period against the constraints with no model parameter
(rows wheredF/dparamsis identically zero; newparameter_free_rows,balance_test, and a
parameter_free=override) and recordbalance_statistic,balance_detectedandbalance_checkson
eachMonitorStep.diagnosedecides on that test where it can (passes: model drift; rejects:
instrument fault or undiagnosed) and falls back on the blame pattern otherwise;MonitorDiagnosis
gainsbalance_rejection_rateandbasis.update_gate(..., step=)also holds amodel driftverdict on
a period whose own parameter-free test rejects, which stops the first days of a new fault moving the parameter (a +4 K
thermocouple bias gaveUA62.7 +/- 0.4 kW/K against 60; it now holds at 60).track_parameters
passes the step. -
reconcile_multirecompiled for every new data set (issues 516, 519). The stacked residual was a
fresh closure per call andsolve_reconciliationtakes the residual as a static argument; it is now a
structurally hashable object, so a sliding window re-uses the compiled solve (about 17 s to about 1.5 s
per week of exchanger data).parameter_measurement's augmented residual gets the same treatment.
Notebook 29 re-run: the default-gate leak of its section 7 (eta dragged to 1.131 by a meter bias) is gone. -
solve_saawith a per-scenario recourse converged poorly, andcheck_scenario_healthmissed it (issue 517).
When the recourse holds a spec exactly (the temperature turned until conversion is 0.90, so the cost has a
kink each scenario sits on), one cosine schedule of projected Adam ran out of budget partway along the kinked
valley: a 128-scenario CSTR came back at 7.1-12.6 m^3 against a 5.68 m^3 scan optimum depending on
SAAOptions, andbounds()brokeWS <= SP <= EEV. Each augmented-Lagrangian round now runs warm
restarts (SAAOptions.max_cycles,cycle_decay,tol): fresh Adam moments, the step halved once progress
slows, stopping when the point stops moving; warm restarts and later rounds keep the final smoothing and
start from the step the previous round ended on instead of re-crossing the box (which also let a later
round wander off a mean-value optimum it had already found). Every setting of that problem now gives
5.679 m^3.check_scenario_healthreportsstationarity(the best risk improvement a feasible, bounded
trial move of each first-stage or recourse variable finds) and flagsnot_stationary; the autodiff
gradient it already printed is one side of a jump at a kink and can be 2-3 at a true optimum.
StochasticConstraint.violation_ratecounts a scenario as violated only pastFEASIBILITY_TOL, the
toleranceSAAResult.feasibleuses, so an output the recourse holds exactly at its bound is not decided by
round-off (FEASIBILITY_TOLnow lives indifflow.stochastic.risk;saare-exports it). Results of every
solve_saachange slightly; solves take up tomax_cyclestimes longer when they need it
(max_cycles=1for one cycle per round).expected_feasibility(distribution="normal")'s docstring now says
in so many words that the box half-widths are one standard deviation.examples/32_stochastic_ree_separation
is re-executed: every solve there now finds a better CVaR (the mean-value and stochastic designs move to the
solvent lower bound; SP 241.0 -> 242.6, VSS 3.9 -> 4.1, EVPI 0.21 -> 0.02 $M/yr), and its prose follows. -
DynamicCSTR(mode="specified_duty")could not set a duty, and there was no jacket (issue 518). The energy
balance readparams["Q_spec"], which nothing stored, so a specified-duty reactor always ran adiabatic.
DynamicCSTRnow takes keyword-onlyduty=(W) for"specified_duty"and a newmode="jacket"withUA=
(W/K) andTc=(K), Q = UA (Tc - T). Each is a constant,f(t), orf(t, args)reading
DynamicFlowsheet.simulate(args=...);Tcmay also name an inlet port whose stream temperature is the
coolant's. They are params keys, sosimulate(params={"UA": ua})overrides them andjax.gradgoes through
them ("Q_spec"is still read as a duty override). NewDynamicCSTR.heat_input(t, T, inputs). Building a
"specified_duty"CSTR withoutduty, a"jacket"one withoutUAorTc, passing them to a mode that does
not use them, or an unknown mode now raisesValueError.DynamicUnitBase.derivatives/outputsno longer
write a call'sparamsinto the unit (a traced value fromjax.gradstayed behind and broke the next call);
the override holds for that call only. They also take the integratorargs(wants_args), which
DynamicFlowsheetnow hands to a unit'sderivativesas it already did tooutputs. -
Estimator,sensitivity_matrix,design_experimentsandrun_mhecompiled per experiment or per
window (issue 519). The estimation objectives looped over the experiments in Python, so onejittraced
a copy of the model perExperiment. They now stack experiments that share their structure (same input
keys and observed outputs, numeric inputs of equal shape) andjax.vmapthe model over them: one trace
however many runs. The model still receives anExperiment(itsinputshold one run's traced values);
runs that cannot be stacked, or a model that cannot be traced that way (Pythonifon an input), fall back
to the loop.Estimator(..., vectorize=False)forces it. Sensitivities,check_identifiabilityand
design_experimentstake one compiled, vmapped Jacobian over the pool. With a difflowCSTRwritten
naively asmodel(theta, exp)on the unit-ops book's 15 runs: fit 7.1 s -> 0.8 s, confidence intervals
28 s -> 3.3 s; a 72-candidate design 100 s -> 2.4 s. The bootstrap and cross-validation refit one compiled
objective (a resample is a vector of per-experiment counts, a residual resample new observations, both
arguments): 1.5 s -> about 0.1 s per refit.fituses onevalue_and_grad.
Experimentobservations may be arrays:Experiment.n_obscounts entries,observed_arrayravels them,
the objectives sum every entry, anddiagnosticsand the Fisher degrees of freedom count entries (they
calledfloat()on each value, and counted keys). The "parametric" bootstrap resamples the fitted residuals
and assumes no distribution; it is nowmethod="residual"/residual_bootstrap, documented as such
(varianceS/n, notS/(n-p));"parametric"andparametric_bootstrapremain as aliases.
run_mhejits the arrival-cost update (it ranekf_predictand the model Jacobians eagerly, one
compilation per window), and the window solve, the arrival update andrun_ekfare cached by model and
settings (thetaandprocess_stdby value), so a second run, andsolve_mhecalled window by window,
compile nothing. The book's 67-window Ch 30 run: 56 s -> 7 s, a second run 51 s -> 1.4 s.
Full diff: v0.4.0...v0.5.0