GQuality & process · doe.sequential
Sequential optimization (Gaussian process)
Given the runs so far, which settings should the next run use to find the best response?
Fits a Gaussian process to the runs you have and suggests the next settings to try: where the response is likely to beat the best run so far (expected or probability of improvement) or where it could be highest (upper confidence bound). A constraint column can rule out settings that would break a limit, and a batch suggests several runs at once. Run them, add the results and run the method again.
A real result
Example “Chemreact ei”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Next run for Yield (maximize): Time = 85, Temp = 175; predicted 81.14 (SD 0.667). Best run so far: 84.3 (run 6).
- Predicted at Next 1
- 81.141
- Expected improvement
- 0.2533
- LOO R²
- 0.0150
Assumptions
- The model predicts left-out runs — Left out one at a time, runs are predicted with R² 0.01; their squared errors are 1.00 times the predicted variances. The model is a weak guide here, so suggestions lean on exploration: add runs spread over the region before trusting them.
Suggested runs
| Run | Time | Temp | Predicted | SD of the mean | 95% low (new run) | 95% high (new run) | Expected improvement |
|---|---|---|---|---|---|---|---|
| Next 1 | 85.000 | 175.00 | 81.141 | 0.6674 | 76.100 | 86.181 | 0.2533 |
Runs so far, with left-out predictions
| Run | Time | Temp | Yield | Left-out prediction | Left-out SD | Standardized error |
|---|---|---|---|---|---|---|
| 1 | 80 | 170 | 80.500 | 80.586 | 2.637 | −0.0325 |
| 2 | 80 | 180 | 81.500 | 80.586 | 2.637 | 0.3467 |
| 3 | 90 | 170 | 82 | 80.586 | 2.637 | 0.5363 |
| 4 | 90 | 180 | 83.500 | 80.586 | 2.637 | 1.105 |
| 5 | 85 | 175 | 83.900 | 80.926 | 2.578 | 1.153 |
| 6 | 85 | 175 | 84.300 | 80.895 | 2.578 | 1.321 |
| 7 | 85 | 175 | 84 | 80.918 | 2.578 | 1.195 |
| 8 | 85 | 175 | 79.700 | 81.253 | 2.578 | −0.6022 |
| 9 | 85 | 175 | 79.800 | 81.245 | 2.578 | −0.5604 |
| 10 | 85 | 175 | 79.500 | 81.268 | 2.578 | −0.6858 |
| 11 | 92.070 | 175 | 78.400 | 80.586 | 2.637 | −0.8288 |
| 12 | 77.930 | 175 | 75.600 | 80.586 | 2.637 | −1.891 |
| 13 | 85 | 182.07 | 78.500 | 80.586 | 2.637 | −0.7909 |
| 14 | 85 | 167.93 | 77 | 80.586 | 2.637 | −1.360 |
Gaussian process settings
| Setting | Value |
|---|---|
| Signal SD | 0.8865 |
| Noise SD | 2.484 |
| Lengthscale: Time | 0.4238 |
| Lengthscale: Temp | 0.4338 |
| Log marginal likelihood | −19.801 |
- 2000 candidate settings from the shared random stream (seed 42), the best five refined by a compass search; factors scaled to their bounds.
- Predicted values and SDs come from the model of the real runs; within a batch, each pick was chosen as if the earlier picks had been run.
Next run for Yield (maximize): Time = 85, Temp = 175; predicted 81.14 (SD 0.667). Best run so far: 84.3 (run 6).
- Predicted at Next 1
- 81.141
- Expected improvement
- 0.2533
- LOO R²
- 0.0150
Assumptions
- The model predicts left-out runs — Left out one at a time, runs are predicted with R² 0.01; their squared errors are 1.00 times the predicted variances. The model is a weak guide here, so suggestions lean on exploration: add runs spread over the region before trusting them.
Suggested runs
| Run | Time | Temp | Predicted | SD of the mean | 95% low (new run) | 95% high (new run) | Expected improvement |
|---|---|---|---|---|---|---|---|
| Next 1 | 85.000 | 175.00 | 81.141 | 0.6674 | 76.100 | 86.181 | 0.2533 |
Runs so far, with left-out predictions
| Run | Time | Temp | Yield | Left-out prediction | Left-out SD | Standardized error |
|---|---|---|---|---|---|---|
| 1 | 80 | 170 | 80.500 | 80.586 | 2.637 | −0.0325 |
| 2 | 80 | 180 | 81.500 | 80.586 | 2.637 | 0.3467 |
| 3 | 90 | 170 | 82 | 80.586 | 2.637 | 0.5363 |
| 4 | 90 | 180 | 83.500 | 80.586 | 2.637 | 1.105 |
| 5 | 85 | 175 | 83.900 | 80.926 | 2.578 | 1.153 |
| 6 | 85 | 175 | 84.300 | 80.895 | 2.578 | 1.321 |
| 7 | 85 | 175 | 84 | 80.918 | 2.578 | 1.195 |
| 8 | 85 | 175 | 79.700 | 81.253 | 2.578 | −0.6022 |
| 9 | 85 | 175 | 79.800 | 81.245 | 2.578 | −0.5604 |
| 10 | 85 | 175 | 79.500 | 81.268 | 2.578 | −0.6858 |
| 11 | 92.070 | 175 | 78.400 | 80.586 | 2.637 | −0.8288 |
| 12 | 77.930 | 175 | 75.600 | 80.586 | 2.637 | −1.891 |
| 13 | 85 | 182.07 | 78.500 | 80.586 | 2.637 | −0.7909 |
| 14 | 85 | 167.93 | 77 | 80.586 | 2.637 | −1.360 |
Gaussian process settings
| Setting | Value |
|---|---|
| Signal SD | 0.8865 |
| Noise SD | 2.484 |
| Lengthscale: Time | 0.4238 |
| Lengthscale: Temp | 0.4338 |
| Log marginal likelihood | −19.801 |
- 2000 candidate settings from the shared random stream (seed 42), the best five refined by a compass search; factors scaled to their bounds.
- Predicted values and SDs come from the model of the real runs; within a batch, each pick was chosen as if the earlier picks had been run.
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Chemreact eiq1_chemreact · factors: Time, Temp · response: Yield
- Chemreact batch boundsq1_chemreact · factors: Time, Temp · response: Yield
- Chemreact ucbq1_chemreact · factors: Time, Temp · response: Yield
- Chemreact minimize piq1_chemreact · factors: Time, Temp · response: Cost
- Chemreact constraintq1_chemreact · constraint: Cost · factors: Time, Temp · response: Yield
- Bbd three factorsq1_bbd · factors: pH, Temperature (°C), Enzyme · response: Activity
- Degenerate constantq1_chemreact · factors: Time, Temp · response: Yield
- Degenerate n3q1_chemreact · factors: Time, Temp · response: Yield
In the guides
Where it sits in the decision guides
- Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes
- Statistical optimization (regression, response surface) · DS & ML Decision Guide · Optimize / decide
What you need
- Factorsnumeric · 1–8 columns
- Numeric settings you can choose for each run, in actual units.
- Responsenumeric · 1 column
- What each run measured; the method looks for settings that maximize or minimize it.
- Constraintnumeric · 0–1 column
- Optional: a second measured value that must stay at or below (or at or above) a limit, such as cost or impurity.
Choices you make
options
- Goaldefault maximize
Whether a higher or a lower response is better.
- Maximize(default) — Look for settings with a higher response.
- Minimize — Look for settings with a lower response.
- Boundsdefault —
“Name: low, high” per factor, e.g. “Time: 75, 95; Temp: 165, 185”. Suggestions stay inside. Empty = each factor's observed range.
- Acquisitiondefault ei
The rule that scores candidate settings.
- Expected improvement(default) — How much a run there is expected to beat the best so far: balances promising and uncertain settings.
- Probability of improvement — The chance a run there beats the best so far: favors safe, small gains.
- Upper confidence bound — The predicted response plus κ standard deviations: favors settings that could be best. Not with a constraint.
- Runs to suggestdefault 1
Several runs at once: each pick is treated as if its predicted response had been observed before the next is chosen.
- Exploration margin ξdefault 0.01
Improvement must exceed this many response SDs to count; larger values explore more.
- Confidence multiplier κdefault 2
How many standard deviations of optimism; larger values explore more.
- Constraint must bedefault at_most
Which side of the limit is allowed (only with a constraint column).
- At most the limit(default) — Runs must keep the constraint at or below the limit.
- At least the limit — Runs must keep the constraint at or above the limit.
- Constraint limitdefault —
The limit the constraint column must respect (needed when a constraint column is chosen).
Advanced
- Kerneldefault matern52
How quickly resemblance between runs fades with distance in the factor space.
- Matérn 5/2(default) — Smooth but not too smooth: the usual default for experiments.
- Matérn 3/2 — Rougher responses that can change quickly.
- Radial basis (squared exponential) — Very smooth responses; can over-smooth sharp changes.
- One lengthscale per factor (ARD)default on
Let each factor have its own lengthscale; a short one marks a factor the response depends on strongly.
- Candidate settingsdefault 2000
Random settings scored before the best few are refined; more find the best spot more reliably in many factors.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
The model predicts left-out runs
Leave-one-out predictions of the runs show whether the Gaussian process is a fair guide; a poor fit means the suggestions mostly explore.
The response is smoothNot checked from data: state why it holds
The kernel assumes the response changes about equally smoothly everywhere in the region.
The bounds are safe to runNot checked from data: state why it holds
Suggestions can sit anywhere inside the bounds, including corners never tried; set bounds the process can run at.
Run-to-run noise is constantNot checked from data: state why it holds
One noise level is fitted for every run; replicate runs help tell noise from the response's shape.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_factors
- Fit a Gaussian process to the runs so far, then run where it says an improvement is most likely; repeat until the gains stop.
- batch
- Fit a Gaussian process to the runs so far, then run where it says an improvement is most likely; repeat until the gains stop.
- best_observed
- The run with the best response so far (among runs that meet the constraint, when there is one).
- best_run
- The run with the best response so far (among runs that meet the constraint, when there is one).
- n_feasible
- The model's chance that a run at a setting keeps a second measure (cost, impurity) on the allowed side of its limit.
- predicted_best
- The settings a sequential design proposes next, with the model's predicted response, its SD and a 95% range for a new run.
- next_mean
- The settings a sequential design proposes next, with the model's predicted response, its SD and a 95% range for a new run.
- next_sd
- The settings a sequential design proposes next, with the model's predicted response, its SD and a 95% range for a new run.
- next_lower
- The settings a sequential design proposes next, with the model's predicted response, its SD and a 95% range for a new run.
- next_upper
- The settings a sequential design proposes next, with the model's predicted response, its SD and a 95% range for a new run.
- next_acquisition
- The score a sequential design gives each candidate setting; the next run goes where it is highest.
- next_feasible
- The model's chance that a run at a setting keeps a second measure (cost, impurity) on the allowed side of its limit.
- loo_rmse
- Each run predicted from the others; RMSE and R² show whether the model is a fair guide before you follow it.
- loo_r2
- Each run predicted from the others; RMSE and R² show whether the model is a fair guide before you follow it.
- loo_msse
- The average of (left-out error ÷ its predicted SD)²: near 1 when the standard errors are honest.
- gp_signal_sd
- How far the Gaussian process function typically moves from its mean, reported on the target's scale.
- gp_noise_sd
- Spread of the rows around the fitted smooth function, on the target's scale; part of every predictive SD.
- gp_log_marginal_likelihood
- How probable the training targets are under the kernel, with the function averaged out; kernel settings maximize it.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Per group, level or term: next[<factor>], gp_lengthscale[<factor>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, pandas, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- The Gaussian process is the learn.gp twin (the same projected BFGS from the same start, on the same unit-box scaling); candidates come from the shared Wichmann–Hill stream and the compass search takes the same steps, so suggestions agree far inside the tolerance.
The exact script CodeSplash ran for example “Chemreact ei” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sequential optimization (Gaussian process)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.sequential 1.0.0 · spec 6d39a8b82b54c6b2
# Dataset: q1_chemreact (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.quality import sequential as sq # twin of codesplashr::cs_doe_seq_* (same model, candidates, search)
# Classic equivalent: R's DiceOptim — EGO.nsteps(km(~1, design, response), fun, nsteps = 1); in Python
# scikit-optimize's gp_minimize or BoTorch's qExpectedImprovement on a SingleTaskGP.
# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_chemreact.parquet", columns=["Time", "Temp", "Yield"])
n_input = len(df)
df = df.dropna(subset=["Time", "Temp", "Yield"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Time", "Temp", "Yield"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
# A Gaussian process on the runs so far (the learn.gp twins, factors scaled to the bounds), then the acquisition
# (Jones et al. 1998; Kushner 1964; Srinivas et al. 2010) maximized over candidates from the shared random stream
# and a compass search; batches by kriging believer (Ginsbourger et al. 2010).
FACTORS = ["Time", "Temp"]
RESPONSE = "Yield"
CONSTRAINT = None
goal = "maximize" # maximize | minimize
bounds = ""
acquisition = "ei" # ei | pi | ucb
batch = int(1)
xi = 0.01
kappa = 2
sense = "at_most" # at_most | at_least
limit = None
kernel = "matern52" # matern52 | matern32 | rbf
ard = True
n_candidates = int(2000)
seed = 42
X = df[FACTORS].to_numpy(dtype=float)
y = df[RESPONSE].to_numpy(dtype=float)
n, d = X.shape
sq.check_runs(y, d, RESPONSE)
c = df[CONSTRAINT].to_numpy(dtype=float) if CONSTRAINT else None
res = sq.suggest(X, y, FACTORS, goal, bounds, acquisition, batch, kernel, ard, xi, kappa, n_candidates, seed, c, sense, limit)
loo = sq.loo_summary(y, res["loo_err"], res["loo_sd"])
gp = res["gp"]
# %% Assumptions
fit_ok = loo["loo_r2"] >= 0.5 and 0.25 <= loo["loo_msse"] <= 4.0
detail = f"Left out one at a time, runs are predicted with R² {loo['loo_r2']:.2f}; their squared errors are {loo['loo_msse']:.2f} times the predicted variances."
if not fit_ok:
detail += (" The model is a weak guide here, so suggestions lean on exploration: add runs spread over the region before trusting them."
if loo["loo_r2"] < 0.5 else " The standard deviations are off, so read the intervals with care.")
assumptions = [{"key": "surrogate_fit", "label": "The model predicts left-out runs", "status": "pass" if fit_ok else "warn", "detail": detail}]
# %% Result
best_run = res["best_run"]
best_observed = float(y[best_run]) if best_run is not None else None
pf = res["pf"]
lower = res["mean"] - 1.959963984540054 * res["pred_sd"]
upper = res["mean"] + 1.959963984540054 * res["pred_sd"]
values = {"n": n, "n_factors": d, "batch": batch, "best_observed": best_observed, "best_run": best_run + 1 if best_run is not None else None,
"n_feasible": int(np.sum(res["feasible_obs"])) if c is not None else None, "predicted_best": res["pred_best"],
"next_mean": float(res["mean"][0]), "next_sd": float(res["sd"][0]), "next_lower": float(lower[0]), "next_upper": float(upper[0]),
"next_acquisition": float(res["acq"][0]), "next_feasible": float(pf[0]) if pf is not None else None,
"loo_rmse": loo["loo_rmse"], "loo_r2": loo["loo_r2"], "loo_msse": loo["loo_msse"],
"gp_signal_sd": gp["signal_sd"], "gp_noise_sd": gp["noise_sd"], "gp_log_marginal_likelihood": gp["lml"],
"missing_share": n_dropped / n_input if n_input else 0.0}
for j, f in enumerate(FACTORS):
values[f"next[{f}]"] = float(res["x"][0, j])
values[f"gp_lengthscale[{f}]"] = float(gp["lengthscale"][j])
settings = ", ".join(f"{f} = {res['x'][0, j]:.4g}" for j, f in enumerate(FACTORS))
summary = f"Next run for {RESPONSE} ({goal}): {settings}; predicted {res['mean'][0]:.4g} (SD {res['sd'][0]:.3g})."
if best_observed is not None:
summary += f" Best run so far: {best_observed:.4g} (run {best_run + 1})."
elif c is not None:
summary += " No run meets the constraint yet, so the suggestion looks for settings that would."
acq_label = {"ei": "Expected improvement", "pi": "Probability of improvement", "ucb": "Upper confidence bound"}[acquisition]
fcols = [{"key": f"x{j + 1}", "label": f, "type": "number"} for j, f in enumerate(FACTORS)]
s_cols = [{"key": "run", "label": "Run", "type": "string"}] + fcols + [
{"key": "predicted", "label": "Predicted", "type": "number"}, {"key": "sd", "label": "SD of the mean", "type": "number"},
{"key": "lower", "label": "95% low (new run)", "type": "number"}, {"key": "upper", "label": "95% high (new run)", "type": "number"},
{"key": "acquisition", "label": acq_label, "type": "number"}]
if pf is not None:
s_cols.append({"key": "feasible", "label": "P(meets constraint)", "type": "number"})
s_rows = []
for k in range(res["x"].shape[0]):
row = {"run": f"Next {k + 1}", **{f"x{j + 1}": float(res["x"][k, j]) for j in range(d)}, "predicted": float(res["mean"][k]), "sd": float(res["sd"][k]),
"lower": float(lower[k]), "upper": float(upper[k]), "acquisition": float(res["acq"][k])}
if pf is not None:
row["feasible"] = float(pf[k])
s_rows.append(row)
r_cols = [{"key": "run", "label": "Run", "type": "integer"}] + fcols + [
{"key": "observed", "label": RESPONSE, "type": "number"}, {"key": "predicted", "label": "Left-out prediction", "type": "number"},
{"key": "sd", "label": "Left-out SD", "type": "number"}, {"key": "z", "label": "Standardized error", "type": "number"}]
if c is not None:
r_cols.append({"key": "meets", "label": "Meets constraint", "type": "boolean"})
r_rows = []
for i in range(n):
row = {"run": i + 1, **{f"x{j + 1}": float(X[i, j]) for j in range(d)}, "observed": float(y[i]), "predicted": float(y[i] - res["loo_err"][i]),
"sd": float(res["loo_sd"][i]), "z": float(res["loo_err"][i] / res["loo_sd"][i])}
if c is not None:
row["meets"] = bool(res["feasible_obs"][i])
r_rows.append(row)
k_rows = [{"setting": "Signal SD", "value": gp["signal_sd"]}, {"setting": "Noise SD", "value": gp["noise_sd"]}]
k_rows += [{"setting": f"Lengthscale: {f}", "value": float(gp["lengthscale"][j])} for j, f in enumerate(FACTORS)]
k_rows.append({"setting": "Log marginal likelihood", "value": gp["lml"]})
tables = [
{"key": "suggestions", "title": "Suggested runs", "columns": s_cols, "rows": s_rows},
{"key": "runs", "title": "Runs so far, with left-out predictions", "columns": r_cols, "rows": r_rows},
{"key": "kernel", "title": "Gaussian process settings", "columns": [{"key": "setting", "label": "Setting", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": k_rows},
]
charts = []
q = res["x"].shape[0]
for j, sl in enumerate(res["slices"]):
m = sl["x"].size
kind = ["curve"] * m + ["run"] * n + ["next"] * q
none_runs = [None] * (n + q)
charts.append(cs.chart(f"slice_{j + 1}", "gp-posterior", f"{RESPONSE} along {FACTORS[j]} (other factors at Next 1)", {
"x": cs.col(FACTORS[j], np.concatenate([sl["x"], X[:, j], res["x"][:, j]])),
"mean": cs.col("Posterior mean", list(sl["mean"].tolist()) + none_runs, "numeric"),
"lower": cs.col("95% low", list(sl["lower"].tolist()) + none_runs, "numeric"),
"upper": cs.col("95% high", list(sl["upper"].tolist()) + none_runs, "numeric"),
"y": cs.col(RESPONSE, [None] * m + y.tolist() + res["mean"].tolist(), "numeric"),
"kind": cs.col("kind", kind, "categorical", ["curve", "run", "next"]),
}))
if res["surface"] is not None:
sf = res["surface"]
gm = sf["z"].size
charts.append(cs.chart("surface", "contour-grid", f"Predicted {RESPONSE} over {FACTORS[0]} and {FACTORS[1]}", {
"x": cs.col(FACTORS[0], np.concatenate([sf["x"], X[:, 0], res["x"][:, 0]])),
"y": cs.col(FACTORS[1], np.concatenate([sf["y"], X[:, 1], res["x"][:, 1]])),
"z": cs.col(f"Predicted {RESPONSE}", np.concatenate([sf["z"], y, res["mean"]])),
"kind": cs.col("kind", ["grid"] * gm + ["point"] * (n + q), "categorical", ["grid", "point"]),
"label": cs.col("label", [None] * (gm + n) + [f"Next {k + 1}" for k in range(q)], "categorical"),
}))
statistics = [{"key": "next_mean", "label": "Predicted at Next 1", "value": float(res["mean"][0])},
{"key": "next_acquisition", "label": acq_label, "value": float(res["acq"][0])},
{"key": "loo_r2", "label": "LOO R²", "value": loo["loo_r2"]}]
notes = [f"{n_candidates} candidate settings from the shared random stream (seed {seed}), the best five refined by a compass search; factors scaled to their bounds.",
"Predicted values and SDs come from the model of the real runs; within a batch, each pick was chosen as if the earlier picks had been run."]
if c is not None:
notes.append(f"Constraint: {CONSTRAINT} {'at most' if sense == 'at_most' else 'at least'} the limit; {int(np.sum(res['feasible_obs']))} of {n} runs meet it.")
cs.publish({
"method": "doe.sequential",
"methodVersion": "1.0.0",
"title": "Sequential optimization",
"engine": cs.engine_info("numpy", "scipy"),
"n": n,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"values": values,
"charts": charts,
})
The exact script CodeSplash ran for example “Chemreact ei” · R version 4.5.1 (2025-06-13)
# Sequential optimization (Gaussian process)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.sequential 1.0.0 · spec 6d39a8b82b54c6b2
# Dataset: q1_chemreact (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_doe_seq_*(): twin of codesplash.quality.sequential (same model, candidates, search)
# Classic equivalent: library(DiceOptim); EGO.nsteps(km(~1, design, response), fun, nsteps = 1).
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_chemreact.parquet", col_select = c("Time", "Temp", "Yield")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Time", "Temp", "Yield")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("Time", "Temp", "Yield")) # infinite values stop the run (registry/errors.yaml)
# %% Model
# A Gaussian process on the runs so far (the learn.gp twins, factors scaled to the bounds), then the acquisition
# (Jones et al. 1998; Kushner 1964; Srinivas et al. 2010) maximized over candidates from the shared random stream
# and a compass search; batches by kriging believer (Ginsbourger et al. 2010).
factors_ <- c("Time", "Temp")
response <- "Yield"
constraint_col <- NULL
goal <- "maximize" # maximize | minimize
bounds <- ""
acquisition <- "ei" # ei | pi | ucb
batch <- as.integer(1)
xi <- 0.01
kappa <- 2
sense <- "at_most" # at_most | at_least
limit <- NULL
kernel <- "matern52" # matern52 | matern32 | rbf
ard <- TRUE
n_candidates <- as.integer(2000)
seed <- 42
X <- as.matrix(df[, factors_, drop = FALSE])
storage.mode(X) <- "double"
y <- as.numeric(df[[response]])
n <- nrow(X)
d <- ncol(X)
cs_doe_seq_check(y, d, response)
cc <- if (!is.null(constraint_col)) as.numeric(df[[constraint_col]]) else NULL
res <- cs_doe_seq_suggest(X, y, factors_, goal, bounds, acquisition, batch, kernel, ard, xi, kappa, n_candidates, seed, cc, sense, limit)
loo <- cs_doe_seq_loo_summary(y, res$loo_err, res$loo_sd)
gp <- res$gp
# %% Assumptions
fit_ok <- loo$loo_r2 >= 0.5 && loo$loo_msse >= 0.25 && loo$loo_msse <= 4
detail <- sprintf("Left out one at a time, runs are predicted with R² %.2f; their squared errors are %.2f times the predicted variances.", loo$loo_r2, loo$loo_msse)
if (!fit_ok) {
detail <- paste0(detail, if (loo$loo_r2 < 0.5) " The model is a weak guide here, so suggestions lean on exploration: add runs spread over the region before trusting them." else " The standard deviations are off, so read the intervals with care.")
}
assumptions <- list(list(key = "surrogate_fit", label = "The model predicts left-out runs", status = if (fit_ok) "pass" else "warn", detail = detail))
# %% Result
best_run <- res$best_run
best_observed <- if (!is.null(best_run)) y[best_run + 1L] else NA_real_
pf <- res$pf
lower <- res$mean - 1.959963984540054 * res$pred_sd
upper <- res$mean + 1.959963984540054 * res$pred_sd
values <- list(n = n, n_factors = d, batch = batch, best_observed = best_observed, best_run = if (!is.null(best_run)) best_run + 1L else NA_integer_,
n_feasible = if (!is.null(cc)) sum(res$feasible_obs) else NA_integer_, predicted_best = if (!is.null(res$pred_best)) res$pred_best else NA_real_,
next_mean = res$mean[1], next_sd = res$sd[1], next_lower = lower[1], next_upper = upper[1],
next_acquisition = res$acq[1], next_feasible = if (!is.null(pf)) pf[1] else NA_real_,
loo_rmse = loo$loo_rmse, loo_r2 = loo$loo_r2, loo_msse = loo$loo_msse,
gp_signal_sd = gp$signal_sd, gp_noise_sd = gp$noise_sd, gp_log_marginal_likelihood = gp$lml,
missing_share = if (n_input > 0) n_dropped / n_input else 0)
for (j in seq_len(d)) {
values[[sprintf("next[%s]", factors_[j])]] <- res$x[1, j]
values[[sprintf("gp_lengthscale[%s]", factors_[j])]] <- gp$lengthscale[j]
}
settings <- paste(sprintf("%s = %.4g", factors_, res$x[1, ]), collapse = ", ")
summary <- sprintf("Next run for %s (%s): %s; predicted %.4g (SD %.3g).", response, goal, settings, res$mean[1], res$sd[1])
if (!is.null(best_run)) {
summary <- paste0(summary, sprintf(" Best run so far: %.4g (run %d).", best_observed, best_run + 1L))
} else if (!is.null(cc)) {
summary <- paste0(summary, " No run meets the constraint yet, so the suggestion looks for settings that would.")
}
acq_label <- c(ei = "Expected improvement", pi = "Probability of improvement", ucb = "Upper confidence bound")[[acquisition]]
fcols <- lapply(seq_len(d), function(j) list(key = sprintf("x%d", j), label = factors_[j], type = "number"))
s_cols <- c(list(list(key = "run", label = "Run", type = "string")), fcols, list(
list(key = "predicted", label = "Predicted", type = "number"), list(key = "sd", label = "SD of the mean", type = "number"),
list(key = "lower", label = "95% low (new run)", type = "number"), list(key = "upper", label = "95% high (new run)", type = "number"),
list(key = "acquisition", label = acq_label, type = "number")))
if (!is.null(pf)) s_cols[[length(s_cols) + 1L]] <- list(key = "feasible", label = "P(meets constraint)", type = "number")
q <- nrow(res$x)
s_rows <- lapply(seq_len(q), function(k) {
row <- list(run = sprintf("Next %d", k))
for (j in seq_len(d)) row[[sprintf("x%d", j)]] <- res$x[k, j]
row <- c(row, list(predicted = res$mean[k], sd = res$sd[k], lower = lower[k], upper = upper[k], acquisition = res$acq[k]))
if (!is.null(pf)) row$feasible <- pf[k]
row
})
r_cols <- c(list(list(key = "run", label = "Run", type = "integer")), fcols, list(
list(key = "observed", label = response, type = "number"), list(key = "predicted", label = "Left-out prediction", type = "number"),
list(key = "sd", label = "Left-out SD", type = "number"), list(key = "z", label = "Standardized error", type = "number")))
if (!is.null(cc)) r_cols[[length(r_cols) + 1L]] <- list(key = "meets", label = "Meets constraint", type = "boolean")
r_rows <- lapply(seq_len(n), function(i) {
row <- list(run = i)
for (j in seq_len(d)) row[[sprintf("x%d", j)]] <- X[i, j]
row <- c(row, list(observed = y[i], predicted = y[i] - res$loo_err[i], sd = res$loo_sd[i], z = res$loo_err[i] / res$loo_sd[i]))
if (!is.null(cc)) row$meets <- isTRUE(res$feasible_obs[i])
row
})
k_rows <- c(list(list(setting = "Signal SD", value = gp$signal_sd), list(setting = "Noise SD", value = gp$noise_sd)),
lapply(seq_len(d), function(j) list(setting = sprintf("Lengthscale: %s", factors_[j]), value = gp$lengthscale[j])),
list(list(setting = "Log marginal likelihood", value = gp$lml)))
tables <- list(
list(key = "suggestions", title = "Suggested runs", columns = s_cols, rows = s_rows),
list(key = "runs", title = "Runs so far, with left-out predictions", columns = r_cols, rows = r_rows),
list(key = "kernel", title = "Gaussian process settings", columns = list(list(key = "setting", label = "Setting", type = "string"), list(key = "value", label = "Value", type = "number")), rows = k_rows)
)
charts <- list()
for (j in seq_along(res$slices)) {
sl <- res$slices[[j]]
m <- length(sl$x)
kind <- c(rep("curve", m), rep("run", n), rep("next", q))
none_runs <- rep(NA_real_, n + q)
charts[[length(charts) + 1L]] <- cs_chart(sprintf("slice_%d", j), "gp-posterior", sprintf("%s along %s (other factors at Next 1)", response, factors_[j]), list(
x = cs_col(factors_[j], c(sl$x, X[, j], res$x[, j])),
mean = cs_col("Posterior mean", c(sl$mean, none_runs), "numeric"),
lower = cs_col("95% low", c(sl$lower, none_runs), "numeric"),
upper = cs_col("95% high", c(sl$upper, none_runs), "numeric"),
y = cs_col(response, c(rep(NA_real_, m), y, res$mean), "numeric"),
kind = cs_col("kind", kind, "categorical", c("curve", "run", "next"))
))
}
if (!is.null(res$surface)) {
sf <- res$surface
gm <- length(sf$z)
charts[[length(charts) + 1L]] <- cs_chart("surface", "contour-grid", sprintf("Predicted %s over %s and %s", response, factors_[1], factors_[2]), list(
x = cs_col(factors_[1], c(sf$x, X[, 1], res$x[, 1])),
y = cs_col(factors_[2], c(sf$y, X[, 2], res$x[, 2])),
z = cs_col(sprintf("Predicted %s", response), c(sf$z, y, res$mean)),
kind = cs_col("kind", c(rep("grid", gm), rep("point", n + q)), "categorical", c("grid", "point")),
label = cs_col("label", c(rep(NA_character_, gm + n), sprintf("Next %d", seq_len(q))), "categorical")
))
}
statistics <- list(list(key = "next_mean", label = "Predicted at Next 1", value = res$mean[1]),
list(key = "next_acquisition", label = acq_label, value = res$acq[1]),
list(key = "loo_r2", label = "LOO R²", value = loo$loo_r2))
notes <- list(sprintf("%d candidate settings from the shared random stream (seed %d), the best five refined by a compass search; factors scaled to their bounds.", n_candidates, as.integer(seed)),
"Predicted values and SDs come from the model of the real runs; within a batch, each pick was chosen as if the earlier picks had been run.")
if (!is.null(cc)) {
notes[[3]] <- sprintf("Constraint: %s %s the limit; %d of %d runs meet it.", constraint_col, if (sense == "at_most") "at most" else "at least", sum(res$feasible_obs), n)
}
cs_publish(list(
method = "doe.sequential",
methodVersion = "1.0.0",
title = "Sequential optimization",
engine = cs_engine_info("stats"),
n = n,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
values = values,
charts = charts
))
Sources
- Jones, D. R., Schonlau, M., & Welch, W. J. (1998). Efficient global optimization of expensive black-box functions. Journal of Global Optimization, 13, 455–492.
- Kushner, H. J. (1964). A new method of locating the maximum point of an arbitrary multipeak curve in the presence of noise. Journal of Basic Engineering, 86, 97–106.
- Srinivas, N., Krause, A., Kakade, S. M., & Seeger, M. (2010). Gaussian process optimization in the bandit setting: no regret and experimental design. ICML 2010.
- Ginsbourger, D., Le Riche, R., & Carraro, L. (2010). Kriging is well-suited to parallelize optimization. In Computational Intelligence in Expensive Optimization Problems, 131–162. Springer.
- Gardner, J. R., Kusner, M. J., Xu, Z., Weinberger, K. Q., & Cunningham, J. P. (2014). Bayesian optimization with inequality constraints. ICML 2014.
- Rasmussen, C. E., & Williams, C. K. I. (2006). Gaussian Processes for Machine Learning. MIT Press.
From the CodeSplash method registry · doe.sequential v1.0.0.