IDAES two-liquid settler#

Evidence: numerical verification. Optimize a nonreactive liquid settler at 293.15 K and 100,000 Pa using a declared aqueous/organic branch. IDAES/Pyomo owns the process equations and outer optimization; every thermodynamic equilibrium evaluation and its exact derivatives run through the Engine’s compiled ASL callback. This is the process-equation exception to the native calculation rule.

Use khudaida-2026-figure-2-electrolyte-lle/7, Khudaida et al. (2026), Tables 2, 5–7 (paper). The retained live-settler analysis supplies the process declaration and numerical checks. This tutorial runs one start rather than its full qualification campaign.

Install the optional IDAES extensions as external build-time-only tools, as described in the installation guide. Ipopt must remain outside the checkout, Engine build, site outputs, downloads and shared caches; preserve the upstream notices. The Engine and outer Ipopt both select MUMPS. The upstream executable also contains HSL: HSL, a collection of Fortran codes for large-scale scientific computation. See https://www.hsl.rl.ac.uk/.

Read the inputs#

Use a repository checkout with the environment described in the installation guide. The wheel alone does not contain these data. All density, association, equilibrium and parameter-fit iterations below run in the native Engine.

from pathlib import Path
import math
import pandas as pd
from IPython.display import display
from epcsaft import (
    Parameters,
    Mixture,
)
from epcsaft import equilibrium as eq

# Start the kernel anywhere within the documented repository checkout.
pd.set_option("display.max_columns", None)
pd.set_option("display.max_colwidth", None)

ROOT = next(
    folder
    for folder in (Path.cwd(), *Path.cwd().parents)
    if (folder / "ARCHITECTURE.yaml").is_file()
)
PACKETS = ROOT / "data" / "packets"

Declare formula flows and their explicit-species map#

The four formula flows (water, ethanol, isobutanol, NaCl) sum to 1 mol/s. Map them to (water, ethanol, isobutanol, Na⁺, Cl⁻) as (Fw, Fe, Fi, Fs, Fs). Explicit-species flow sums to 1 + Fs mol/s. Each callback value uses the same numerical basis as an amount in mol; the steady process interprets that value as flow in mol/s.

import os
import re
import time
import numpy as np
from epcsaft import _core
from idaes.core import FlowsheetBlock, UnitModelBlockData, declare_process_block_class
from idaes.core.solvers import get_solver
from idaes.core.util.model_statistics import degrees_of_freedom
from pyomo.common.config import ConfigValue
from pyomo.contrib.pynumero.interfaces.ampl_nlp import AslNLP
from pyomo.environ import (
    ConcreteModel,
    Constraint,
    Expression,
    ExternalFunction,
    NonNegativeReals,
    Objective,
    Suffix,
    Var,
    check_optimal_termination,
    value,
)
from pyomo.environ import units as u
from pyomo.network import Port
import idaes

assert "EPCSAFT_HSL_LIBRARY" not in os.environ
assert "EPCSAFT_IPOPT_OPTIONS_FILE" not in os.environ
assert _core.linear_solver() == "mumps"
ipopt = Path(idaes.bin_directory) / "ipopt"
assert ipopt.is_file(), (
    "Install the optional IDAES extensions described in the installation guide."
)
assert not ipopt.resolve().is_relative_to(ROOT)
library = Path(_core.__file__).resolve().with_name("libepcsaft_asl.so")
output = ROOT / "build/docs/settler"
output.mkdir(parents=True, exist_ok=True)
COMPONENTS = ("water", "ethanol", "isobutanol", "sodium-cation", "chloride-anion")
PHASES = ("aqueous", "organic")
GAP = 0.001
F0 = np.array(
    (0.7198946513021484, 0.03377833329223333, 0.21864518731791907, 0.02768182808769922)
)
assert abs(sum(F0) - 1) < 1e-12
FLOW = u.mol / u.s
TP = (293.15, 100000)  # fixed temperature / K and pressure / Pa
NAME = "epcsaft_equilibrium_phase_component_amount"
OPTIONS = eq.Continuation(
    initial_step=0.25, minimum_step=0.25, max_steps=4, max_retries_per_step=1
)


def feed(F):
    return (*F[:3], F[3], F[3])


def engine_problem(flows):
    return eq.Problem(
        T=TP[0],
        P=TP[1],
        feed=eq.Amounts(dict(zip(COMPONENTS, flows))),
        phases=[
            eq.Phase(
                "phase-0",
                kind="liquid",
                support=COMPONENTS,
                composition_guess=(0.8, 0.05, 0.05, 0.05, 0.05),
            ),
            eq.Phase(
                "phase-1",
                kind="liquid",
                support=COMPONENTS,
                composition_guess=(0.2, 0.1, 0.6998, 0.0001, 0.0001),
            ),
        ],
        row_tolerance=1e-10,
    )


def phase_data(model, central, flows):
    assert central.success, central.message
    assert central.requested_tolerance_met
    assert central.phase_count == 2
    x = np.array(central.mole_fractions).reshape(2, 5)
    material = np.max(abs(np.array(central.amounts) @ x - flows))
    charge = np.max(abs(x[:, 3] - x[:, 4]))
    pressure_errors = []
    for p in range(2):
        state = model.state(293.15, rho=central.molar_densities[p], x=x[p].tolist())
        assert state.pressure_density_derivative > 0
        pressure_errors.append(abs(state.pressure / 100000 - 1))
    classified = max(map(abs, central.classified_residuals))
    assert material <= 1e-10 and charge <= 1e-10
    assert max(pressure_errors) <= 1e-08 and classified <= 1e-10
    assert (
        math.isfinite(central.reduced_hessian_minimum)
        and central.reduced_hessian_minimum > 0
    )
    assert x[0, 0] - x[1, 0] > GAP
    diagnostics = dict(
        classified=classified,
        hessian=central.reduced_hessian_minimum,
        material=float(material),
        charge=float(charge),
        pressure=max(pressure_errors),
    )
    return diagnostics

Solve the anchor and check exact derivative transport#

The record carries the explicit affine feed map, phase supports, continuation controls and the aqueous water-fraction identity gap above 10⁻³. Check the anchor’s component/charge closure, pressure closure and classified residuals, then compare all ten component values, four feed gradients and ten symmetric second actions per value with ASL at 10⁻⁹ absolute. Unit feed increments are 1 mol for native amounts and 1 mol/s for the process coordinates; divide by these increments to interpret partial derivatives. No thermal direction is used.

def encode_record(model, problem, options, anchor):
    return eq.asl_record(
        model,
        problem,
        options,
        [0.0] * 5,
        np.array([feed(row) for row in np.eye(4)]).T.tolist(),
        list(anchor),
        0,
        GAP,
    )


class Reference:
    def __init__(self):
        self.model = Mixture(
            Parameters.from_json(
                PACKETS
                / "khudaida-2026-figure-2-electrolyte-lle/7/parameters/parameters.json",
                components=COMPONENTS,
            )
        )
        self.problem = engine_problem(feed(F0))
        self.anchor = eq.solve_equilibrium(self.model, self.problem)
        self.record = encode_record(self.model, self.problem, OPTIONS, F0)
        self.observables = [
            eq.SolvedStateObservable(
                eq.SolvedStateObservableKind.PhaseComponentAmount, p, i
            )
            for p in range(2)
            for i in range(5)
        ]
        self.feed_increment_mol = 1.0
        self.directions = [
            eq.SolvedStateActionDirection(
                0.0, 0.0, feed(self.feed_increment_mol * row), []
            )
            for row in np.eye(4)
        ]
        self.library = library
        self.external = ExternalFunction(
            library=str(self.library),
            function=NAME,
            units=FLOW,
            arg_units=[u.K, u.Pa] + [FLOW] * 4 + [None] * 3,
        )

    def public(self, F, order=2):
        problem = engine_problem(feed(F))
        continuation = (
            None
            if np.array_equal(F, F0)
            else eq.continue_equilibrium(
                self.model, self.problem, problem, OPTIONS, start_result=self.anchor
            )
        )
        if continuation is not None and (
            not continuation.success
            or continuation.stop != eq.ContinuationStop.reached_target
        ):
            raise RuntimeError(
                f"continuation: {continuation.stop}: {continuation.message}"
            )
        central = self.anchor if continuation is None else continuation.states[-1]
        diagnostics = phase_data(self.model, central, feed(F))
        if central.mole_fractions[0] - central.mole_fractions[5] <= GAP:
            raise RuntimeError(f"branch/certificate: {diagnostics}")
        compiled = eq.compile_problem(self.model, problem)
        y, g, h, statuses = (np.zeros(10), np.zeros((10, 4)), np.zeros((10, 4, 4)), [])
        pairs = [(-1,)] if order == 0 else [(i,) for i in range(4)]
        if order == 2:
            pairs += [(i, j) for j in range(4) for i in range(j + 1)]
        for indices in pairs:
            directions = (
                [eq.SolvedStateActionDirection(0.0, 0.0, [0.0] * 5, [])]
                if indices == (-1,)
                else [self.directions[i] for i in indices]
            )
            batch = eq.solved_state_actions(
                compiled,
                central,
                eq.SolvedStateActionRequest(self.observables, directions),
            )
            for row, item in enumerate(batch.results):
                statuses.append(item.status.name)
                if (
                    item.status != eq.SolvedStateActionStatus.Available
                    or item.value is None
                    or item.action is None
                    or (not np.isfinite([item.value, item.action]).all())
                ):
                    raise RuntimeError(f"unavailable E5 action: {item.status}")
                y[row] = item.value
                if indices == (-1,):
                    continue
                if len(indices) == 1:
                    g[row, indices[0]] = item.action / self.feed_increment_mol
                else:
                    i, j = indices
                    h[row, i, j] = h[row, j, i] = (
                        item.action / self.feed_increment_mol**2
                    )
        assert batch.diagnostics.rank == batch.diagnostics.state_dimension
        return (
            (y, g, h),
            {
                "rank": batch.diagnostics.rank,
                "dimension": batch.diagnostics.state_dimension,
                "statuses": sorted(set(statuses)),
                "classified_residual": diagnostics["classified"],
                "reduced_hessian_minimum": diagnostics["hessian"],
                "steps": 0 if continuation is None else continuation.accepted_steps,
                "requested_tolerance_met": central.requested_tolerance_met,
                "water_gap": central.mole_fractions[0] - central.mole_fractions[5],
            },
        )

    def asl(self, F, order=2, rows=range(10)):
        y, g, h = (np.zeros(10), np.zeros((10, 4)), np.zeros((10, 4, 4)))
        for row in rows:
            y[row], gradient, packed = self.external.evaluate_fgh(
                [*TP, *F, self.record, str(row // 5), str(row % 5)], fgh=order
            )
            if order >= 1:
                g[row] = gradient[2:6]
            if order == 2:
                h[row] = [
                    [
                        packed[min(i, j) + max(i, j) * (max(i, j) + 1) // 2]
                        for j in range(2, 6)
                    ]
                    for i in range(2, 6)
                ]
        if not all((np.isfinite(array).all() for array in (y, g, h))):
            raise RuntimeError("nonfinite ASL response")
        return (y, g, h)


reference = Reference()
anchor_checks = phase_data(reference.model, reference.anchor, feed(F0))
public, anchor_actions = reference.public(F0)
transported = reference.asl(F0)
public_asl_error = max((float(abs(a - b).max()) for a, b in zip(public, transported)))
assert public_asl_error <= 1e-09
display(pd.DataFrame([anchor_checks | {"public_asl_max_abs": public_asl_error}]))
epcsaft_equilibrium prepared record 1
classified hessian material charge pressure public_asl_max_abs
0 2.504494e-14 0.00011 1.110223e-16 0.0 5.020062e-11 0.0

Declare an IDAES unit and a live flowsheet#

The inlet, aqueous and organic ports carry five component flows, temperature and pressure. Ten outlet equations call the Engine at each requested feed. Isobutanol and NaCl feed scales range from 0.85 to 1.15 and start at 1. Minimize their sum while organic ethanol recovery is at least 0.965. Temperature and pressure are fixed; no energy equation or reacting process derivative is implied. Two free process variables remain before optimization.

@declare_process_block_class("TwoLiquidSettler")
class TwoLiquidSettlerData(UnitModelBlockData):
    CONFIG = UnitModelBlockData.CONFIG()
    CONFIG.declare("inlet_flows", ConfigValue(default=()))

    def build(self):
        super().build()
        inlet = self.config.inlet_flows
        self.flow_mol_in = Var(
            COMPONENTS,
            domain=NonNegativeReals,
            units=FLOW,
            initialize=dict(zip(COMPONENTS, inlet)),
        )
        for name, amount in zip(COMPONENTS, inlet):
            self.flow_mol_in[name].fix(amount)
        self.temperature_in = Var(units=u.K, initialize=293.15)
        self.pressure_in = Var(units=u.Pa, initialize=100000)
        self.temperature_in.fix()
        self.pressure_in.fix()
        self.flow_mol_aqueous = Var(
            COMPONENTS, domain=NonNegativeReals, units=FLOW, initialize=0.5
        )
        self.flow_mol_organic = Var(
            COMPONENTS, domain=NonNegativeReals, units=FLOW, initialize=0.5
        )
        self.temperature_out = Var(PHASES, units=u.K, initialize=293.15)
        self.pressure_out = Var(PHASES, units=u.Pa, initialize=100000)
        self.inlet, self.aqueous, self.organic = (Port(), Port(), Port())
        for port, flow, temperature, pressure in (
            (self.inlet, self.flow_mol_in, self.temperature_in, self.pressure_in),
            (
                self.aqueous,
                self.flow_mol_aqueous,
                self.temperature_out["aqueous"],
                self.pressure_out["aqueous"],
            ),
            (
                self.organic,
                self.flow_mol_organic,
                self.temperature_out["organic"],
                self.pressure_out["organic"],
            ),
        ):
            port.add(flow, "flow_mol")
            port.add(temperature, "temperature")
            port.add(pressure, "pressure")
        self.temperature_mapping = Constraint(
            PHASES, rule=lambda b, p: b.temperature_out[p] == 293.15 * u.K
        )
        self.pressure_mapping = Constraint(
            PHASES, rule=lambda b, p: b.pressure_out[p] == 100000 * u.Pa
        )
        self.component_balance_residual = Expression(
            COMPONENTS,
            rule=lambda b, i: (
                b.flow_mol_in[i] - b.flow_mol_aqueous[i] - b.flow_mol_organic[i]
            ),
        )
        self.charge_residual = Expression(
            PHASES,
            rule=lambda b, p: (
                (b.flow_mol_aqueous if p == "aqueous" else b.flow_mol_organic)[
                    "sodium-cation"
                ]
                - (b.flow_mol_aqueous if p == "aqueous" else b.flow_mol_organic)[
                    "chloride-anion"
                ]
            ),
        )


def stage(reference, start, optimize):
    F = F0 * np.array((1.0, 1.0, *start))
    (y, _, _), _ = reference.public(F, 0)
    m = ConcreteModel()
    m.fs = FlowsheetBlock(dynamic=False)
    m.fs.settler = TwoLiquidSettler(
        dynamic=False, has_holdup=False, inlet_flows=feed(F0)
    )
    b = m.fs.settler
    m.si, m.ss = (
        Var(bounds=(0.85, 1.15), initialize=start[0]),
        Var(bounds=(0.85, 1.15), initialize=start[1]),
    )
    if not optimize:
        m.si.fix()
        m.ss.fix()
    for i in (2, 3, 4):
        b.flow_mol_in[COMPONENTS[i]].unfix()
        b.flow_mol_in[COMPONENTS[i]].set_value(feed(F)[i])
    b.feed_links = Constraint(
        (2, 3, 4),
        rule=lambda b, i: (
            b.flow_mol_in[COMPONENTS[i]]
            == (F0[2] * m.si if i == 2 else F0[3] * m.ss) * FLOW
        ),
    )
    m.response = ExternalFunction(
        library=str(reference.library),
        function=NAME,
        units=FLOW,
        arg_units=[u.K, u.Pa] + [FLOW] * 4 + [None] * 3,
    )
    flows = [b.flow_mol_aqueous, b.flow_mol_organic]
    b.live_outlets = Constraint(
        range(2),
        range(5),
        rule=lambda b, p, i: (
            (
                flows[p][COMPONENTS[i]]
                - m.response(
                    TP[0] * u.K,
                    TP[1] * u.Pa,
                    *[b.flow_mol_in[c] for c in COMPONENTS[:4]],
                    reference.record,
                    str(p),
                    str(i),
                )
            )
            / FLOW
            == 0
        ),
    )
    for row in range(10):
        flows[row // 5][COMPONENTS[row % 5]].set_value(y[row])
    m.recovery = Constraint(
        expr=0.965 - b.flow_mol_organic["ethanol"] / b.flow_mol_in["ethanol"] <= 0
    )
    m.objective = Objective(expr=m.si + m.ss)
    for name in ("dual", "ipopt_zL_out", "ipopt_zU_out"):
        setattr(m, name, Suffix(direction=Suffix.IMPORT))
    assert degrees_of_freedom(m) == (2 if optimize else 0)
    return m

Retain independent optimality and NL derivative checks#

Write a named NL problem without linear presolve or scaling so the original process rows remain inspectable. Re-evaluate its Jacobian and Lagrangian Hessian through PyNumero, compare the live rows with public exact actions, and reconstruct stationarity, feasibility, multiplier sign and complementarity. The sign convention uses the negated Ipopt row duals for the NL calculation.

Require stationarity and complementarity at most 10⁻⁷, feasibility at most 10⁻⁸, multiplier-sign error at most 10⁻⁸ and derivative transport at most 10⁻⁹. These dimensionless residual limits belong to this scaled declaration.

def named_file_rows(path: Path) -> tuple[list[str], list[str]]:
    columns = path.with_suffix(".col").read_text(encoding="utf-8").splitlines()
    rows = path.with_suffix(".row").read_text(encoding="utf-8").splitlines()
    return (columns, rows)


def nl_checks(m, path, reference, compare=True):
    os.environ["AMPLFUNC"] = str(reference.library)
    nlp = AslNLP(str(path))
    columns, rows = named_file_rows(path)
    variables = [m.find_component(name) for name in columns]
    constraints = [m.find_component(name) for name in rows[: nlp.n_constraints()]]
    x = np.array([value(v) for v in variables])
    lam = -np.array([m.dual.get(c, 0.0) for c in constraints])
    lower, upper = (nlp.primals_lb(), nlp.primals_ub())
    zl, zu = (
        np.array([m.ipopt_zL_out.get(v, 0.0) for v in variables]),
        -np.array([m.ipopt_zU_out.get(v, 0.0) for v in variables]),
    )
    nlp.set_primals(x)
    nlp.set_duals(lam)
    nlp.set_obj_factor(1.0)
    c, jac = (nlp.evaluate_constraints(), nlp.evaluate_jacobian().toarray())
    cl, cu = (nlp.constraints_lb(), nlp.constraints_ub())
    masks = (np.isfinite(lower), np.isfinite(upper), np.isfinite(cl), np.isfinite(cu))
    comp = np.r_[
        zl[masks[0]] * (x - lower)[masks[0]],
        zu[masks[1]] * (upper - x)[masks[1]],
        lam[masks[3]] * (cu - c)[masks[3]],
    ]
    metrics = {
        "stationarity": float(
            np.max(abs(nlp.evaluate_grad_objective() + jac.T @ lam - zl + zu))
        ),
        "feasibility": float(
            max(
                np.max(np.maximum(cl - c, 0)),
                np.max(np.maximum(c - cu, 0)),
                np.max(np.maximum(lower - x, 0)),
                np.max(np.maximum(x - upper, 0)),
            )
        ),
        "multiplier_sign": float(
            max(
                0.0,
                np.max(-zl),
                np.max(-zu),
                *[
                    -lam[i]
                    for i in range(len(c))
                    if cl[i] < cu[i] and np.isfinite(cu[i])
                ],
            )
        ),
        "complementarity": float(np.max(abs(comp))),
    }
    metrics.update(
        {
            "lambda": dict(zip(rows[: len(lam)], lam.tolist())),
            "zL": dict(zip(columns, zl.tolist())),
            "zU": dict(zip(columns, zu.tolist())),
        }
    )
    if compare:
        F = np.array([value(m.fs.settler.flow_mol_in[i]) for i in COMPONENTS[:4]])
        (y, g, h), _ = reference.public(F)
        D = np.diag(F0[2:4])
        P = np.zeros((len(columns), 2))
        for name, axis, factor in (
            ("si", 0, 1.0),
            ("ss", 1, 1.0),
            ("fs.settler.flow_mol_in[isobutanol]", 0, F0[2]),
            ("fs.settler.flow_mol_in[sodium-cation]", 1, F0[3]),
            ("fs.settler.flow_mol_in[chloride-anion]", 1, F0[3]),
        ):
            P[columns.index(name), axis] = factor
        weighted = np.zeros((2, 2))
        errors = []
        for row in range(10):
            index = rows.index(f"fs.settler.live_outlets[{row // 5},{row % 5}]")
            outlet = (
                m.fs.settler.flow_mol_aqueous
                if row < 5
                else m.fs.settler.flow_mol_organic
            )
            expected = np.zeros(len(columns))
            expected[columns.index(outlet[COMPONENTS[row % 5]].name)] = 1.0
            expected[
                [columns.index(f"fs.settler.flow_mol_in[{i}]") for i in COMPONENTS[2:4]]
            ] = -g[row, 2:4]
            errors.append(float(np.max(abs(jac[index] - expected))))
            errors.extend(
                (
                    abs(c[index] - (value(outlet[COMPONENTS[row % 5]]) - y[row])),
                    float(np.linalg.norm(jac[index] @ P + g[row, 2:4] @ D, ord=np.inf)),
                )
            )
            weighted -= lam[index] * D @ h[row, 2:4, 2:4] @ D
            dual = np.zeros(len(c))
            dual[index] = 1.0
            nlp.set_duals(dual)
            nlp.set_obj_factor(0.0)
            errors.append(
                float(
                    np.linalg.norm(
                        P.T @ nlp.evaluate_hessian_lag().toarray() @ P
                        + D @ h[row, 2:4, 2:4] @ D,
                        ord=np.inf,
                    )
                )
            )
        nlp.set_duals(lam)
        nlp.set_obj_factor(1.0)
        errors.append(
            float(
                np.linalg.norm(
                    P.T @ nlp.evaluate_hessian_lag().toarray() @ P - weighted,
                    ord=np.inf,
                )
            )
        )
        metrics["nl_transport_max_abs"] = max(errors)
        assert max(errors) <= 1e-09
    assert all(
        (
            metrics[k] <= tolerance
            for k, tolerance in (
                ("stationarity", 1e-07),
                ("feasibility", 1e-08),
                ("multiplier_sign", 1e-08),
                ("complementarity", 1e-07),
            )
        )
    ), metrics
    return metrics

Solve once with MUMPS and exact Hessians#

The outer second-order derivative checker must report no errors, MUMPS must appear in the applied solver options, and exact Hessian/Jacobian evaluations must occur. Require component/charge closure within 10⁻¹⁰ mol/s and recovery at least 0.965 within 10⁻⁸. The retained scale baselines are compared within 10⁻⁷ absolute. A termination word alone does not satisfy these checks.

NL_IO_OPTIONS = {
    "symbolic_solver_labels": True,
    "linear_presolve": False,
    "scale_model": False,
    "skip_trivial_constraints": False,
}
SOLVER_OPTIONS = {
    "hessian_approximation": "exact",
    "point_perturbation_radius": 0,
    "bound_relax_factor": 0,
    "nlp_scaling_method": "none",
    "tol": 1e-09,
    "constr_viol_tol": 1e-08,
    "dual_inf_tol": 1e-07,
    "compl_inf_tol": 1e-07,
    "acceptable_iter": 0,
    "max_iter": 200,
}
DERIVATIVE_TEST_OPTIONS = {
    "derivative_test": "second-order",
    "derivative_test_perturbation": 1e-06,
    "derivative_test_tol": 0.0001,
}
SOLVER_OPTIONS["linear_solver"] = "mumps"


def solve(reference, start, output, ipopt, optimize=True):
    output.mkdir(parents=True, exist_ok=True)
    m = stage(reference, start, optimize)
    path = output / "stage.nl"
    m.write(str(path), format="nl", io_options=NL_IO_OPTIONS)
    options = {
        **SOLVER_OPTIONS,
        "print_user_options": "yes",
        "file_print_level": 5,
        "output_file": str(output / "ipopt.log"),
    }
    if optimize:
        options.update(DERIVATIVE_TEST_OPTIONS)
    option_file = output / "ipopt.opt"
    option_file.write_text("".join((f"{key} {v}\n" for key, v in options.items())))
    solver = get_solver(solver_options={"option_file_name": str(option_file)})
    solver.set_executable(str(ipopt))
    os.environ["AMPLFUNC"] = str(reference.library)
    started = time.monotonic()
    result = solver.solve(
        str(path),
        load_solutions=False,
        suffixes=["dual", "ipopt_zL_out", "ipopt_zU_out"],
    )
    assert check_optimal_termination(result), str(result.solver)
    columns, rows = named_file_rows(path)
    for index, name in enumerate(columns):
        v = m.find_component(name)
        record = result.solution[0].variable[f"v{index}"]
        v.set_value(record["Value"])
        for suffix in ("ipopt_zL_out", "ipopt_zU_out"):
            getattr(m, suffix)[v] = record.get(suffix, 0.0)
    for index, name in enumerate(rows[:-1]):
        m.dual[m.find_component(name)] = (
            result.solution[0].constraint[f"c{index}"].get("Dual", 0.0)
        )
    text = (output / "ipopt.log").read_text()
    applied = {
        m[0]: m[1]
        for m in re.findall("^\\s*(\\w+)\\s*=\\s*(\\S+)\\s+yes\\s*$", text, re.M)
    }
    for key, expected_option in options.items():
        assert key in applied and (
            float(applied[key]) == expected_option
            if isinstance(expected_option, (int, float))
            else applied[key] == expected_option
        ), (key, applied)
    if optimize:
        assert "No errors detected by derivative checker." in text
        for quantity in (
            "Number of Lagrangian Hessian evaluations",
            "Number of equality constraint Jacobian evaluations",
        ):
            assert any(
                (
                    quantity in line and int(line.rsplit(None, 1)[-1]) > 0
                    for line in text.splitlines()
                )
            )
    b = m.fs.settler
    y = np.array(
        [
            value(v[i])
            for v in (b.flow_mol_aqueous, b.flow_mol_organic)
            for i in COMPONENTS
        ]
    )
    metrics = {
        "si": value(m.si),
        "ss": value(m.ss),
        "objective": value(m.objective),
        "recovery": y[6] / F0[1],
        "material": max((abs(value(v)) for v in b.component_balance_residual.values())),
        "charge": max((abs(value(v)) for v in b.charge_residual.values())),
        "elapsed_s": time.monotonic() - started,
        "flows": y.tolist(),
        "termination": str(result.solver.termination_condition),
        "options": {
            **options,
            "output_file": (output / "ipopt.log").relative_to(ROOT).as_posix(),
        },
        **nl_checks(m, path, reference, optimize),
    }
    assert (
        metrics["material"] <= 1e-10
        and metrics["charge"] <= 1e-10
        and (metrics["recovery"] >= 0.965 - 1e-08)
    )
    return metrics


values = solve(reference, (1.0, 1.0), output, ipopt)
values["public_asl_max_abs"] = public_asl_error
values["anchor_checks"] = anchor_checks
assert abs(values["si"] - 1.060400841356) < 1e-07
assert abs(values["ss"] - 0.915238531399) < 1e-07
log = (output / "ipopt.log").read_text()
assert "running with linear solver mumps." in log
assert "No errors detected by derivative checker." in log
inlet = np.array(feed(F0 * np.array((1, 1, values["si"], values["ss"]))))
display(
    pd.DataFrame(
        {
            "Component": COMPONENTS,
            "Inlet / mol s^-1": inlet,
            "Aqueous / mol s^-1": values["flows"][:5],
            "Organic / mol s^-1": values["flows"][5:],
        }
    )
)
display(
    pd.DataFrame(
        [
            {
                key: values[key]
                for key in (
                    "si",
                    "ss",
                    "objective",
                    "recovery",
                    "material",
                    "charge",
                    "stationarity",
                    "feasibility",
                    "multiplier_sign",
                    "complementarity",
                    "nl_transport_max_abs",
                    "public_asl_max_abs",
                )
            }
        ]
    )
)
Component Inlet / mol s^-1 Aqueous / mol s^-1 Organic / mol s^-1
0 water 0.719895 0.541465 0.178430
1 ethanol 0.033778 0.001182 0.032596
2 isobutanol 0.231852 0.000733 0.231119
3 sodium-cation 0.025335 0.025204 0.000131
4 chloride-anion 0.025335 0.025204 0.000131
si ss objective recovery material charge stationarity feasibility multiplier_sign complementarity nl_transport_max_abs public_asl_max_abs
0 1.060401 0.915239 1.975639 0.965 2.103352e-17 0.0 3.985710e-12 1.265654e-14 0.0 9.091158e-11 1.822986e-13 0.0
display(pd.DataFrame([values["anchor_checks"]]).rename(columns={
    "classified": "Anchor maximum classified residual / 1",
    "hessian": "Anchor reduced Hessian minimum / 1",
    "material": "Anchor material balance error / mol",
    "charge": "Anchor charge fraction error / 1",
    "pressure": "Anchor relative pressure error / 1",
}))
display(pd.DataFrame([{
    "Solve time / s": values["elapsed_s"],
    "Termination": values["termination"],
}]))
display(pd.DataFrame(values["options"].items(), columns=["Solver option", "Setting"]))
display(pd.DataFrame({
    "Constraint": list(values["lambda"]),
    "Constraint multiplier / 1": list(values["lambda"].values()),
}))
display(pd.DataFrame({
    "Variable": list(values["zL"]),
    "Lower bound multiplier / 1": list(values["zL"].values()),
    "Upper bound multiplier / 1": list(values["zU"].values()),
}))
Anchor maximum classified residual / 1 Anchor reduced Hessian minimum / 1 Anchor material balance error / mol Anchor charge fraction error / 1 Anchor relative pressure error / 1
0 2.504494e-14 0.00011 1.110223e-16 0.0 5.020062e-11
Solve time / s Termination
0 0.51502 optimal
Solver option Setting
0 hessian_approximation exact
1 point_perturbation_radius 0
2 bound_relax_factor 0
3 nlp_scaling_method none
4 tol 0.0
5 constr_viol_tol 0.0
6 dual_inf_tol 0.0
7 compl_inf_tol 0.0
8 acceptable_iter 0
9 max_iter 200
10 linear_solver mumps
11 print_user_options yes
12 file_print_level 5
13 output_file build/docs/settler/ipopt.log
14 derivative_test second-order
15 derivative_test_perturbation 0.000001
16 derivative_test_tol 0.0001
Constraint Constraint multiplier / 1
0 fs.settler.live_outlets[0,0] 1.678940e-10
1 fs.settler.live_outlets[0,1] 7.689552e-08
2 fs.settler.live_outlets[0,2] 1.241078e-07
3 fs.settler.live_outlets[0,3] 3.606912e-09
4 fs.settler.live_outlets[0,4] 3.606912e-09
5 fs.settler.live_outlets[1,0] 5.094925e-10
6 fs.settler.live_outlets[1,1] 6.208608e+02
7 fs.settler.live_outlets[1,2] 3.933417e-10
8 fs.settler.live_outlets[1,3] 6.923239e-07
9 fs.settler.live_outlets[1,4] 6.923239e-07
10 recovery 2.097164e+01
11 fs.settler.temperature_mapping[aqueous] -0.000000e+00
12 fs.settler.temperature_mapping[organic] -0.000000e+00
13 fs.settler.pressure_mapping[aqueous] -0.000000e+00
14 fs.settler.pressure_mapping[organic] -0.000000e+00
15 fs.settler.feed_links[2] 4.573620e+00
16 fs.settler.feed_links[3] 3.612478e+01
17 fs.settler.feed_links[4] 3.588218e-09
Variable Lower bound multiplier / 1 Upper bound multiplier / 1
0 fs.settler.flow_mol_in[isobutanol] 3.920999e-10 -0.000000e+00
1 fs.settler.flow_mol_in[sodium-cation] 3.588219e-09 -0.000000e+00
2 si 4.320728e-10 1.014636e-09
3 ss 1.393519e-09 3.872378e-10
4 fs.settler.flow_mol_organic[water] 5.094934e-10 -0.000000e+00
5 fs.settler.flow_mol_organic[ethanol] 2.788957e-09 -0.000000e+00
6 fs.settler.flow_mol_organic[isobutanol] 3.933426e-10 -0.000000e+00
7 fs.settler.flow_mol_organic[sodium-cation] 6.923239e-07 -0.000000e+00
8 fs.settler.flow_mol_organic[chloride-anion] 6.923239e-07 -0.000000e+00
9 fs.settler.temperature_out[aqueous] 0.000000e+00 -0.000000e+00
10 fs.settler.temperature_out[organic] 0.000000e+00 -0.000000e+00
11 fs.settler.pressure_out[aqueous] 0.000000e+00 -0.000000e+00
12 fs.settler.pressure_out[organic] 0.000000e+00 -0.000000e+00
13 fs.settler.flow_mol_in[chloride-anion] 3.588219e-09 -0.000000e+00
14 fs.settler.flow_mol_aqueous[water] 1.678949e-10 -0.000000e+00
15 fs.settler.flow_mol_aqueous[ethanol] 7.689552e-08 -0.000000e+00
16 fs.settler.flow_mol_aqueous[isobutanol] 1.241078e-07 -0.000000e+00
17 fs.settler.flow_mol_aqueous[sodium-cation] 3.606913e-09 -0.000000e+00
18 fs.settler.flow_mol_aqueous[chloride-anion] 3.606913e-09 -0.000000e+00

Meaning and limits#

The optimum is local on the declared nonreactive two-liquid branch. The component flows, balances and derivative comparisons verify this process calculation; they do not establish a global optimum or independent physical validation of the source parameters. Reacting-process and thermal derivative qualification remain outside this example. Text logs and numerical outputs remain under build/docs/settler; no solver binary is copied there.