Skip to content

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.

Advanced ~12 min7 steps

What runs in CodeSplash

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

01

When every run is expensive

Read

A 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.

02

Where should the next run go?

Predict

Predict 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?

Where the predicted response is highestWhere the model is most unsureWhere a high prediction and a wide uncertainty balance best
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.

03

Ask for the next run

In the app
Sequential optimizationRecorded · Python and R agreeRecorded 2026-11-21 · 26 values compared
R

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

RunpHTemperature (°C)EnzymePredictedSD of the mean95% low (new run)95% high (new run)Expected improvement
Next 17.00038.111380.9931.66077.72584.2611.348
Next 27.00937.988379.8502.60074.74684.9550.4587

Runs so far, with left-out predictions

RunpHTemperature (°C)EnzymeActivityLeft-out predictionLeft-out SDStandardized error
16.50035276.25074.0753.4440.6316
27.50035277.92075.0503.4440.8334
36.50045267.12072.6413.444−1.603
47.50045274.52074.5163.4440.0012
56.50040170.01072.3772.636−0.8978
67.50040173.32076.1752.636−1.083
76.50040372.36071.0482.6360.4978
87.50040376.31074.4842.6360.6928
9735176.41079.0662.697−0.9847
10745170.54074.4522.697−1.450
11735379.87077.0742.6971.037
12745373.26073.0012.6970.0962
13740279.68079.8090.1907−0.6753
14740279.95079.6740.19071.447
15740279.68079.8090.1907−0.6753

Gaussian process settings

SettingValue
Signal SD3.951
Noise SD0.1557
Lengthscale: pH0.0175
Lengthscale: Temperature (°C)4.520
Lengthscale: Enzyme2.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
))
Python

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

RunpHTemperature (°C)EnzymePredictedSD of the mean95% low (new run)95% high (new run)Expected improvement
Next 17.00038.111380.9931.66077.72584.2611.348
Next 27.00937.988379.8502.60074.74684.9550.4587

Runs so far, with left-out predictions

RunpHTemperature (°C)EnzymeActivityLeft-out predictionLeft-out SDStandardized error
16.50035276.25074.0753.4440.6316
27.50035277.92075.0503.4440.8334
36.50045267.12072.6413.444−1.603
47.50045274.52074.5163.4440.0012
56.50040170.01072.3772.636−0.8978
67.50040173.32076.1752.636−1.083
76.50040372.36071.0482.6360.4978
87.50040376.31074.4842.6360.6928
9735176.41079.0662.697−0.9847
10745170.54074.4522.697−1.450
11735379.87077.0742.6971.037
12745373.26073.0012.6970.0962
13740279.68079.8090.1907−0.6753
14740279.95079.6740.19071.447
15740279.68079.8090.1907−0.6753

Gaussian process settings

SettingValue
Signal SD3.951
Noise SD0.1557
Lengthscale: pH0.0175
Lengthscale: Temperature (°C)4.520
Lengthscale: Enzyme2.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.

04

Is the model a fair guide?

Predict

Predict 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?

High: the model predicts left-out runs wellLow: the runs are hard to predict from each other
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.

05

Several runs at once

Read

When 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.

Sequential optimizationRecorded · Python and R agreeRecorded 2026-11-21 · 24 values compared
R

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

RunTimeTempPredictedSD of the mean95% low (new run)95% high (new run)Expected improvement
Next 185.000175.0081.1410.667476.10086.1810.2533
Next 285.142174.7980.8680.835575.73286.0030.1781
Next 389.998180.0080.9150.834975.78086.0510.2221

Runs so far, with left-out predictions

RunTimeTempYieldLeft-out predictionLeft-out SDStandardized error
18017080.50080.5862.637−0.0325
28018081.50080.5862.6370.3467
3901708280.5862.6370.5363
49018083.50080.5862.6371.105
58517583.90080.9262.5781.153
68517584.30080.8952.5781.321
7851758480.9182.5781.195
88517579.70081.2532.578−0.6022
98517579.80081.2452.578−0.5604
108517579.50081.2682.578−0.6858
1192.07017578.40080.5862.637−0.8288
1277.93017575.60080.5862.637−1.891
1385182.0778.50080.5862.637−0.7909
1485167.937780.5862.637−1.360

Gaussian process settings

SettingValue
Signal SD0.8865
Noise SD2.484
Lengthscale: Time0.5647
Lengthscale: Temp0.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
))
Python

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

RunTimeTempPredictedSD of the mean95% low (new run)95% high (new run)Expected improvement
Next 185.000175.0081.1410.667476.10086.1810.2533
Next 285.142174.7980.8680.835575.73286.0030.1781
Next 389.998180.0080.9150.834975.78086.0510.2221

Runs so far, with left-out predictions

RunTimeTempYieldLeft-out predictionLeft-out SDStandardized error
18017080.50080.5862.637−0.0325
28018081.50080.5862.6370.3467
3901708280.5862.6370.5363
49018083.50080.5862.6371.105
58517583.90080.9262.5781.153
68517584.30080.8952.5781.321
7851758480.9182.5781.195
88517579.70081.2532.578−0.6022
98517579.80081.2452.578−0.5604
108517579.50081.2682.578−0.6858
1192.07017578.40080.5862.637−0.8288
1277.93017575.60080.5862.637−1.891
1385182.0778.50080.5862.637−0.7909
1485167.937780.5862.637−1.360

Gaussian process settings

SettingValue
Signal SD0.8865
Noise SD2.484
Lengthscale: Time0.5647
Lengthscale: Temp0.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.

06

Keep cost under a limit

Read
Sequential optimizationRecorded · Python and R agreeRecorded 2026-11-21 · 24 values compared
R

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

RunTimeTempPredictedSD of the mean95% low (new run)95% high (new run)Expected improvementP(meets constraint)
Next 185.000175.0081.1410.667476.10086.1810.25331
Next 285.000175.4580.8670.835775.73186.0030.17821

Runs so far, with left-out predictions

RunTimeTempYieldLeft-out predictionLeft-out SDStandardized errorMeets constraint
18017080.50080.5862.637−0.0325yes
28018081.50080.5862.6370.3467no
3901708280.5862.6370.5363yes
49018083.50080.5862.6371.105no
58517583.90080.9262.5781.153yes
68517584.30080.8952.5781.321yes
7851758480.9182.5781.195yes
88517579.70081.2532.578−0.6022yes
98517579.80081.2452.578−0.5604yes
108517579.50081.2682.578−0.6858yes
1192.07017578.40080.5862.637−0.8288no
1277.93017575.60080.5862.637−1.891no
1385182.0778.50080.5862.637−0.7909yes
1485167.937780.5862.637−1.360yes

Gaussian process settings

SettingValue
Signal SD0.8865
Noise SD2.484
Lengthscale: Time0.4238
Lengthscale: Temp0.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
))
Python

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

RunTimeTempPredictedSD of the mean95% low (new run)95% high (new run)Expected improvementP(meets constraint)
Next 185.000175.0081.1410.667476.10086.1810.25331
Next 285.000175.4580.8670.835775.73186.0030.17821

Runs so far, with left-out predictions

RunTimeTempYieldLeft-out predictionLeft-out SDStandardized errorMeets constraint
18017080.50080.5862.637−0.0325yes
28018081.50080.5862.6370.3467no
3901708280.5862.6370.5363yes
49018083.50080.5862.6371.105no
58517583.90080.9262.5781.153yes
68517584.30080.8952.5781.321yes
7851758480.9182.5781.195yes
88517579.70081.2532.578−0.6022yes
98517579.80081.2452.578−0.5604yes
108517579.50081.2682.578−0.6858yes
1192.07017578.40080.5862.637−0.8288no
1277.93017575.60080.5862.637−1.891no
1385182.0778.50080.5862.637−0.7909yes
1485167.937780.5862.637−1.360yes

Gaussian process settings

SettingValue
Signal SD0.8865
Noise SD2.484
Lengthscale: Time0.4238
Lengthscale: Temp0.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.

07

Check your understanding

Checkpoint

Check 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