Read the effects
Estimate main effects and interactions from a two-level experiment, judge them when you have no replicates, and test for curvature with center points.
What runs in CodeSplash
- Analyze a two-level factorial experiment (effects, Lenth, ANOVA) Verified in Python and R
You will be able to
- Compute a main effect, and interpret it alongside its interactions
- Use Lenth's method, and name what it assumes
- Read a curvature test and a predicted R²
Read first
An effect is a difference
ReadIn a two-level design, a factor's main effect is the average response at its high setting minus the average at its low setting:
Your experiment has four factors and 16 runs, measuring how fast a chemical filters. Each setting appears in half the runs, so every effect uses all the data.
What stands out?
In the app5 of 10 effects stand out (Temperature, Formaldehyde (%), Stirring, Temperature × Formaldehyde (%), Temperature × Stirring) at α = 0.05.
- Runs
- 16
- Center runs
- 0
- Residual df
- 5
- R²
- 0.9777
- S
- 5.056
Plots
View data
| Term | |t| |
|---|---|
| Temperature | 8.554 |
| Temperature × Formaldehyde (%) | 7.170 |
| Temperature × Stirring | 6.576 |
| Stirring | 5.785 |
| Formaldehyde (%) | 3.906 |
| Pressure | 1.236 |
| Pressure × Formaldehyde (%) | 0.9395 |
| Formaldehyde (%) × Stirring | 0.4450 |
| Pressure × Stirring | 0.1483 |
| Temperature × Pressure | 0.0494 |
View data
| |Effect| | Term | Half-normal quantile | Significant |
|---|---|---|---|
| 0.1250 | Temperature × Pressure | 0.0627 | false |
| 0.3750 | Pressure × Stirring | 0.1891 | false |
| 1.125 | Formaldehyde (%) × Stirring | 0.3186 | false |
| 2.375 | Pressure × Formaldehyde (%) | 0.4538 | false |
| 3.125 | Pressure | 0.5978 | false |
| 9.875 | Formaldehyde (%) | 0.7554 | true |
| 14.625 | Stirring | 0.9346 | true |
| 16.625 | Temperature × Stirring | 1.150 | true |
| 18.125 | Temperature × Formaldehyde (%) | 1.440 | true |
| 21.625 | Temperature | 1.960 | true |
View data
| Factor | Level | Mean Filtration rate |
|---|---|---|
| Temperature | 24.00 | 59.250 |
| Temperature | 35.00 | 80.875 |
| Pressure | 10.00 | 68.500 |
| Pressure | 15.00 | 71.625 |
| Formaldehyde (%) | 2.00 | 65.125 |
| Formaldehyde (%) | 4.00 | 75 |
| Stirring | slow | 62.750 |
| Stirring | fast | 77.375 |
View data
| Formaldehyde (%) | Temperature | Filtration rate |
|---|---|---|
| 2.00 | 24.00 | 45 |
| 2.00 | 35.00 | 71 |
| 2.00 | 24.00 | 48 |
| 2.00 | 35.00 | 65 |
| 4.00 | 24.00 | 68 |
| 4.00 | 35.00 | 60 |
| 4.00 | 24.00 | 80 |
| 4.00 | 35.00 | 65 |
| 2.00 | 24.00 | 43 |
| 2.00 | 35.00 | 100 |
| 2.00 | 24.00 | 45 |
| 2.00 | 35.00 | 104 |
| 4.00 | 24.00 | 75 |
| 4.00 | 35.00 | 86 |
| 4.00 | 24.00 | 70 |
| 4.00 | 35.00 | 96 |
View data
| Fitted values | Residuals |
|---|---|
| 45.188 | −0.1875 |
| 68.188 | 2.813 |
| 46.188 | 1.812 |
| 69.438 | −4.438 |
| 71.938 | −3.938 |
| 58.688 | 1.313 |
| 77.688 | 2.313 |
| 64.688 | 0.3125 |
| 44.688 | −1.688 |
| 100.94 | −0.9375 |
| 44.938 | 0.0625 |
| 101.44 | 2.563 |
| 69.188 | 5.813 |
| 89.188 | −3.188 |
| 74.188 | −4.188 |
| 94.438 | 1.563 |
Effects and coefficients (coded units)
| Term | Effect | Coefficient | SE | t | p |
|---|---|---|---|---|---|
| (Intercept) | — | 70.063 | 1.264 | 55.430 | < .001 |
| Temperature | 21.625 | 10.813 | 1.264 | 8.554 | < .001 |
| Pressure | 3.125 | 1.563 | 1.264 | 1.236 | .271 |
| Formaldehyde (%) | 9.875 | 4.938 | 1.264 | 3.906 | .011 |
| Stirring | 14.625 | 7.313 | 1.264 | 5.785 | .002 |
| Temperature × Pressure | 0.1250 | 0.0625 | 1.264 | 0.0494 | .962 |
| Temperature × Formaldehyde (%) | −18.125 | −9.063 | 1.264 | −7.170 | < .001 |
| Temperature × Stirring | 16.625 | 8.313 | 1.264 | 6.576 | .001 |
| Pressure × Formaldehyde (%) | 2.375 | 1.188 | 1.264 | 0.9395 | .391 |
| Pressure × Stirring | −0.3750 | −0.1875 | 1.264 | −0.1483 | .888 |
| Formaldehyde (%) × Stirring | −1.125 | −0.5625 | 1.264 | −0.4450 | .675 |
Analysis of variance (sequential)
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| Main effects | 4 | 3155.25 | 788.81 | 30.858 | .001 |
| 2-way interactions | 6 | 2447.88 | 407.98 | 15.960 | .004 |
| Residual error | 5 | 127.81 | 25.563 | — | — |
| Total | 15 | 5730.94 | — | — | — |
Factor coding
| Factor | Low (−1) | High (+1) | Center (0) |
|---|---|---|---|
| Temperature | 24.00 | 35.00 | 29.50 |
| Pressure | 10.00 | 15.00 | 12.50 |
| Formaldehyde (%) | 2.00 | 4.00 | 3.00 |
| Stirring | slow | fast | — |
- Effects are differences between the high and low settings (2 × the coded coefficient).
The exact R script · R R version 4.5.1 (2025-06-13)
# Analyze a two-level factorial experiment (effects, Lenth, ANOVA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.analyze 1.0.1 · spec 6522775f4b2584ee
# Dataset: q1_filtration (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_analyze(): coding, aliasing and Lenth twin of codesplash.quality.analyze
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_filtration.parquet", col_select = c("Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring")))
n_input <- nrow(df)
df[["Stirring"]] <- factor(df[["Stirring"]], levels = c("slow", "fast")) # stored level order
df <- df[stats::complete.cases(df[c("Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring")]), , 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("Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring")) # infinite values stop the run (registry/errors.yaml)
# %% Coding (low = -1, high = +1, center runs = 0)
y_name <- "Filtration rate"
factors_ <- c("Temperature", "Pressure", "Formaldehyde (%)", "Stirring")
kinds_ <- c("numeric", "numeric", "numeric", "categorical")
block_col <- NULL
y <- as.numeric(df[[y_name]])
coding <- list(); coded <- NULL; numeric_ <- logical()
for (j in seq_along(factors_)) {
f <- factors_[j]
cf <- if (kinds_[j] %in% c("categorical", "boolean")) cs_doe_code_factor(as.character(df[[f]]), kinds_[j], levels(df[[f]]), f)
else cs_doe_code_factor(as.numeric(df[[f]]), kinds_[j], NULL, f)
coded <- cbind(coded, cf$coded)
coding[[j]] <- cf$info
numeric_ <- c(numeric_, kinds_[j] == "numeric")
}
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = y_name) # a constant response has no effects to estimate
block <- if (!is.null(block_col)) as.character(df[[block_col]]) else NULL
alpha <- 0.05
# %% Model: effects in coded units; aliased terms dropped
# Classic idiom: lm(y ~ (A + B + C)^2, data = coded) — the twin fits lm() on the retained columns and
# drops aliased terms the same way as the Python twin.
res <- cs_doe_analyze(y, coded, factors_, numeric_, order = 2, block = block, alpha = alpha)
df_resid <- res$df_resid
ln <- res$lenth
eff <- res$effects
eff_terms <- res$effect_terms
sig <- if (df_resid > 0) eff_terms[res$effect_p < alpha] else eff_terms[abs(eff) > ln$me]
# %% Tables
tables <- list(list(
key = "effects", title = "Effects and coefficients (coded units)",
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "effect", label = "Effect", type = "number"),
list(key = "coef", label = "Coefficient", 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(res$terms), function(i) list(
term = res$terms[i], effect = if (res$terms[i] %in% eff_terms) 2 * res$coef[i] else NULL, coef = res$coef[i],
se = res$se[i], t = res$t[i], p = res$p[i]))
))
tables[[2]] <- list(
key = "anova", title = "Analysis of variance (sequential)",
columns = 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")),
rows = res$anova)
tables[[3]] <- list(
key = "coding", title = "Factor coding",
columns = list(list(key = "name", label = "Factor", type = "string"), list(key = "low", label = "Low (−1)", type = "string"),
list(key = "high", label = "High (+1)", type = "string"), list(key = "center", label = "Center (0)", type = "string")),
rows = lapply(coding, function(c) list(name = c$name,
low = if (c$kind == "numeric") cs_fmt_num(c$low) else c$low, high = if (c$kind == "numeric") cs_fmt_num(c$high) else c$high,
center = if (c$kind == "numeric") cs_fmt_num(c$center) else "—")))
if (length(res$aliases)) tables[[4]] <- list(
key = "aliases", title = "Aliased terms (not estimable separately)",
columns = list(list(key = "alias", label = "Alias", type = "string")), rows = lapply(res$aliases, function(a) list(alias = a)))
# %% Charts
charts <- list()
order_abs <- order(-abs(eff), method = "radix")
if (df_resid > 0) {
pareto_vals <- abs(res$effect_t)
controls <- list(margin = stats::qt(1 - alpha / 2, df_resid), smargin = NULL)
plab <- "|t|"
} else {
pareto_vals <- abs(eff)
controls <- list(margin = ln$me, smargin = ln$sme)
plab <- "|Effect|"
}
charts[[1]] <- cs_chart("pareto", "pareto-effects", "Pareto chart of effects",
list(effect = cs_col("Term", eff_terms[order_abs], "categorical"), value = cs_col(plab, pareto_vals[order_abs])),
controls = controls)
m <- length(eff)
if (m >= 2) {
asc <- order(abs(eff), method = "radix")
charts[[length(charts) + 1]] <- cs_chart(
"half-normal", "half-normal-effects", "Half-normal plot of effects",
list(effect = cs_col("Term", eff_terms[asc], "categorical"), abs_effect = cs_col("|Effect|", abs(eff[asc])),
quantile = cs_col("Half-normal quantile", cs_doe_half_normal(m)),
significant = cs_col("Significant", eff_terms[asc] %in% sig, "boolean")))
}
lvl <- function(c, v) if (c$kind == "numeric") cs_fmt_num(v) else as.character(v)
me_factor <- unlist(lapply(coding, function(c) c(c$name, c$name)))
me_level <- unlist(lapply(coding, function(c) c(lvl(c, c$low), lvl(c, c$high))))
me_mean <- unlist(lapply(res$means, function(m) c(m$low, m$high)))
charts[[length(charts) + 1]] <- cs_chart(
"main-effects", "main-effects", "Main effects (mean response at each level)",
list(factor = cs_col("Factor", me_factor, "categorical"), level = cs_col("Level", me_level, "categorical"),
mean = cs_col(paste("Mean", y_name), me_mean)))
two <- order_abs[grepl(" × ", eff_terms[order_abs]) & lengths(regmatches(eff_terms[order_abs], gregexpr(" × ", eff_terms[order_abs]))) == 1]
if (length(two)) {
ab <- strsplit(eff_terms[two[1]], " × ", fixed = TRUE)[[1]]
num_idx <- which(numeric_)
keep <- if (length(num_idx)) !apply(coded[, num_idx, drop = FALSE] == 0, 1, all) else rep(TRUE, length(y))
lab <- function(j, v) { c <- coding[[j]]; if (c$kind == "numeric") ifelse(v < 0, cs_fmt_num(c$low), cs_fmt_num(c$high)) else ifelse(v < 0, c$low, c$high) }
ja <- match(ab[1], factors_); jb <- match(ab[2], factors_)
charts[[length(charts) + 1]] <- cs_chart(
"interaction", "interaction", sprintf("Interaction: %s × %s", ab[1], ab[2]),
list(y = cs_col(y_name, y[keep]), x = cs_col(ab[1], lab(ja, coded[keep, ja]), "categorical"),
trace = cs_col(ab[2], lab(jb, coded[keep, jb]), "categorical")))
}
if (df_resid > 0) charts[[length(charts) + 1]] <- cs_chart(
"residuals", "residual-panel", "Residual diagnostics",
list(fitted = cs_col("Fitted values", res$fitted), residual = cs_col("Residuals", res$resid)))
# %% Result
n_eff <- length(eff_terms)
values <- list(
n = res$n, n_center = res$n_center, k = length(factors_), df_resid = df_resid,
terms = I(res$terms), coef = I(res$coef), effect_terms = I(eff_terms), effects = I(eff), effect_p = I(res$effect_p),
lenth_pse = ln$pse, lenth_me = ln$me, lenth_sme = ln$sme,
r2 = res$r2, adj_r2 = res$adj_r2, pred_r2 = res$pred_r2, s = res$s, curvature_p = res$curvature_p,
aliases = I(res$aliases), significant = I(sig), n_significant = length(sig), n_effects = n_eff,
significant_text = paste(sig, collapse = ", ")
)
summary <- if (length(sig)) sprintf("%d of %d effects stand out (%s)", length(sig), n_eff, paste(sig, collapse = ", ")) else
sprintf("No effect stands out among the %d estimated", n_eff)
summary <- paste0(summary, if (df_resid == 0) " by Lenth's method." else sprintf(" at α = %s.", format(alpha)))
stats_list <- list(list(key = "n", label = "Runs", value = res$n, format = "integer"),
list(key = "n_center", label = "Center runs", value = res$n_center, format = "integer"),
list(key = "df_resid", label = "Residual df", value = df_resid, format = "integer"))
stats_list <- c(stats_list, if (df_resid > 0) list(list(key = "r2", label = "R²", value = res$r2), list(key = "s", label = "S", value = res$s))
else list(list(key = "lenth_pse", label = "Lenth PSE", value = ln$pse), list(key = "lenth_me", label = "Margin of error", value = ln$me)))
cs_publish(list(
method = "doe.analyze",
methodVersion = "1.0.1",
title = "Analyze a two-level factorial experiment (effects, Lenth, ANOVA)",
engine = cs_engine_info("stats", "codesplashr"),
n = res$n,
summary = summary,
statistics = stats_list,
tables = tables,
charts = charts,
warnings = warnings,
notes = c("Effects are differences between the high and low settings (2 × the coded coefficient).",
if (df_resid == 0) "No residual degrees of freedom: effects are judged with Lenth's pseudo standard error (ME individual, SME simultaneous)."),
values = values
))
5 of 10 effects stand out (Temperature, Formaldehyde (%), Stirring, Temperature × Formaldehyde (%), Temperature × Stirring) at α = 0.05.
- Runs
- 16
- Center runs
- 0
- Residual df
- 5
- R²
- 0.9777
- S
- 5.056
To keep this page light, the plots are shown once, under the R tab.
Effects and coefficients (coded units)
| Term | Effect | Coefficient | SE | t | p |
|---|---|---|---|---|---|
| (Intercept) | — | 70.063 | 1.264 | 55.430 | < .001 |
| Temperature | 21.625 | 10.812 | 1.264 | 8.554 | < .001 |
| Pressure | 3.125 | 1.562 | 1.264 | 1.236 | .271 |
| Formaldehyde (%) | 9.875 | 4.937 | 1.264 | 3.906 | .011 |
| Stirring | 14.625 | 7.312 | 1.264 | 5.785 | .002 |
| Temperature × Pressure | 0.1250 | 0.0625 | 1.264 | 0.0494 | .962 |
| Temperature × Formaldehyde (%) | −18.125 | −9.063 | 1.264 | −7.170 | < .001 |
| Temperature × Stirring | 16.625 | 8.313 | 1.264 | 6.576 | .001 |
| Pressure × Formaldehyde (%) | 2.375 | 1.188 | 1.264 | 0.9395 | .391 |
| Pressure × Stirring | −0.3750 | −0.1875 | 1.264 | −0.1483 | .888 |
| Formaldehyde (%) × Stirring | −1.125 | −0.5625 | 1.264 | −0.4450 | .675 |
Analysis of variance (sequential)
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| Main effects | 4 | 3155.25 | 788.81 | 30.858 | .001 |
| 2-way interactions | 6 | 2447.88 | 407.98 | 15.960 | .004 |
| Residual error | 5 | 127.81 | 25.562 | — | — |
| Total | 15 | 5730.94 | — | — | — |
Factor coding
| Factor | Low (−1) | High (+1) | Center (0) |
|---|---|---|---|
| Temperature | 24.00 | 35.00 | 29.50 |
| Pressure | 10.00 | 15.00 | 12.50 |
| Formaldehyde (%) | 2.00 | 4.00 | 3.00 |
| Stirring | slow | fast | — |
- Effects are differences between the high and low settings (2 × the coded coefficient).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Analyze a two-level factorial experiment (effects, Lenth, ANOVA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.analyze 1.0.1 · spec 6522775f4b2584ee
# Dataset: q1_filtration (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 analyze as qa # twin of codesplashr::cs_doe_analyze (coding, aliasing, Lenth)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_filtration.parquet", columns=["Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring"])
n_input = len(df)
df["Stirring"] = pd.Categorical(df["Stirring"], categories=["slow", "fast"]) # stored level order
df = df.dropna(subset=["Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring"]) # listwise deletion over the analysis columns
df["Stirring"] = df["Stirring"].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, ["Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring"]) # infinite values stop the run (registry/errors.yaml)
# %% Coding (low = −1, high = +1, center runs = 0)
y_name = "Filtration rate"
FACTORS = ["Temperature", "Pressure", "Formaldehyde (%)", "Stirring"]
KINDS = ["numeric", "numeric", "numeric", "categorical", ]
block_col = None
y = df[y_name].to_numpy(dtype=float)
coded_cols, coding, numeric = [], [], []
for f, kind in zip(FACTORS, KINDS):
if kind in ("categorical", "boolean"):
c, info = qa.code_factor(df[f].astype(str).tolist(), kind, [str(x) for x in df[f].cat.categories], f)
else:
c, info = qa.code_factor(df[f].to_numpy(dtype=float), kind, None, f)
coded_cols.append(c)
coding.append(info)
numeric.append(kind == "numeric")
coded = np.column_stack(coded_cols)
if len(np.unique(y)) < 2: # a constant response has no effects to estimate
cs.cs_error("CS_E_CONSTANT", column=y_name)
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()
alpha = 0.05
# %% Model: effects in coded units; aliased terms dropped
res = qa.analyze(y, coded, FACTORS, numeric, order=2, block=block, alpha=alpha)
# Classic idiom: statsmodels.formula.api.ols("y ~ (A + B + C)**2", coded data) — the twin fits the same
# least-squares model on the retained columns and drops aliased terms the same way as the R twin.
fit_terms = res["terms"]
df_resid = res["df_resid"]
lenth = res["lenth"]
eff = np.asarray(res["effects"])
eff_terms = res["effect_terms"]
if df_resid > 0:
sig = [t for t, p in zip(eff_terms, res["effect_p"]) if p < alpha]
else:
sig = [t for t, e in zip(eff_terms, eff) if abs(e) > lenth["me"]]
# %% Tables
rows = []
for i, t in enumerate(fit_terms):
is_effect = t in eff_terms
rows.append({
"term": t, "effect": 2 * res["coef"][i] if is_effect else None, "coef": res["coef"][i],
"se": res["se"][i], "t": res["t"][i], "p": res["p"][i],
})
tables = [{
"key": "effects", "title": "Effects and coefficients (coded units)",
"columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "effect", "label": "Effect", "type": "number"},
{"key": "coef", "label": "Coefficient", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
],
"rows": rows,
}]
tables.append({
"key": "anova", "title": "Analysis of variance (sequential)",
"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": res["anova"],
})
tables.append({
"key": "coding", "title": "Factor coding",
"columns": [{"key": "name", "label": "Factor", "type": "string"}, {"key": "low", "label": "Low (−1)", "type": "string"},
{"key": "high", "label": "High (+1)", "type": "string"}, {"key": "center", "label": "Center (0)", "type": "string"}],
"rows": [{"name": c["name"], "low": cs.fmt_num(c["low"]) if c["kind"] == "numeric" else c["low"],
"high": cs.fmt_num(c["high"]) if c["kind"] == "numeric" else c["high"],
"center": cs.fmt_num(c["center"]) if c["kind"] == "numeric" else "—"} for c in coding],
})
if res["aliases"]:
tables.append({"key": "aliases", "title": "Aliased terms (not estimable separately)",
"columns": [{"key": "alias", "label": "Alias", "type": "string"}], "rows": [{"alias": a} for a in res["aliases"]]})
# %% Charts
charts = []
order_abs = np.argsort(-np.abs(eff), kind="stable")
if df_resid > 0:
pareto_vals = np.abs(np.asarray(res["effect_t"]))
from scipy import stats as _st
margin = float(_st.t.ppf(1 - alpha / 2, df_resid))
controls = {"margin": margin, "smargin": None}
label = "|t|"
else:
pareto_vals = np.abs(eff)
controls = {"margin": lenth["me"], "smargin": lenth["sme"]}
label = "|Effect|"
charts.append(cs.chart(
"pareto", "pareto-effects", "Pareto chart of effects",
{"effect": cs.col("Term", [eff_terms[i] for i in order_abs], "categorical"),
"value": cs.col(label, [float(pareto_vals[i]) for i in order_abs])},
controls=controls,
))
m = len(eff)
if m >= 2:
asc = np.argsort(np.abs(eff), kind="stable")
charts.append(cs.chart(
"half-normal", "half-normal-effects", "Half-normal plot of effects",
{"effect": cs.col("Term", [eff_terms[i] for i in asc], "categorical"),
"abs_effect": cs.col("|Effect|", [float(abs(eff[i])) for i in asc]),
"quantile": cs.col("Half-normal quantile", qa.half_normal_quantiles(m).tolist()),
"significant": cs.col("Significant", [eff_terms[i] in sig for i in asc], "boolean")},
))
me_factor, me_level, me_mean = [], [], []
for c, (nm, lo, hi) in zip(coding, res["means"]):
me_factor += [nm, nm]
me_level += [cs.fmt_num(c["low"]) if c["kind"] == "numeric" else str(c["low"]), cs.fmt_num(c["high"]) if c["kind"] == "numeric" else str(c["high"])]
me_mean += [lo, hi]
charts.append(cs.chart(
"main-effects", "main-effects", "Main effects (mean response at each level)",
{"factor": cs.col("Factor", me_factor, "categorical"), "level": cs.col("Level", me_level, "categorical"),
"mean": cs.col(f"Mean {y_name}", me_mean)},
))
two = [i for i in order_abs if " × " in eff_terms[i] and eff_terms[i].count(" × ") == 1]
if two:
a_name, b_name = eff_terms[two[0]].split(" × ")
keep = ~(np.all(coded[:, [j for j in range(len(FACTORS)) if numeric[j]]] == 0, axis=1)) if any(numeric) else np.ones(len(y), dtype=bool)
def lab(j, v):
c = coding[j]
return (cs.fmt_num(c["low"]) if v < 0 else cs.fmt_num(c["high"])) if c["kind"] == "numeric" else (c["low"] if v < 0 else c["high"])
ja, jb = FACTORS.index(a_name), FACTORS.index(b_name)
charts.append(cs.chart(
"interaction", "interaction", f"Interaction: {a_name} × {b_name}",
{"y": cs.col(y_name, y[keep].tolist()),
"x": cs.col(a_name, [lab(ja, v) for v in coded[keep, ja]], "categorical"),
"trace": cs.col(b_name, [lab(jb, v) for v in coded[keep, jb]], "categorical")},
))
if df_resid > 0:
charts.append(cs.chart(
"residuals", "residual-panel", "Residual diagnostics",
{"fitted": cs.col("Fitted values", np.asarray(res["fitted"]).tolist()),
"residual": cs.col("Residuals", np.asarray(res["resid"]).tolist())},
))
# %% Result
n_eff = len(eff_terms)
values = {
"n": res["n"], "n_center": res["n_center"], "k": len(FACTORS), "df_resid": df_resid,
"terms": list(fit_terms), "coef": list(map(float, res["coef"])),
"effect_terms": list(eff_terms), "effects": list(map(float, eff)), "effect_p": list(map(float, res["effect_p"])),
"lenth_pse": lenth["pse"], "lenth_me": lenth["me"], "lenth_sme": lenth["sme"],
"r2": res["r2"], "adj_r2": res["adj_r2"], "pred_r2": res["pred_r2"], "s": res["s"], "curvature_p": res["curvature_p"],
"aliases": list(res["aliases"]), "significant": sig, "n_significant": len(sig), "n_effects": n_eff,
"significant_text": ", ".join(sig),
}
if sig:
summary = f"{len(sig)} of {n_eff} effects stand out ({', '.join(sig)})"
else:
summary = f"No effect stands out among the {n_eff} estimated"
summary += " by Lenth's method." if df_resid == 0 else f" at α = {alpha:g}."
cs.publish({
"title": "Analyze a two-level factorial experiment (effects, Lenth, ANOVA)",
"engine": cs.engine_info("numpy", "scipy"),
"n": res["n"],
"summary": summary,
"statistics": [
{"key": "n", "label": "Runs", "value": res["n"], "format": "integer"},
{"key": "n_center", "label": "Center runs", "value": res["n_center"], "format": "integer"},
{"key": "df_resid", "label": "Residual df", "value": df_resid, "format": "integer"},
] + ([{"key": "r2", "label": "R²", "value": res["r2"]}, {"key": "s", "label": "S", "value": res["s"]}] if df_resid > 0 else
[{"key": "lenth_pse", "label": "Lenth PSE", "value": lenth["pse"]}, {"key": "lenth_me", "label": "Margin of error", "value": lenth["me"]}]),
"tables": tables,
"charts": charts,
"warnings": warnings,
"notes": ["Effects are differences between the high and low settings (2 × the coded coefficient)."]
+ (["No residual degrees of freedom: effects are judged with Lenth's pseudo standard error (ME individual, SME simultaneous)."] if df_resid == 0 else []),
"values": values,
})
5 of 10 effects stand out: Temperature, Formaldehyde (%), Stirring, Temperature × Formaldehyde (%), Temperature × Stirring.
The Pareto chart ranks them by size. The half-normal plot shows them against a straight line: small effects follow the line, as noise would, and real ones lift off it.
Read the interaction
PredictPredict first
Temperature has the largest main effect, and it also has large interactions with formaldehyde and stirring. What's your advice about temperature?
Reveal
It depends on them. The interaction plot shows that the temperature effect changes with both of those settings. A main effect is an average across the other factors' settings, so read it alongside any large interaction it's part of. Here, high temperature with low formaldehyde and fast stirring does best.
With no replicates
CheckpointWithout repeated runs, there may be little or no direct estimate of noise. Lenth's methodLenth's methodJudges effects in an unreplicated factorial by treating the many small ones as an estimate of noise. uses the effects themselves. If most are small, they're mostly noise, so the median of their sizes estimates it.
Check yourself
The ten effects, by absolute size, are 0.12, 0.38, 1.12, 2.38, 3.12, 9.88, 14.62, 16.62, 18.12 and 21.62. Lenth's starting estimate is 1.5 times their median. What is it? Give two decimals.
Show the answer
Answer: 9.75
The median is (3.12 + 9.88) / 2 = 6.5, and 1.5 × 6.5 = 9.75. All ten are below 2.5 times that, so nothing gets trimmed and the pseudo standard error stays 9.75.
When the assumption fails
PredictPredict first
Half of those ten effects are large. Lenth's method assumes most effects are negligible. What happens to it here?
Reveal
Its margin of error comes out at 29.3, larger than every effect, so by itself it would flag none. This run has 5 residual degrees of freedom, so the app judges effects with those instead. It uses Lenth's margin only when no residual degrees of freedom remain.
Is it curved?
In the appA factorial with two levels can only fit straight lines. Center points test that. A second study adds 4 of them to a fraction.
11 of 15 effects stand out (Speed, Feed, Depth, Coolant, Angle, Speed × Feed, Speed × Angle, Feed × Depth, Feed × Coolant, Depth × Coolant, Coolant × Angle) at α = 0.05.
- Runs
- 20
- Center runs
- 4
- Residual df
- 2
- R²
- 0.9999
- S
- 0.1412
Plots
View data
| Term | |t| |
|---|---|
| Speed | 90.662 |
| Feed | 56.693 |
| Depth | 39.832 |
| Speed × Feed | 30.764 |
| Coolant | 6.693 |
| Feed × Depth | 8.023 |
| Feed × Coolant | 7.492 |
| Depth × Coolant | 5.650 |
| Speed × Angle | 5.544 |
| Angle | 5.437 |
| Coolant × Angle | 4.729 |
| Speed × Depth | 2.604 |
| Depth × Angle | 2.320 |
| Feed × Angle | 1.824 |
| Speed × Coolant | 1.824 |
View data
| |Effect| | Term | Half-normal quantile | Significant |
|---|---|---|---|
| 0.1288 | Speed × Coolant | 0.0418 | false |
| 0.1288 | Feed × Angle | 0.1257 | false |
| 0.1637 | Depth × Angle | 0.2104 | false |
| 0.1838 | Speed × Depth | 0.2967 | false |
| 0.3338 | Coolant × Angle | 0.3853 | true |
| 0.3838 | Angle | 0.4770 | true |
| 0.3912 | Speed × Angle | 0.5730 | true |
| 0.3988 | Depth × Coolant | 0.6745 | true |
| 0.5287 | Feed × Coolant | 0.7835 | true |
| 0.5662 | Feed × Depth | 0.9027 | true |
| 1.056 | Coolant | 1.036 | true |
| 2.171 | Speed × Feed | 1.192 | true |
| 2.811 | Depth | 1.383 | true |
| 4.001 | Feed | 1.645 | true |
| 6.399 | Speed | 2.128 | true |
View data
| Factor | Level | Mean Surface quality |
|---|---|---|
| Speed | 80.00 | 47.279 |
| Speed | 120.00 | 53.678 |
| Feed | 0.15 | 52.479 |
| Feed | 0.25 | 48.477 |
| Depth | 0.50 | 49.072 |
| Depth | 1.50 | 51.884 |
| Coolant | 4.00 | 50.474 |
| Coolant | 6.00 | 50.483 |
| Angle | 8.00 | 50.286 |
| Angle | 12.00 | 50.670 |
View data
| Feed | Speed | Surface quality |
|---|---|---|
| 0.15 | 80.00 | 48.780 |
| 0.15 | 120.00 | 52.270 |
| 0.25 | 80.00 | 43.540 |
| 0.25 | 120.00 | 52.480 |
| 0.15 | 80.00 | 51.120 |
| 0.15 | 120.00 | 56.670 |
| 0.25 | 80.00 | 45.400 |
| 0.25 | 120.00 | 53.530 |
| 0.15 | 80.00 | 49.090 |
| 0.15 | 120.00 | 53.020 |
| 0.25 | 80.00 | 42.450 |
| 0.25 | 120.00 | 50.950 |
| 0.15 | 80.00 | 52.470 |
| 0.15 | 120.00 | 56.410 |
| 0.25 | 80.00 | 45.380 |
| 0.25 | 120.00 | 54.090 |
View data
| Fitted values | Residuals |
|---|---|
| 48.780 | −4.533e-19 |
| 52.270 | −1.344e-18 |
| 43.540 | −1.474e-18 |
| 52.480 | 2.067e-19 |
| 51.120 | −1.629e-18 |
| 56.670 | −9.390e-19 |
| 45.400 | 1.338e-18 |
| 53.530 | −7.169e-21 |
| 49.090 | 1.930e-18 |
| 53.020 | −1.542e-18 |
| 42.450 | −1.020e-18 |
| 50.950 | 8.793e-20 |
| 52.470 | 2.443e-19 |
| 56.410 | 1.347e-18 |
| 45.380 | −5.333e-19 |
| 54.090 | 1.156e-18 |
| 51.330 | −0.1300 |
| 51.330 | 0.1300 |
| 52.395 | 0.0550 |
| 52.395 | −0.0550 |
Effects and coefficients (coded units)
| Term | Effect | Coefficient | SE | t | p |
|---|---|---|---|---|---|
| (Intercept) | — | 49.946 | 0.0789 | 632.96 | < .001 |
| Block Day 2 | — | 1.065 | 0.1412 | 7.545 | .017 |
| Speed | 6.399 | 3.199 | 0.0353 | 90.662 | < .001 |
| Feed | −4.001 | −2.001 | 0.0353 | −56.693 | < .001 |
| Depth | 2.811 | 1.406 | 0.0353 | 39.832 | < .001 |
| Coolant | −1.056 | −0.5281 | 0.0789 | −6.693 | .022 |
| Angle | 0.3838 | 0.1919 | 0.0353 | 5.437 | .032 |
| Speed × Feed | 2.171 | 1.086 | 0.0353 | 30.764 | .001 |
| Speed × Depth | 0.1838 | 0.0919 | 0.0353 | 2.604 | .121 |
| Speed × Coolant | −0.1288 | −0.0644 | 0.0353 | −1.824 | .210 |
| Speed × Angle | 0.3912 | 0.1956 | 0.0353 | 5.544 | .031 |
| Feed × Depth | −0.5662 | −0.2831 | 0.0353 | −8.023 | .015 |
| Feed × Coolant | −0.5287 | −0.2644 | 0.0353 | −7.492 | .017 |
| Feed × Angle | −0.1288 | −0.0644 | 0.0353 | −1.824 | .210 |
| Depth × Coolant | 0.3988 | 0.1994 | 0.0353 | 5.650 | .030 |
| Depth × Angle | 0.1637 | 0.0819 | 0.0353 | 2.320 | .146 |
| Coolant × Angle | −0.3338 | −0.1669 | 0.0353 | −4.729 | .042 |
| Ct Pt | — | 1.384 | 0.0789 | 17.544 | .003 |
Analysis of variance (sequential)
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| Blocks | 1 | 0.2420 | 0.2420 | 12.146 | .073 |
| Main effects | 5 | 260.91 | 52.182 | 2618.92 | < .001 |
| 2-way interactions | 10 | 23.327 | 2.333 | 117.07 | .008 |
| Curvature | 1 | 6.133 | 6.133 | 307.79 | .003 |
| Residual error | 2 | 0.0398 | 0.0199 | — | — |
| Total | 19 | 290.65 | — | — | — |
Factor coding
| Factor | Low (−1) | High (+1) | Center (0) |
|---|---|---|---|
| Speed | 80.00 | 120.00 | 100.00 |
| Feed | 0.15 | 0.25 | 0.20 |
| Depth | 0.50 | 1.50 | 1.00 |
| Coolant | 4.00 | 6.00 | 5.00 |
| Angle | 8.00 | 12.00 | 10.00 |
- Effects are differences between the high and low settings (2 × the coded coefficient).
The exact R script · R R version 4.5.1 (2025-06-13)
# Analyze a two-level factorial experiment (effects, Lenth, ANOVA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.analyze 1.0.1 · spec e8fd8fc55cabb067
# Dataset: q1_fraction (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_analyze(): coding, aliasing and Lenth twin of codesplash.quality.analyze
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_fraction.parquet", col_select = c("Surface quality", "Speed", "Feed", "Depth", "Coolant", "Angle", "Day")))
n_input <- nrow(df)
df[["Day"]] <- factor(df[["Day"]], levels = c("Day 1", "Day 2")) # stored level order
df <- df[stats::complete.cases(df[c("Surface quality", "Speed", "Feed", "Depth", "Coolant", "Angle", "Day")]), , 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("Surface quality", "Speed", "Feed", "Depth", "Coolant", "Angle", "Day")) # infinite values stop the run (registry/errors.yaml)
# %% Coding (low = -1, high = +1, center runs = 0)
y_name <- "Surface quality"
factors_ <- c("Speed", "Feed", "Depth", "Coolant", "Angle")
kinds_ <- c("numeric", "numeric", "numeric", "numeric", "numeric")
block_col <- "Day"
y <- as.numeric(df[[y_name]])
coding <- list(); coded <- NULL; numeric_ <- logical()
for (j in seq_along(factors_)) {
f <- factors_[j]
cf <- if (kinds_[j] %in% c("categorical", "boolean")) cs_doe_code_factor(as.character(df[[f]]), kinds_[j], levels(df[[f]]), f)
else cs_doe_code_factor(as.numeric(df[[f]]), kinds_[j], NULL, f)
coded <- cbind(coded, cf$coded)
coding[[j]] <- cf$info
numeric_ <- c(numeric_, kinds_[j] == "numeric")
}
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = y_name) # a constant response has no effects to estimate
block <- if (!is.null(block_col)) as.character(df[[block_col]]) else NULL
alpha <- 0.05
# %% Model: effects in coded units; aliased terms dropped
# Classic idiom: lm(y ~ (A + B + C)^2, data = coded) — the twin fits lm() on the retained columns and
# drops aliased terms the same way as the Python twin.
res <- cs_doe_analyze(y, coded, factors_, numeric_, order = 2, block = block, alpha = alpha)
df_resid <- res$df_resid
ln <- res$lenth
eff <- res$effects
eff_terms <- res$effect_terms
sig <- if (df_resid > 0) eff_terms[res$effect_p < alpha] else eff_terms[abs(eff) > ln$me]
# %% Tables
tables <- list(list(
key = "effects", title = "Effects and coefficients (coded units)",
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "effect", label = "Effect", type = "number"),
list(key = "coef", label = "Coefficient", 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(res$terms), function(i) list(
term = res$terms[i], effect = if (res$terms[i] %in% eff_terms) 2 * res$coef[i] else NULL, coef = res$coef[i],
se = res$se[i], t = res$t[i], p = res$p[i]))
))
tables[[2]] <- list(
key = "anova", title = "Analysis of variance (sequential)",
columns = 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")),
rows = res$anova)
tables[[3]] <- list(
key = "coding", title = "Factor coding",
columns = list(list(key = "name", label = "Factor", type = "string"), list(key = "low", label = "Low (−1)", type = "string"),
list(key = "high", label = "High (+1)", type = "string"), list(key = "center", label = "Center (0)", type = "string")),
rows = lapply(coding, function(c) list(name = c$name,
low = if (c$kind == "numeric") cs_fmt_num(c$low) else c$low, high = if (c$kind == "numeric") cs_fmt_num(c$high) else c$high,
center = if (c$kind == "numeric") cs_fmt_num(c$center) else "—")))
if (length(res$aliases)) tables[[4]] <- list(
key = "aliases", title = "Aliased terms (not estimable separately)",
columns = list(list(key = "alias", label = "Alias", type = "string")), rows = lapply(res$aliases, function(a) list(alias = a)))
# %% Charts
charts <- list()
order_abs <- order(-abs(eff), method = "radix")
if (df_resid > 0) {
pareto_vals <- abs(res$effect_t)
controls <- list(margin = stats::qt(1 - alpha / 2, df_resid), smargin = NULL)
plab <- "|t|"
} else {
pareto_vals <- abs(eff)
controls <- list(margin = ln$me, smargin = ln$sme)
plab <- "|Effect|"
}
charts[[1]] <- cs_chart("pareto", "pareto-effects", "Pareto chart of effects",
list(effect = cs_col("Term", eff_terms[order_abs], "categorical"), value = cs_col(plab, pareto_vals[order_abs])),
controls = controls)
m <- length(eff)
if (m >= 2) {
asc <- order(abs(eff), method = "radix")
charts[[length(charts) + 1]] <- cs_chart(
"half-normal", "half-normal-effects", "Half-normal plot of effects",
list(effect = cs_col("Term", eff_terms[asc], "categorical"), abs_effect = cs_col("|Effect|", abs(eff[asc])),
quantile = cs_col("Half-normal quantile", cs_doe_half_normal(m)),
significant = cs_col("Significant", eff_terms[asc] %in% sig, "boolean")))
}
lvl <- function(c, v) if (c$kind == "numeric") cs_fmt_num(v) else as.character(v)
me_factor <- unlist(lapply(coding, function(c) c(c$name, c$name)))
me_level <- unlist(lapply(coding, function(c) c(lvl(c, c$low), lvl(c, c$high))))
me_mean <- unlist(lapply(res$means, function(m) c(m$low, m$high)))
charts[[length(charts) + 1]] <- cs_chart(
"main-effects", "main-effects", "Main effects (mean response at each level)",
list(factor = cs_col("Factor", me_factor, "categorical"), level = cs_col("Level", me_level, "categorical"),
mean = cs_col(paste("Mean", y_name), me_mean)))
two <- order_abs[grepl(" × ", eff_terms[order_abs]) & lengths(regmatches(eff_terms[order_abs], gregexpr(" × ", eff_terms[order_abs]))) == 1]
if (length(two)) {
ab <- strsplit(eff_terms[two[1]], " × ", fixed = TRUE)[[1]]
num_idx <- which(numeric_)
keep <- if (length(num_idx)) !apply(coded[, num_idx, drop = FALSE] == 0, 1, all) else rep(TRUE, length(y))
lab <- function(j, v) { c <- coding[[j]]; if (c$kind == "numeric") ifelse(v < 0, cs_fmt_num(c$low), cs_fmt_num(c$high)) else ifelse(v < 0, c$low, c$high) }
ja <- match(ab[1], factors_); jb <- match(ab[2], factors_)
charts[[length(charts) + 1]] <- cs_chart(
"interaction", "interaction", sprintf("Interaction: %s × %s", ab[1], ab[2]),
list(y = cs_col(y_name, y[keep]), x = cs_col(ab[1], lab(ja, coded[keep, ja]), "categorical"),
trace = cs_col(ab[2], lab(jb, coded[keep, jb]), "categorical")))
}
if (df_resid > 0) charts[[length(charts) + 1]] <- cs_chart(
"residuals", "residual-panel", "Residual diagnostics",
list(fitted = cs_col("Fitted values", res$fitted), residual = cs_col("Residuals", res$resid)))
# %% Result
n_eff <- length(eff_terms)
values <- list(
n = res$n, n_center = res$n_center, k = length(factors_), df_resid = df_resid,
terms = I(res$terms), coef = I(res$coef), effect_terms = I(eff_terms), effects = I(eff), effect_p = I(res$effect_p),
lenth_pse = ln$pse, lenth_me = ln$me, lenth_sme = ln$sme,
r2 = res$r2, adj_r2 = res$adj_r2, pred_r2 = res$pred_r2, s = res$s, curvature_p = res$curvature_p,
aliases = I(res$aliases), significant = I(sig), n_significant = length(sig), n_effects = n_eff,
significant_text = paste(sig, collapse = ", ")
)
summary <- if (length(sig)) sprintf("%d of %d effects stand out (%s)", length(sig), n_eff, paste(sig, collapse = ", ")) else
sprintf("No effect stands out among the %d estimated", n_eff)
summary <- paste0(summary, if (df_resid == 0) " by Lenth's method." else sprintf(" at α = %s.", format(alpha)))
stats_list <- list(list(key = "n", label = "Runs", value = res$n, format = "integer"),
list(key = "n_center", label = "Center runs", value = res$n_center, format = "integer"),
list(key = "df_resid", label = "Residual df", value = df_resid, format = "integer"))
stats_list <- c(stats_list, if (df_resid > 0) list(list(key = "r2", label = "R²", value = res$r2), list(key = "s", label = "S", value = res$s))
else list(list(key = "lenth_pse", label = "Lenth PSE", value = ln$pse), list(key = "lenth_me", label = "Margin of error", value = ln$me)))
cs_publish(list(
method = "doe.analyze",
methodVersion = "1.0.1",
title = "Analyze a two-level factorial experiment (effects, Lenth, ANOVA)",
engine = cs_engine_info("stats", "codesplashr"),
n = res$n,
summary = summary,
statistics = stats_list,
tables = tables,
charts = charts,
warnings = warnings,
notes = c("Effects are differences between the high and low settings (2 × the coded coefficient).",
if (df_resid == 0) "No residual degrees of freedom: effects are judged with Lenth's pseudo standard error (ME individual, SME simultaneous)."),
values = values
))
11 of 15 effects stand out (Speed, Feed, Depth, Coolant, Angle, Speed × Feed, Speed × Angle, Feed × Depth, Feed × Coolant, Depth × Coolant, Coolant × Angle) at α = 0.05.
- Runs
- 20
- Center runs
- 4
- Residual df
- 2
- R²
- 0.9999
- S
- 0.1412
To keep this page light, the plots are shown once, under the R tab.
Effects and coefficients (coded units)
| Term | Effect | Coefficient | SE | t | p |
|---|---|---|---|---|---|
| (Intercept) | — | 49.946 | 0.0789 | 632.96 | < .001 |
| Block Day 2 | — | 1.065 | 0.1412 | 7.545 | .017 |
| Speed | 6.399 | 3.199 | 0.0353 | 90.662 | < .001 |
| Feed | −4.001 | −2.001 | 0.0353 | −56.693 | < .001 |
| Depth | 2.811 | 1.406 | 0.0353 | 39.832 | < .001 |
| Coolant | −1.056 | −0.5281 | 0.0789 | −6.693 | .022 |
| Angle | 0.3837 | 0.1919 | 0.0353 | 5.437 | .032 |
| Speed × Feed | 2.171 | 1.086 | 0.0353 | 30.764 | .001 |
| Speed × Depth | 0.1837 | 0.0919 | 0.0353 | 2.604 | .121 |
| Speed × Coolant | −0.1288 | −0.0644 | 0.0353 | −1.824 | .210 |
| Speed × Angle | 0.3913 | 0.1956 | 0.0353 | 5.544 | .031 |
| Feed × Depth | −0.5663 | −0.2831 | 0.0353 | −8.023 | .015 |
| Feed × Coolant | −0.5287 | −0.2644 | 0.0353 | −7.492 | .017 |
| Feed × Angle | −0.1287 | −0.0644 | 0.0353 | −1.824 | .210 |
| Depth × Coolant | 0.3987 | 0.1994 | 0.0353 | 5.650 | .030 |
| Depth × Angle | 0.1638 | 0.0819 | 0.0353 | 2.320 | .146 |
| Coolant × Angle | −0.3337 | −0.1669 | 0.0353 | −4.729 | .042 |
| Ct Pt | — | 1.384 | 0.0789 | 17.544 | .003 |
Analysis of variance (sequential)
| Source | df | SS | MS | F | p |
|---|---|---|---|---|---|
| Blocks | 1 | 0.2420 | 0.2420 | 12.146 | .073 |
| Main effects | 5 | 260.91 | 52.182 | 2618.92 | < .001 |
| 2-way interactions | 10 | 23.327 | 2.333 | 117.07 | .008 |
| Curvature | 1 | 6.133 | 6.133 | 307.79 | .003 |
| Residual error | 2 | 0.0398 | 0.0199 | — | — |
| Total | 19 | 290.65 | — | — | — |
Factor coding
| Factor | Low (−1) | High (+1) | Center (0) |
|---|---|---|---|
| Speed | 80.00 | 120.00 | 100.00 |
| Feed | 0.15 | 0.25 | 0.20 |
| Depth | 0.50 | 1.50 | 1.00 |
| Coolant | 4.00 | 6.00 | 5.00 |
| Angle | 8.00 | 12.00 | 10.00 |
- Effects are differences between the high and low settings (2 × the coded coefficient).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Analyze a two-level factorial experiment (effects, Lenth, ANOVA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.analyze 1.0.1 · spec e8fd8fc55cabb067
# Dataset: q1_fraction (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 analyze as qa # twin of codesplashr::cs_doe_analyze (coding, aliasing, Lenth)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_fraction.parquet", columns=["Surface quality", "Speed", "Feed", "Depth", "Coolant", "Angle", "Day"])
n_input = len(df)
df["Day"] = pd.Categorical(df["Day"], categories=["Day 1", "Day 2"]) # stored level order
df = df.dropna(subset=["Surface quality", "Speed", "Feed", "Depth", "Coolant", "Angle", "Day"]) # listwise deletion over the analysis columns
df["Day"] = df["Day"].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, ["Surface quality", "Speed", "Feed", "Depth", "Coolant", "Angle", "Day"]) # infinite values stop the run (registry/errors.yaml)
# %% Coding (low = −1, high = +1, center runs = 0)
y_name = "Surface quality"
FACTORS = ["Speed", "Feed", "Depth", "Coolant", "Angle"]
KINDS = ["numeric", "numeric", "numeric", "numeric", "numeric", ]
block_col = "Day"
y = df[y_name].to_numpy(dtype=float)
coded_cols, coding, numeric = [], [], []
for f, kind in zip(FACTORS, KINDS):
if kind in ("categorical", "boolean"):
c, info = qa.code_factor(df[f].astype(str).tolist(), kind, [str(x) for x in df[f].cat.categories], f)
else:
c, info = qa.code_factor(df[f].to_numpy(dtype=float), kind, None, f)
coded_cols.append(c)
coding.append(info)
numeric.append(kind == "numeric")
coded = np.column_stack(coded_cols)
if len(np.unique(y)) < 2: # a constant response has no effects to estimate
cs.cs_error("CS_E_CONSTANT", column=y_name)
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()
alpha = 0.05
# %% Model: effects in coded units; aliased terms dropped
res = qa.analyze(y, coded, FACTORS, numeric, order=2, block=block, alpha=alpha)
# Classic idiom: statsmodels.formula.api.ols("y ~ (A + B + C)**2", coded data) — the twin fits the same
# least-squares model on the retained columns and drops aliased terms the same way as the R twin.
fit_terms = res["terms"]
df_resid = res["df_resid"]
lenth = res["lenth"]
eff = np.asarray(res["effects"])
eff_terms = res["effect_terms"]
if df_resid > 0:
sig = [t for t, p in zip(eff_terms, res["effect_p"]) if p < alpha]
else:
sig = [t for t, e in zip(eff_terms, eff) if abs(e) > lenth["me"]]
# %% Tables
rows = []
for i, t in enumerate(fit_terms):
is_effect = t in eff_terms
rows.append({
"term": t, "effect": 2 * res["coef"][i] if is_effect else None, "coef": res["coef"][i],
"se": res["se"][i], "t": res["t"][i], "p": res["p"][i],
})
tables = [{
"key": "effects", "title": "Effects and coefficients (coded units)",
"columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "effect", "label": "Effect", "type": "number"},
{"key": "coef", "label": "Coefficient", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
],
"rows": rows,
}]
tables.append({
"key": "anova", "title": "Analysis of variance (sequential)",
"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": res["anova"],
})
tables.append({
"key": "coding", "title": "Factor coding",
"columns": [{"key": "name", "label": "Factor", "type": "string"}, {"key": "low", "label": "Low (−1)", "type": "string"},
{"key": "high", "label": "High (+1)", "type": "string"}, {"key": "center", "label": "Center (0)", "type": "string"}],
"rows": [{"name": c["name"], "low": cs.fmt_num(c["low"]) if c["kind"] == "numeric" else c["low"],
"high": cs.fmt_num(c["high"]) if c["kind"] == "numeric" else c["high"],
"center": cs.fmt_num(c["center"]) if c["kind"] == "numeric" else "—"} for c in coding],
})
if res["aliases"]:
tables.append({"key": "aliases", "title": "Aliased terms (not estimable separately)",
"columns": [{"key": "alias", "label": "Alias", "type": "string"}], "rows": [{"alias": a} for a in res["aliases"]]})
# %% Charts
charts = []
order_abs = np.argsort(-np.abs(eff), kind="stable")
if df_resid > 0:
pareto_vals = np.abs(np.asarray(res["effect_t"]))
from scipy import stats as _st
margin = float(_st.t.ppf(1 - alpha / 2, df_resid))
controls = {"margin": margin, "smargin": None}
label = "|t|"
else:
pareto_vals = np.abs(eff)
controls = {"margin": lenth["me"], "smargin": lenth["sme"]}
label = "|Effect|"
charts.append(cs.chart(
"pareto", "pareto-effects", "Pareto chart of effects",
{"effect": cs.col("Term", [eff_terms[i] for i in order_abs], "categorical"),
"value": cs.col(label, [float(pareto_vals[i]) for i in order_abs])},
controls=controls,
))
m = len(eff)
if m >= 2:
asc = np.argsort(np.abs(eff), kind="stable")
charts.append(cs.chart(
"half-normal", "half-normal-effects", "Half-normal plot of effects",
{"effect": cs.col("Term", [eff_terms[i] for i in asc], "categorical"),
"abs_effect": cs.col("|Effect|", [float(abs(eff[i])) for i in asc]),
"quantile": cs.col("Half-normal quantile", qa.half_normal_quantiles(m).tolist()),
"significant": cs.col("Significant", [eff_terms[i] in sig for i in asc], "boolean")},
))
me_factor, me_level, me_mean = [], [], []
for c, (nm, lo, hi) in zip(coding, res["means"]):
me_factor += [nm, nm]
me_level += [cs.fmt_num(c["low"]) if c["kind"] == "numeric" else str(c["low"]), cs.fmt_num(c["high"]) if c["kind"] == "numeric" else str(c["high"])]
me_mean += [lo, hi]
charts.append(cs.chart(
"main-effects", "main-effects", "Main effects (mean response at each level)",
{"factor": cs.col("Factor", me_factor, "categorical"), "level": cs.col("Level", me_level, "categorical"),
"mean": cs.col(f"Mean {y_name}", me_mean)},
))
two = [i for i in order_abs if " × " in eff_terms[i] and eff_terms[i].count(" × ") == 1]
if two:
a_name, b_name = eff_terms[two[0]].split(" × ")
keep = ~(np.all(coded[:, [j for j in range(len(FACTORS)) if numeric[j]]] == 0, axis=1)) if any(numeric) else np.ones(len(y), dtype=bool)
def lab(j, v):
c = coding[j]
return (cs.fmt_num(c["low"]) if v < 0 else cs.fmt_num(c["high"])) if c["kind"] == "numeric" else (c["low"] if v < 0 else c["high"])
ja, jb = FACTORS.index(a_name), FACTORS.index(b_name)
charts.append(cs.chart(
"interaction", "interaction", f"Interaction: {a_name} × {b_name}",
{"y": cs.col(y_name, y[keep].tolist()),
"x": cs.col(a_name, [lab(ja, v) for v in coded[keep, ja]], "categorical"),
"trace": cs.col(b_name, [lab(jb, v) for v in coded[keep, jb]], "categorical")},
))
if df_resid > 0:
charts.append(cs.chart(
"residuals", "residual-panel", "Residual diagnostics",
{"fitted": cs.col("Fitted values", np.asarray(res["fitted"]).tolist()),
"residual": cs.col("Residuals", np.asarray(res["resid"]).tolist())},
))
# %% Result
n_eff = len(eff_terms)
values = {
"n": res["n"], "n_center": res["n_center"], "k": len(FACTORS), "df_resid": df_resid,
"terms": list(fit_terms), "coef": list(map(float, res["coef"])),
"effect_terms": list(eff_terms), "effects": list(map(float, eff)), "effect_p": list(map(float, res["effect_p"])),
"lenth_pse": lenth["pse"], "lenth_me": lenth["me"], "lenth_sme": lenth["sme"],
"r2": res["r2"], "adj_r2": res["adj_r2"], "pred_r2": res["pred_r2"], "s": res["s"], "curvature_p": res["curvature_p"],
"aliases": list(res["aliases"]), "significant": sig, "n_significant": len(sig), "n_effects": n_eff,
"significant_text": ", ".join(sig),
}
if sig:
summary = f"{len(sig)} of {n_eff} effects stand out ({', '.join(sig)})"
else:
summary = f"No effect stands out among the {n_eff} estimated"
summary += " by Lenth's method." if df_resid == 0 else f" at α = {alpha:g}."
cs.publish({
"title": "Analyze a two-level factorial experiment (effects, Lenth, ANOVA)",
"engine": cs.engine_info("numpy", "scipy"),
"n": res["n"],
"summary": summary,
"statistics": [
{"key": "n", "label": "Runs", "value": res["n"], "format": "integer"},
{"key": "n_center", "label": "Center runs", "value": res["n_center"], "format": "integer"},
{"key": "df_resid", "label": "Residual df", "value": df_resid, "format": "integer"},
] + ([{"key": "r2", "label": "R²", "value": res["r2"]}, {"key": "s", "label": "S", "value": res["s"]}] if df_resid > 0 else
[{"key": "lenth_pse", "label": "Lenth PSE", "value": lenth["pse"]}, {"key": "lenth_me", "label": "Margin of error", "value": lenth["me"]}]),
"tables": tables,
"charts": charts,
"warnings": warnings,
"notes": ["Effects are differences between the high and low settings (2 × the coded coefficient)."]
+ (["No residual degrees of freedom: effects are judged with Lenth's pseudo standard error (ME individual, SME simultaneous)."] if df_resid == 0 else []),
"values": values,
})
The curvature test gives p = .003. The middle of the design isn't where the corners predict, so a first-order model won't do. That's the cue for a response surface.
Is the fit too good?
ReadR² always rises with more terms. Predicted R² asks how well the model predicts each run when that run is left out.
For the first study, R² is 0.978 and predicted R² is 0.772. A wide gap warns that the model is leaning on individual runs. With few runs, drop terms that don't earn their place.
Check your understanding
CheckpointCheck yourself
A × B is large, and B's main effect is small. Should you drop B from the model?
Show the answer
Answer: b
This is the hierarchy principle. A small main effect can hide a factor that matters in opposite directions at the two levels of another.
Check yourself
On a half-normal plot, what does a point far above the line suggest?
Show the answer
Answer: a
The plot compares effect sizes with what noise alone would give. The ones that lift off the line deserve attention.
Check yourself
Four runs at high temperature average 70, and four at low temperature average 50. What is the main effect of temperature?
Show the answer
Answer: 20
70 − 50 = 20. In a regression with −1 and +1 coding, the coefficient is half that, at 10.
Try it
In the appIn the Quality studio, after filling in your responses on the Run sheet step, open the Effects step.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("filtration.csv")
df.columns = ["T", "P", "F", "S", "y"]
for col in ["T", "P", "F"]:
df[col] = df[col].map({df[col].min(): -1, df[col].max(): 1})
df["S"] = df["S"].map({"slow": -1, "fast": 1})
fit = smf.ols("y ~ (T + P + F + S) ** 2", df).fit()
print((2 * fit.params.drop("Intercept")).round(2)) # effects are twice the coefficientsdf <- read.csv("filtration.csv", check.names = FALSE)
names(df) <- c("T", "P", "F", "S", "y")
code <- function(x, high) ifelse(x == high, 1, -1)
df <- transform(df,
T = code(T, max(T)), P = code(P, max(P)), F = code(F, max(F)), S = code(S, "fast"))
fit <- lm(y ~ (T + P + F + S)^2, df)
round(2 * coef(fit)[-1], 2) # effects are twice the coefficientsRecap
Recap- A main effect is a difference in averages. Read it alongside its interactions.
- Lenth's method assumes most effects are small, so it fails when many are large.
- Center points test for curvature.
- A wide gap between R² and predicted R² means the model is overfitting.
Concepts in this lesson