Let the runs choose the next run
Fit a Gaussian process to the runs you have, and let expected improvement pick the next settings, one run or one batch at a time.
What runs in CodeSplash
- Sequential optimization (Gaussian process) Verified in Python and R
You will be able to
- Explain why expected improvement balances promising and uncertain settings
- Check a Gaussian process's leave-one-out fit before following its suggestions
- Use a batch and a constraint, and say what each changes
Read first
When every run is expensive
ReadA response surface design fixes all its runs in advance. When each run costs a day of plant time, you may prefer to decide one run at a time, using everything learned so far.
That is Bayesian optimizationBayesian optimizationFit a Gaussian process to the runs so far, then run where it says an improvement is most likely; repeat until the gains stop.. A Gaussian processGaussian processA prior over smooth functions set by a kernel; updated with data it gives a predictive mean and SD for every row. is fitted to the runs, giving a predicted response and an uncertainty everywhere in the region. A score, the acquisition functionAcquisition functionThe score a sequential design gives each candidate setting; the next run goes where it is highest., then picks the next settings.
Where should the next run go?
PredictPredict first
An enzyme study has 15 runs of a Box–Behnken design over pH, temperature and the amount of enzyme. Expected improvement scores each candidate setting. Where do you expect it to put the next run?
Reveal
Where they balance. Expected improvementExpected improvementHow much a run at a setting is expected to beat the best run so far: large where the mean is high, the SD wide, or both. is large where the mean is high, where the band is wide, or both. Following the mean alone repeats what you know; following the uncertainty alone wanders.
Ask for the next run
In the appNext run for Activity (maximize): pH = 7, Temperature (°C) = 38.11, Enzyme = 3; predicted 80.99 (SD 1.66). Best run so far: 79.95 (run 14).
- Predicted at Next 1
- 80.993
- Expected improvement
- 1.348
- LOO R²
- 0.5892
Assumptions
- The model predicts left-out runs — Left out one at a time, runs are predicted with R² 0.59; their squared errors are 0.90 times the predicted variances.
Suggested runs
| Run | pH | Temperature (°C) | Enzyme | Predicted | SD of the mean | 95% low (new run) | 95% high (new run) | Expected improvement |
|---|---|---|---|---|---|---|---|---|
| Next 1 | 7.000 | 38.111 | 3 | 80.993 | 1.660 | 77.725 | 84.261 | 1.348 |
| Next 2 | 7.009 | 37.988 | 3 | 79.850 | 2.600 | 74.746 | 84.955 | 0.4587 |
Runs so far, with left-out predictions
| Run | pH | Temperature (°C) | Enzyme | Activity | Left-out prediction | Left-out SD | Standardized error |
|---|---|---|---|---|---|---|---|
| 1 | 6.500 | 35 | 2 | 76.250 | 74.075 | 3.444 | 0.6316 |
| 2 | 7.500 | 35 | 2 | 77.920 | 75.050 | 3.444 | 0.8334 |
| 3 | 6.500 | 45 | 2 | 67.120 | 72.641 | 3.444 | −1.603 |
| 4 | 7.500 | 45 | 2 | 74.520 | 74.516 | 3.444 | 0.0012 |
| 5 | 6.500 | 40 | 1 | 70.010 | 72.377 | 2.636 | −0.8978 |
| 6 | 7.500 | 40 | 1 | 73.320 | 76.175 | 2.636 | −1.083 |
| 7 | 6.500 | 40 | 3 | 72.360 | 71.048 | 2.636 | 0.4978 |
| 8 | 7.500 | 40 | 3 | 76.310 | 74.484 | 2.636 | 0.6928 |
| 9 | 7 | 35 | 1 | 76.410 | 79.066 | 2.697 | −0.9847 |
| 10 | 7 | 45 | 1 | 70.540 | 74.452 | 2.697 | −1.450 |
| 11 | 7 | 35 | 3 | 79.870 | 77.074 | 2.697 | 1.037 |
| 12 | 7 | 45 | 3 | 73.260 | 73.001 | 2.697 | 0.0962 |
| 13 | 7 | 40 | 2 | 79.680 | 79.809 | 0.1907 | −0.6753 |
| 14 | 7 | 40 | 2 | 79.950 | 79.674 | 0.1907 | 1.447 |
| 15 | 7 | 40 | 2 | 79.680 | 79.809 | 0.1907 | −0.6753 |
Gaussian process settings
| Setting | Value |
|---|---|
| Signal SD | 3.951 |
| Noise SD | 0.1557 |
| Lengthscale: pH | 0.0175 |
| Lengthscale: Temperature (°C) | 4.520 |
| Lengthscale: Enzyme | 2.926 |
| Log marginal likelihood | −13.432 |
- 1000 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.
The exact R script · R 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 e2fdbe9d902e48cd
# Dataset: q1_bbd (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_bbd.parquet", col_select = c("pH", "Temperature (°C)", "Enzyme", "Activity")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("pH", "Temperature (°C)", "Enzyme", "Activity")]), , 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("pH", "Temperature (°C)", "Enzyme", "Activity")) # 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("pH", "Temperature (°C)", "Enzyme")
response <- "Activity"
constraint_col <- NULL
goal <- "maximize" # maximize | minimize
bounds <- "Enzyme: 1, 3"
acquisition <- "ei" # ei | pi | ucb
batch <- as.integer(2)
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(1000)
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
))
Next run for Activity (maximize): pH = 7, Temperature (°C) = 38.11, Enzyme = 3; predicted 80.99 (SD 1.66). Best run so far: 79.95 (run 14).
- Predicted at Next 1
- 80.993
- Expected improvement
- 1.348
- LOO R²
- 0.5892
Assumptions
- The model predicts left-out runs — Left out one at a time, runs are predicted with R² 0.59; their squared errors are 0.90 times the predicted variances.
Suggested runs
| Run | pH | Temperature (°C) | Enzyme | Predicted | SD of the mean | 95% low (new run) | 95% high (new run) | Expected improvement |
|---|---|---|---|---|---|---|---|---|
| Next 1 | 7.000 | 38.111 | 3 | 80.993 | 1.660 | 77.725 | 84.261 | 1.348 |
| Next 2 | 7.009 | 37.988 | 3 | 79.850 | 2.600 | 74.746 | 84.955 | 0.4587 |
Runs so far, with left-out predictions
| Run | pH | Temperature (°C) | Enzyme | Activity | Left-out prediction | Left-out SD | Standardized error |
|---|---|---|---|---|---|---|---|
| 1 | 6.500 | 35 | 2 | 76.250 | 74.075 | 3.444 | 0.6316 |
| 2 | 7.500 | 35 | 2 | 77.920 | 75.050 | 3.444 | 0.8334 |
| 3 | 6.500 | 45 | 2 | 67.120 | 72.641 | 3.444 | −1.603 |
| 4 | 7.500 | 45 | 2 | 74.520 | 74.516 | 3.444 | 0.0012 |
| 5 | 6.500 | 40 | 1 | 70.010 | 72.377 | 2.636 | −0.8978 |
| 6 | 7.500 | 40 | 1 | 73.320 | 76.175 | 2.636 | −1.083 |
| 7 | 6.500 | 40 | 3 | 72.360 | 71.048 | 2.636 | 0.4978 |
| 8 | 7.500 | 40 | 3 | 76.310 | 74.484 | 2.636 | 0.6928 |
| 9 | 7 | 35 | 1 | 76.410 | 79.066 | 2.697 | −0.9847 |
| 10 | 7 | 45 | 1 | 70.540 | 74.452 | 2.697 | −1.450 |
| 11 | 7 | 35 | 3 | 79.870 | 77.074 | 2.697 | 1.037 |
| 12 | 7 | 45 | 3 | 73.260 | 73.001 | 2.697 | 0.0962 |
| 13 | 7 | 40 | 2 | 79.680 | 79.809 | 0.1907 | −0.6753 |
| 14 | 7 | 40 | 2 | 79.950 | 79.674 | 0.1907 | 1.447 |
| 15 | 7 | 40 | 2 | 79.680 | 79.809 | 0.1907 | −0.6753 |
Gaussian process settings
| Setting | Value |
|---|---|
| Signal SD | 3.951 |
| Noise SD | 0.1557 |
| Lengthscale: pH | 0.0175 |
| Lengthscale: Temperature (°C) | 4.520 |
| Lengthscale: Enzyme | 2.926 |
| Log marginal likelihood | −13.432 |
- 1000 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.
The exact Python script · Python 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 e2fdbe9d902e48cd
# Dataset: q1_bbd (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_bbd.parquet", columns=["pH", "Temperature (°C)", "Enzyme", "Activity"])
n_input = len(df)
df = df.dropna(subset=["pH", "Temperature (°C)", "Enzyme", "Activity"]) # 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, ["pH", "Temperature (°C)", "Enzyme", "Activity"]) # 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 = ["pH", "Temperature (°C)", "Enzyme"]
RESPONSE = "Activity"
CONSTRAINT = None
goal = "maximize" # maximize | minimize
bounds = "Enzyme: 1, 3"
acquisition = "ei" # ei | pi | ucb
batch = int(2)
xi = 0.01
kappa = 2
sense = "at_most" # at_most | at_least
limit = None
kernel = "matern52" # matern52 | matern32 | rbf
ard = True
n_candidates = int(1000)
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,
})
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; 4 chart(s) dropped to stay under 100 KB.
The next run is predicted to give 80.99 activity, against 79.95 for the best run so far. The slice charts show the posterior mean with its band along each factor, holding the others at the suggested settings. Left out one at a time, runs are predicted with R² 0.59: a usable guide.
Is the model a fair guide?
PredictPredict first
Now the chemical reaction from the response-surface lesson: 14 runs in two blocks, whose center runs differ by about 4 points. Predicting each run from the others, what R² do you expect?
Reveal
0.01. The model fits one noise level to the whole design, so the block difference counts as noise, and the suggestion predicts 81.1, below the best run's 84.3. A low leave-one-outLeave-one-out check of a Gaussian processEach run predicted from the others; RMSE and R² show whether the model is a fair guide before you follow it. R² means suggestions lean on exploration: add spread-out runs before you trust them.
Several runs at once
ReadWhen you can make several runs in parallel, ask for a batch. The kriging believerKriging believerA batch of runs from one model: each pick's prediction is treated as observed before the next pick is made. treats each pick's prediction as if it had been run, so the next pick moves somewhere else.
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 |
| Next 2 | 85.142 | 174.79 | 80.868 | 0.8355 | 75.732 | 86.003 | 0.1781 |
| Next 3 | 89.998 | 180.00 | 80.915 | 0.8349 | 75.780 | 86.051 | 0.2221 |
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.5647 |
| Lengthscale: Temp | 0.2058 |
| 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.
The exact R script · R 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 e4c2f20c60effef3
# 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 <- "Time: 75, 95; Temp: 165, 185"
acquisition <- "ei" # ei | pi | ucb
batch <- as.integer(3)
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
))
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 |
| Next 2 | 85.142 | 174.79 | 80.868 | 0.8355 | 75.732 | 86.003 | 0.1781 |
| Next 3 | 89.998 | 180.00 | 80.915 | 0.8349 | 75.780 | 86.051 | 0.2221 |
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.5647 |
| Lengthscale: Temp | 0.2058 |
| 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.
The exact Python script · Python 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 e4c2f20c60effef3
# 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 = "Time: 75, 95; Temp: 165, 185"
acquisition = "ei" # ei | pi | ucb
batch = int(3)
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,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
This batch of 3 stays inside the bounds you set. The first pick is the same one a single suggestion would give.
Keep cost under a limit
ReadNext 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 | P(meets constraint) |
|---|---|---|---|---|---|---|---|---|
| Next 1 | 85.000 | 175.00 | 81.141 | 0.6674 | 76.100 | 86.181 | 0.2533 | 1 |
| Next 2 | 85.000 | 175.45 | 80.867 | 0.8357 | 75.731 | 86.003 | 0.1782 | 1 |
Runs so far, with left-out predictions
| Run | Time | Temp | Yield | Left-out prediction | Left-out SD | Standardized error | Meets constraint |
|---|---|---|---|---|---|---|---|
| 1 | 80 | 170 | 80.500 | 80.586 | 2.637 | −0.0325 | yes |
| 2 | 80 | 180 | 81.500 | 80.586 | 2.637 | 0.3467 | no |
| 3 | 90 | 170 | 82 | 80.586 | 2.637 | 0.5363 | yes |
| 4 | 90 | 180 | 83.500 | 80.586 | 2.637 | 1.105 | no |
| 5 | 85 | 175 | 83.900 | 80.926 | 2.578 | 1.153 | yes |
| 6 | 85 | 175 | 84.300 | 80.895 | 2.578 | 1.321 | yes |
| 7 | 85 | 175 | 84 | 80.918 | 2.578 | 1.195 | yes |
| 8 | 85 | 175 | 79.700 | 81.253 | 2.578 | −0.6022 | yes |
| 9 | 85 | 175 | 79.800 | 81.245 | 2.578 | −0.5604 | yes |
| 10 | 85 | 175 | 79.500 | 81.268 | 2.578 | −0.6858 | yes |
| 11 | 92.070 | 175 | 78.400 | 80.586 | 2.637 | −0.8288 | no |
| 12 | 77.930 | 175 | 75.600 | 80.586 | 2.637 | −1.891 | no |
| 13 | 85 | 182.07 | 78.500 | 80.586 | 2.637 | −0.7909 | yes |
| 14 | 85 | 167.93 | 77 | 80.586 | 2.637 | −1.360 | yes |
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.
- Constraint: Cost at most the limit; 10 of 14 runs meet it.
The exact R script · R 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 0125aaebe965a20a
# 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", "Cost")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Time", "Temp", "Yield", "Cost")]), , 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", "Cost")) # 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 <- "Cost"
goal <- "maximize" # maximize | minimize
bounds <- ""
acquisition <- "ei" # ei | pi | ucb
batch <- as.integer(2)
xi <- 0.01
kappa <- 2
sense <- "at_most" # at_most | at_least
limit <- 22
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
))
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 | P(meets constraint) |
|---|---|---|---|---|---|---|---|---|
| Next 1 | 85.000 | 175.00 | 81.141 | 0.6674 | 76.100 | 86.181 | 0.2533 | 1 |
| Next 2 | 85.000 | 175.45 | 80.867 | 0.8357 | 75.731 | 86.003 | 0.1782 | 1 |
Runs so far, with left-out predictions
| Run | Time | Temp | Yield | Left-out prediction | Left-out SD | Standardized error | Meets constraint |
|---|---|---|---|---|---|---|---|
| 1 | 80 | 170 | 80.500 | 80.586 | 2.637 | −0.0325 | yes |
| 2 | 80 | 180 | 81.500 | 80.586 | 2.637 | 0.3467 | no |
| 3 | 90 | 170 | 82 | 80.586 | 2.637 | 0.5363 | yes |
| 4 | 90 | 180 | 83.500 | 80.586 | 2.637 | 1.105 | no |
| 5 | 85 | 175 | 83.900 | 80.926 | 2.578 | 1.153 | yes |
| 6 | 85 | 175 | 84.300 | 80.895 | 2.578 | 1.321 | yes |
| 7 | 85 | 175 | 84 | 80.918 | 2.578 | 1.195 | yes |
| 8 | 85 | 175 | 79.700 | 81.253 | 2.578 | −0.6022 | yes |
| 9 | 85 | 175 | 79.800 | 81.245 | 2.578 | −0.5604 | yes |
| 10 | 85 | 175 | 79.500 | 81.268 | 2.578 | −0.6858 | yes |
| 11 | 92.070 | 175 | 78.400 | 80.586 | 2.637 | −0.8288 | no |
| 12 | 77.930 | 175 | 75.600 | 80.586 | 2.637 | −1.891 | no |
| 13 | 85 | 182.07 | 78.500 | 80.586 | 2.637 | −0.7909 | yes |
| 14 | 85 | 167.93 | 77 | 80.586 | 2.637 | −1.360 | yes |
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.
- Constraint: Cost at most the limit; 10 of 14 runs meet it.
The exact Python script · Python 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 0125aaebe965a20a
# 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", "Cost"])
n_input = len(df)
df = df.dropna(subset=["Time", "Temp", "Yield", "Cost"]) # 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", "Cost"]) # 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 = "Cost"
goal = "maximize" # maximize | minimize
bounds = ""
acquisition = "ei" # ei | pi | ucb
batch = int(2)
xi = 0.01
kappa = 2
sense = "at_most" # at_most | at_least
limit = 22
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,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
A second Gaussian process models cost. Expected improvement is multiplied by the probability of meeting the constraintProbability of meeting the constraintThe model's chance that a run at a setting keeps a second measure (cost, impurity) on the allowed side of its limit., here 100.0% at the suggested run. 10 of the 14 runs met the limit of 22.
Check your understanding
CheckpointCheck yourself
At a setting you have already run three times, the model's band is very narrow and the mean is below the best run. What is the expected improvement there?
Show the answer
Answer: a
With a narrow band and a mean below the best, almost no outcome there would improve on it, so expected improvement is near zero.
Check yourself
You raise κ in the upper confidence bound from 1.5 to 4. What changes?
Show the answer
Answer: b
A larger κ adds more standard deviations of optimism, so uncertain settings score higher and the search explores more.
Check yourself
Why does a batch not suggest the same settings three times?
Show the answer
Answer: b
The believed result removes the uncertainty around that pick, so expected improvement there drops and the next pick goes elsewhere.
Check yourself
A new run lands just outside the band on the slice chart. Is the model broken?
Show the answer
Answer: b
The suggestions table gives a 95% range for a new run, which adds the noise; the chart's band does not.
Concepts in this lesson