GQuality & process · doe.rsm
Response surface analysis (canonical analysis, steepest ascent, desirability)
Which factor settings give the best response, and what shape does the response surface have?
Fits first- or second-order response-surface models in coded units (with blocks), tests lack of fit against pure error, locates and classifies the stationary point by canonical analysis, gives the path of steepest ascent from the first-order fit, and finds settings that balance several responses with Derringer–Suich desirability. Contour plots show the fitted surface.
A real result
Example “Chemreact blocked”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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 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.
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Chemreact blockedq1_chemreact · block: Block · factors: Time, Temp · responses: Yield
- Chemreact desirabilityq1_chemreact · factors: Time, Temp · responses: Yield, Cost
- Bbd threeq1_bbd · factors: pH, Temperature (°C), Enzyme · responses: Activity
- First order ascentq1_chemreact · factors: Time, Temp · responses: Yield
- Degenerate constantq1_chemreact · block: Block · factors: Time, Temp · responses: Yield
- Degenerate n1q1_chemreact · block: Block · factors: Time, Temp · responses: Yield
- Degenerate n3q1_chemreact · block: Block · factors: Time, Temp · responses: Yield
- Degenerate single levelq1_chemreact · block: Block · factors: Time, Temp · responses: Yield
In the guides
Where it sits in the decision guides
- Statistical optimization (regression, response surface) · DS & ML Decision Guide · Optimize / decide
What you need
- Responsesnumeric · 1–5 columns
- The first response is the primary one (contours, canonical analysis); all are used for desirability.
- Factorsnumeric · 2–8 columns
- Numeric factors in actual units.
- Blockcategorical / numeric · 0–1 column
- Optional blocks (e.g. the factorial and axial blocks of a central composite design).
Choices you make
hypothesis
- Modeldefault so
Terms in the response-surface model. Second order adds squared terms, so it can find a peak or a valley.
- Second order (quadratic)(default) — Adds squares and interactions; pick it to find a peak or valley, from a design with center and axial points.
- First order with two-factor interactions — Adds interactions to straight-line effects; pick it for a twisted surface with no curvature.
- First order — Fits straight-line effects only; pick it to find the direction of steepest ascent.
- Significance level (α)default 0.05
The false-alarm rate you accept: the chance of a significant result when there is truly no effect. 0.05 is conventional.
options
- Codingdefault —
“Name: low, high” per factor maps the low/high settings to −1/+1. Empty = automatic (central composite axial levels are recognized).
- Desirability goalsdefault —
e.g. “Yield: max 80 90; Cost: min 18 25; Purity: target 95 98 100”, optionally with weights. Empty = no optimization.
- Search regiondefault cube
Where to search for the optimum: inside the coded cube, or out to the axial points.
- Cube (−1 to +1 coded)(default) — Searches within −1 to +1 coded, where the design has the most data; the safer choice.
- Design region (to the axial points) — Searches out to the axial points; a wider range, with fewer runs near its edges.
- Path of steepest descent (minimize)default off
Follow the path of steepest descent (to minimize) instead of ascent.
Advanced
- Grid points per factordefault —
Grid points per factor for the response-surface search. Leave empty for the default.
plots
- Contour x-factordefault —
Factor on the contour plot's x-axis (empty = the first factor); other factors are held at the stationary point when it lies in the design region, else at the center.
- Contour y-factordefault —
Factor on the y-axis of the contour plot (the x-axis uses the first factor).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
No lack of fit
Replicated runs (e.g. center points) give a pure-error test of the model's form.
Normal residuals
Residual normal plot.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- terms
- Names of the fitted model's terms, intercept first, in the same order as the list of coefficients.
- coef
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- r2
- The share of the outcome's variance explained by the model, from 0 to 1.
- adj_r2
- R² penalized for the number of predictors, so adding useless ones lowers it.
- lof_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- stationary_coded
- Where a fitted surface is flat. Its eigenvalues show whether it's a maximum, a minimum or a saddle.
- stationary_actual
- Where a fitted surface is flat. Its eigenvalues show whether it's a maximum, a minimum or a saddle.
- eigenvalues
- Where a fitted surface is flat. Its eigenvalues show whether it's a maximum, a minimum or a saddle.
- kind
- Where a fitted surface is flat. Its eigenvalues show whether it's a maximum, a minimum or a saddle.
- y_stationary
- Where a fitted surface is flat. Its eigenvalues show whether it's a maximum, a minimum or a saddle.
- ascent_coded
- The direction in which a first-order model says the response rises fastest, used to move toward better settings.
- ascent_pred
- The direction in which a first-order model says the response rises fastest, used to move toward better settings.
- desirability
- Turns several responses into one 0–1 score so you can search for settings that are good on all of them.
- best_coded
- Turns several responses into one 0–1 score so you can search for settings that are good on all of them.
- best_actual
- Turns several responses into one 0–1 score so you can search for settings that are good on all of them.
- best_pred
- Turns several responses into one 0–1 score so you can search for settings that are good on all of them.
- best_text
- Factor settings (in actual units) of the best predicted point in the design region; empty when there is none.
- model_label
- Which polynomial was fitted: first-order (plane) or second-order (with curvature and interactions).
- stationary_inside
- True when the fitted surface's stationary point lies within the experimental region, so it can be trusted.
- stationary_text
- Factor settings (in actual units) where the fitted surface is flat: a maximum, minimum or saddle.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses numpy, pandas, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Least squares by numpy QR ↔ R lm.fit (QR); eigen-decomposition by LAPACK in both (numpy eigh ↔ R eigen) with eigenvector signs fixed (largest |component| positive) — rsm::canonical leaves the sign to LAPACK.
- Desirability is maximized on a grid (identical in both engines); a continuous optimizer could move the optimum slightly between grid points.
The exact script CodeSplash ran for example “Chemreact blocked” · 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,
})
The exact script CodeSplash ran for example “Chemreact blocked” · 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
))
Sources
- Box, G. E. P., & Wilson, K. B. (1951). On the experimental attainment of optimum conditions. JRSS B, 13, 1–45.
- Lenth, R. V. (2009). Response-surface methods in R, using rsm. Journal of Statistical Software, 32(7).
- Derringer, G., & Suich, R. (1980). Simultaneous optimization of several response variables. Journal of Quality Technology, 12, 214–219.
- Myers, R. H., Montgomery, D. C., & Anderson-Cook, C. M. (2016). Response surface methodology (4th ed.). Wiley.
From the CodeSplash method registry · doe.rsm v1.0.1.