Find the best settings
Follow the path of steepest ascent, fit a curved surface near the peak, and balance several responses with desirability.
What runs in CodeSplash
- Response surface analysis (canonical analysis, steepest ascent, desirability) Verified in Python and R
You will be able to
- Say when a first-order model is enough, and when you need curvature
- Classify a stationary point, and check that it's inside the design
- Balance several responses with a desirability function
Read first
Climb, then map
ReadA response surfaceResponse surfaceA curved model of a response over factor settings, used to find the settings that give the best result. study works in two stages.
Far from the best settings, the surface looks like a tilted plane, so a first-order model shows which way is uphill. You follow the path of steepest ascentPath of steepest ascentThe direction in which a first-order model says the response rises fastest, used to move toward better settings. until the response stops improving.
Near the top, the surface curves. You need a second-order model, with squared terms, and a design with more than two levels of each factor.
Is a plane enough?
PredictPredict first
A chemical reaction has been run around what may be its best time and temperature. What R² do you expect from a first-order model here?
Reveal
9.9%. A flat plane through a hill's summit has almost no slope. A poor first-order fit near the middle of your region tells you to add curvature. It doesn't say the factors don't matter.
Fit the curve
In the appThe second-order model for Yield explains 99.8% of the variation. The stationary point is a maximum at Time = 86.861, Temp = 176.672, predicted Yield 84.366.
- R²
- 0.9981
- Adjusted R²
- 0.9964
- Lack of fit p
- 0.6851
Coefficients — Yield (coded units)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| (Intercept) | 84.095 | 0.0796 | 1056.07 | < .001 |
| Block B2 | −4.458 | 0.0872 | −51.103 | < .001 |
| Time | 0.9325 | 0.0577 | 16.162 | < .001 |
| Temp | 0.5777 | 0.0577 | 10.013 | < .001 |
| Time × Temp | 0.1250 | 0.0816 | 1.532 | .169 |
| Time² | −1.309 | 0.0601 | −21.786 | < .001 |
| Temp² | −0.9334 | 0.0601 | −15.541 | < .001 |
Analysis of variance — Yield
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| Blocks | 1 | 69.531 | 69.531 | 2611.10 | < .001 |
| First-order | 2 | 9.626 | 4.813 | 180.73 | < .001 |
| Two-way interaction | 1 | 0.0625 | 0.0625 | 2.347 | .169 |
| Pure quadratic | 2 | 17.791 | 8.896 | 334.05 | < .001 |
| Residuals | 7 | 0.1864 | 0.0266 | — | — |
| Lack of fit | 3 | 0.0531 | 0.0177 | 0.5307 | .685 |
| Pure error | 4 | 0.1333 | 0.0333 | — | — |
Stationary point (maximum) — Yield
| Factor | Coded | Actual |
|---|---|---|
| Time | 0.3723 | 86.861 |
| Temp | 0.3344 | 176.67 |
Canonical analysis (eigenvalues and eigenvectors)
| Axis | Eigenvalue | Time | Temp |
|---|---|---|---|
| W1 | −0.9233 | 0.1601 | 0.9871 |
| W2 | −1.319 | 0.9871 | −0.1601 |
Path of steepest ascent (first-order fit, Yield)
| Distance (coded) | Time | Temp | Predicted Yield |
|---|---|---|---|
| 0 | 85 | 175 | 82.814 |
| 0.5000 | 87.125 | 176.32 | 83.363 |
| 1 | 89.250 | 177.63 | 83.911 |
| 1.500 | 91.376 | 178.95 | 84.460 |
| 2 | 93.501 | 180.27 | 85.008 |
| 2.500 | 95.626 | 181.58 | 85.557 |
| 3 | 97.751 | 182.90 | 86.105 |
| 3.500 | 99.877 | 184.22 | 86.654 |
| 4 | 102.00 | 185.53 | 87.202 |
| 4.500 | 104.13 | 186.85 | 87.751 |
| 5 | 106.25 | 188.17 | 88.299 |
- Coded units: Time: (Time − 85.0000) / 5.0000, Temp: (Temp − 175.0000) / 5.0000.
The exact R script · R R version 4.5.1 (2025-06-13)
# Response surface analysis (canonical analysis, steepest ascent, desirability)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.rsm 1.0.1 · spec 00e46f72c391b511
# 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_rsm_*(): twin of codesplash.quality.rsm (same fits, canonical analysis, grid search)
# Classic equivalent: library(rsm); fit <- rsm(y ~ SO(x1, x2), data = coded.data(df, x1 ~ (Time - 85) / 5, ...));
# canonical(fit); steepest(rsm(y ~ FO(x1, x2), ...)); desirability via desirability2.
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_chemreact.parquet", col_select = c("Yield", "Time", "Temp", "Block")))
n_input <- nrow(df)
df[["Block"]] <- factor(df[["Block"]], levels = c("B1", "B2")) # stored level order
df <- df[stats::complete.cases(df[c("Yield", "Time", "Temp", "Block")]), , 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("Yield", "Time", "Temp", "Block")) # infinite values stop the run (registry/errors.yaml)
# %% Coding
responses <- c("Yield")
factors_ <- c("Time", "Temp")
block_col <- "Block"
block <- if (!is.null(block_col)) as.character(df[[block_col]]) else NULL
given <- cs_doe_rsm_parse_coding("")
unknown <- setdiff(names(given), factors_)
if (length(unknown)) stop(sprintf("Coding names %s are not among the factors.", paste(unknown, collapse = ", ")), call. = FALSE)
lh <- lapply(factors_, function(f) if (!is.null(given[[f]])) given[[f]] else cs_doe_rsm_auto_coding(df[[f]]))
lows <- vapply(lh, `[`, 0, 1); highs <- vapply(lh, `[`, 0, 2)
if (any(highs == lows)) {
f1 <- factors_[highs == lows][1]
if (is.null(given[[f1]])) cs_error("CS_E_CONSTANT", column = f1) # a single setting in the data: nothing to code
stop(sprintf("“%s” has a single setting; it cannot be coded.", f1), call. = FALSE)
}
for (r in responses) { # a constant response has no surface to fit
if (length(unique(df[[r]])) < 2) cs_error("CS_E_CONSTANT", column = r)
}
center <- (lows + highs) / 2
half <- (highs - lows) / 2
X <- as.matrix(df[, factors_, drop = FALSE])
xc <- sweep(sweep(X, 2, center), 2, half, "/")
k <- length(factors_)
model <- "so"
alpha <- 0.05
model_label <- switch(model, so = "second-order", twi = "first-order-with-interactions", fo = "first-order")
# %% Fits
fits <- lapply(responses, function(r) cs_doe_rsm_fit(df[[r]], xc, factors_, model, block))
f0 <- fits[[1]]
fo <- cs_doe_rsm_fit(df[[responses[1]]], xc, factors_, "fo", block)
design_r <- max(abs(xc))
radius <- if ("cube" == "design") design_r else 1
to_actual <- function(c) center + half * c
# %% Canonical analysis
can <- if (model == "so") cs_doe_rsm_canonical(f0, k) else NULL
xs <- if (!is.null(can)) can$xs else NULL
inside <- !is.null(can) && max(abs(xs)) <= design_r + 1e-9
y_stat <- if (!is.null(can)) cs_doe_rsm_predict(f0, xs) else NaN
# %% Steepest ascent / descent (first-order fit)
path <- cs_doe_rsm_steepest(fo, k, descent = FALSE)
# %% Desirability
goals <- cs_doe_rsm_parse_goals("", responses)
grid_n <- NULL
if (is.null(grid_n)) grid_n <- cs_doe_rsm_default_grid(k)
best <- if (length(goals)) cs_doe_rsm_optimize(fits, goals, responses, k, grid_n, radius) else NULL
# %% Tables
tables <- list()
anova_cols <- list(list(key = "source", label = "Source", type = "string"), list(key = "df", label = "df", type = "integer"),
list(key = "ss", label = "SS", type = "number"), list(key = "ms", label = "MS", type = "number"),
list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue"))
for (i in seq_along(responses)) {
f <- fits[[i]]
tables[[length(tables) + 1]] <- list(
key = paste0("coef-", responses[i]), title = sprintf("Coefficients — %s (coded units)", responses[i]),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
list(key = "p", label = "p", type = "pvalue")),
rows = lapply(seq_along(f$beta), function(j) list(term = f$coef_names[j], coef = f$beta[j], se = f$se[j], t = f$t[j], p = f$p[j])))
tables[[length(tables) + 1]] <- list(key = paste0("anova-", responses[i]), title = sprintf("Analysis of variance — %s", responses[i]),
columns = anova_cols, rows = f$anova)
}
if (!is.null(can)) {
tables[[length(tables) + 1]] <- list(
key = "stationary", title = sprintf("Stationary point (%s) — %s", can$kind, responses[1]),
columns = list(list(key = "factor", label = "Factor", type = "string"), list(key = "coded", label = "Coded", type = "number"),
list(key = "actual", label = "Actual", type = "number")),
rows = lapply(seq_len(k), function(j) list(factor = factors_[j], coded = xs[j], actual = to_actual(xs)[j])))
tables[[length(tables) + 1]] <- list(
key = "canonical", title = "Canonical analysis (eigenvalues and eigenvectors)",
columns = c(list(list(key = "axis", label = "Axis", type = "string"), list(key = "eigenvalue", label = "Eigenvalue", type = "number")),
lapply(seq_len(k), function(i) list(key = paste0("v", i - 1), label = factors_[i], type = "number"))),
rows = lapply(seq_len(k), function(j) {
row <- list(axis = paste0("W", j), eigenvalue = can$eigenvalues[j])
for (i in seq_len(k)) row[[paste0("v", i - 1)]] <- can$eigenvectors[i, j]
row
}))
}
tables[[length(tables) + 1]] <- list(
key = "ascent", title = sprintf("Path of steepest %s (first-order fit, %s)", if (FALSE) "descent" else "ascent", responses[1]),
columns = c(list(list(key = "dist", label = "Distance (coded)", type = "number")),
lapply(seq_len(k), function(i) list(key = paste0("a", i - 1), label = factors_[i], type = "number")),
list(list(key = "pred", label = paste("Predicted", responses[1]), type = "number"))),
rows = lapply(seq_along(path$dist), function(i) {
row <- list(dist = path$dist[i], pred = path$pred[i])
a <- to_actual(path$coded[i, ])
for (j in seq_len(k)) row[[paste0("a", j - 1)]] <- a[j]
row
}))
if (!is.null(best)) {
ba <- to_actual(best$coded)
tables[[length(tables) + 1]] <- list(
key = "desirability", title = sprintf("Most desirable settings (overall D = %.3f)", best$D),
columns = list(list(key = "name", label = "Factor / response", type = "string"), list(key = "value", label = "Setting / prediction", type = "number"),
list(key = "d", label = "Desirability", type = "number")),
rows = c(lapply(seq_len(k), function(j) list(name = factors_[j], value = ba[j], d = NULL)),
lapply(seq_along(goals), function(i) list(name = goals[[i]]$response, value = best$pred[[goals[[i]]$response]], d = best$d[i]))))
}
# %% Charts
cx <- ""; if (!nzchar(cx)) cx <- factors_[1]
cy <- ""; if (!nzchar(cy)) cy <- setdiff(factors_, cx)[1]
if (!cx %in% factors_ || !cy %in% factors_ || cx == cy) stop("Contour factors must be two different factors of the analysis.", call. = FALSE)
ix <- match(cx, factors_); iy <- match(cy, factors_)
base <- if (!is.null(can) && inside) xs else rep(0, k)
gx <- seq(min(xc[, ix]), max(xc[, ix]), length.out = 41)
gy <- seq(min(xc[, iy]), max(xc[, iy]), length.out = 41)
pts <- matrix(base, 41 * 41, k, byrow = TRUE)
pts[, ix] <- rep(gx, 41)
pts[, iy] <- rep(gy, each = 41)
z <- cs_doe_rsm_predict(f0, pts)
y0 <- as.numeric(df[[responses[1]]])
charts <- list(cs_chart(
"contour", "contour-grid", sprintf("Fitted %s over %s and %s", responses[1], cx, cy),
list(x = cs_col(cx, c(center[ix] + half[ix] * pts[, ix], X[, ix])),
y = cs_col(cy, c(center[iy] + half[iy] * pts[, iy], X[, iy])),
z = cs_col(responses[1], c(z, y0)),
kind = cs_col("Kind", c(rep("grid", length(z)), rep("point", length(y0))), "categorical")),
controls = list(levels = 10)))
if (f0$df_resid > 0) charts[[2]] <- cs_chart(
"residuals", "residual-panel", sprintf("Residual diagnostics — %s", responses[1]),
list(fitted = cs_col("Fitted values", f0$fitted), residual = cs_col("Residuals", f0$resid)))
# %% Result
fmt3 <- function(v) cs_fmt_num(v, 3)
stat_text <- if (!is.null(can)) paste(sprintf("%s = %s", factors_, vapply(to_actual(xs), fmt3, "")), collapse = ", ") else ""
best_text <- if (!is.null(best)) paste(sprintf("%s = %s", factors_, vapply(to_actual(best$coded), fmt3, "")), collapse = ", ") else ""
values <- list(
n = length(y0), model_label = model_label, terms = I(f0$coef_names), coef = I(f0$beta), p = I(f0$p),
r2 = f0$r2, adj_r2 = f0$adj_r2, s = f0$s, lof_p = f0$lof_p,
stationary_coded = if (!is.null(can)) I(xs) else NULL, stationary_actual = if (!is.null(can)) I(to_actual(xs)) else NULL,
eigenvalues = if (!is.null(can)) I(can$eigenvalues) else NULL, kind = if (!is.null(can)) can$kind else NULL,
y_stationary = if (!is.null(can)) y_stat else NULL, stationary_inside = inside, stationary_text = stat_text,
ascent_coded = path$coded, ascent_pred = I(path$pred),
desirability = if (!is.null(best)) best$D else NULL, best_coded = if (!is.null(best)) I(best$coded) else NULL,
best_actual = if (!is.null(best)) I(to_actual(best$coded)) else NULL,
best_pred = if (!is.null(best)) I(unname(best$pred)) else NULL, best_text = best_text,
all_coef = lapply(fits, function(f) I(f$beta))
)
summary <- sprintf("The %s model for %s explains %.1f%% of the variation.", model_label, responses[1], 100 * f0$r2)
if (!is.null(can)) summary <- paste(summary, sprintf("The stationary point is a %s at %s, predicted %s %s.", can$kind, stat_text, responses[1], fmt3(y_stat)))
if (!is.null(best)) summary <- paste(summary, sprintf("Most desirable settings: %s (D = %.3f).", best_text, best$D))
extra <- list()
if (!is.null(can) && !inside) extra <- c(extra, "The stationary point lies outside the design region; follow the ridge or run more experiments there before trusting it.")
if (!is.null(can) && can$ridge) extra <- c(extra, "One eigenvalue is near zero: the surface has a ridge, so many settings give nearly the same response.")
if (model == "so" && is.null(can)) extra <- c(extra, "The quadratic part is singular; no unique stationary point.")
stats_list <- list(list(key = "r2", label = "R²", value = f0$r2), list(key = "adj_r2", label = "Adjusted R²", value = f0$adj_r2),
list(key = "lof_p", label = "Lack of fit p", value = f0$lof_p, format = "pvalue"))
if (!is.null(best)) stats_list[[length(stats_list) + 1]] <- list(key = "desirability", label = "Overall desirability", value = best$D)
cs_publish(list(
method = "doe.rsm",
methodVersion = "1.0.1",
title = "Response surface analysis (canonical analysis, steepest ascent, desirability)",
engine = cs_engine_info("stats", "codesplashr"),
n = length(y0),
summary = summary,
statistics = stats_list,
tables = tables,
charts = charts,
warnings = c(warnings, extra),
notes = list(sprintf("Coded units: %s.", paste(sprintf("%s: (%s − %s) / %s", factors_, factors_, vapply(center, function(v) cs_fmt_num(v, 4), ""),
vapply(half, function(v) cs_fmt_num(v, 4), "")), collapse = ", "))),
values = values
))
The second-order model for Yield explains 99.8% of the variation. The stationary point is a maximum at Time = 86.861, Temp = 176.672, predicted Yield 84.366.
- R²
- 0.9981
- Adjusted R²
- 0.9964
- Lack of fit p
- 0.6851
Coefficients — Yield (coded units)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| (Intercept) | 84.095 | 0.0796 | 1056.07 | < .001 |
| Block B2 | −4.458 | 0.0872 | −51.103 | < .001 |
| Time | 0.9325 | 0.0577 | 16.162 | < .001 |
| Temp | 0.5777 | 0.0577 | 10.013 | < .001 |
| Time × Temp | 0.1250 | 0.0816 | 1.532 | .169 |
| Time² | −1.309 | 0.0601 | −21.786 | < .001 |
| Temp² | −0.9334 | 0.0601 | −15.541 | < .001 |
Analysis of variance — Yield
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| Blocks | 1 | 69.531 | 69.531 | 2611.10 | < .001 |
| First-order | 2 | 9.626 | 4.813 | 180.73 | < .001 |
| Two-way interaction | 1 | 0.0625 | 0.0625 | 2.347 | .169 |
| Pure quadratic | 2 | 17.791 | 8.896 | 334.05 | < .001 |
| Residuals | 7 | 0.1864 | 0.0266 | — | — |
| Lack of fit | 3 | 0.0531 | 0.0177 | 0.5307 | .685 |
| Pure error | 4 | 0.1333 | 0.0333 | — | — |
Stationary point (maximum) — Yield
| Factor | Coded | Actual |
|---|---|---|
| Time | 0.3723 | 86.861 |
| Temp | 0.3344 | 176.67 |
Canonical analysis (eigenvalues and eigenvectors)
| Axis | Eigenvalue | Time | Temp |
|---|---|---|---|
| W1 | −0.9233 | 0.1601 | 0.9871 |
| W2 | −1.319 | 0.9871 | −0.1601 |
Path of steepest ascent (first-order fit, Yield)
| Distance (coded) | Time | Temp | Predicted Yield |
|---|---|---|---|
| 0 | 85 | 175 | 82.814 |
| 0.5000 | 87.125 | 176.32 | 83.363 |
| 1 | 89.250 | 177.63 | 83.911 |
| 1.500 | 91.376 | 178.95 | 84.460 |
| 2 | 93.501 | 180.27 | 85.008 |
| 2.500 | 95.626 | 181.58 | 85.557 |
| 3 | 97.751 | 182.90 | 86.105 |
| 3.500 | 99.877 | 184.22 | 86.654 |
| 4 | 102.00 | 185.53 | 87.202 |
| 4.500 | 104.13 | 186.85 | 87.751 |
| 5 | 106.25 | 188.17 | 88.299 |
- Coded units: Time: (Time − 85.0000) / 5.0000, Temp: (Temp − 175.0000) / 5.0000.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Response surface analysis (canonical analysis, steepest ascent, desirability)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.rsm 1.0.1 · spec 00e46f72c391b511
# 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 rsm # twin of codesplashr::cs_doe_rsm_* (same fits, canonical analysis, grid search)
# Classic equivalent: R's rsm package — rsm(y ~ SO(x1, x2)), canonical(), steepest(); in Python
# statsmodels.formula.api.ols("y ~ x1 + x2 + I(x1**2) + I(x2**2) + x1:x2") on coded data.
# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_chemreact.parquet", columns=["Yield", "Time", "Temp", "Block"])
n_input = len(df)
df["Block"] = pd.Categorical(df["Block"], categories=["B1", "B2"]) # stored level order
df = df.dropna(subset=["Yield", "Time", "Temp", "Block"]) # listwise deletion over the analysis columns
df["Block"] = df["Block"].cat.remove_unused_categories()
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, ["Yield", "Time", "Temp", "Block"]) # infinite values stop the run (registry/errors.yaml)
# %% Coding
RESPONSES = ["Yield"]
FACTORS = ["Time", "Temp"]
block_col = "Block"
def _label(v):
return str(int(v)) if isinstance(v, float) and v.is_integer() else str(v)
block = [_label(v) for v in df[block_col]] if block_col else None # numeric blocks labeled like R's as.character()
given = rsm.parse_coding("")
unknown = [n for n in given if n not in FACTORS]
if unknown:
raise ValueError(f"Coding names {', '.join(unknown)} are not among the factors.")
lows, highs = [], []
for f in FACTORS:
lo, hi = given.get(f) or rsm.auto_coding(df[f].to_numpy(dtype=float))
if hi == lo:
if f not in given: # a single setting in the data: nothing to code
cs.cs_error("CS_E_CONSTANT", column=f)
raise ValueError(f"“{f}” has a single setting; it cannot be coded.")
lows.append(lo)
highs.append(hi)
for r in RESPONSES: # a constant response has no surface to fit
if df[r].nunique() < 2:
cs.cs_error("CS_E_CONSTANT", column=r)
center = (np.asarray(lows) + np.asarray(highs)) / 2
half = (np.asarray(highs) - np.asarray(lows)) / 2
X = df[FACTORS].to_numpy(dtype=float)
xc = (X - center) / half
k = len(FACTORS)
model = "so"
alpha = 0.05
model_label = {"so": "second-order", "twi": "first-order-with-interactions", "fo": "first-order"}[model]
# %% Fits
fits = [rsm.fit(df[r].to_numpy(dtype=float), xc, FACTORS, model, block) for r in RESPONSES]
f0 = fits[0]
fo = rsm.fit(df[RESPONSES[0]].to_numpy(dtype=float), xc, FACTORS, "fo", block)
radius = float(np.max(np.abs(xc))) if "cube" == "design" else 1.0
design_r = float(np.max(np.abs(xc)))
def to_actual(c):
return (center + half * np.asarray(c)).tolist()
# %% Canonical analysis
can = rsm.canonical(f0, k) if model == "so" else None
xs = can["xs"] if can else None
inside = bool(can and np.max(np.abs(xs)) <= design_r + 1e-9)
y_stat = float(rsm.predict(f0, xs)[0]) if can else float("nan")
# %% Steepest ascent / descent (first-order fit)
path = rsm.steepest(fo, k, descent=False)
# %% Desirability
goals = rsm.parse_goals("", RESPONSES)
grid_n = None or rsm.default_grid(k)
best = rsm.optimize(fits, goals, RESPONSES, k, int(grid_n), radius) if goals else None
# %% Tables
tables = []
for r, f in zip(RESPONSES, fits):
tables.append({
"key": f"coef-{r}", "title": f"Coefficients — {r} (coded units)",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}],
"rows": [{"term": n, "coef": b, "se": s, "t": t, "p": p} for n, b, s, t, p in zip(f["coef_names"], f["beta"], f["se"], f["t"], f["p"])],
})
tables.append({
"key": f"anova-{r}", "title": f"Analysis of variance — {r}",
"columns": [{"key": "source", "label": "Source", "type": "string"}, {"key": "df", "label": "df", "type": "integer"},
{"key": "ss", "label": "SS", "type": "number"}, {"key": "ms", "label": "MS", "type": "number"},
{"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": f["anova"],
})
if can:
tables.append({
"key": "stationary", "title": f"Stationary point ({can['kind']}) — {RESPONSES[0]}",
"columns": [{"key": "factor", "label": "Factor", "type": "string"}, {"key": "coded", "label": "Coded", "type": "number"},
{"key": "actual", "label": "Actual", "type": "number"}],
"rows": [{"factor": n, "coded": float(c), "actual": a} for n, c, a in zip(FACTORS, xs, to_actual(xs))],
})
erows = []
for j, ev in enumerate(can["eigenvalues"]):
row = {"axis": f"W{j + 1}", "eigenvalue": float(ev)}
for i, n in enumerate(FACTORS):
row[f"v{i}"] = float(can["eigenvectors"][i, j])
erows.append(row)
tables.append({
"key": "canonical", "title": "Canonical analysis (eigenvalues and eigenvectors)",
"columns": [{"key": "axis", "label": "Axis", "type": "string"}, {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"}]
+ [{"key": f"v{i}", "label": n, "type": "number"} for i, n in enumerate(FACTORS)],
"rows": erows,
})
prow = []
for d_, c, yhat in zip(path["dist"], path["coded"], path["pred"]):
row = {"dist": float(d_), "pred": float(yhat)}
for i, a in enumerate(to_actual(c)):
row[f"a{i}"] = a
prow.append(row)
tables.append({
"key": "ascent", "title": f"Path of steepest {'descent' if False else 'ascent'} (first-order fit, {RESPONSES[0]})",
"columns": [{"key": "dist", "label": "Distance (coded)", "type": "number"}]
+ [{"key": f"a{i}", "label": n, "type": "number"} for i, n in enumerate(FACTORS)]
+ [{"key": "pred", "label": f"Predicted {RESPONSES[0]}", "type": "number"}],
"rows": prow,
})
if best:
tables.append({
"key": "desirability", "title": f"Most desirable settings (overall D = {best['D']:.3f})",
"columns": [{"key": "name", "label": "Factor / response", "type": "string"}, {"key": "value", "label": "Setting / prediction", "type": "number"},
{"key": "d", "label": "Desirability", "type": "number"}],
"rows": [{"name": n, "value": a, "d": None} for n, a in zip(FACTORS, to_actual(best["coded"]))]
+ [{"name": g["response"], "value": best["pred"][g["response"]], "d": dv} for g, dv in zip(goals, best["d"])],
})
# %% Charts
charts = []
cx = "" or FACTORS[0]
cy = "" or next(f for f in FACTORS if f != cx)
if cx not in FACTORS or cy not in FACTORS or cx == cy:
raise ValueError("Contour factors must be two different factors of the analysis.")
ix, iy = FACTORS.index(cx), FACTORS.index(cy)
base = xs.copy() if (can and inside) else np.zeros(k)
gx = np.linspace(float(xc[:, ix].min()), float(xc[:, ix].max()), 41)
gy = np.linspace(float(xc[:, iy].min()), float(xc[:, iy].max()), 41)
pts = np.tile(base, (41 * 41, 1))
pts[:, ix] = np.tile(gx, 41)
pts[:, iy] = np.repeat(gy, 41)
z = rsm.predict(f0, pts)
y0 = df[RESPONSES[0]].to_numpy(dtype=float)
charts.append(cs.chart(
"contour", "contour-grid", f"Fitted {RESPONSES[0]} over {cx} and {cy}",
{"x": cs.col(cx, (center[ix] + half[ix] * pts[:, ix]).tolist() + X[:, ix].tolist()),
"y": cs.col(cy, (center[iy] + half[iy] * pts[:, iy]).tolist() + X[:, iy].tolist()),
"z": cs.col(RESPONSES[0], z.tolist() + y0.tolist()),
"kind": cs.col("Kind", ["grid"] * len(z) + ["point"] * len(y0), "categorical")},
controls={"levels": 10},
))
if f0["df_resid"] > 0:
charts.append(cs.chart(
"residuals", "residual-panel", f"Residual diagnostics — {RESPONSES[0]}",
{"fitted": cs.col("Fitted values", f0["fitted"].tolist()), "residual": cs.col("Residuals", f0["resid"].tolist())},
))
# %% Result
coef_p = f0["p"]
stat_text = ", ".join(f"{n} = {cs.fmt_num(a, 3)}" for n, a in zip(FACTORS, to_actual(xs))) if can else ""
best_text = ", ".join(f"{n} = {cs.fmt_num(a, 3)}" for n, a in zip(FACTORS, to_actual(best["coded"]))) if best else ""
values = {
"n": len(y0), "model_label": model_label, "terms": list(f0["coef_names"]), "coef": [float(b) for b in f0["beta"]], "p": [float(p) for p in coef_p],
"r2": f0["r2"], "adj_r2": f0["adj_r2"], "s": f0["s"], "lof_p": f0["lof_p"],
"stationary_coded": [float(v) for v in xs] if can else None, "stationary_actual": to_actual(xs) if can else None,
"eigenvalues": [float(v) for v in can["eigenvalues"]] if can else None, "kind": can["kind"] if can else None,
"y_stationary": y_stat if can else None, "stationary_inside": inside, "stationary_text": stat_text,
"ascent_coded": path["coded"].tolist(), "ascent_pred": path["pred"].tolist(),
"desirability": best["D"] if best else None, "best_coded": best["coded"].tolist() if best else None,
"best_actual": to_actual(best["coded"]) if best else None,
"best_pred": [best["pred"][r] for r in RESPONSES] if best else None, "best_text": best_text,
"all_coef": [[float(b) for b in f["beta"]] for f in fits],
}
summary = f"The {model_label} model for {RESPONSES[0]} explains {100 * f0['r2']:.1f}% of the variation."
if can:
summary += f" The stationary point is a {can['kind']} at {stat_text}, predicted {RESPONSES[0]} {cs.fmt_num(y_stat, 3)}."
if best:
summary += f" Most desirable settings: {best_text} (D = {best['D']:.3f})."
warnings_extra = []
if can and not inside:
warnings_extra.append("The stationary point lies outside the design region; follow the ridge or run more experiments there before trusting it.")
if can and can["ridge"]:
warnings_extra.append("One eigenvalue is near zero: the surface has a ridge, so many settings give nearly the same response.")
if model == "so" and not can:
warnings_extra.append("The quadratic part is singular; no unique stationary point.")
cs.publish({
"title": "Response surface analysis (canonical analysis, steepest ascent, desirability)",
"engine": cs.engine_info("numpy", "scipy"),
"n": len(y0),
"summary": summary,
"statistics": [
{"key": "r2", "label": "R²", "value": f0["r2"]},
{"key": "adj_r2", "label": "Adjusted R²", "value": f0["adj_r2"]},
{"key": "lof_p", "label": "Lack of fit p", "value": f0["lof_p"], "format": "pvalue"},
] + ([{"key": "desirability", "label": "Overall desirability", "value": best["D"]}] if best else []),
"tables": tables,
"charts": charts,
"warnings": warnings + warnings_extra,
"notes": [f"Coded units: {', '.join(f'{n}: ({n} − {cs.fmt_num(c, 4)}) / {cs.fmt_num(h, 4)}' for n, c, h in zip(FACTORS, center, half))}."],
"values": values,
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
The second-order model reaches R² of 0.998. Lack of fit, tested against the replicated center points, gives p = .685: no sign the model's form is wrong.
The contour plot shows the fitted surface. This design also includes a block, so batch-to-batch differences stay out of the factor effects.
What kind of point is it?
PredictPredict first
The stationary pointStationary pointWhere a fitted surface is flat. Its eigenvalues show whether it's a maximum, a minimum or a saddle. is where the surface is flat. Canonical analysis looks at the eigenvalues of . Here, both are negative, meaning the surface curves down in every direction. What is this point?
Reveal
A maximum, at Time = 86.861, Temp = 176.672, with a predicted yield of 84.4. All positive would mean a minimum, and mixed signs a saddle, where the best setting lies along a ridge and the point itself isn't the answer.
More than one goal
In the appYield and cost pull in different directions. A desirability functionDesirability functionTurns several responses into one 0–1 score so you can search for settings that are good on all of them. scores each response from 0 to 1, and combines the scores with a geometric mean, so a zero on any response rules a setting out.
The second-order model for Yield explains 28.3% of the variation. The stationary point is a maximum at Time = 86.862, Temp = 176.673, predicted Yield 82.136. Most desirable settings: Time = 85.353, Temp = 174.647 (D = 0.897).
- R²
- 0.2826
- Adjusted R²
- −0.1658
- Lack of fit p
- 0.1928
- Overall desirability
- 0.8970
Coefficients — Yield (coded units)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| (Intercept) | 81.866 | 1.205 | 67.923 | < .001 |
| Time | 0.9325 | 1.044 | 0.8933 | .398 |
| Temp | 0.5777 | 1.044 | 0.5534 | .595 |
| Time × Temp | 0.1250 | 1.476 | 0.0847 | .935 |
| Time² | −1.308 | 1.087 | −1.204 | .263 |
| Temp² | −0.9330 | 1.087 | −0.8586 | .416 |
Analysis of variance — Yield
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| First-order | 2 | 9.626 | 4.813 | 0.5522 | .596 |
| Two-way interaction | 1 | 0.0625 | 0.0625 | 0.0072 | .935 |
| Pure quadratic | 2 | 17.779 | 8.890 | 1.020 | .403 |
| Residuals | 8 | 69.730 | 8.716 | — | — |
| Lack of fit | 3 | 40.557 | 13.519 | 2.317 | .193 |
| Pure error | 5 | 29.173 | 5.835 | — | — |
Coefficients — Cost (coded units)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| (Intercept) | 20.350 | 0.0535 | 380.15 | < .001 |
| Time | 0.0154 | 0.0464 | 0.3320 | .748 |
| Temp | 0.2868 | 0.0464 | 6.187 | < .001 |
| Time × Temp | −0.0575 | 0.0656 | −0.8770 | .406 |
| Time² | 1.970 | 0.0483 | 40.814 | < .001 |
| Temp² | −0.0458 | 0.0483 | −0.9490 | .370 |
Analysis of variance — Cost
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| First-order | 2 | 0.6600 | 0.3300 | 19.192 | < .001 |
| Two-way interaction | 1 | 0.0132 | 0.0132 | 0.7692 | .406 |
| Pure quadratic | 2 | 28.929 | 14.464 | 841.25 | < .001 |
| Residuals | 8 | 0.1376 | 0.0172 | — | — |
| Lack of fit | 3 | 0.0886 | 0.0295 | 3.012 | .133 |
| Pure error | 5 | 0.0490 | 0.0098 | — | — |
Stationary point (maximum) — Yield
| Factor | Coded | Actual |
|---|---|---|
| Time | 0.3724 | 86.862 |
| Temp | 0.3345 | 176.67 |
Canonical analysis (eigenvalues and eigenvectors)
| Axis | Eigenvalue | Time | Temp |
|---|---|---|---|
| W1 | −0.9229 | 0.1601 | 0.9871 |
| W2 | −1.318 | 0.9871 | −0.1601 |
Path of steepest ascent (first-order fit, Yield)
| Distance (coded) | Time | Temp | Predicted Yield |
|---|---|---|---|
| 0 | 85 | 175 | 80.586 |
| 0.5000 | 87.125 | 176.32 | 81.134 |
| 1 | 89.250 | 177.63 | 81.683 |
| 1.500 | 91.376 | 178.95 | 82.231 |
| 2 | 93.501 | 180.27 | 82.780 |
| 2.500 | 95.626 | 181.58 | 83.328 |
| 3 | 97.751 | 182.90 | 83.877 |
| 3.500 | 99.877 | 184.22 | 84.425 |
| 4 | 102.00 | 185.53 | 84.974 |
| 4.500 | 104.13 | 186.85 | 85.522 |
| 5 | 106.25 | 188.17 | 86.071 |
Most desirable settings (overall D = 0.897)
| Factor / response | Setting / prediction | Desirability |
|---|---|---|
| Time | 85.353 | — |
| Temp | 174.65 | — |
| Yield | 81.879 | 0.9699 |
| Cost | 20.341 | 0.8296 |
- Coded units: Time: (Time − 85.0000) / 5.0000, Temp: (Temp − 175.0000) / 5.0000.
The exact R script · R R version 4.5.1 (2025-06-13)
# Response surface analysis (canonical analysis, steepest ascent, desirability)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.rsm 1.0.1 · spec 1b94aa38305f0a1b
# 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_rsm_*(): twin of codesplash.quality.rsm (same fits, canonical analysis, grid search)
# Classic equivalent: library(rsm); fit <- rsm(y ~ SO(x1, x2), data = coded.data(df, x1 ~ (Time - 85) / 5, ...));
# canonical(fit); steepest(rsm(y ~ FO(x1, x2), ...)); desirability via desirability2.
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_chemreact.parquet", col_select = c("Yield", "Cost", "Time", "Temp")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Yield", "Cost", "Time", "Temp")]), , 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("Yield", "Cost", "Time", "Temp")) # infinite values stop the run (registry/errors.yaml)
# %% Coding
responses <- c("Yield", "Cost")
factors_ <- c("Time", "Temp")
block_col <- NULL
block <- if (!is.null(block_col)) as.character(df[[block_col]]) else NULL
given <- cs_doe_rsm_parse_coding("")
unknown <- setdiff(names(given), factors_)
if (length(unknown)) stop(sprintf("Coding names %s are not among the factors.", paste(unknown, collapse = ", ")), call. = FALSE)
lh <- lapply(factors_, function(f) if (!is.null(given[[f]])) given[[f]] else cs_doe_rsm_auto_coding(df[[f]]))
lows <- vapply(lh, `[`, 0, 1); highs <- vapply(lh, `[`, 0, 2)
if (any(highs == lows)) {
f1 <- factors_[highs == lows][1]
if (is.null(given[[f1]])) cs_error("CS_E_CONSTANT", column = f1) # a single setting in the data: nothing to code
stop(sprintf("“%s” has a single setting; it cannot be coded.", f1), call. = FALSE)
}
for (r in responses) { # a constant response has no surface to fit
if (length(unique(df[[r]])) < 2) cs_error("CS_E_CONSTANT", column = r)
}
center <- (lows + highs) / 2
half <- (highs - lows) / 2
X <- as.matrix(df[, factors_, drop = FALSE])
xc <- sweep(sweep(X, 2, center), 2, half, "/")
k <- length(factors_)
model <- "so"
alpha <- 0.05
model_label <- switch(model, so = "second-order", twi = "first-order-with-interactions", fo = "first-order")
# %% Fits
fits <- lapply(responses, function(r) cs_doe_rsm_fit(df[[r]], xc, factors_, model, block))
f0 <- fits[[1]]
fo <- cs_doe_rsm_fit(df[[responses[1]]], xc, factors_, "fo", block)
design_r <- max(abs(xc))
radius <- if ("design" == "design") design_r else 1
to_actual <- function(c) center + half * c
# %% Canonical analysis
can <- if (model == "so") cs_doe_rsm_canonical(f0, k) else NULL
xs <- if (!is.null(can)) can$xs else NULL
inside <- !is.null(can) && max(abs(xs)) <= design_r + 1e-9
y_stat <- if (!is.null(can)) cs_doe_rsm_predict(f0, xs) else NaN
# %% Steepest ascent / descent (first-order fit)
path <- cs_doe_rsm_steepest(fo, k, descent = FALSE)
# %% Desirability
goals <- cs_doe_rsm_parse_goals("Yield: max 78 82; Cost: min 20 22", responses)
grid_n <- NULL
if (is.null(grid_n)) grid_n <- cs_doe_rsm_default_grid(k)
best <- if (length(goals)) cs_doe_rsm_optimize(fits, goals, responses, k, grid_n, radius) else NULL
# %% Tables
tables <- list()
anova_cols <- list(list(key = "source", label = "Source", type = "string"), list(key = "df", label = "df", type = "integer"),
list(key = "ss", label = "SS", type = "number"), list(key = "ms", label = "MS", type = "number"),
list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue"))
for (i in seq_along(responses)) {
f <- fits[[i]]
tables[[length(tables) + 1]] <- list(
key = paste0("coef-", responses[i]), title = sprintf("Coefficients — %s (coded units)", responses[i]),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
list(key = "p", label = "p", type = "pvalue")),
rows = lapply(seq_along(f$beta), function(j) list(term = f$coef_names[j], coef = f$beta[j], se = f$se[j], t = f$t[j], p = f$p[j])))
tables[[length(tables) + 1]] <- list(key = paste0("anova-", responses[i]), title = sprintf("Analysis of variance — %s", responses[i]),
columns = anova_cols, rows = f$anova)
}
if (!is.null(can)) {
tables[[length(tables) + 1]] <- list(
key = "stationary", title = sprintf("Stationary point (%s) — %s", can$kind, responses[1]),
columns = list(list(key = "factor", label = "Factor", type = "string"), list(key = "coded", label = "Coded", type = "number"),
list(key = "actual", label = "Actual", type = "number")),
rows = lapply(seq_len(k), function(j) list(factor = factors_[j], coded = xs[j], actual = to_actual(xs)[j])))
tables[[length(tables) + 1]] <- list(
key = "canonical", title = "Canonical analysis (eigenvalues and eigenvectors)",
columns = c(list(list(key = "axis", label = "Axis", type = "string"), list(key = "eigenvalue", label = "Eigenvalue", type = "number")),
lapply(seq_len(k), function(i) list(key = paste0("v", i - 1), label = factors_[i], type = "number"))),
rows = lapply(seq_len(k), function(j) {
row <- list(axis = paste0("W", j), eigenvalue = can$eigenvalues[j])
for (i in seq_len(k)) row[[paste0("v", i - 1)]] <- can$eigenvectors[i, j]
row
}))
}
tables[[length(tables) + 1]] <- list(
key = "ascent", title = sprintf("Path of steepest %s (first-order fit, %s)", if (FALSE) "descent" else "ascent", responses[1]),
columns = c(list(list(key = "dist", label = "Distance (coded)", type = "number")),
lapply(seq_len(k), function(i) list(key = paste0("a", i - 1), label = factors_[i], type = "number")),
list(list(key = "pred", label = paste("Predicted", responses[1]), type = "number"))),
rows = lapply(seq_along(path$dist), function(i) {
row <- list(dist = path$dist[i], pred = path$pred[i])
a <- to_actual(path$coded[i, ])
for (j in seq_len(k)) row[[paste0("a", j - 1)]] <- a[j]
row
}))
if (!is.null(best)) {
ba <- to_actual(best$coded)
tables[[length(tables) + 1]] <- list(
key = "desirability", title = sprintf("Most desirable settings (overall D = %.3f)", best$D),
columns = list(list(key = "name", label = "Factor / response", type = "string"), list(key = "value", label = "Setting / prediction", type = "number"),
list(key = "d", label = "Desirability", type = "number")),
rows = c(lapply(seq_len(k), function(j) list(name = factors_[j], value = ba[j], d = NULL)),
lapply(seq_along(goals), function(i) list(name = goals[[i]]$response, value = best$pred[[goals[[i]]$response]], d = best$d[i]))))
}
# %% Charts
cx <- ""; if (!nzchar(cx)) cx <- factors_[1]
cy <- ""; if (!nzchar(cy)) cy <- setdiff(factors_, cx)[1]
if (!cx %in% factors_ || !cy %in% factors_ || cx == cy) stop("Contour factors must be two different factors of the analysis.", call. = FALSE)
ix <- match(cx, factors_); iy <- match(cy, factors_)
base <- if (!is.null(can) && inside) xs else rep(0, k)
gx <- seq(min(xc[, ix]), max(xc[, ix]), length.out = 41)
gy <- seq(min(xc[, iy]), max(xc[, iy]), length.out = 41)
pts <- matrix(base, 41 * 41, k, byrow = TRUE)
pts[, ix] <- rep(gx, 41)
pts[, iy] <- rep(gy, each = 41)
z <- cs_doe_rsm_predict(f0, pts)
y0 <- as.numeric(df[[responses[1]]])
charts <- list(cs_chart(
"contour", "contour-grid", sprintf("Fitted %s over %s and %s", responses[1], cx, cy),
list(x = cs_col(cx, c(center[ix] + half[ix] * pts[, ix], X[, ix])),
y = cs_col(cy, c(center[iy] + half[iy] * pts[, iy], X[, iy])),
z = cs_col(responses[1], c(z, y0)),
kind = cs_col("Kind", c(rep("grid", length(z)), rep("point", length(y0))), "categorical")),
controls = list(levels = 10)))
if (f0$df_resid > 0) charts[[2]] <- cs_chart(
"residuals", "residual-panel", sprintf("Residual diagnostics — %s", responses[1]),
list(fitted = cs_col("Fitted values", f0$fitted), residual = cs_col("Residuals", f0$resid)))
# %% Result
fmt3 <- function(v) cs_fmt_num(v, 3)
stat_text <- if (!is.null(can)) paste(sprintf("%s = %s", factors_, vapply(to_actual(xs), fmt3, "")), collapse = ", ") else ""
best_text <- if (!is.null(best)) paste(sprintf("%s = %s", factors_, vapply(to_actual(best$coded), fmt3, "")), collapse = ", ") else ""
values <- list(
n = length(y0), model_label = model_label, terms = I(f0$coef_names), coef = I(f0$beta), p = I(f0$p),
r2 = f0$r2, adj_r2 = f0$adj_r2, s = f0$s, lof_p = f0$lof_p,
stationary_coded = if (!is.null(can)) I(xs) else NULL, stationary_actual = if (!is.null(can)) I(to_actual(xs)) else NULL,
eigenvalues = if (!is.null(can)) I(can$eigenvalues) else NULL, kind = if (!is.null(can)) can$kind else NULL,
y_stationary = if (!is.null(can)) y_stat else NULL, stationary_inside = inside, stationary_text = stat_text,
ascent_coded = path$coded, ascent_pred = I(path$pred),
desirability = if (!is.null(best)) best$D else NULL, best_coded = if (!is.null(best)) I(best$coded) else NULL,
best_actual = if (!is.null(best)) I(to_actual(best$coded)) else NULL,
best_pred = if (!is.null(best)) I(unname(best$pred)) else NULL, best_text = best_text,
all_coef = lapply(fits, function(f) I(f$beta))
)
summary <- sprintf("The %s model for %s explains %.1f%% of the variation.", model_label, responses[1], 100 * f0$r2)
if (!is.null(can)) summary <- paste(summary, sprintf("The stationary point is a %s at %s, predicted %s %s.", can$kind, stat_text, responses[1], fmt3(y_stat)))
if (!is.null(best)) summary <- paste(summary, sprintf("Most desirable settings: %s (D = %.3f).", best_text, best$D))
extra <- list()
if (!is.null(can) && !inside) extra <- c(extra, "The stationary point lies outside the design region; follow the ridge or run more experiments there before trusting it.")
if (!is.null(can) && can$ridge) extra <- c(extra, "One eigenvalue is near zero: the surface has a ridge, so many settings give nearly the same response.")
if (model == "so" && is.null(can)) extra <- c(extra, "The quadratic part is singular; no unique stationary point.")
stats_list <- list(list(key = "r2", label = "R²", value = f0$r2), list(key = "adj_r2", label = "Adjusted R²", value = f0$adj_r2),
list(key = "lof_p", label = "Lack of fit p", value = f0$lof_p, format = "pvalue"))
if (!is.null(best)) stats_list[[length(stats_list) + 1]] <- list(key = "desirability", label = "Overall desirability", value = best$D)
cs_publish(list(
method = "doe.rsm",
methodVersion = "1.0.1",
title = "Response surface analysis (canonical analysis, steepest ascent, desirability)",
engine = cs_engine_info("stats", "codesplashr"),
n = length(y0),
summary = summary,
statistics = stats_list,
tables = tables,
charts = charts,
warnings = c(warnings, extra),
notes = list(sprintf("Coded units: %s.", paste(sprintf("%s: (%s − %s) / %s", factors_, factors_, vapply(center, function(v) cs_fmt_num(v, 4), ""),
vapply(half, function(v) cs_fmt_num(v, 4), "")), collapse = ", "))),
values = values
))
The second-order model for Yield explains 28.3% of the variation. The stationary point is a maximum at Time = 86.862, Temp = 176.673, predicted Yield 82.136. Most desirable settings: Time = 85.353, Temp = 174.647 (D = 0.897).
- R²
- 0.2826
- Adjusted R²
- −0.1658
- Lack of fit p
- 0.1928
- Overall desirability
- 0.8970
Coefficients — Yield (coded units)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| (Intercept) | 81.866 | 1.205 | 67.923 | < .001 |
| Time | 0.9325 | 1.044 | 0.8933 | .398 |
| Temp | 0.5777 | 1.044 | 0.5534 | .595 |
| Time × Temp | 0.1250 | 1.476 | 0.0847 | .935 |
| Time² | −1.308 | 1.087 | −1.204 | .263 |
| Temp² | −0.9330 | 1.087 | −0.8586 | .416 |
Analysis of variance — Yield
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| First-order | 2 | 9.626 | 4.813 | 0.5522 | .596 |
| Two-way interaction | 1 | 0.0625 | 0.0625 | 0.0072 | .935 |
| Pure quadratic | 2 | 17.779 | 8.890 | 1.020 | .403 |
| Residuals | 8 | 69.730 | 8.716 | — | — |
| Lack of fit | 3 | 40.557 | 13.519 | 2.317 | .193 |
| Pure error | 5 | 29.173 | 5.835 | — | — |
Coefficients — Cost (coded units)
| Term | Estimate | SE | t | p |
|---|---|---|---|---|
| (Intercept) | 20.350 | 0.0535 | 380.15 | < .001 |
| Time | 0.0154 | 0.0464 | 0.3320 | .748 |
| Temp | 0.2868 | 0.0464 | 6.187 | < .001 |
| Time × Temp | −0.0575 | 0.0656 | −0.8770 | .406 |
| Time² | 1.970 | 0.0483 | 40.814 | < .001 |
| Temp² | −0.0458 | 0.0483 | −0.9490 | .370 |
Analysis of variance — Cost
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| First-order | 2 | 0.6600 | 0.3300 | 19.192 | < .001 |
| Two-way interaction | 1 | 0.0132 | 0.0132 | 0.7692 | .406 |
| Pure quadratic | 2 | 28.929 | 14.464 | 841.25 | < .001 |
| Residuals | 8 | 0.1376 | 0.0172 | — | — |
| Lack of fit | 3 | 0.0886 | 0.0295 | 3.012 | .133 |
| Pure error | 5 | 0.0490 | 0.0098 | — | — |
Stationary point (maximum) — Yield
| Factor | Coded | Actual |
|---|---|---|
| Time | 0.3724 | 86.862 |
| Temp | 0.3345 | 176.67 |
Canonical analysis (eigenvalues and eigenvectors)
| Axis | Eigenvalue | Time | Temp |
|---|---|---|---|
| W1 | −0.9229 | 0.1601 | 0.9871 |
| W2 | −1.318 | 0.9871 | −0.1601 |
Path of steepest ascent (first-order fit, Yield)
| Distance (coded) | Time | Temp | Predicted Yield |
|---|---|---|---|
| 0 | 85 | 175 | 80.586 |
| 0.5000 | 87.125 | 176.32 | 81.134 |
| 1 | 89.250 | 177.63 | 81.683 |
| 1.500 | 91.376 | 178.95 | 82.231 |
| 2 | 93.501 | 180.27 | 82.780 |
| 2.500 | 95.626 | 181.58 | 83.328 |
| 3 | 97.751 | 182.90 | 83.877 |
| 3.500 | 99.877 | 184.22 | 84.425 |
| 4 | 102.00 | 185.53 | 84.974 |
| 4.500 | 104.13 | 186.85 | 85.522 |
| 5 | 106.25 | 188.17 | 86.071 |
Most desirable settings (overall D = 0.897)
| Factor / response | Setting / prediction | Desirability |
|---|---|---|
| Time | 85.353 | — |
| Temp | 174.65 | — |
| Yield | 81.879 | 0.9699 |
| Cost | 20.341 | 0.8296 |
- Coded units: Time: (Time − 85.0000) / 5.0000, Temp: (Temp − 175.0000) / 5.0000.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Response surface analysis (canonical analysis, steepest ascent, desirability)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.rsm 1.0.1 · spec 1b94aa38305f0a1b
# 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 rsm # twin of codesplashr::cs_doe_rsm_* (same fits, canonical analysis, grid search)
# Classic equivalent: R's rsm package — rsm(y ~ SO(x1, x2)), canonical(), steepest(); in Python
# statsmodels.formula.api.ols("y ~ x1 + x2 + I(x1**2) + I(x2**2) + x1:x2") on coded data.
# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_chemreact.parquet", columns=["Yield", "Cost", "Time", "Temp"])
n_input = len(df)
df = df.dropna(subset=["Yield", "Cost", "Time", "Temp"]) # 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, ["Yield", "Cost", "Time", "Temp"]) # infinite values stop the run (registry/errors.yaml)
# %% Coding
RESPONSES = ["Yield", "Cost"]
FACTORS = ["Time", "Temp"]
block_col = None
def _label(v):
return str(int(v)) if isinstance(v, float) and v.is_integer() else str(v)
block = [_label(v) for v in df[block_col]] if block_col else None # numeric blocks labeled like R's as.character()
given = rsm.parse_coding("")
unknown = [n for n in given if n not in FACTORS]
if unknown:
raise ValueError(f"Coding names {', '.join(unknown)} are not among the factors.")
lows, highs = [], []
for f in FACTORS:
lo, hi = given.get(f) or rsm.auto_coding(df[f].to_numpy(dtype=float))
if hi == lo:
if f not in given: # a single setting in the data: nothing to code
cs.cs_error("CS_E_CONSTANT", column=f)
raise ValueError(f"“{f}” has a single setting; it cannot be coded.")
lows.append(lo)
highs.append(hi)
for r in RESPONSES: # a constant response has no surface to fit
if df[r].nunique() < 2:
cs.cs_error("CS_E_CONSTANT", column=r)
center = (np.asarray(lows) + np.asarray(highs)) / 2
half = (np.asarray(highs) - np.asarray(lows)) / 2
X = df[FACTORS].to_numpy(dtype=float)
xc = (X - center) / half
k = len(FACTORS)
model = "so"
alpha = 0.05
model_label = {"so": "second-order", "twi": "first-order-with-interactions", "fo": "first-order"}[model]
# %% Fits
fits = [rsm.fit(df[r].to_numpy(dtype=float), xc, FACTORS, model, block) for r in RESPONSES]
f0 = fits[0]
fo = rsm.fit(df[RESPONSES[0]].to_numpy(dtype=float), xc, FACTORS, "fo", block)
radius = float(np.max(np.abs(xc))) if "design" == "design" else 1.0
design_r = float(np.max(np.abs(xc)))
def to_actual(c):
return (center + half * np.asarray(c)).tolist()
# %% Canonical analysis
can = rsm.canonical(f0, k) if model == "so" else None
xs = can["xs"] if can else None
inside = bool(can and np.max(np.abs(xs)) <= design_r + 1e-9)
y_stat = float(rsm.predict(f0, xs)[0]) if can else float("nan")
# %% Steepest ascent / descent (first-order fit)
path = rsm.steepest(fo, k, descent=False)
# %% Desirability
goals = rsm.parse_goals("Yield: max 78 82; Cost: min 20 22", RESPONSES)
grid_n = None or rsm.default_grid(k)
best = rsm.optimize(fits, goals, RESPONSES, k, int(grid_n), radius) if goals else None
# %% Tables
tables = []
for r, f in zip(RESPONSES, fits):
tables.append({
"key": f"coef-{r}", "title": f"Coefficients — {r} (coded units)",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}],
"rows": [{"term": n, "coef": b, "se": s, "t": t, "p": p} for n, b, s, t, p in zip(f["coef_names"], f["beta"], f["se"], f["t"], f["p"])],
})
tables.append({
"key": f"anova-{r}", "title": f"Analysis of variance — {r}",
"columns": [{"key": "source", "label": "Source", "type": "string"}, {"key": "df", "label": "df", "type": "integer"},
{"key": "ss", "label": "SS", "type": "number"}, {"key": "ms", "label": "MS", "type": "number"},
{"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": f["anova"],
})
if can:
tables.append({
"key": "stationary", "title": f"Stationary point ({can['kind']}) — {RESPONSES[0]}",
"columns": [{"key": "factor", "label": "Factor", "type": "string"}, {"key": "coded", "label": "Coded", "type": "number"},
{"key": "actual", "label": "Actual", "type": "number"}],
"rows": [{"factor": n, "coded": float(c), "actual": a} for n, c, a in zip(FACTORS, xs, to_actual(xs))],
})
erows = []
for j, ev in enumerate(can["eigenvalues"]):
row = {"axis": f"W{j + 1}", "eigenvalue": float(ev)}
for i, n in enumerate(FACTORS):
row[f"v{i}"] = float(can["eigenvectors"][i, j])
erows.append(row)
tables.append({
"key": "canonical", "title": "Canonical analysis (eigenvalues and eigenvectors)",
"columns": [{"key": "axis", "label": "Axis", "type": "string"}, {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"}]
+ [{"key": f"v{i}", "label": n, "type": "number"} for i, n in enumerate(FACTORS)],
"rows": erows,
})
prow = []
for d_, c, yhat in zip(path["dist"], path["coded"], path["pred"]):
row = {"dist": float(d_), "pred": float(yhat)}
for i, a in enumerate(to_actual(c)):
row[f"a{i}"] = a
prow.append(row)
tables.append({
"key": "ascent", "title": f"Path of steepest {'descent' if False else 'ascent'} (first-order fit, {RESPONSES[0]})",
"columns": [{"key": "dist", "label": "Distance (coded)", "type": "number"}]
+ [{"key": f"a{i}", "label": n, "type": "number"} for i, n in enumerate(FACTORS)]
+ [{"key": "pred", "label": f"Predicted {RESPONSES[0]}", "type": "number"}],
"rows": prow,
})
if best:
tables.append({
"key": "desirability", "title": f"Most desirable settings (overall D = {best['D']:.3f})",
"columns": [{"key": "name", "label": "Factor / response", "type": "string"}, {"key": "value", "label": "Setting / prediction", "type": "number"},
{"key": "d", "label": "Desirability", "type": "number"}],
"rows": [{"name": n, "value": a, "d": None} for n, a in zip(FACTORS, to_actual(best["coded"]))]
+ [{"name": g["response"], "value": best["pred"][g["response"]], "d": dv} for g, dv in zip(goals, best["d"])],
})
# %% Charts
charts = []
cx = "" or FACTORS[0]
cy = "" or next(f for f in FACTORS if f != cx)
if cx not in FACTORS or cy not in FACTORS or cx == cy:
raise ValueError("Contour factors must be two different factors of the analysis.")
ix, iy = FACTORS.index(cx), FACTORS.index(cy)
base = xs.copy() if (can and inside) else np.zeros(k)
gx = np.linspace(float(xc[:, ix].min()), float(xc[:, ix].max()), 41)
gy = np.linspace(float(xc[:, iy].min()), float(xc[:, iy].max()), 41)
pts = np.tile(base, (41 * 41, 1))
pts[:, ix] = np.tile(gx, 41)
pts[:, iy] = np.repeat(gy, 41)
z = rsm.predict(f0, pts)
y0 = df[RESPONSES[0]].to_numpy(dtype=float)
charts.append(cs.chart(
"contour", "contour-grid", f"Fitted {RESPONSES[0]} over {cx} and {cy}",
{"x": cs.col(cx, (center[ix] + half[ix] * pts[:, ix]).tolist() + X[:, ix].tolist()),
"y": cs.col(cy, (center[iy] + half[iy] * pts[:, iy]).tolist() + X[:, iy].tolist()),
"z": cs.col(RESPONSES[0], z.tolist() + y0.tolist()),
"kind": cs.col("Kind", ["grid"] * len(z) + ["point"] * len(y0), "categorical")},
controls={"levels": 10},
))
if f0["df_resid"] > 0:
charts.append(cs.chart(
"residuals", "residual-panel", f"Residual diagnostics — {RESPONSES[0]}",
{"fitted": cs.col("Fitted values", f0["fitted"].tolist()), "residual": cs.col("Residuals", f0["resid"].tolist())},
))
# %% Result
coef_p = f0["p"]
stat_text = ", ".join(f"{n} = {cs.fmt_num(a, 3)}" for n, a in zip(FACTORS, to_actual(xs))) if can else ""
best_text = ", ".join(f"{n} = {cs.fmt_num(a, 3)}" for n, a in zip(FACTORS, to_actual(best["coded"]))) if best else ""
values = {
"n": len(y0), "model_label": model_label, "terms": list(f0["coef_names"]), "coef": [float(b) for b in f0["beta"]], "p": [float(p) for p in coef_p],
"r2": f0["r2"], "adj_r2": f0["adj_r2"], "s": f0["s"], "lof_p": f0["lof_p"],
"stationary_coded": [float(v) for v in xs] if can else None, "stationary_actual": to_actual(xs) if can else None,
"eigenvalues": [float(v) for v in can["eigenvalues"]] if can else None, "kind": can["kind"] if can else None,
"y_stationary": y_stat if can else None, "stationary_inside": inside, "stationary_text": stat_text,
"ascent_coded": path["coded"].tolist(), "ascent_pred": path["pred"].tolist(),
"desirability": best["D"] if best else None, "best_coded": best["coded"].tolist() if best else None,
"best_actual": to_actual(best["coded"]) if best else None,
"best_pred": [best["pred"][r] for r in RESPONSES] if best else None, "best_text": best_text,
"all_coef": [[float(b) for b in f["beta"]] for f in fits],
}
summary = f"The {model_label} model for {RESPONSES[0]} explains {100 * f0['r2']:.1f}% of the variation."
if can:
summary += f" The stationary point is a {can['kind']} at {stat_text}, predicted {RESPONSES[0]} {cs.fmt_num(y_stat, 3)}."
if best:
summary += f" Most desirable settings: {best_text} (D = {best['D']:.3f})."
warnings_extra = []
if can and not inside:
warnings_extra.append("The stationary point lies outside the design region; follow the ridge or run more experiments there before trusting it.")
if can and can["ridge"]:
warnings_extra.append("One eigenvalue is near zero: the surface has a ridge, so many settings give nearly the same response.")
if model == "so" and not can:
warnings_extra.append("The quadratic part is singular; no unique stationary point.")
cs.publish({
"title": "Response surface analysis (canonical analysis, steepest ascent, desirability)",
"engine": cs.engine_info("numpy", "scipy"),
"n": len(y0),
"summary": summary,
"statistics": [
{"key": "r2", "label": "R²", "value": f0["r2"]},
{"key": "adj_r2", "label": "Adjusted R²", "value": f0["adj_r2"]},
{"key": "lof_p", "label": "Lack of fit p", "value": f0["lof_p"], "format": "pvalue"},
] + ([{"key": "desirability", "label": "Overall desirability", "value": best["D"]}] if best else []),
"tables": tables,
"charts": charts,
"warnings": warnings + warnings_extra,
"notes": [f"Coded units: {', '.join(f'{n}: ({n} − {cs.fmt_num(c, 4)}) / {cs.fmt_num(h, 4)}' for n, c, h in zip(FACTORS, center, half))}."],
"values": values,
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
With yield rising from 78 to 82, and cost falling from 22 to 20, the best compromise is Time = 85.353, Temp = 174.647, at an overall desirability of 0.897. It's not where yield peaks, because cost counts too. The goals are your judgment: change them, and the answer changes.
Which design?
ReadSecond-order models need three or more levels:
- Central composite: a factorial, plus axial points and center points. It builds on a factorial you've already run. A five-factor face-centered version takes 32 runs.
- Box–Behnken: no corner runs, which helps when extreme combinations are unsafe or impossible. A three-factor version here takes 15 runs, and finds a maximum at pH = 7.061, Temperature (°C) = 36.045, Enzyme = 2.282.
Check your understanding
CheckpointCheck yourself
The stationary point is a maximum, but it lies outside the region you tested. What do you do?
Show the answer
Answer: b
The model is only trustworthy where you have data. The app says when the point lies outside the design region.
Check yourself
The eigenvalues have opposite signs. What does the surface look like?
Show the answer
Answer: c
At a saddle, the stationary point is neither best nor worst. Follow the direction that improves the response, and test further.
Check yourself
Why combine desirabilities with a geometric mean, rather than an arithmetic one?
Show the answer
Answer: a
With an arithmetic mean, an excellent yield could offset an unacceptable cost. With a geometric mean, a zero on either response makes the overall score zero.
Check yourself
Put a response surface study in order.
Show the answer
The order:
- Screen many factors to find the few that matter.
- Follow the path of steepest ascent toward better settings.
- Fit a second-order model near the best region.
- Confirm the predicted optimum with new runs.
Each stage narrows the region and spends runs where they tell you most. Confirmation runs check the model's promise.
Try it
In the appIn the Quality studio, choose Response surface (central composite). After you've entered your responses, open the Response surface step. Goals go in the Desirability goals option.
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("chemreact.csv")
df["x1"] = (df["Time"] - 85) / 5
df["x2"] = (df["Temp"] - 175) / 5
fit = smf.ols("Yield ~ C(Block) + x1 + x2 + x1:x2 + I(x1**2) + I(x2**2)", df).fit()
p = fit.params
b = np.array([p["x1"], p["x2"]])
B = np.array([[p["I(x1 ** 2)"], p["x1:x2"] / 2], [p["x1:x2"] / 2, p["I(x2 ** 2)"]]])
xs = -0.5 * np.linalg.solve(B, b)
print("Time", 85 + 5 * xs[0], "Temp", 175 + 5 * xs[1])
print("eigenvalues", np.linalg.eigvalsh(B))library(rsm)
df <- read.csv("chemreact.csv")
coded <- coded.data(df, x1 ~ (Time - 85) / 5, x2 ~ (Temp - 175) / 5)
fit <- rsm(Yield ~ Block + SO(x1, x2), data = coded)
summary(fit)Recap
Recap- A first-order model points the way. A second-order model maps the peak.
- Eigenvalues classify the stationary point. Check that it's inside your design.
- Desirability balances several responses, and the goals are your judgment.
- Confirm the optimum with new runs.
Concepts in this lesson