Problem and setup
At fixed T=330 K and feed=1.2 mol/L, choose residence time between 2 and 10 min. Require B≥0.40 and C≤0.25 mol/L and nonnegative outputs. With flow 1 L/min, minimizing residence time also minimizes reactor volume. Fit a piecewise-linear surrogate, then reproduce its exact ReLU mapping inside an MILP.
Extract the lab ZIP, keeping requirements.txt, the notebook, Python scripts, and supplied models together. These exercises were checked with Python 3.12. Use that folder as the working directory and run the commands below, or execute the notebook cells in order. Downloading the notebook alone can omit required scripts or model files.
python -m pip install -r requirements.txt
python guided_lab.py
guided_lab.py executes the calculations below in order and checks key values with assertions. Files in guided-results/ belong to your new run; compare them with the supplied reference results. For Jupyter, select a kernel from the same Python environment. For ModuleNotFoundError, check that requirements were installed in that environment. For missing local files, check the working directory.
1. Follow scaling, hinges, and output contributions
Five reference knots at 2,4,6,8,10 min define linear interpolation. Scale tau by x=(tau−2)/8. Each hidden unit turns on after one threshold; its weight changes the output slope. At tau=5, only the first two hinges are active.
from pathlib import Path
import numpy as np
from scipy.optimize import milp
import week05_lab as lab
net = lab.fit_network()
a,h,y = lab.forward(5., net)
contributions = h[:,None]*np.asarray(net["weights"])
print("scaled x:", (5-2)/8, "a:", a, "h:", h)
print("output bias:", net["bias"], "contributions by hidden unit:", contributions)
print("output:", y, "reference:", lab.reference(5.))
np.testing.assert_allclose(a, [.375,.125,-.125,-.375])
np.testing.assert_allclose(y, np.asarray(net["bias"])+contributions.sum(0))
np.testing.assert_allclose(y, (lab.reference(4.)+lab.reference(6.))/2)
The surrogate at 5 min is the midpoint of the 4- and 6-min outputs, about [0.606061,0.395022,0.198918]. The physical reference is [0.6,0.4,0.2]. This interpolation error remains even when an MILP represents the neural network exactly.
2. Read one matrix row as a constraint
Variables are [x,h0,h1,h2,h3,yA,yB,yC,z1,z2,z3]. The first row h0−x=0 encodes the always-active hinge. For threshold 0.25, preactivation a=x−0.25 lies in [−0.25,0.75]. Binary z selects inactive h=0 or active h=a through the two upper bounds and h≥a,h≥0.
c, integrality, bounds, constraint = lab.formulate(net)
print("first row:", constraint.A[0], "row limits:", constraint.lb[0], constraint.ub[0])
print("binary positions:", np.flatnonzero(integrality))
fixed = lab.solve(net, fixed_tau=5., specifications=False)
v = fixed.x
print("fixed solution [x,h,y,z]:", v)
print("all row values:", constraint.A@v)
np.testing.assert_allclose(v[1:5], h, atol=1e-8)
np.testing.assert_allclose(v[5:8], y, atol=1e-8)
Binary positions are 8,9,10, and the fixed hidden values are [0.375,0.125,0,0]. Disable product specifications during a fixed-input equivalence test: tau=5 fails the surrogate B≥0.40 specification, but still has a valid forward evaluation.
3. Optimize, restore the objective constant, and recheck
The solver minimizes 8x; adding the omitted constant 2 gives residence time. Recompute outputs using forward at the returned tau and then the process reference. The first comparison checks implementation; the second checks the selected process condition.
optimal = lab.solve(net)
tau = 2+8*optimal.x[0]
prediction = lab.forward(tau, net)[2]
truth = lab.reference(tau)
print("objective without constant:", optimal.fun, "tau:", tau)
print("surrogate:", prediction, "reference:", truth)
np.testing.assert_allclose(tau, 2+optimal.fun, atol=1e-8)
np.testing.assert_allclose(optimal.x[5:8], prediction, atol=1e-8)
np.testing.assert_allclose(tau, lab.enumerate_segments(net), atol=1e-8)
report = lab.run(Path("guided-results"))
The selected residence time is about 5.353846 min. B lies at the surrogate lower bound. Segment enumeration independently checks the one-dimensional optimum, and run also audits fixed inputs near activation boundaries. State whether the reference outputs meet every original specification.
4. Explain an infeasible result
Raise only the B lower bound to 0.41 and keep C≤0.25. B peaks at about 0.410256 at 8 min, but C there exceeds its limit. C increases across all knots and reaches 0.25 between 6 and 8 min. Interpolate that crossing first; then read the largest B allowed before it.
values = lab.forward(lab.KNOTS, net)[2]
tau_cap = 6+2*(.25-values[2,2])/(values[3,2]-values[2,2])
max_allowed_b = lab.forward(tau_cap, net)[2][1]
print("B and C at knots:", values[:,1:])
print("C-limited maximum tau:",tau_cap,"maximum allowed B:",max_allowed_b)
assert np.all(np.diff(values[:,2]) > 0) and np.all(np.diff(values[:4,1]) > 0)
c, integer, bounds, con = lab.formulate(net)
bounds.lb[6] = .41
infeasible = milp(c, integrality=integer, bounds=bounds, constraints=con)
print("status:", infeasible.status, infeasible.message)
assert max_allowed_b < .41 and infeasible.status == 2
C restricts tau to at most 6.109859 min, where B is only 0.409155 mol/L. Thus both specifications cannot hold together for this frozen surrogate. Do not read result.x or report an operating point without a feasible solution. Submit the hand forward table, one decoded row, fixed-input comparison, selected point, reference check, and infeasibility argument.
What to report
Record the inputs, outputs, units and fixed conditions; your hand prediction; intermediate computed values; and final metrics with interpretation. Before changing one setting, predict the direction of its effect, then revise that explanation after execution. Record the environment and seed.