Skip to content

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.

Applied ~12 min10 steps

What runs in CodeSplash

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

01

An effect is a difference

Read

In a two-level design, a factor's main effect is the average response at its high setting minus the average at its low setting:

EffectA=yˉA+−yˉA−\text{Effect}_A = \bar y_{A+} - \bar y_{A-}

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.

02

What stands out?

In the app
Analyze a two-level factorial experiment (effects, Lenth, ANOVA)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

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

Plots

Pareto chart of effectsWhich effects are largest, and which exceed Lenth's margin of error?
View data
Term|t|
Temperature8.554
Temperature × Formaldehyde (%)7.170
Temperature × Stirring6.576
Stirring5.785
Formaldehyde (%)3.906
Pressure1.236
Pressure × Formaldehyde (%)0.9395
Formaldehyde (%) × Stirring0.4450
Pressure × Stirring0.1483
Temperature × Pressure0.0494
Half-normal plot of effectsWhich factor effects in an unreplicated factorial stand out from noise?
View data
|Effect|TermHalf-normal quantileSignificant
0.1250Temperature × Pressure0.0627false
0.3750Pressure × Stirring0.1891false
1.125Formaldehyde (%) × Stirring0.3186false
2.375Pressure × Formaldehyde (%)0.4538false
3.125Pressure0.5978false
9.875Formaldehyde (%)0.7554true
14.625Stirring0.9346true
16.625Temperature × Stirring1.150true
18.125Temperature × Formaldehyde (%)1.440true
21.625Temperature1.960true
Main effects (mean response at each level)How does the mean response change across each factor's levels?
View data
FactorLevelMean Filtration rate
Temperature24.0059.250
Temperature35.0080.875
Pressure10.0068.500
Pressure15.0071.625
Formaldehyde (%)2.0065.125
Formaldehyde (%)4.0075
Stirringslow62.750
Stirringfast77.375
Interaction: Temperature × Formaldehyde (%)Does the effect of one factor depend on another?
View data
Formaldehyde (%)TemperatureFiltration rate
2.0024.0045
2.0035.0071
2.0024.0048
2.0035.0065
4.0024.0068
4.0035.0060
4.0024.0080
4.0035.0065
2.0024.0043
2.0035.00100
2.0024.0045
2.0035.00104
4.0024.0075
4.0035.0086
4.0024.0070
4.0035.0096
Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
Fitted valuesResiduals
45.188−0.1875
68.1882.813
46.1881.812
69.438−4.438
71.938−3.938
58.6881.313
77.6882.313
64.6880.3125
44.688−1.688
100.94−0.9375
44.9380.0625
101.442.563
69.1885.813
89.188−3.188
74.188−4.188
94.4381.563

Effects and coefficients (coded units)

TermEffectCoefficientSEtp
(Intercept)—70.0631.26455.430< .001
Temperature21.62510.8131.2648.554< .001
Pressure3.1251.5631.2641.236.271
Formaldehyde (%)9.8754.9381.2643.906.011
Stirring14.6257.3131.2645.785.002
Temperature × Pressure0.12500.06251.2640.0494.962
Temperature × Formaldehyde (%)−18.125−9.0631.264−7.170< .001
Temperature × Stirring16.6258.3131.2646.576.001
Pressure × Formaldehyde (%)2.3751.1881.2640.9395.391
Pressure × Stirring−0.3750−0.18751.264−0.1483.888
Formaldehyde (%) × Stirring−1.125−0.56251.264−0.4450.675

Analysis of variance (sequential)

SourcedfSSMSFp
Main effects43155.25788.8130.858.001
2-way interactions62447.88407.9815.960.004
Residual error5127.8125.563——
Total155730.94———

Factor coding

FactorLow (−1)High (+1)Center (0)
Temperature24.0035.0029.50
Pressure10.0015.0012.50
Formaldehyde (%)2.004.003.00
Stirringslowfast—
  • 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
))
Python

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)

TermEffectCoefficientSEtp
(Intercept)—70.0631.26455.430< .001
Temperature21.62510.8121.2648.554< .001
Pressure3.1251.5621.2641.236.271
Formaldehyde (%)9.8754.9371.2643.906.011
Stirring14.6257.3121.2645.785.002
Temperature × Pressure0.12500.06251.2640.0494.962
Temperature × Formaldehyde (%)−18.125−9.0631.264−7.170< .001
Temperature × Stirring16.6258.3131.2646.576.001
Pressure × Formaldehyde (%)2.3751.1881.2640.9395.391
Pressure × Stirring−0.3750−0.18751.264−0.1483.888
Formaldehyde (%) × Stirring−1.125−0.56251.264−0.4450.675

Analysis of variance (sequential)

SourcedfSSMSFp
Main effects43155.25788.8130.858.001
2-way interactions62447.88407.9815.960.004
Residual error5127.8125.562——
Total155730.94———

Factor coding

FactorLow (−1)High (+1)Center (0)
Temperature24.0035.0029.50
Pressure10.0015.0012.50
Formaldehyde (%)2.004.003.00
Stirringslowfast—
  • 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.

03

Read the interaction

Predict

Predict first

Temperature has the largest main effect, and it also has large interactions with formaldehyde and stirring. What's your advice about temperature?

Raise temperature, whatever else you doIt depends on formaldehyde and stirringIt doesn't matter
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.

04

With no replicates

Checkpoint

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

05

When the assumption fails

Predict

Predict first

Half of those ten effects are large. Lenth's method assumes most effects are negligible. What happens to it here?

Lenth finds even more effectsLenth finds fewer, because its noise estimate is inflatedThere's no difference
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.

06

Is it curved?

In the app

A factorial with two levels can only fit straight lines. Center points test that. A second study adds 4 of them to a fraction.

Analyze a two-level factorial experiment (effects, Lenth, ANOVA)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

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

Pareto chart of effectsWhich effects are largest, and which exceed Lenth's margin of error?
View data
Term|t|
Speed90.662
Feed56.693
Depth39.832
Speed × Feed30.764
Coolant6.693
Feed × Depth8.023
Feed × Coolant7.492
Depth × Coolant5.650
Speed × Angle5.544
Angle5.437
Coolant × Angle4.729
Speed × Depth2.604
Depth × Angle2.320
Feed × Angle1.824
Speed × Coolant1.824
Half-normal plot of effectsWhich factor effects in an unreplicated factorial stand out from noise?
View data
|Effect|TermHalf-normal quantileSignificant
0.1288Speed × Coolant0.0418false
0.1288Feed × Angle0.1257false
0.1637Depth × Angle0.2104false
0.1838Speed × Depth0.2967false
0.3338Coolant × Angle0.3853true
0.3838Angle0.4770true
0.3912Speed × Angle0.5730true
0.3988Depth × Coolant0.6745true
0.5287Feed × Coolant0.7835true
0.5662Feed × Depth0.9027true
1.056Coolant1.036true
2.171Speed × Feed1.192true
2.811Depth1.383true
4.001Feed1.645true
6.399Speed2.128true
Main effects (mean response at each level)How does the mean response change across each factor's levels?
View data
FactorLevelMean Surface quality
Speed80.0047.279
Speed120.0053.678
Feed0.1552.479
Feed0.2548.477
Depth0.5049.072
Depth1.5051.884
Coolant4.0050.474
Coolant6.0050.483
Angle8.0050.286
Angle12.0050.670
Interaction: Speed × FeedDoes the effect of one factor depend on another?
View data
FeedSpeedSurface quality
0.1580.0048.780
0.15120.0052.270
0.2580.0043.540
0.25120.0052.480
0.1580.0051.120
0.15120.0056.670
0.2580.0045.400
0.25120.0053.530
0.1580.0049.090
0.15120.0053.020
0.2580.0042.450
0.25120.0050.950
0.1580.0052.470
0.15120.0056.410
0.2580.0045.380
0.25120.0054.090
Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
Fitted valuesResiduals
48.780−4.533e-19
52.270−1.344e-18
43.540−1.474e-18
52.4802.067e-19
51.120−1.629e-18
56.670−9.390e-19
45.4001.338e-18
53.530−7.169e-21
49.0901.930e-18
53.020−1.542e-18
42.450−1.020e-18
50.9508.793e-20
52.4702.443e-19
56.4101.347e-18
45.380−5.333e-19
54.0901.156e-18
51.330−0.1300
51.3300.1300
52.3950.0550
52.395−0.0550

Effects and coefficients (coded units)

TermEffectCoefficientSEtp
(Intercept)—49.9460.0789632.96< .001
Block Day 2—1.0650.14127.545.017
Speed6.3993.1990.035390.662< .001
Feed−4.001−2.0010.0353−56.693< .001
Depth2.8111.4060.035339.832< .001
Coolant−1.056−0.52810.0789−6.693.022
Angle0.38380.19190.03535.437.032
Speed × Feed2.1711.0860.035330.764.001
Speed × Depth0.18380.09190.03532.604.121
Speed × Coolant−0.1288−0.06440.0353−1.824.210
Speed × Angle0.39120.19560.03535.544.031
Feed × Depth−0.5662−0.28310.0353−8.023.015
Feed × Coolant−0.5287−0.26440.0353−7.492.017
Feed × Angle−0.1288−0.06440.0353−1.824.210
Depth × Coolant0.39880.19940.03535.650.030
Depth × Angle0.16370.08190.03532.320.146
Coolant × Angle−0.3338−0.16690.0353−4.729.042
Ct Pt—1.3840.078917.544.003

Analysis of variance (sequential)

SourcedfSSMSFp
Blocks10.24200.242012.146.073
Main effects5260.9152.1822618.92< .001
2-way interactions1023.3272.333117.07.008
Curvature16.1336.133307.79.003
Residual error20.03980.0199——
Total19290.65———

Factor coding

FactorLow (−1)High (+1)Center (0)
Speed80.00120.00100.00
Feed0.150.250.20
Depth0.501.501.00
Coolant4.006.005.00
Angle8.0012.0010.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
))
Python

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)

TermEffectCoefficientSEtp
(Intercept)—49.9460.0789632.96< .001
Block Day 2—1.0650.14127.545.017
Speed6.3993.1990.035390.662< .001
Feed−4.001−2.0010.0353−56.693< .001
Depth2.8111.4060.035339.832< .001
Coolant−1.056−0.52810.0789−6.693.022
Angle0.38370.19190.03535.437.032
Speed × Feed2.1711.0860.035330.764.001
Speed × Depth0.18370.09190.03532.604.121
Speed × Coolant−0.1288−0.06440.0353−1.824.210
Speed × Angle0.39130.19560.03535.544.031
Feed × Depth−0.5663−0.28310.0353−8.023.015
Feed × Coolant−0.5287−0.26440.0353−7.492.017
Feed × Angle−0.1287−0.06440.0353−1.824.210
Depth × Coolant0.39870.19940.03535.650.030
Depth × Angle0.16380.08190.03532.320.146
Coolant × Angle−0.3337−0.16690.0353−4.729.042
Ct Pt—1.3840.078917.544.003

Analysis of variance (sequential)

SourcedfSSMSFp
Blocks10.24200.242012.146.073
Main effects5260.9152.1822618.92< .001
2-way interactions1023.3272.333117.07.008
Curvature16.1336.133307.79.003
Residual error20.03980.0199——
Total19290.65———

Factor coding

FactorLow (−1)High (+1)Center (0)
Speed80.00120.00100.00
Feed0.150.250.20
Depth0.501.501.00
Coolant4.006.005.00
Angle8.0012.0010.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.

07

Is the fit too good?

Read

R² 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.

08

Check your understanding

Checkpoint

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

09

Try it

In the app

In the Quality studio, after filling in your responses on the Run sheet step, open the Effects step.

Python
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 coefficients
R
df <- 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 coefficients
10

Recap

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