Design of Experiments from the Command Line#

discopt.doe ships a full Fisher-information-matrix-based design API, but writing a Python Experiment subclass and stitching the design \(\to\) measure \(\to\) fit \(\to\) extend loop together by hand is a lot to ask of an experimentalist whose lab notebook is a spreadsheet. The discopt doe CLI closes that gap by wrapping the same machinery around a single .xlsx workbook that moves between the bench and the terminal.

Classical response-surface methodology [Box et al., 2005], optimal-design theory [Atkinson et al., 2007], and the model-based framing of parameter-precision DoE [Franceschini and Macchietto, 2008] all trace back to Fisher’s foundational treatment of randomized experimentation [Fisher, 1935]. The CLI gives you a five-verb loop on top of that legacy:

discopt doe templates                    # list built-in templates
discopt doe new TEMPLATE ... -o file     # initial D-optimal batch
discopt doe status file                  # completed vs pending runs
discopt doe fit file                     # OLS fit + FIM update
discopt doe extend file --n M            # next D-optimal batch

Every verb also accepts --json, so an LLM agent (or a future GUI) can drive the same workflow without parsing prose. This notebook walks through the loop end-to-end against a synthetic ground-truth response surface so the recovered parameters can be checked against the truth.

import os

os.environ["JAX_PLATFORMS"] = "cpu"
os.environ["JAX_ENABLE_X64"] = "1"

import json
from pathlib import Path

import numpy as np
import openpyxl

from discopt.doe.cli import (
    ExtendParams,
    FoldoverParams,
    NewParams,
    do_extend,
    do_foldover,
    do_fit,
    do_new,
    do_status,
    do_templates,
)

1. Templates#

do_templates() is the in-process equivalent of discopt doe templates --json. Four built-in templates cover the classical response-surface menu — all linear in parameters, so the first batch needs no parameter prior.

info = do_templates()
for t in info["templates"]:
    print(f"  {t['name']:<24}  {t['description']}")
  linear                    y = b0 + sum_i bi * xi.  Inputs: --input NAME:LB:UB (repeatable). Parameters: 1 + n_inputs.
  polynomial-1d             y = sum_{j=0..d} bj * x**j.  Inputs: --input NAME:LB:UB (single), --degree D.  Parameters: D + 1.
  response-surface-2d       Full quadratic in 2 factors (intercept, 2 main, 2 square, 1 cross). Inputs: --input NAME:LB:UB (exactly 2).  Parameters: 6.
  response-surface-3d       Full quadratic in 3 factors (intercept, 3 main, 3 square, 3 cross). Inputs: --input NAME:LB:UB (exactly 3).  Parameters: 10.
  scheffe-linear            Scheffé canonical linear mixture: y = sum_i bi * xi, with sum(components) == --mixture-total.  Inputs: --input NAME:LB:UB (>= 2 components), --mixture-total T (default 1.0).  Parameters: q.
  scheffe-quadratic         Scheffé canonical quadratic mixture: pure-blend + pairwise blending terms.  Inputs: --input NAME:LB:UB (>= 2), --mixture-total T.  Parameters: q + q(q-1)/2.
  scheffe-special-cubic     Scheffé canonical special-cubic mixture: adds three-way blending to the quadratic.  Inputs: --input NAME:LB:UB (>= 3), --mixture-total T.  Parameters: q + q(q-1)/2 + q(q-1)(q-2)/6.
  latin-square              Latin-square design for ANOVA on 3 factors (1 treatment + 2 blocks). Inputs: --levels NAME:L1,L2,... (exactly 3 factors, same level count). Optional: --replicates R.
  graeco-latin              Graeco-Latin square for ANOVA on 4 factors. Inputs: --levels NAME:L1,L2,... (exactly 4 factors, k>=3 and k!=6). Optional: --replicates R.
  hyper-graeco-latin        Hyper-Graeco-Latin square for ANOVA on 5 factors (3 MOLS). Inputs: --levels NAME:L1,L2,... (exactly 5 factors, k in {4,5,7,...}). Optional: --replicates R.
  factorial-2level          2-level full factorial for screening. Inputs: --factor NAME:LOW:HIGH (repeatable, 2-8 factors; LOW/HIGH may be numeric or string). Optional: --center-points N (numeric factors only), --replicates R. Use this to answer 'does each factor matter?' before fitting a response surface.
  fractional-factorial      2-level fractional factorial for screening many factors in few runs. Inputs: --factor NAME:LOW:HIGH (repeatable, 3-15 factors) and either --generator 'D=ABC' (repeatable; written in the factor names -- single-letter names concatenate, longer ones join with '*', e.g. 'cat=temp*time') or --runs N [--resolution R] to search for a fraction (the search needs the base discopt solver). Optional: --center-points N, --replicates R. Check what is aliased with what using discopt.doe.alias_structure before you run it.
  plackett-burman           Plackett-Burman screening design: main effects of up to N-1 two-level factors in N runs (N a multiple of 4). Inputs: --factor NAME:LOW:HIGH (repeatable, 2-23 factors). Optional: --runs N (default: the smallest multiple of 4 above the factor count), --center-points N, --replicates R. Main effects are partially aliased with two-factor interactions.
  definitive-screening      Definitive screening design (Jones & Nachtsheim 2011): three levels per factor in 2m+1 runs; main effects are clear of every two-factor interaction and quadratic effect. Inputs: --input NAME:LB:UB (3-12 factors). Optional: --fake-factors F, --center-points N (default 1), --basis (default linear). Use `fit` on the completed runs.
  latin-hypercube           Latin hypercube: space-filling stratified sample over a continuous box, with the run count set by you rather than by the factor count. Inputs: --input NAME:LB:UB (repeatable), --n RUNS. Optional: --basis {linear,quadratic} (default linear here; the model `fit` will estimate), --optimize {discrepancy,maximin,none} (default discrepancy). Use this for surrogate fitting or when you want coverage without assuming a model form.
  central-composite         Central composite design for a full quadratic response surface: 2**k factorial core + 2k axial points + centre replicates. Inputs: --input NAME:LB:UB (2-6 factors). Optional: --center-points N (default 4), --alpha {rotatable,face} or a number, --outside-bounds to use the textbook scaling where the axial points fall beyond LB/UB. By default every run stays within the bounds you give.
  box-behnken               Box-Behnken design for a full quadratic response surface without visiting any corner of the design box — every run sits at an edge midpoint, so no run combines the extreme level of every factor. Inputs: --input NAME:LB:UB (3-5 factors). Optional: --center-points N (default 3).
  symbolic                  Your own model, differentiated symbolically. Inputs: --expr 'EXPRESSION' (e.g. 'k0 * exp(-Ea / (8.314 * T))'), --param NAME=VALUE (repeatable; the nominal guess a locally-optimal design is built around), --input NAME:LB:UB (repeatable), --n RUNS. Optional: --criterion, --n-starts. `fit` estimates the parameters by nonlinear least squares and `extend` designs the next batch around them. Allowed in the expression: + - * / **, numbers, your declared names, pi/E, and exp log ln log10 sqrt sin cos tan asin acos atan sinh cosh tanh abs erf.
  optimize                  Active-learning workbook for sequential optimization. Inputs: --input NAME:LB:UB (repeatable). The seed batch is sampled by Sobol; subsequent rounds are produced by 'discopt doe optimize WORKBOOK' which fits a surrogate and proposes new runs via the chosen acquisition. Optional: --optimize-criterion {maximize,minimize}, --optimize-surrogate (preset name), --optimize-acquisition.

2. New campaign — initial D-optimal batch#

The example below is a two-factor full-quadratic response surface (temperature and pH for yield in a notional chemistry lab). do_new writes a workbook with n=10 pending runs at or near the D-optimal support points of the square — corners, edge midpoints and the centre — plus a metadata sheet that lets every subsequent command reconstruct the experiment from the file alone.

wb_path = Path("campaign.xlsx")
if wb_path.exists():
    wb_path.unlink()

new_out = do_new(
    NewParams(
        output=wb_path,
        n=10,
        inputs=[("temp", 50.0, 100.0), ("ph", 3.0, 9.0)],
        response_name="yield",
        measurement_error=0.05,
        criterion="determinant",
        seed=0,
        n_starts=5,
        template="response-surface-2d",
    )
)

print("template       :", new_out["template"])
print("parameter_names:", new_out["parameter_names"])
print("workbook_path  :", new_out["workbook_path"])
print("next_command   :", new_out["next_command"])
print("\nInitial design points:")
for row in new_out["designs"]:
    print(f"  run {row['run_id']:>2}:  temp={row['temp']:6.2f}  ph={row['ph']:4.2f}")
template       : response-surface-2d
parameter_names: ['b0', 'b1', 'b2', 'b11', 'b22', 'b12']
workbook_path  : campaign.xlsx
next_command   : discopt doe status campaign.xlsx

Initial design points:
  run  1:  temp=100.00  ph=9.00
  run  2:  temp=100.00  ph=3.00
  run  3:  temp= 50.00  ph=9.00
  run  4:  temp= 50.00  ph=3.00
  run  5:  temp= 76.00  ph=6.00
  run  6:  temp= 74.27  ph=9.00
  run  7:  temp= 50.00  ph=6.10
  run  8:  temp= 74.25  ph=3.00
  run  9:  temp=100.00  ph=6.00
  run 10:  temp= 50.00  ph=5.92

3. Run the experiments#

In the lab you would open campaign.xlsx, execute each run, type the measured yield value into the runs sheet, and save the file. Here we substitute a known ground-truth response with a small amount of noise so the downstream fits can be validated.

truth = {
    "b0": 12.0,
    "b1": 0.30,
    "b2": -0.80,
    "b11": -0.002,
    "b22": 0.05,
    "b12": 0.01,
}


def predict(temp, ph):
    return (
        truth["b0"]
        + truth["b1"] * temp
        + truth["b2"] * ph
        + truth["b11"] * temp * temp
        + truth["b22"] * ph * ph
        + truth["b12"] * temp * ph
    )


rng = np.random.default_rng(42)
wb = openpyxl.load_workbook(wb_path)
runs = wb["runs"]
headers = [c.value for c in runs[1]]
i_temp = headers.index("temp")
i_ph = headers.index("ph")
i_y = headers.index("yield")
for row in runs.iter_rows(min_row=2):
    if row[0].value is None:
        continue
    t, p = float(row[i_temp].value), float(row[i_ph].value)
    row[i_y].value = float(predict(t, p) + rng.normal(0, 0.05))
wb.save(wb_path)

status = do_status({"workbook": str(wb_path)})
print(
    f"{status['n_completed']} completed, "
    f"{status['n_pending']} pending, {status['n_total']} total."
)
10 completed, 0 pending, 10 total.

4. Fit parameters#

do_fit reads the completed rows, performs an ordinary-least- squares fit against the template’s design matrix, updates the parameters and fim sheets, and returns a structured payload with point estimates and the log-determinant of the FIM (the objective optimized by the D-optimal criterion [Atkinson et al., 2007]).

fit_out = do_fit({"workbook": str(wb_path)})
estimates = {p["name"]: p["estimate"] for p in fit_out["parameters"]}

print(f"n_observations : {fit_out['n_observations']}")
print(f"log_det_fim    : {fit_out['log_det_fim']:.3f}\n")
print(f"{'name':<6} {'truth':>10} {'estimate':>10}")
for name, true_val in truth.items():
    print(f"{name:<6} {true_val:>10.4f} {estimates[name]:>10.4f}")
n_observations : 10
log_det_fim    : 79.489

name        truth   estimate
b0        12.0000    12.7839
b1         0.3000     0.2828
b2        -0.8000    -0.8678
b11       -0.0020    -0.0019
b22        0.0500     0.0541
b12        0.0100     0.0103

5. Extend — next D-optimal batch#

do_extend loads the persisted FIM from the workbook, uses it as a prior, and appends a fresh batch of D-optimal runs that maximize information given what we already learned. The new rows show up in the runs sheet with the next batch index and blank response cells, ready for the lab.

ext_out = do_extend(ExtendParams(workbook=wb_path, n=4, n_starts=5))
print(f"batch          : {ext_out['batch']}")
print(f"new run ids    : {ext_out['new_run_ids']}\n")
for row in ext_out["designs"]:
    print(f"  run {row['run_id']:>2}:  temp={row['temp']:6.2f}  ph={row['ph']:4.2f}")

status = do_status({"workbook": str(wb_path)})
print(
    f"\nworkbook now: {status['n_completed']} completed, "
    f"{status['n_pending']} pending, {status['n_total']} total."
)
batch          : 2
new run ids    : [11, 12, 13, 14]

  run 11:  temp=100.00  ph=9.00
  run 12:  temp= 70.25  ph=3.00
  run 13:  temp=100.00  ph=3.00
  run 14:  temp= 50.00  ph=9.00

workbook now: 10 completed, 4 pending, 14 total.

6. Following up a classical or screening design#

extend works on the classical templates too. A central composite records a regression basis rather than a model, so the new runs are D-optimal for that basis, counting every run already in the workbook as prior information (measured or not: a linear model’s information does not depend on the responses). precision_gain is the average factor by which the coefficient intervals shrink.

ccd_path = Path("ccd.xlsx")
ccd_path.unlink(missing_ok=True)
do_new(
    NewParams(
        output=ccd_path,
        n=0,
        inputs=[("T", 300.0, 400.0), ("P", 1.0, 5.0)],
        response_name="yield",
        measurement_error=1.0,
        criterion="determinant",
        seed=0,
        n_starts=1,
        template="central-composite",
    )
)
aug = do_extend(ExtendParams(workbook=ccd_path, n=3, n_starts=5))
print(f"new runs       : {[(d['T'], d['P']) for d in aug['designs']]}")
print(f"intervals      : about {(1 - 1 / aug['precision_gain']) * 100:.0f}% narrower")
new runs       : [(300.0, 5.0), (300.0, 1.0), (400.0, 1.0)]
intervals      : about 24% narrower

A two-level screening design is a different case. Optimal runs would not undo its aliasing, so extend refuses it; do_foldover (discopt doe foldover) appends the mirror image of the original runs instead, which separates every main effect from the two-factor interactions.

ff_path = Path("screen.xlsx")
ff_path.unlink(missing_ok=True)
do_new(
    NewParams(
        output=ff_path,
        n=0,
        inputs=[],
        response_name="y",
        measurement_error=1.0,
        criterion="anova",
        seed=0,
        n_starts=1,
        template="fractional-factorial",
        factor_pairs={name: (-1.0, 1.0) for name in "abcde"},
        generators=["d=ab", "e=ac"],
    )
)
fold = do_foldover(FoldoverParams(workbook=ff_path))
print(f"fold-over runs : {len(fold['designs'])} (batch {fold['batch']})")
print(f"resolution     : {fold['resolution']} with both halves")
ccd_path.unlink(missing_ok=True)
ff_path.unlink(missing_ok=True)
fold-over runs : 8 (batch 2)
resolution     : 4 with both halves

7. JSON output for agents and GUIs#

The do_* functions return plain dictionaries; the CLI’s --json flag is just a serializer over that contract. An LLM agent (or a Streamlit / NiceGUI / Marimo front-end) can read next_command and status fields to drive the loop without scraping text.

print(json.dumps(do_status({"workbook": str(wb_path)}), indent=2, default=str))
{
  "workbook_path": "campaign.xlsx",
  "template": "response-surface-2d",
  "template_args": {},
  "module_callable": null,
  "response_name": "yield",
  "response_names": [
    "yield"
  ],
  "responses": [
    {
      "name": "yield",
      "sigma": 0.05
    }
  ],
  "seed": 0,
  "input_specs": [
    {
      "name": "temp",
      "lb": 50.0,
      "ub": 100.0
    },
    {
      "name": "ph",
      "lb": 3.0,
      "ub": 9.0
    }
  ],
  "n_total": 14,
  "n_completed": 10,
  "n_pending": 4,
  "next_batch_index": 3,
  "parameters": [
    {
      "name": "b0",
      "estimate": 12.78385382955063,
      "std_error": 0.2767915607801507,
      "ci_lower_95": 12.01535725546253,
      "ci_upper_95": 13.55235040363874,
      "updated_at": "2026-11-14T13:58:14+00:00"
    },
    {
      "name": "b1",
      "estimate": 0.282846627155168,
      "std_error": 0.006636064353664426,
      "ci_lower_95": 0.2644219587626588,
      "ci_upper_95": 0.3012712955476771,
      "updated_at": "2026-11-14T13:58:14+00:00"
    },
    {
      "name": "b2",
      "estimate": -0.8678141764584015,
      "std_error": 0.0392442456973917,
      "ci_lower_95": -0.9767736703321043,
      "ci_upper_95": -0.7588546825846988,
      "updated_at": "2026-11-14T13:58:14+00:00"
    },
    {
      "name": "b11",
      "estimate": -0.001900024074157149,
      "std_error": 4.308461780639668e-05,
      "ci_lower_95": -0.002019646150375037,
      "ci_upper_95": -0.001780401997939261,
      "updated_at": "2026-11-14T13:58:14+00:00"
    },
    {
      "name": "b22",
      "estimate": 0.0541017068812319,
      "std_error": 0.002814845432935933,
      "ci_lower_95": 0.04628644305706857,
      "ci_upper_95": 0.06191697070539523,
      "updated_at": "2026-11-14T13:58:14+00:00"
    },
    {
      "name": "b12",
      "estimate": 0.01025608610842896,
      "std_error": 0.0002581968757379315,
      "ci_lower_95": 0.00953921665660902,
      "ci_upper_95": 0.01097295556024891,
      "updated_at": "2026-11-14T13:58:14+00:00"
    }
  ],
  "has_fim": true,
  "fim_size": 6,
  "next_command": "discopt doe fit campaign.xlsx  # 4 run(s) still pending"
}

8. Your own model, several responses per run#

When no template fits (nonlinear kinetics, partitioning, a mechanistic model), discopt doe new module --module pkg.mod:callable loads a discopt.estimate.Experiment of your own. The workbook stores the import path and the parameter guesses, and every verb works on it: new designs the first batch, fit estimates the parameters, and extend designs the next batch around the fitted values.

The response columns come from the model. Each entry in the ExperimentModel’s responses gets its own column on the runs sheet, with the model’s measurement_error as its standard deviation (override one with --sigma NAME=VALUE). The example below has two species split between an organic and an aqueous phase, so there are four responses per run, six parameters, and one design input (pH):

MODULE_SOURCE = """
import discopt.modeling as dm
from discopt.estimate import Experiment, ExperimentModel


class Partition(Experiment):
    \"\"\"Species A and B split between two phases; log D is quadratic in pH.\"\"\"

    def create_model(self, **kwargs):
        m = dm.Model("partition")
        p = {n: m.continuous(n, lb=-10.0, ub=10.0)
             for n in ("aA", "bA", "cA", "aB", "bB", "cB")}
        pH = m.continuous("pH", lb=2.0, ub=8.0)
        u = pH - 5.0
        out = {}
        for s in ("A", "B"):
            D = dm.exp(p["a" + s] + p["b" + s] * u + p["c" + s] * u * u)
            out[s + "_org"] = D / (1 + D)   # fraction in the organic phase
            out[s + "_aq"] = 1 / (1 + D)    # fraction in the aqueous phase
        return ExperimentModel(
            model=m,
            unknown_parameters=p,
            design_inputs={"pH": pH},
            responses=out,
            measurement_error={k: 0.02 for k in out},
        )
"""
import sys

Path("partition_demo.py").write_text(MODULE_SOURCE)
sys.path.insert(0, str(Path.cwd()))

From the shell the campaign starts with

discopt doe new module --module partition_demo:Partition --bounds pH:2:8 \
    --params aA=0.5 --params bA=0.8 --params cA=-0.1 \
    --params aB=-0.3 --params bB=-0.6 --params cB=0.05 \
    --sigma B_aq=0.03 --n 8 -o partition.xlsx

--response and --error are refused for a module, since the model already names its responses. Here is the same call in process:

guess = {"aA": 0.5, "bA": 0.8, "cA": -0.1, "aB": -0.3, "bB": -0.6, "cB": 0.05}
part_path = Path("partition.xlsx")
part_path.unlink(missing_ok=True)
new_part = do_new(
    NewParams(
        output=part_path,
        n=8,
        inputs=[("pH", 2.0, 8.0)],
        response_name="y",  # ignored for a module: the model names its responses
        measurement_error=1.0,  # ditto; per-response errors come from the model
        criterion="determinant",
        seed=40,
        n_starts=10,
        module_callable="partition_demo:Partition",
        param_initial_guess=guess,
        sigma_overrides={"B_aq": 0.03},
    )
)
print("responses :", new_part["response_names"])
print("pH        :", [round(d["pH"], 3) for d in new_part["designs"]])
responses : ['A_org', 'A_aq', 'B_org', 'B_aq']
pH        : [8.0, 2.883, 4.954, 2.812, 8.0, 4.97, 2.784, 8.0]

Partial rows#

Not every cell gets measured: a phase goes unassayed, a sample is lost. Leave it blank. A run counts as done once any of its responses is filled in. A blank cell in a done run is a missing value: fit leaves it out of the likelihood (it is not read as zero), and extend counts only the information that was actually measured. Below, run 3’s B_aq and run 5’s A_org are left empty. Workbook.record_responses takes a {response: value} mapping for each run, which is what the GUI’s runs grid writes too.

from discopt.doe.workbook import Workbook

truth = {"aA": 0.7, "bA": 0.6, "cA": -0.05, "aB": -0.1, "bB": -0.8, "cB": 0.08}


def partition_truth(pH):
    u = pH - 5.0
    out = {}
    for s in ("A", "B"):
        D = np.exp(truth["a" + s] + truth["b" + s] * u + truth["c" + s] * u * u)
        out[s + "_org"], out[s + "_aq"] = D / (1 + D), 1 / (1 + D)
    return out


rng = np.random.default_rng(0)


def run_lab(path, run_ids, blank=()):
    wb = Workbook.open(path)
    rows = {int(r["run_id"]): r for r in wb.all_runs()}
    wb.record_responses(
        {
            rid: {
                k: None if (rid, k) in blank else float(v + 0.01 * rng.standard_normal())
                for k, v in partition_truth(float(rows[rid]["pH"])).items()
            }
            for rid in run_ids
        }
    )
    wb.save()


run_lab(part_path, range(1, 9), blank={(3, "B_aq"), (5, "A_org")})
st = do_status({"workbook": str(part_path)})
print(f"completed {st['n_completed']} / pending {st['n_pending']}")
completed 8 / pending 0

Fit, extend, fit again#

fit stacks the model over every completed run’s pH, as discopt.doe.campaign_experiment does, and solves the weighted least-squares problem from the stored guesses. The standard errors come from the declared measurement errors, which is how the Python API reports them too. The reduced chi-square tells you whether those errors are believable: about 1 means the scatter matches what you declared. Much more than 1 means the noise is larger than you declared, so the intervals are too narrow. Well below 1 (as here, where the simulated noise is 0.01 against a declared 0.02) means the declared errors are pessimistic.

fit1 = do_fit({"workbook": str(part_path)})
print(f"observations {fit1['n_observations']}  (missing {fit1['n_missing']})")
print(f"reduced chi-square {fit1['reduced_chi_square']:.2f}")
for p in fit1["parameters"]:
    print(f"  {p['name']:>3s} = {p['estimate']:8.4f} ± {p['std_error']:.4f}   (truth {truth[p['name']]:+.2f})")
observations 30  (missing 2)
reduced chi-square 0.16
   aA =   0.6990 ± 0.0449   (truth +0.70)
   bA =   0.6022 ± 0.0174   (truth +0.60)
   cA =  -0.0480 ± 0.0096   (truth -0.05)
   aB =  -0.1228 ± 0.0515   (truth -0.10)
   bB =  -0.8165 ± 0.0288   (truth -0.80)
   cB =   0.0873 ± 0.0128   (truth +0.08)

extend re-centres the design on those estimates, using the fitted FIM as the prior. --batch-strategy joint (the batch_strategy= field) optimizes the whole batch at once instead of one run at a time.

ext_part = do_extend(ExtendParams(workbook=part_path, n=10, n_starts=10))
print("batch", ext_part["batch"], "pH:", sorted(round(d["pH"], 3) for d in ext_part["designs"]))

run_lab(part_path, ext_part["new_run_ids"])
fit2 = do_fit({"workbook": str(part_path)})
se1 = {p["name"]: p["std_error"] for p in fit1["parameters"]}
for p in fit2["parameters"]:
    print(f"  {p['name']:>3s} = {p['estimate']:8.4f} ± {p['std_error']:.4f}   (was ± {se1[p['name']]:.4f})")
batch 2 pH: [2.711, 2.721, 2.741, 4.989, 4.992, 4.994, 4.996, 8.0, 8.0, 8.0]
   aA =   0.7084 ± 0.0261   (was ± 0.0449)
   bA =   0.6014 ± 0.0116   (was ± 0.0174)
   cA =  -0.0514 ± 0.0059   (was ± 0.0096)
   aB =  -0.1175 ± 0.0280   (was ± 0.0515)
   bB =  -0.8145 ± 0.0203   (was ± 0.0288)
   cB =   0.0871 ± 0.0083   (was ± 0.0128)

Same answer as the Python loop#

The CLI computes exactly what sequential_doe does with initial_runs. Pass it the workbook’s completed rows, with blanks as None, and the estimates and standard errors agree with fit:

from discopt.doe import sequential_doe
from discopt.doe.workbook import module_experiment_with_sigmas
from partition_demo import Partition

wb = Workbook.open(part_path)
responses = wb.response_names()
runs = [
    {"run_id": r["run_id"], "pH": float(r["pH"]),
     **{k: (None if r.get(k) is None else float(r[k])) for k in responses}}
    for r in wb.completed_runs()
]
# The campaign overrode B_aq's sigma (--sigma B_aq=0.03); give Python the same one.
experiment = module_experiment_with_sigmas(Partition(), wb.response_sigmas(), guess)
est = sequential_doe(
    experiment, None, guess, {"pH": (2.0, 8.0)}, initial_runs=runs, n_rounds=1,
)[0].estimation
print("max |estimate difference| :",
      max(abs(p["estimate"] - est.parameters[p["name"]]) for p in fit2["parameters"]))
max |estimate difference| : 0.0

Note

Relative (RSD) errors. Analytical data often have an error proportional to the value. The usual treatment is to fit the logarithm, since a constant RSD becomes a constant standard deviation in log10(y) of about RSD / ln(10). To do that here, write the responses as logs in the model (for example out["A_org"] = dm.log10(D / (1 + D))), set each measurement_error to RSD / 2.303, and type log10 of the measured value into the column. The workbook does not transform values for you: what you type in a column is what gets fitted against the model response of the same name.

9. Cleanup#

wb_path.unlink(missing_ok=True)
for f in ("partition.xlsx", "partition.xlsx.bak", "partition_demo.py"):
    Path(f).unlink(missing_ok=True)

See also#