Skip to content

Charts for counts and defects

Choose p, np, c and u charts by what you count, read an improvement as a signal, and widen limits with Laney p′ when samples are large.

Applied ~12 min10 steps

What runs in CodeSplash

You will be able to

  • Choose the right attribute chart for what you count
  • Compute limits for p and c charts
  • Explain when a p chart raises too many alarms, and what Laney p′ does

Read first

01

What are you counting?

Read

Pass or fail, or a count of flaws, needs an attribute chartAttribute chartA control chart for counts or pass and fail results, instead of a measurement.:

You countSample sizeChart
Defective itemsVariesp (proportion)
Defective itemsFixednp (number)
Defects on each itemSame area each timec
Defects on each itemArea variesu (per unit)

An item with three scratches is one defective, and three defects.

02

Pick the chart

Checkpoint

Check yourself

Each day you inspect every invoice and record how many have errors. The daily number of invoices varies. Which chart fits?

Show the answer

Answer: a

Each invoice is good or bad, and the sample size changes, so plot the proportion. An np chart needs equal samples.

Check yourself

You count paint flaws on car panels of different sizes. Which chart fits?

Show the answer

Answer: c

These are defects, not defective items, and the area varies, so plot flaws per unit of area.

03

An improvement looks like a signal

Predict

Predict first

A machine makes juice cans, and 54 samples of 50 are inspected. Limits come from the first 30, centered on 23.1% defective. Then the machine is adjusted. If the fix worked, what will the later samples show?

Nothing changesPoints run below the center linePoints run above the upper limit
Reveal

A long run below the center line. Of 23 signals, most come after the adjustment. They're good news, and signals all the same: the process changed. Now you'd set new limits on the improved process.

04

See it, and compute it

In the app
p control chartRecorded · Python and R agreeRecorded 2026-11-17 · 19 values compared
R

p chart of Nonconforming: 54 subgroups; 23 signals (Western Electric rules).

Center
0.2313
σ
0.4217
Subgroups
54
Signals
23

Plots

p chart of NonconformingIs the process in statistical control, and where are the signals?
View data
CenterChartSampleLCLRulesUCLStatisticSignal
0.2313p10.05240.41020.2400false
0.2313p20.05240.41020.3000false
0.2313p30.05240.41020.1600false
0.2313p40.05240.41020.2000false
0.2313p50.05240.41020.0800false
0.2313p60.05240.41020.1400false
0.2313p70.05240.41020.3200false
0.2313p80.05240.41020.1800false
0.2313p90.05240.41020.2800false
0.2313p100.05240.41020.2000false
0.2313p110.05240.41020.1000false
0.2313p120.05240.41020.1200false
0.2313p130.05240.41020.3400false
0.2313p140.05240.41020.2400false
0.2313p150.052410.41020.4400true
0.2313p160.05240.41020.1600false
0.2313p170.05240.41020.2000false
0.2313p180.05240.41020.1000false
0.2313p190.05240.41020.2600false
0.2313p200.05240.41020.2200false
0.2313p210.05240.41020.4000false
0.2313p220.052420.41020.3600true
0.2313p230.05241,20.41020.4800true
0.2313p240.052430.41020.3000true
0.2313p250.05240.41020.1800false
0.2313p260.05240.41020.2400false
0.2313p270.05240.41020.1400false
0.2313p280.05240.41020.2600false
0.2313p290.05240.41020.1800false
0.2313p300.05240.41020.1200false
0.2313p310.05240.41020.1800false
0.2313p320.05240.41020.1200false
0.2313p330.05240.41020.2400false
0.2313p340.05240.41020.1000false
0.2313p350.05240.41020.1200false
0.2313p360.05242,30.41020.0800true
0.2313p370.052430.41020.1200true
0.2313p380.05242,30.41020.0600true
0.2313p390.052430.41020.1400true
0.2313p400.052430.41020.1200true
0.2313p410.05241,3,40.41020.0400true
0.2313p420.05242,3,40.41020.0800true
0.2313p430.05242,3,40.41020.0600true
0.2313p440.05243,40.41020.1200true
0.2313p450.05242,3,40.41020.1000true
0.2313p460.05242,3,40.41020.0800true
0.2313p470.05243,40.41020.1600true
0.2313p480.05242,3,40.41020.1000true
0.2313p490.05243,40.41020.1200true
0.2313p500.05243,40.41020.1400true
0.2313p510.05243,40.41020.1000true
0.2313p520.05243,40.41020.1200true
0.2313p530.05242,3,40.41020.0600true
0.2313p540.05242,3,40.41020.1000true

Points and limits

SubgroupnStatisticCenterLCLUCLRules broken
1500.24000.23130.05240.4102
2500.30000.23130.05240.4102
3500.16000.23130.05240.4102
4500.20000.23130.05240.4102
5500.08000.23130.05240.4102
6500.14000.23130.05240.4102
7500.32000.23130.05240.4102
8500.18000.23130.05240.4102
9500.28000.23130.05240.4102
10500.20000.23130.05240.4102
11500.10000.23130.05240.4102
12500.12000.23130.05240.4102
13500.34000.23130.05240.4102
14500.24000.23130.05240.4102
15500.44000.23130.05240.41021
16500.16000.23130.05240.4102
17500.20000.23130.05240.4102
18500.10000.23130.05240.4102
19500.26000.23130.05240.4102
20500.22000.23130.05240.4102
21500.40000.23130.05240.4102
22500.36000.23130.05240.41022
23500.48000.23130.05240.41021, 2
24500.30000.23130.05240.41023
25500.18000.23130.05240.4102
26500.24000.23130.05240.4102
27500.14000.23130.05240.4102
28500.26000.23130.05240.4102
29500.18000.23130.05240.4102
30500.12000.23130.05240.4102
31500.18000.23130.05240.4102
32500.12000.23130.05240.4102
33500.24000.23130.05240.4102
34500.10000.23130.05240.4102
35500.12000.23130.05240.4102
36500.08000.23130.05240.41022, 3
37500.12000.23130.05240.41023
38500.06000.23130.05240.41022, 3
39500.14000.23130.05240.41023
40500.12000.23130.05240.41023

First 40 of 54 rows.

  • σ estimated from the first 30 subgroups (phase I).
The exact R script · R R version 4.5.1 (2025-06-13)
# Control chart (X̄–R, X̄–S, I–MR, p, np, c, u, Laney p′, CUSUM, EWMA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.control_chart 1.0.1 · spec b9febfd9ce75de3f
# Dataset: q1_orangejuice (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_spc_*(): twin of codesplash.quality.spc (qcc 2.7 conventions)

# Classic equivalent: qcc::qcc(qcc.groups(x, sample), type = "xbar"), qcc(type = "R" | "S" | "xbar.one" |
# "p" | "np" | "c" | "u"), qcc::cusum(), qcc::ewma() — same constants and sigma estimators.

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_orangejuice.parquet", col_select = c("Nonconforming", "Size")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Nonconforming", "Size")]), , 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("Nonconforming", "Size"))  # infinite values stop the run (registry/errors.yaml)

# %% Subgroups
chart <- "p"
value_col <- "Nonconforming"
subgroup_col <- NULL
size_col <- "Size"
phase1 <- as.integer(30)
nsigmas <- 3
rules <- "western_electric"
x <- as.numeric(df[[value_col]])
labels_raw <- if (!is.null(subgroup_col)) as.character(df[[subgroup_col]]) else NULL
attribute <- chart %in% c("p", "np", "c", "u", "laney_p")

if (attribute) {
  sizes <- if (!is.null(size_col)) as.numeric(df[[size_col]]) else NULL
  if (!is.null(labels_raw)) {
    lv <- unique(labels_raw)
    d <- vapply(lv, function(l) sum(x[labels_raw == l]), 0)
    n_ <- if (!is.null(sizes)) vapply(lv, function(l) sum(sizes[labels_raw == l]), 0) else NULL
    labels <- lv
  } else {
    d <- x; n_ <- sizes; labels <- as.character(seq_along(x))
  }
  res <- cs_spc_attributes(unname(d), if (is.null(n_)) NULL else unname(n_), chart, phase1, nsigmas)
} else {
  sg <- cs_spc_subgroups(x, labels_raw, NULL)
  groups <- sg$groups; labels <- sg$labels
  if (length(groups) < 2) {  # control limits need two subgroups (registry/errors.yaml)
    if (!is.null(subgroup_col)) cs_error("CS_E_TOO_FEW_GROUPS", column = subgroup_col, min = 2, k = length(groups))
    cs_check_rows(length(x), 2, "A control chart")
  }
  if (chart == "cusum") {
    res <- cs_spc_cusum(groups, phase1, NULL, 5, 1)
  } else if (chart == "ewma") {
    res <- cs_spc_ewma(groups, phase1, NULL, 0.2, nsigmas)
  } else {
    if (chart == "imr" && any(lengths(groups) != 1)) stop("I–MR charts use one value per row; choose X̄–R or X̄–S for subgroups.", call. = FALSE)
    res <- cs_spc_variables(groups, chart, phase1, nsigmas)
  }
}
m <- length(labels)

# %% Signals
if (chart == "cusum") {
  stat <- res$stat
  center <- rep(res$center, m)
  viol_rules <- lapply(seq_len(m), function(i) if (res$pos[i] > res$h || res$neg[i] < -res$h) 1L else integer())
  lcl <- rep(-res$h, m); ucl <- rep(res$h, m)
} else if (chart == "ewma") {
  stat <- res$ewma
  center <- res$center; lcl <- res$lcl; ucl <- res$ucl
  viol_rules <- lapply(seq_len(m), function(i) if (stat[i] > ucl[i] || stat[i] < lcl[i]) 1L else integer())
} else {
  stat <- res$stat; center <- res$center; lcl <- res$lcl; ucl <- res$ucl
  viol_rules <- cs_spc_rules(stat, center, lcl, ucl, res$sd, rules)
}
violations <- which(lengths(viol_rules) > 0)
sec <- res$secondary
sec_viol <- integer()
if (!is.null(sec)) sec_viol <- which(is.finite(sec$stat) & (sec$stat > sec$ucl | sec$stat < sec$lcl))

# %% Tables and chart
chart_labels <- c(xbar_r = "X̄–R", xbar_s = "X̄–S", imr = "I–MR", p = "p", np = "np", c = "c", u = "u",
                  laney_p = "Laney p′", cusum = "CUSUM", ewma = "EWMA")
label <- chart_labels[[chart]]
panel <- c(xbar_r = "X̄", xbar_s = "X̄", imr = "Individuals", p = "p", np = "np", c = "c", u = "u", laney_p = "p′",
           cusum = "CUSUM", ewma = "EWMA")[[chart]]
rule_text <- vapply(viol_rules, function(r) paste(r, collapse = ","), "")
idx <- seq_len(m)
if (chart == "cusum") {
  ch <- data.frame(index = c(idx, idx), value = c(res$pos, res$neg), center = 0, lcl = c(lcl, lcl), ucl = c(ucl, ucl),
                   violation = c(lengths(viol_rules) > 0, lengths(viol_rules) > 0), rule = c(rule_text, rule_text),
                   chart = rep(c("C⁺", "C⁻"), each = m), stringsAsFactors = FALSE)
} else {
  ch <- data.frame(index = idx, value = stat, center = center, lcl = lcl, ucl = ucl, violation = lengths(viol_rules) > 0,
                   rule = rule_text, chart = panel, stringsAsFactors = FALSE)
  if (!is.null(sec)) ch <- rbind(ch, data.frame(index = idx, value = sec$stat, center = sec$center, lcl = sec$lcl, ucl = sec$ucl,
                                                violation = idx %in% sec_viol, rule = ifelse(idx %in% sec_viol, "1", ""),
                                                chart = sec$label, stringsAsFactors = FALSE))
}
charts <- list(cs_chart(
  "control", "control-chart", sprintf("%s chart of %s", label, value_col),
  list(index = cs_col(if (!attribute || !is.null(labels_raw)) "Subgroup" else "Sample", ch$index),
       value = cs_col(if (chart == "imr") value_col else "Statistic", ch$value),
       center = cs_col("Center", ch$center), lcl = cs_col("LCL", ch$lcl), ucl = cs_col("UCL", ch$ucl),
       violation = cs_col("Signal", ch$violation, "boolean"), rule = cs_col("Rules", ch$rule, "categorical"),
       chart = cs_col("Chart", ch$chart, "categorical"))))
tables <- list(list(
  key = "points", title = "Points and limits",
  columns = list(list(key = "label", label = "Subgroup", type = "string"), list(key = "n", label = "n", type = "number"),
                 list(key = "stat", label = "Statistic", type = "number"), list(key = "center", label = "Center", type = "number"),
                 list(key = "lcl", label = "LCL", type = "number"), list(key = "ucl", label = "UCL", type = "number"),
                 list(key = "rules", label = "Rules broken", type = "string")),
  rows = data.frame(label = labels, n = as.numeric(res$sizes), stat = stat, center = center, lcl = lcl, ucl = ucl,
                    rules = vapply(viol_rules, function(r) paste(r, collapse = ", "), ""), stringsAsFactors = FALSE)
))

# %% Result
sizes_arr <- as.numeric(res$sizes)
values <- list(
  chart = chart, chart_label = label, n_subgroups = m, mean_size = mean(sizes_arr),
  center = center[1], sigma = res$sigma,
  stat = I(stat), lcl = I(lcl), ucl = I(ucl),
  violations = I(violations), violation_rules = I(rule_text[lengths(viol_rules) > 0]), n_signals = length(violations),
  sec_stat = if (!is.null(sec)) I(sec$stat) else NULL, sec_center = if (!is.null(sec)) sec$center[1] else NULL,
  sec_lcl = if (!is.null(sec)) I(sec$lcl) else NULL, sec_ucl = if (!is.null(sec)) I(sec$ucl) else NULL,
  sec_violations = I(sec_viol),
  cusum_pos = if (chart == "cusum") I(res$pos) else NULL,
  cusum_neg = if (chart == "cusum") I(res$neg) else NULL
)
rule_names <- c(basic = "points beyond the limits", western_electric = "Western Electric rules", nelson = "Nelson rules")
summary <- sprintf("%s chart of %s: %d %s; ", label, value_col, m, if (mean(sizes_arr) != 1) "subgroups" else "points")
summary <- paste0(summary, if (length(violations)) sprintf("%d signal%s (%s).", length(violations), if (length(violations) != 1) "s" else "",
                                                            if (chart %in% c("cusum", "ewma")) "beyond the limits" else rule_names[[rules]]) else "no signals.")
notes <- sprintf("σ estimated from %s.", if (phase1 > 0 && phase1 < m) sprintf("the first %d subgroups (phase I)", phase1) else "all subgroups")
if (chart %in% c("xbar_r", "xbar_s", "imr"))
  notes <- c(notes, c(xbar_r = "σ = mean(R / d2) (qcc UWAVE-R).", xbar_s = "σ = mean(S / c4) (qcc UWAVE-SD).", imr = "σ = mean moving range / 1.128.")[[chart]])
cs_publish(list(
  method = "spc.control_chart",
  methodVersion = "1.0.1",
  title = sprintf("%s control chart", label),
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(x),
  summary = summary,
  statistics = list(list(key = "center", label = "Center", value = center[1]), list(key = "sigma", label = "σ", value = res$sigma),
                    list(key = "n_subgroups", label = "Subgroups", value = m, format = "integer"),
                    list(key = "n_signals", label = "Signals", value = length(violations), format = "integer")),
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = as.list(notes),
  values = values
))
Python

p chart of Nonconforming: 54 subgroups; 23 signals (Western Electric rules).

Center
0.2313
σ
0.4217
Subgroups
54
Signals
23

To keep this page light, the plots are shown once, under the R tab.

Points and limits

SubgroupnStatisticCenterLCLUCLRules broken
1500.24000.23130.05240.4102
2500.30000.23130.05240.4102
3500.16000.23130.05240.4102
4500.20000.23130.05240.4102
5500.08000.23130.05240.4102
6500.14000.23130.05240.4102
7500.32000.23130.05240.4102
8500.18000.23130.05240.4102
9500.28000.23130.05240.4102
10500.20000.23130.05240.4102
11500.10000.23130.05240.4102
12500.12000.23130.05240.4102
13500.34000.23130.05240.4102
14500.24000.23130.05240.4102
15500.44000.23130.05240.41021
16500.16000.23130.05240.4102
17500.20000.23130.05240.4102
18500.10000.23130.05240.4102
19500.26000.23130.05240.4102
20500.22000.23130.05240.4102
21500.40000.23130.05240.4102
22500.36000.23130.05240.41022
23500.48000.23130.05240.41021, 2
24500.30000.23130.05240.41023
25500.18000.23130.05240.4102
26500.24000.23130.05240.4102
27500.14000.23130.05240.4102
28500.26000.23130.05240.4102
29500.18000.23130.05240.4102
30500.12000.23130.05240.4102
31500.18000.23130.05240.4102
32500.12000.23130.05240.4102
33500.24000.23130.05240.4102
34500.10000.23130.05240.4102
35500.12000.23130.05240.4102
36500.08000.23130.05240.41022, 3
37500.12000.23130.05240.41023
38500.06000.23130.05240.41022, 3
39500.14000.23130.05240.41023
40500.12000.23130.05240.41023

First 40 of 54 rows.

  • σ estimated from the first 30 subgroups (phase I).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Control chart (X̄–R, X̄–S, I–MR, p, np, c, u, Laney p′, CUSUM, EWMA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.control_chart 1.0.1 · spec b9febfd9ce75de3f
# Dataset: q1_orangejuice (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 spc  # twin of codesplashr::cs_spc_* (qcc 2.7 conventions)

# Classic equivalent in R: qcc::qcc(data, type = "xbar" | "R" | "S" | "xbar.one" | "p" | "np" | "c" | "u"),
# qcc::cusum(), qcc::ewma(). Python has no maintained SPC library with the same constants.

# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_orangejuice.parquet", columns=["Nonconforming", "Size"])
n_input = len(df)
df = df.dropna(subset=["Nonconforming", "Size"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Nonconforming", "Size"])  # infinite values stop the run (registry/errors.yaml)

# %% Subgroups
chart = "p"
value_col = "Nonconforming"
subgroup_col = None
size_col = "Size"
phase1 = int(30)
nsigmas = 3
rules = "western_electric"
x = df[value_col].to_numpy(dtype=float)
def _label(v):
    return str(int(v)) if isinstance(v, float) and v.is_integer() else str(v)


labels_raw = [_label(v) for v in df[subgroup_col]] if subgroup_col else None
attribute = chart in ("p", "np", "c", "u", "laney_p")

if attribute:
    sizes = df[size_col].to_numpy(dtype=float) if size_col else None
    if labels_raw is not None:
        order = list(dict.fromkeys(labels_raw))
        d = np.asarray([x[[i for i, l in enumerate(labels_raw) if l == lv]].sum() for lv in order])
        n_ = np.asarray([sizes[[i for i, l in enumerate(labels_raw) if l == lv]].sum() for lv in order]) if sizes is not None else None
        labels = order
    else:
        d, n_, labels = x, sizes, [str(i + 1) for i in range(len(x))]
    res = spc.attributes_chart(d, n_, chart, phase1, nsigmas)
else:
    groups, labels = spc.subgroups(x, labels_raw, None)
    if len(groups) < 2:  # control limits need two subgroups (registry/errors.yaml)
        if subgroup_col:
            cs.cs_error("CS_E_TOO_FEW_GROUPS", column=subgroup_col, min=2, k=len(groups))
        cs.check_rows(len(x), 2, "A control chart")
    if chart == "cusum":
        res = spc.cusum(groups, phase1, None, 5, 1)
    elif chart == "ewma":
        res = spc.ewma(groups, phase1, None, 0.2, nsigmas)
    else:
        if chart == "imr" and any(len(g) != 1 for g in groups):
            raise ValueError("I–MR charts use one value per row; choose X̄–R or X̄–S for subgroups.")
        res = spc.variables_chart(groups, chart, phase1, nsigmas)
m = len(labels)

# %% Signals
if chart == "cusum":
    stat = res["stat"]
    center = np.full(m, res["center"])
    viol_rules = [[1] if (res["pos"][i] > res["h"] or res["neg"][i] < -res["h"]) else [] for i in range(m)]
    lcl = np.full(m, -res["h"])
    ucl = np.full(m, res["h"])
elif chart == "ewma":
    stat = res["ewma"]
    center, lcl, ucl = res["center"], res["lcl"], res["ucl"]
    viol_rules = [[1] if (stat[i] > ucl[i] or stat[i] < lcl[i]) else [] for i in range(m)]
else:
    stat, center, lcl, ucl = res["stat"], res["center"], res["lcl"], res["ucl"]
    viol_rules = spc.run_rules(stat, center, lcl, ucl, res["sd"], rules)
violations = [i + 1 for i in range(m) if viol_rules[i]]
sec = res.get("secondary")
sec_viol = []
if sec:
    s_ok = np.isfinite(sec["stat"])
    sec_viol = [i + 1 for i in range(m) if s_ok[i] and (sec["stat"][i] > sec["ucl"][i] or sec["stat"][i] < sec["lcl"][i])]

# %% Tables and chart
label = spc.CHART_LABEL[chart]
idx = list(range(1, m + 1))
panel = {"xbar_r": "X̄", "xbar_s": "X̄", "imr": "Individuals", "p": "p", "np": "np", "c": "c", "u": "u", "laney_p": "p′", "cusum": "CUSUM", "ewma": "EWMA"}[chart]
rows_idx, rows_val, rows_c, rows_l, rows_u, rows_v, rows_r, rows_f = [], [], [], [], [], [], [], []
if chart == "cusum":
    for name, series in (("C⁺", res["pos"]), ("C⁻", res["neg"])):
        rows_idx += idx; rows_val += list(map(float, series)); rows_c += [0.0] * m; rows_l += list(map(float, lcl)); rows_u += list(map(float, ucl))
        rows_v += [bool(viol_rules[i]) for i in range(m)]; rows_r += [",".join(map(str, viol_rules[i])) for i in range(m)]; rows_f += [name] * m
else:
    rows_idx += idx; rows_val += list(map(float, stat)); rows_c += list(map(float, center)); rows_l += list(map(float, lcl)); rows_u += list(map(float, ucl))
    rows_v += [bool(viol_rules[i]) for i in range(m)]; rows_r += [",".join(map(str, viol_rules[i])) for i in range(m)]; rows_f += [panel] * m
    if sec:
        rows_idx += idx; rows_val += list(map(float, sec["stat"])); rows_c += list(map(float, sec["center"])); rows_l += list(map(float, sec["lcl"]))
        rows_u += list(map(float, sec["ucl"])); rows_v += [i + 1 in sec_viol for i in range(m)]; rows_r += ["1" if i + 1 in sec_viol else "" for i in range(m)]
        rows_f += [sec["label"]] * m
charts = [cs.chart(
    "control", "control-chart", f"{label} chart of {value_col}",
    {"index": cs.col("Subgroup" if not attribute or labels_raw else "Sample", rows_idx),
     "value": cs.col(value_col if chart in ("imr",) else "Statistic", rows_val),
     "center": cs.col("Center", rows_c), "lcl": cs.col("LCL", rows_l), "ucl": cs.col("UCL", rows_u),
     "violation": cs.col("Signal", rows_v, "boolean"), "rule": cs.col("Rules", rows_r, "categorical"),
     "chart": cs.col("Chart", rows_f, "categorical")},
)]
table_rows = []
for i in range(m):
    table_rows.append({"label": labels[i], "n": float(res["sizes"][i]) if res.get("sizes") is not None else None, "stat": float(stat[i]),
                       "center": float(center[i]), "lcl": float(lcl[i]), "ucl": float(ucl[i]), "rules": ", ".join(map(str, viol_rules[i]))})
tables = [{
    "key": "points", "title": "Points and limits",
    "columns": [{"key": "label", "label": "Subgroup", "type": "string"}, {"key": "n", "label": "n", "type": "number"},
                {"key": "stat", "label": "Statistic", "type": "number"}, {"key": "center", "label": "Center", "type": "number"},
                {"key": "lcl", "label": "LCL", "type": "number"}, {"key": "ucl", "label": "UCL", "type": "number"},
                {"key": "rules", "label": "Rules broken", "type": "string"}],
    "rows": table_rows,
}]

# %% Result
sizes_arr = np.asarray(res["sizes"], dtype=float)
values = {
    "chart": chart, "chart_label": label, "n_subgroups": m, "mean_size": float(np.mean(sizes_arr)),
    "center": float(center[0]), "sigma": float(res["sigma"]),
    "stat": list(map(float, stat)), "lcl": list(map(float, lcl)), "ucl": list(map(float, ucl)),
    "violations": violations, "violation_rules": [",".join(map(str, r)) for r in viol_rules if r], "n_signals": len(violations),
    "sec_stat": list(map(float, sec["stat"])) if sec else None, "sec_center": float(sec["center"][0]) if sec else None,
    "sec_lcl": list(map(float, sec["lcl"])) if sec else None, "sec_ucl": list(map(float, sec["ucl"])) if sec else None,
    "sec_violations": sec_viol,
    "cusum_pos": list(map(float, res["pos"])) if chart == "cusum" else None,
    "cusum_neg": list(map(float, res["neg"])) if chart == "cusum" else None,
}
rule_names = {"basic": "points beyond the limits", "western_electric": "Western Electric rules", "nelson": "Nelson rules"}
summary = f"{label} chart of {value_col}: {m} {'subgroups' if np.mean(sizes_arr) != 1 else 'points'}; "
summary += f"{len(violations)} signal{'s' if len(violations) != 1 else ''} ({rule_names[rules] if chart not in ('cusum', 'ewma') else 'beyond the limits'})." if violations else "no signals."
notes = [f"σ estimated from {'the first ' + str(phase1) + ' subgroups (phase I)' if 0 < phase1 < m else 'all subgroups'}."]
if chart in ("xbar_r", "xbar_s", "imr"):
    notes.append({"xbar_r": "σ = mean(R / d2) (qcc UWAVE-R).", "xbar_s": "σ = mean(S / c4) (qcc UWAVE-SD).", "imr": "σ = mean moving range / 1.128."}[chart])
cs.publish({
    "title": f"{label} control chart",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(x),
    "summary": summary,
    "statistics": [
        {"key": "center", "label": "Center", "value": float(center[0])},
        {"key": "sigma", "label": "σ", "value": float(res["sigma"])},
        {"key": "n_subgroups", "label": "Subgroups", "value": m, "format": "integer"},
        {"key": "n_signals", "label": "Signals", "value": len(violations), "format": "integer"},
    ],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": notes,
    "values": values,
})

The limits come from the binomial distribution:

pˉ±3pˉ (1−pˉ)n\bar p \pm 3\sqrt{\frac{\bar p\,(1-\bar p)}{n}}

Check yourself

With p̄ = 0.2313 and n = 50, what is the upper control limit? Give three decimals.

Show the answer

Answer: 0.41

0.2313 + 3 × √(0.2313 × 0.7687 / 50) = 0.2313 + 0.1789 = 0.410.

05

Too many alarms

Read

Binomial limits assume each sample shares one true rate. Real processes vary between samples too. When samples are large, the limits become very narrow, and ordinary variation between samples looks like a signal. That's overdispersionOverdispersionCounts that vary more than a Poisson model allows; standard errors come out too small..

A Laney p′ chartLaney p′ chartA p chart whose limits are widened to match the variation between samples, for when binomial limits are too tight. measures the extra variation from the z-scores of neighboring samples, then widens the limits to match.

06

Try the Laney chart

In the app
Laney p′ control chartRecorded · Python and R agreeRecorded 2026-11-17 · 19 values compared
R

Laney p′ chart of Nonconforming: 54 subgroups; 19 signals (Western Electric rules).

Center
0.1778
σ
0.5275
Subgroups
54
Signals
19

Plots

Laney p′ chart of NonconformingIs the process in statistical control, and where are the signals?
View data
CenterChartSampleLCLRulesUCLStatisticSignal
0.1778p′100.40160.2400false
0.1778p′200.40160.3000false
0.1778p′300.40160.1600false
0.1778p′400.40160.2000false
0.1778p′500.40160.0800false
0.1778p′600.40160.1400false
0.1778p′700.40160.3200false
0.1778p′800.40160.1800false
0.1778p′900.40160.2800false
0.1778p′1000.40160.2000false
0.1778p′1100.40160.1000false
0.1778p′1200.40160.1200false
0.1778p′1300.40160.3400false
0.1778p′1400.40160.2400false
0.1778p′1501,20.40160.4400true
0.1778p′1600.40160.1600false
0.1778p′1700.40160.2000false
0.1778p′1800.40160.1000false
0.1778p′1900.40160.2600false
0.1778p′2000.40160.2200false
0.1778p′2100.40160.4000false
0.1778p′22020.40160.3600true
0.1778p′2301,2,30.40160.4800true
0.1778p′24030.40160.3000true
0.1778p′2500.40160.1800false
0.1778p′26040.40160.2400true
0.1778p′2700.40160.1400false
0.1778p′2800.40160.2600false
0.1778p′2900.40160.1800false
0.1778p′3000.40160.1200false
0.1778p′3100.40160.1800false
0.1778p′3200.40160.1200false
0.1778p′3300.40160.2400false
0.1778p′3400.40160.1000false
0.1778p′3500.40160.1200false
0.1778p′3600.40160.0800false
0.1778p′3700.40160.1200false
0.1778p′3800.40160.0600false
0.1778p′3900.40160.1400false
0.1778p′4000.40160.1200false
0.1778p′41040.40160.0400true
0.1778p′42040.40160.0800true
0.1778p′43040.40160.0600true
0.1778p′44040.40160.1200true
0.1778p′4503,40.40160.1000true
0.1778p′4603,40.40160.0800true
0.1778p′47040.40160.1600true
0.1778p′48040.40160.1000true
0.1778p′49040.40160.1200true
0.1778p′50040.40160.1400true
0.1778p′51040.40160.1000true
0.1778p′52040.40160.1200true
0.1778p′53040.40160.0600true
0.1778p′54040.40160.1000true

Points and limits

SubgroupnStatisticCenterLCLUCLRules broken
1500.24000.177800.4016
2500.30000.177800.4016
3500.16000.177800.4016
4500.20000.177800.4016
5500.08000.177800.4016
6500.14000.177800.4016
7500.32000.177800.4016
8500.18000.177800.4016
9500.28000.177800.4016
10500.20000.177800.4016
11500.10000.177800.4016
12500.12000.177800.4016
13500.34000.177800.4016
14500.24000.177800.4016
15500.44000.177800.40161, 2
16500.16000.177800.4016
17500.20000.177800.4016
18500.10000.177800.4016
19500.26000.177800.4016
20500.22000.177800.4016
21500.40000.177800.4016
22500.36000.177800.40162
23500.48000.177800.40161, 2, 3
24500.30000.177800.40163
25500.18000.177800.4016
26500.24000.177800.40164
27500.14000.177800.4016
28500.26000.177800.4016
29500.18000.177800.4016
30500.12000.177800.4016
31500.18000.177800.4016
32500.12000.177800.4016
33500.24000.177800.4016
34500.10000.177800.4016
35500.12000.177800.4016
36500.08000.177800.4016
37500.12000.177800.4016
38500.06000.177800.4016
39500.14000.177800.4016
40500.12000.177800.4016

First 40 of 54 rows.

  • σ estimated from all subgroups.
The exact R script · R R version 4.5.1 (2025-06-13)
# Control chart (X̄–R, X̄–S, I–MR, p, np, c, u, Laney p′, CUSUM, EWMA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.control_chart 1.0.1 · spec cb7f22d1e83eb02a
# Dataset: q1_orangejuice (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_spc_*(): twin of codesplash.quality.spc (qcc 2.7 conventions)

# Classic equivalent: qcc::qcc(qcc.groups(x, sample), type = "xbar"), qcc(type = "R" | "S" | "xbar.one" |
# "p" | "np" | "c" | "u"), qcc::cusum(), qcc::ewma() — same constants and sigma estimators.

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_orangejuice.parquet", col_select = c("Nonconforming", "Size")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Nonconforming", "Size")]), , 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("Nonconforming", "Size"))  # infinite values stop the run (registry/errors.yaml)

# %% Subgroups
chart <- "laney_p"
value_col <- "Nonconforming"
subgroup_col <- NULL
size_col <- "Size"
phase1 <- as.integer(0)
nsigmas <- 3
rules <- "western_electric"
x <- as.numeric(df[[value_col]])
labels_raw <- if (!is.null(subgroup_col)) as.character(df[[subgroup_col]]) else NULL
attribute <- chart %in% c("p", "np", "c", "u", "laney_p")

if (attribute) {
  sizes <- if (!is.null(size_col)) as.numeric(df[[size_col]]) else NULL
  if (!is.null(labels_raw)) {
    lv <- unique(labels_raw)
    d <- vapply(lv, function(l) sum(x[labels_raw == l]), 0)
    n_ <- if (!is.null(sizes)) vapply(lv, function(l) sum(sizes[labels_raw == l]), 0) else NULL
    labels <- lv
  } else {
    d <- x; n_ <- sizes; labels <- as.character(seq_along(x))
  }
  res <- cs_spc_attributes(unname(d), if (is.null(n_)) NULL else unname(n_), chart, phase1, nsigmas)
} else {
  sg <- cs_spc_subgroups(x, labels_raw, NULL)
  groups <- sg$groups; labels <- sg$labels
  if (length(groups) < 2) {  # control limits need two subgroups (registry/errors.yaml)
    if (!is.null(subgroup_col)) cs_error("CS_E_TOO_FEW_GROUPS", column = subgroup_col, min = 2, k = length(groups))
    cs_check_rows(length(x), 2, "A control chart")
  }
  if (chart == "cusum") {
    res <- cs_spc_cusum(groups, phase1, NULL, 5, 1)
  } else if (chart == "ewma") {
    res <- cs_spc_ewma(groups, phase1, NULL, 0.2, nsigmas)
  } else {
    if (chart == "imr" && any(lengths(groups) != 1)) stop("I–MR charts use one value per row; choose X̄–R or X̄–S for subgroups.", call. = FALSE)
    res <- cs_spc_variables(groups, chart, phase1, nsigmas)
  }
}
m <- length(labels)

# %% Signals
if (chart == "cusum") {
  stat <- res$stat
  center <- rep(res$center, m)
  viol_rules <- lapply(seq_len(m), function(i) if (res$pos[i] > res$h || res$neg[i] < -res$h) 1L else integer())
  lcl <- rep(-res$h, m); ucl <- rep(res$h, m)
} else if (chart == "ewma") {
  stat <- res$ewma
  center <- res$center; lcl <- res$lcl; ucl <- res$ucl
  viol_rules <- lapply(seq_len(m), function(i) if (stat[i] > ucl[i] || stat[i] < lcl[i]) 1L else integer())
} else {
  stat <- res$stat; center <- res$center; lcl <- res$lcl; ucl <- res$ucl
  viol_rules <- cs_spc_rules(stat, center, lcl, ucl, res$sd, rules)
}
violations <- which(lengths(viol_rules) > 0)
sec <- res$secondary
sec_viol <- integer()
if (!is.null(sec)) sec_viol <- which(is.finite(sec$stat) & (sec$stat > sec$ucl | sec$stat < sec$lcl))

# %% Tables and chart
chart_labels <- c(xbar_r = "X̄–R", xbar_s = "X̄–S", imr = "I–MR", p = "p", np = "np", c = "c", u = "u",
                  laney_p = "Laney p′", cusum = "CUSUM", ewma = "EWMA")
label <- chart_labels[[chart]]
panel <- c(xbar_r = "X̄", xbar_s = "X̄", imr = "Individuals", p = "p", np = "np", c = "c", u = "u", laney_p = "p′",
           cusum = "CUSUM", ewma = "EWMA")[[chart]]
rule_text <- vapply(viol_rules, function(r) paste(r, collapse = ","), "")
idx <- seq_len(m)
if (chart == "cusum") {
  ch <- data.frame(index = c(idx, idx), value = c(res$pos, res$neg), center = 0, lcl = c(lcl, lcl), ucl = c(ucl, ucl),
                   violation = c(lengths(viol_rules) > 0, lengths(viol_rules) > 0), rule = c(rule_text, rule_text),
                   chart = rep(c("C⁺", "C⁻"), each = m), stringsAsFactors = FALSE)
} else {
  ch <- data.frame(index = idx, value = stat, center = center, lcl = lcl, ucl = ucl, violation = lengths(viol_rules) > 0,
                   rule = rule_text, chart = panel, stringsAsFactors = FALSE)
  if (!is.null(sec)) ch <- rbind(ch, data.frame(index = idx, value = sec$stat, center = sec$center, lcl = sec$lcl, ucl = sec$ucl,
                                                violation = idx %in% sec_viol, rule = ifelse(idx %in% sec_viol, "1", ""),
                                                chart = sec$label, stringsAsFactors = FALSE))
}
charts <- list(cs_chart(
  "control", "control-chart", sprintf("%s chart of %s", label, value_col),
  list(index = cs_col(if (!attribute || !is.null(labels_raw)) "Subgroup" else "Sample", ch$index),
       value = cs_col(if (chart == "imr") value_col else "Statistic", ch$value),
       center = cs_col("Center", ch$center), lcl = cs_col("LCL", ch$lcl), ucl = cs_col("UCL", ch$ucl),
       violation = cs_col("Signal", ch$violation, "boolean"), rule = cs_col("Rules", ch$rule, "categorical"),
       chart = cs_col("Chart", ch$chart, "categorical"))))
tables <- list(list(
  key = "points", title = "Points and limits",
  columns = list(list(key = "label", label = "Subgroup", type = "string"), list(key = "n", label = "n", type = "number"),
                 list(key = "stat", label = "Statistic", type = "number"), list(key = "center", label = "Center", type = "number"),
                 list(key = "lcl", label = "LCL", type = "number"), list(key = "ucl", label = "UCL", type = "number"),
                 list(key = "rules", label = "Rules broken", type = "string")),
  rows = data.frame(label = labels, n = as.numeric(res$sizes), stat = stat, center = center, lcl = lcl, ucl = ucl,
                    rules = vapply(viol_rules, function(r) paste(r, collapse = ", "), ""), stringsAsFactors = FALSE)
))

# %% Result
sizes_arr <- as.numeric(res$sizes)
values <- list(
  chart = chart, chart_label = label, n_subgroups = m, mean_size = mean(sizes_arr),
  center = center[1], sigma = res$sigma,
  stat = I(stat), lcl = I(lcl), ucl = I(ucl),
  violations = I(violations), violation_rules = I(rule_text[lengths(viol_rules) > 0]), n_signals = length(violations),
  sec_stat = if (!is.null(sec)) I(sec$stat) else NULL, sec_center = if (!is.null(sec)) sec$center[1] else NULL,
  sec_lcl = if (!is.null(sec)) I(sec$lcl) else NULL, sec_ucl = if (!is.null(sec)) I(sec$ucl) else NULL,
  sec_violations = I(sec_viol),
  cusum_pos = if (chart == "cusum") I(res$pos) else NULL,
  cusum_neg = if (chart == "cusum") I(res$neg) else NULL
)
rule_names <- c(basic = "points beyond the limits", western_electric = "Western Electric rules", nelson = "Nelson rules")
summary <- sprintf("%s chart of %s: %d %s; ", label, value_col, m, if (mean(sizes_arr) != 1) "subgroups" else "points")
summary <- paste0(summary, if (length(violations)) sprintf("%d signal%s (%s).", length(violations), if (length(violations) != 1) "s" else "",
                                                            if (chart %in% c("cusum", "ewma")) "beyond the limits" else rule_names[[rules]]) else "no signals.")
notes <- sprintf("σ estimated from %s.", if (phase1 > 0 && phase1 < m) sprintf("the first %d subgroups (phase I)", phase1) else "all subgroups")
if (chart %in% c("xbar_r", "xbar_s", "imr"))
  notes <- c(notes, c(xbar_r = "σ = mean(R / d2) (qcc UWAVE-R).", xbar_s = "σ = mean(S / c4) (qcc UWAVE-SD).", imr = "σ = mean moving range / 1.128.")[[chart]])
cs_publish(list(
  method = "spc.control_chart",
  methodVersion = "1.0.1",
  title = sprintf("%s control chart", label),
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(x),
  summary = summary,
  statistics = list(list(key = "center", label = "Center", value = center[1]), list(key = "sigma", label = "σ", value = res$sigma),
                    list(key = "n_subgroups", label = "Subgroups", value = m, format = "integer"),
                    list(key = "n_signals", label = "Signals", value = length(violations), format = "integer")),
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = as.list(notes),
  values = values
))
Python

Laney p′ chart of Nonconforming: 54 subgroups; 19 signals (Western Electric rules).

Center
0.1778
σ
0.5275
Subgroups
54
Signals
19

To keep this page light, the plots are shown once, under the R tab.

Points and limits

SubgroupnStatisticCenterLCLUCLRules broken
1500.24000.177800.4016
2500.30000.177800.4016
3500.16000.177800.4016
4500.20000.177800.4016
5500.08000.177800.4016
6500.14000.177800.4016
7500.32000.177800.4016
8500.18000.177800.4016
9500.28000.177800.4016
10500.20000.177800.4016
11500.10000.177800.4016
12500.12000.177800.4016
13500.34000.177800.4016
14500.24000.177800.4016
15500.44000.177800.40161, 2
16500.16000.177800.4016
17500.20000.177800.4016
18500.10000.177800.4016
19500.26000.177800.4016
20500.22000.177800.4016
21500.40000.177800.4016
22500.36000.177800.40162
23500.48000.177800.40161, 2, 3
24500.30000.177800.40163
25500.18000.177800.4016
26500.24000.177800.40164
27500.14000.177800.4016
28500.26000.177800.4016
29500.18000.177800.4016
30500.12000.177800.4016
31500.18000.177800.4016
32500.12000.177800.4016
33500.24000.177800.4016
34500.10000.177800.4016
35500.12000.177800.4016
36500.08000.177800.4016
37500.12000.177800.4016
38500.06000.177800.4016
39500.14000.177800.4016
40500.12000.177800.4016

First 40 of 54 rows.

  • σ estimated from all subgroups.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Control chart (X̄–R, X̄–S, I–MR, p, np, c, u, Laney p′, CUSUM, EWMA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.control_chart 1.0.1 · spec cb7f22d1e83eb02a
# Dataset: q1_orangejuice (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 spc  # twin of codesplashr::cs_spc_* (qcc 2.7 conventions)

# Classic equivalent in R: qcc::qcc(data, type = "xbar" | "R" | "S" | "xbar.one" | "p" | "np" | "c" | "u"),
# qcc::cusum(), qcc::ewma(). Python has no maintained SPC library with the same constants.

# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_orangejuice.parquet", columns=["Nonconforming", "Size"])
n_input = len(df)
df = df.dropna(subset=["Nonconforming", "Size"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Nonconforming", "Size"])  # infinite values stop the run (registry/errors.yaml)

# %% Subgroups
chart = "laney_p"
value_col = "Nonconforming"
subgroup_col = None
size_col = "Size"
phase1 = int(0)
nsigmas = 3
rules = "western_electric"
x = df[value_col].to_numpy(dtype=float)
def _label(v):
    return str(int(v)) if isinstance(v, float) and v.is_integer() else str(v)


labels_raw = [_label(v) for v in df[subgroup_col]] if subgroup_col else None
attribute = chart in ("p", "np", "c", "u", "laney_p")

if attribute:
    sizes = df[size_col].to_numpy(dtype=float) if size_col else None
    if labels_raw is not None:
        order = list(dict.fromkeys(labels_raw))
        d = np.asarray([x[[i for i, l in enumerate(labels_raw) if l == lv]].sum() for lv in order])
        n_ = np.asarray([sizes[[i for i, l in enumerate(labels_raw) if l == lv]].sum() for lv in order]) if sizes is not None else None
        labels = order
    else:
        d, n_, labels = x, sizes, [str(i + 1) for i in range(len(x))]
    res = spc.attributes_chart(d, n_, chart, phase1, nsigmas)
else:
    groups, labels = spc.subgroups(x, labels_raw, None)
    if len(groups) < 2:  # control limits need two subgroups (registry/errors.yaml)
        if subgroup_col:
            cs.cs_error("CS_E_TOO_FEW_GROUPS", column=subgroup_col, min=2, k=len(groups))
        cs.check_rows(len(x), 2, "A control chart")
    if chart == "cusum":
        res = spc.cusum(groups, phase1, None, 5, 1)
    elif chart == "ewma":
        res = spc.ewma(groups, phase1, None, 0.2, nsigmas)
    else:
        if chart == "imr" and any(len(g) != 1 for g in groups):
            raise ValueError("I–MR charts use one value per row; choose X̄–R or X̄–S for subgroups.")
        res = spc.variables_chart(groups, chart, phase1, nsigmas)
m = len(labels)

# %% Signals
if chart == "cusum":
    stat = res["stat"]
    center = np.full(m, res["center"])
    viol_rules = [[1] if (res["pos"][i] > res["h"] or res["neg"][i] < -res["h"]) else [] for i in range(m)]
    lcl = np.full(m, -res["h"])
    ucl = np.full(m, res["h"])
elif chart == "ewma":
    stat = res["ewma"]
    center, lcl, ucl = res["center"], res["lcl"], res["ucl"]
    viol_rules = [[1] if (stat[i] > ucl[i] or stat[i] < lcl[i]) else [] for i in range(m)]
else:
    stat, center, lcl, ucl = res["stat"], res["center"], res["lcl"], res["ucl"]
    viol_rules = spc.run_rules(stat, center, lcl, ucl, res["sd"], rules)
violations = [i + 1 for i in range(m) if viol_rules[i]]
sec = res.get("secondary")
sec_viol = []
if sec:
    s_ok = np.isfinite(sec["stat"])
    sec_viol = [i + 1 for i in range(m) if s_ok[i] and (sec["stat"][i] > sec["ucl"][i] or sec["stat"][i] < sec["lcl"][i])]

# %% Tables and chart
label = spc.CHART_LABEL[chart]
idx = list(range(1, m + 1))
panel = {"xbar_r": "X̄", "xbar_s": "X̄", "imr": "Individuals", "p": "p", "np": "np", "c": "c", "u": "u", "laney_p": "p′", "cusum": "CUSUM", "ewma": "EWMA"}[chart]
rows_idx, rows_val, rows_c, rows_l, rows_u, rows_v, rows_r, rows_f = [], [], [], [], [], [], [], []
if chart == "cusum":
    for name, series in (("C⁺", res["pos"]), ("C⁻", res["neg"])):
        rows_idx += idx; rows_val += list(map(float, series)); rows_c += [0.0] * m; rows_l += list(map(float, lcl)); rows_u += list(map(float, ucl))
        rows_v += [bool(viol_rules[i]) for i in range(m)]; rows_r += [",".join(map(str, viol_rules[i])) for i in range(m)]; rows_f += [name] * m
else:
    rows_idx += idx; rows_val += list(map(float, stat)); rows_c += list(map(float, center)); rows_l += list(map(float, lcl)); rows_u += list(map(float, ucl))
    rows_v += [bool(viol_rules[i]) for i in range(m)]; rows_r += [",".join(map(str, viol_rules[i])) for i in range(m)]; rows_f += [panel] * m
    if sec:
        rows_idx += idx; rows_val += list(map(float, sec["stat"])); rows_c += list(map(float, sec["center"])); rows_l += list(map(float, sec["lcl"]))
        rows_u += list(map(float, sec["ucl"])); rows_v += [i + 1 in sec_viol for i in range(m)]; rows_r += ["1" if i + 1 in sec_viol else "" for i in range(m)]
        rows_f += [sec["label"]] * m
charts = [cs.chart(
    "control", "control-chart", f"{label} chart of {value_col}",
    {"index": cs.col("Subgroup" if not attribute or labels_raw else "Sample", rows_idx),
     "value": cs.col(value_col if chart in ("imr",) else "Statistic", rows_val),
     "center": cs.col("Center", rows_c), "lcl": cs.col("LCL", rows_l), "ucl": cs.col("UCL", rows_u),
     "violation": cs.col("Signal", rows_v, "boolean"), "rule": cs.col("Rules", rows_r, "categorical"),
     "chart": cs.col("Chart", rows_f, "categorical")},
)]
table_rows = []
for i in range(m):
    table_rows.append({"label": labels[i], "n": float(res["sizes"][i]) if res.get("sizes") is not None else None, "stat": float(stat[i]),
                       "center": float(center[i]), "lcl": float(lcl[i]), "ucl": float(ucl[i]), "rules": ", ".join(map(str, viol_rules[i]))})
tables = [{
    "key": "points", "title": "Points and limits",
    "columns": [{"key": "label", "label": "Subgroup", "type": "string"}, {"key": "n", "label": "n", "type": "number"},
                {"key": "stat", "label": "Statistic", "type": "number"}, {"key": "center", "label": "Center", "type": "number"},
                {"key": "lcl", "label": "LCL", "type": "number"}, {"key": "ucl", "label": "UCL", "type": "number"},
                {"key": "rules", "label": "Rules broken", "type": "string"}],
    "rows": table_rows,
}]

# %% Result
sizes_arr = np.asarray(res["sizes"], dtype=float)
values = {
    "chart": chart, "chart_label": label, "n_subgroups": m, "mean_size": float(np.mean(sizes_arr)),
    "center": float(center[0]), "sigma": float(res["sigma"]),
    "stat": list(map(float, stat)), "lcl": list(map(float, lcl)), "ucl": list(map(float, ucl)),
    "violations": violations, "violation_rules": [",".join(map(str, r)) for r in viol_rules if r], "n_signals": len(violations),
    "sec_stat": list(map(float, sec["stat"])) if sec else None, "sec_center": float(sec["center"][0]) if sec else None,
    "sec_lcl": list(map(float, sec["lcl"])) if sec else None, "sec_ucl": list(map(float, sec["ucl"])) if sec else None,
    "sec_violations": sec_viol,
    "cusum_pos": list(map(float, res["pos"])) if chart == "cusum" else None,
    "cusum_neg": list(map(float, res["neg"])) if chart == "cusum" else None,
}
rule_names = {"basic": "points beyond the limits", "western_electric": "Western Electric rules", "nelson": "Nelson rules"}
summary = f"{label} chart of {value_col}: {m} {'subgroups' if np.mean(sizes_arr) != 1 else 'points'}; "
summary += f"{len(violations)} signal{'s' if len(violations) != 1 else ''} ({rule_names[rules] if chart not in ('cusum', 'ewma') else 'beyond the limits'})." if violations else "no signals."
notes = [f"σ estimated from {'the first ' + str(phase1) + ' subgroups (phase I)' if 0 < phase1 < m else 'all subgroups'}."]
if chart in ("xbar_r", "xbar_s", "imr"):
    notes.append({"xbar_r": "σ = mean(R / d2) (qcc UWAVE-R).", "xbar_s": "σ = mean(S / c4) (qcc UWAVE-SD).", "imr": "σ = mean moving range / 1.128."}[chart])
cs.publish({
    "title": f"{label} control chart",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(x),
    "summary": summary,
    "statistics": [
        {"key": "center", "label": "Center", "value": float(center[0])},
        {"key": "sigma", "label": "σ", "value": float(res["sigma"])},
        {"key": "n_subgroups", "label": "Subgroups", "value": m, "format": "integer"},
        {"key": "n_signals", "label": "Signals", "value": len(violations), "format": "integer"},
    ],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": notes,
    "values": values,
})

Using all the samples, the center is 0.178, and the card's scaled sigma is 0.528. The plain binomial value is 0.178×0.822=0.382\sqrt{0.178 \times 0.822} = 0.382, so the limits are about 0.528/0.382=1.380.528 / 0.382 = 1.38 times wider.

19 points still signal. Wider limits absorb routine variation, and they don't hide a real, sustained change.

07

Counting defects

In the app

Circuit boards are inspected for flaws, in a fixed inspection unit. A c chart assumes Poisson counts, so its standard deviation is the square root of its mean.

c control chartRecorded · Python and R agreeRecorded 2026-11-17 · 19 values compared
R

c chart of Defects: 46 points; 5 signals (Western Electric rules).

Center
19.174
σ
4.379
Subgroups
46
Signals
5

Plots

c chart of DefectsIs the process in statistical control, and where are the signals?
View data
CenterChartSampleLCLRulesUCLStatisticSignal
19.174c16.03832.31021false
19.174c26.03832.31024false
19.174c36.03832.31016false
19.174c46.03832.31012false
19.174c56.03832.31015false
19.174c66.038132.3105true
19.174c76.03832.31028false
19.174c86.03832.31020false
19.174c96.038232.31031true
19.174c106.03832.31025false
19.174c116.03832.31020false
19.174c126.03832.31024false
19.174c136.03832.31016false
19.174c146.03832.31019false
19.174c156.03832.31010false
19.174c166.03832.31017false
19.174c176.03832.31013false
19.174c186.03832.31022false
19.174c196.03832.31018false
19.174c206.038132.31039true
19.174c216.038232.31030true
19.174c226.03832.31024false
19.174c236.03832.31016false
19.174c246.03832.31019false
19.174c256.03832.31017false
19.174c266.03832.31015false
19.174c276.03832.31016false
19.174c286.03832.31018false
19.174c296.03832.31012false
19.174c306.038432.31015true
19.174c316.03832.31024false
19.174c326.03832.31021false
19.174c336.03832.31028false
19.174c346.03832.31020false
19.174c356.03832.31025false
19.174c366.03832.31019false
19.174c376.03832.31018false
19.174c386.03832.31021false
19.174c396.03832.31016false
19.174c406.03832.31022false
19.174c416.03832.31019false
19.174c426.03832.31012false
19.174c436.03832.31014false
19.174c446.03832.3109false
19.174c456.03832.31016false
19.174c466.03832.31021false

Points and limits

SubgroupnStatisticCenterLCLUCLRules broken
112119.1746.03832.310
212419.1746.03832.310
311619.1746.03832.310
411219.1746.03832.310
511519.1746.03832.310
61519.1746.03832.3101
712819.1746.03832.310
812019.1746.03832.310
913119.1746.03832.3102
1012519.1746.03832.310
1112019.1746.03832.310
1212419.1746.03832.310
1311619.1746.03832.310
1411919.1746.03832.310
1511019.1746.03832.310
1611719.1746.03832.310
1711319.1746.03832.310
1812219.1746.03832.310
1911819.1746.03832.310
2013919.1746.03832.3101
2113019.1746.03832.3102
2212419.1746.03832.310
2311619.1746.03832.310
2411919.1746.03832.310
2511719.1746.03832.310
2611519.1746.03832.310
2711619.1746.03832.310
2811819.1746.03832.310
2911219.1746.03832.310
3011519.1746.03832.3104
3112419.1746.03832.310
3212119.1746.03832.310
3312819.1746.03832.310
3412019.1746.03832.310
3512519.1746.03832.310
3611919.1746.03832.310
3711819.1746.03832.310
3812119.1746.03832.310
3911619.1746.03832.310
4012219.1746.03832.310

First 40 of 46 rows.

  • σ estimated from all subgroups.
The exact R script · R R version 4.5.1 (2025-06-13)
# Control chart (X̄–R, X̄–S, I–MR, p, np, c, u, Laney p′, CUSUM, EWMA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.control_chart 1.0.1 · spec f13918f944567f74
# Dataset: q1_circuit (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_spc_*(): twin of codesplash.quality.spc (qcc 2.7 conventions)

# Classic equivalent: qcc::qcc(qcc.groups(x, sample), type = "xbar"), qcc(type = "R" | "S" | "xbar.one" |
# "p" | "np" | "c" | "u"), qcc::cusum(), qcc::ewma() — same constants and sigma estimators.

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_circuit.parquet", col_select = c("Defects")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Defects")]), , 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("Defects"))  # infinite values stop the run (registry/errors.yaml)

# %% Subgroups
chart <- "c"
value_col <- "Defects"
subgroup_col <- NULL
size_col <- NULL
phase1 <- as.integer(0)
nsigmas <- 3
rules <- "western_electric"
x <- as.numeric(df[[value_col]])
labels_raw <- if (!is.null(subgroup_col)) as.character(df[[subgroup_col]]) else NULL
attribute <- chart %in% c("p", "np", "c", "u", "laney_p")

if (attribute) {
  sizes <- if (!is.null(size_col)) as.numeric(df[[size_col]]) else NULL
  if (!is.null(labels_raw)) {
    lv <- unique(labels_raw)
    d <- vapply(lv, function(l) sum(x[labels_raw == l]), 0)
    n_ <- if (!is.null(sizes)) vapply(lv, function(l) sum(sizes[labels_raw == l]), 0) else NULL
    labels <- lv
  } else {
    d <- x; n_ <- sizes; labels <- as.character(seq_along(x))
  }
  res <- cs_spc_attributes(unname(d), if (is.null(n_)) NULL else unname(n_), chart, phase1, nsigmas)
} else {
  sg <- cs_spc_subgroups(x, labels_raw, NULL)
  groups <- sg$groups; labels <- sg$labels
  if (length(groups) < 2) {  # control limits need two subgroups (registry/errors.yaml)
    if (!is.null(subgroup_col)) cs_error("CS_E_TOO_FEW_GROUPS", column = subgroup_col, min = 2, k = length(groups))
    cs_check_rows(length(x), 2, "A control chart")
  }
  if (chart == "cusum") {
    res <- cs_spc_cusum(groups, phase1, NULL, 5, 1)
  } else if (chart == "ewma") {
    res <- cs_spc_ewma(groups, phase1, NULL, 0.2, nsigmas)
  } else {
    if (chart == "imr" && any(lengths(groups) != 1)) stop("I–MR charts use one value per row; choose X̄–R or X̄–S for subgroups.", call. = FALSE)
    res <- cs_spc_variables(groups, chart, phase1, nsigmas)
  }
}
m <- length(labels)

# %% Signals
if (chart == "cusum") {
  stat <- res$stat
  center <- rep(res$center, m)
  viol_rules <- lapply(seq_len(m), function(i) if (res$pos[i] > res$h || res$neg[i] < -res$h) 1L else integer())
  lcl <- rep(-res$h, m); ucl <- rep(res$h, m)
} else if (chart == "ewma") {
  stat <- res$ewma
  center <- res$center; lcl <- res$lcl; ucl <- res$ucl
  viol_rules <- lapply(seq_len(m), function(i) if (stat[i] > ucl[i] || stat[i] < lcl[i]) 1L else integer())
} else {
  stat <- res$stat; center <- res$center; lcl <- res$lcl; ucl <- res$ucl
  viol_rules <- cs_spc_rules(stat, center, lcl, ucl, res$sd, rules)
}
violations <- which(lengths(viol_rules) > 0)
sec <- res$secondary
sec_viol <- integer()
if (!is.null(sec)) sec_viol <- which(is.finite(sec$stat) & (sec$stat > sec$ucl | sec$stat < sec$lcl))

# %% Tables and chart
chart_labels <- c(xbar_r = "X̄–R", xbar_s = "X̄–S", imr = "I–MR", p = "p", np = "np", c = "c", u = "u",
                  laney_p = "Laney p′", cusum = "CUSUM", ewma = "EWMA")
label <- chart_labels[[chart]]
panel <- c(xbar_r = "X̄", xbar_s = "X̄", imr = "Individuals", p = "p", np = "np", c = "c", u = "u", laney_p = "p′",
           cusum = "CUSUM", ewma = "EWMA")[[chart]]
rule_text <- vapply(viol_rules, function(r) paste(r, collapse = ","), "")
idx <- seq_len(m)
if (chart == "cusum") {
  ch <- data.frame(index = c(idx, idx), value = c(res$pos, res$neg), center = 0, lcl = c(lcl, lcl), ucl = c(ucl, ucl),
                   violation = c(lengths(viol_rules) > 0, lengths(viol_rules) > 0), rule = c(rule_text, rule_text),
                   chart = rep(c("C⁺", "C⁻"), each = m), stringsAsFactors = FALSE)
} else {
  ch <- data.frame(index = idx, value = stat, center = center, lcl = lcl, ucl = ucl, violation = lengths(viol_rules) > 0,
                   rule = rule_text, chart = panel, stringsAsFactors = FALSE)
  if (!is.null(sec)) ch <- rbind(ch, data.frame(index = idx, value = sec$stat, center = sec$center, lcl = sec$lcl, ucl = sec$ucl,
                                                violation = idx %in% sec_viol, rule = ifelse(idx %in% sec_viol, "1", ""),
                                                chart = sec$label, stringsAsFactors = FALSE))
}
charts <- list(cs_chart(
  "control", "control-chart", sprintf("%s chart of %s", label, value_col),
  list(index = cs_col(if (!attribute || !is.null(labels_raw)) "Subgroup" else "Sample", ch$index),
       value = cs_col(if (chart == "imr") value_col else "Statistic", ch$value),
       center = cs_col("Center", ch$center), lcl = cs_col("LCL", ch$lcl), ucl = cs_col("UCL", ch$ucl),
       violation = cs_col("Signal", ch$violation, "boolean"), rule = cs_col("Rules", ch$rule, "categorical"),
       chart = cs_col("Chart", ch$chart, "categorical"))))
tables <- list(list(
  key = "points", title = "Points and limits",
  columns = list(list(key = "label", label = "Subgroup", type = "string"), list(key = "n", label = "n", type = "number"),
                 list(key = "stat", label = "Statistic", type = "number"), list(key = "center", label = "Center", type = "number"),
                 list(key = "lcl", label = "LCL", type = "number"), list(key = "ucl", label = "UCL", type = "number"),
                 list(key = "rules", label = "Rules broken", type = "string")),
  rows = data.frame(label = labels, n = as.numeric(res$sizes), stat = stat, center = center, lcl = lcl, ucl = ucl,
                    rules = vapply(viol_rules, function(r) paste(r, collapse = ", "), ""), stringsAsFactors = FALSE)
))

# %% Result
sizes_arr <- as.numeric(res$sizes)
values <- list(
  chart = chart, chart_label = label, n_subgroups = m, mean_size = mean(sizes_arr),
  center = center[1], sigma = res$sigma,
  stat = I(stat), lcl = I(lcl), ucl = I(ucl),
  violations = I(violations), violation_rules = I(rule_text[lengths(viol_rules) > 0]), n_signals = length(violations),
  sec_stat = if (!is.null(sec)) I(sec$stat) else NULL, sec_center = if (!is.null(sec)) sec$center[1] else NULL,
  sec_lcl = if (!is.null(sec)) I(sec$lcl) else NULL, sec_ucl = if (!is.null(sec)) I(sec$ucl) else NULL,
  sec_violations = I(sec_viol),
  cusum_pos = if (chart == "cusum") I(res$pos) else NULL,
  cusum_neg = if (chart == "cusum") I(res$neg) else NULL
)
rule_names <- c(basic = "points beyond the limits", western_electric = "Western Electric rules", nelson = "Nelson rules")
summary <- sprintf("%s chart of %s: %d %s; ", label, value_col, m, if (mean(sizes_arr) != 1) "subgroups" else "points")
summary <- paste0(summary, if (length(violations)) sprintf("%d signal%s (%s).", length(violations), if (length(violations) != 1) "s" else "",
                                                            if (chart %in% c("cusum", "ewma")) "beyond the limits" else rule_names[[rules]]) else "no signals.")
notes <- sprintf("σ estimated from %s.", if (phase1 > 0 && phase1 < m) sprintf("the first %d subgroups (phase I)", phase1) else "all subgroups")
if (chart %in% c("xbar_r", "xbar_s", "imr"))
  notes <- c(notes, c(xbar_r = "σ = mean(R / d2) (qcc UWAVE-R).", xbar_s = "σ = mean(S / c4) (qcc UWAVE-SD).", imr = "σ = mean moving range / 1.128.")[[chart]])
cs_publish(list(
  method = "spc.control_chart",
  methodVersion = "1.0.1",
  title = sprintf("%s control chart", label),
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(x),
  summary = summary,
  statistics = list(list(key = "center", label = "Center", value = center[1]), list(key = "sigma", label = "σ", value = res$sigma),
                    list(key = "n_subgroups", label = "Subgroups", value = m, format = "integer"),
                    list(key = "n_signals", label = "Signals", value = length(violations), format = "integer")),
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = as.list(notes),
  values = values
))
Python

c chart of Defects: 46 points; 5 signals (Western Electric rules).

Center
19.174
σ
4.379
Subgroups
46
Signals
5

To keep this page light, the plots are shown once, under the R tab.

Points and limits

SubgroupnStatisticCenterLCLUCLRules broken
112119.1746.03832.310
212419.1746.03832.310
311619.1746.03832.310
411219.1746.03832.310
511519.1746.03832.310
61519.1746.03832.3101
712819.1746.03832.310
812019.1746.03832.310
913119.1746.03832.3102
1012519.1746.03832.310
1112019.1746.03832.310
1212419.1746.03832.310
1311619.1746.03832.310
1411919.1746.03832.310
1511019.1746.03832.310
1611719.1746.03832.310
1711319.1746.03832.310
1812219.1746.03832.310
1911819.1746.03832.310
2013919.1746.03832.3101
2113019.1746.03832.3102
2212419.1746.03832.310
2311619.1746.03832.310
2411919.1746.03832.310
2511719.1746.03832.310
2611519.1746.03832.310
2711619.1746.03832.310
2811819.1746.03832.310
2911219.1746.03832.310
3011519.1746.03832.3104
3112419.1746.03832.310
3212119.1746.03832.310
3312819.1746.03832.310
3412019.1746.03832.310
3512519.1746.03832.310
3611919.1746.03832.310
3711819.1746.03832.310
3812119.1746.03832.310
3911619.1746.03832.310
4012219.1746.03832.310

First 40 of 46 rows.

  • σ estimated from all subgroups.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Control chart (X̄–R, X̄–S, I–MR, p, np, c, u, Laney p′, CUSUM, EWMA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.control_chart 1.0.1 · spec f13918f944567f74
# Dataset: q1_circuit (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 spc  # twin of codesplashr::cs_spc_* (qcc 2.7 conventions)

# Classic equivalent in R: qcc::qcc(data, type = "xbar" | "R" | "S" | "xbar.one" | "p" | "np" | "c" | "u"),
# qcc::cusum(), qcc::ewma(). Python has no maintained SPC library with the same constants.

# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_circuit.parquet", columns=["Defects"])
n_input = len(df)
df = df.dropna(subset=["Defects"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Defects"])  # infinite values stop the run (registry/errors.yaml)

# %% Subgroups
chart = "c"
value_col = "Defects"
subgroup_col = None
size_col = None
phase1 = int(0)
nsigmas = 3
rules = "western_electric"
x = df[value_col].to_numpy(dtype=float)
def _label(v):
    return str(int(v)) if isinstance(v, float) and v.is_integer() else str(v)


labels_raw = [_label(v) for v in df[subgroup_col]] if subgroup_col else None
attribute = chart in ("p", "np", "c", "u", "laney_p")

if attribute:
    sizes = df[size_col].to_numpy(dtype=float) if size_col else None
    if labels_raw is not None:
        order = list(dict.fromkeys(labels_raw))
        d = np.asarray([x[[i for i, l in enumerate(labels_raw) if l == lv]].sum() for lv in order])
        n_ = np.asarray([sizes[[i for i, l in enumerate(labels_raw) if l == lv]].sum() for lv in order]) if sizes is not None else None
        labels = order
    else:
        d, n_, labels = x, sizes, [str(i + 1) for i in range(len(x))]
    res = spc.attributes_chart(d, n_, chart, phase1, nsigmas)
else:
    groups, labels = spc.subgroups(x, labels_raw, None)
    if len(groups) < 2:  # control limits need two subgroups (registry/errors.yaml)
        if subgroup_col:
            cs.cs_error("CS_E_TOO_FEW_GROUPS", column=subgroup_col, min=2, k=len(groups))
        cs.check_rows(len(x), 2, "A control chart")
    if chart == "cusum":
        res = spc.cusum(groups, phase1, None, 5, 1)
    elif chart == "ewma":
        res = spc.ewma(groups, phase1, None, 0.2, nsigmas)
    else:
        if chart == "imr" and any(len(g) != 1 for g in groups):
            raise ValueError("I–MR charts use one value per row; choose X̄–R or X̄–S for subgroups.")
        res = spc.variables_chart(groups, chart, phase1, nsigmas)
m = len(labels)

# %% Signals
if chart == "cusum":
    stat = res["stat"]
    center = np.full(m, res["center"])
    viol_rules = [[1] if (res["pos"][i] > res["h"] or res["neg"][i] < -res["h"]) else [] for i in range(m)]
    lcl = np.full(m, -res["h"])
    ucl = np.full(m, res["h"])
elif chart == "ewma":
    stat = res["ewma"]
    center, lcl, ucl = res["center"], res["lcl"], res["ucl"]
    viol_rules = [[1] if (stat[i] > ucl[i] or stat[i] < lcl[i]) else [] for i in range(m)]
else:
    stat, center, lcl, ucl = res["stat"], res["center"], res["lcl"], res["ucl"]
    viol_rules = spc.run_rules(stat, center, lcl, ucl, res["sd"], rules)
violations = [i + 1 for i in range(m) if viol_rules[i]]
sec = res.get("secondary")
sec_viol = []
if sec:
    s_ok = np.isfinite(sec["stat"])
    sec_viol = [i + 1 for i in range(m) if s_ok[i] and (sec["stat"][i] > sec["ucl"][i] or sec["stat"][i] < sec["lcl"][i])]

# %% Tables and chart
label = spc.CHART_LABEL[chart]
idx = list(range(1, m + 1))
panel = {"xbar_r": "X̄", "xbar_s": "X̄", "imr": "Individuals", "p": "p", "np": "np", "c": "c", "u": "u", "laney_p": "p′", "cusum": "CUSUM", "ewma": "EWMA"}[chart]
rows_idx, rows_val, rows_c, rows_l, rows_u, rows_v, rows_r, rows_f = [], [], [], [], [], [], [], []
if chart == "cusum":
    for name, series in (("C⁺", res["pos"]), ("C⁻", res["neg"])):
        rows_idx += idx; rows_val += list(map(float, series)); rows_c += [0.0] * m; rows_l += list(map(float, lcl)); rows_u += list(map(float, ucl))
        rows_v += [bool(viol_rules[i]) for i in range(m)]; rows_r += [",".join(map(str, viol_rules[i])) for i in range(m)]; rows_f += [name] * m
else:
    rows_idx += idx; rows_val += list(map(float, stat)); rows_c += list(map(float, center)); rows_l += list(map(float, lcl)); rows_u += list(map(float, ucl))
    rows_v += [bool(viol_rules[i]) for i in range(m)]; rows_r += [",".join(map(str, viol_rules[i])) for i in range(m)]; rows_f += [panel] * m
    if sec:
        rows_idx += idx; rows_val += list(map(float, sec["stat"])); rows_c += list(map(float, sec["center"])); rows_l += list(map(float, sec["lcl"]))
        rows_u += list(map(float, sec["ucl"])); rows_v += [i + 1 in sec_viol for i in range(m)]; rows_r += ["1" if i + 1 in sec_viol else "" for i in range(m)]
        rows_f += [sec["label"]] * m
charts = [cs.chart(
    "control", "control-chart", f"{label} chart of {value_col}",
    {"index": cs.col("Subgroup" if not attribute or labels_raw else "Sample", rows_idx),
     "value": cs.col(value_col if chart in ("imr",) else "Statistic", rows_val),
     "center": cs.col("Center", rows_c), "lcl": cs.col("LCL", rows_l), "ucl": cs.col("UCL", rows_u),
     "violation": cs.col("Signal", rows_v, "boolean"), "rule": cs.col("Rules", rows_r, "categorical"),
     "chart": cs.col("Chart", rows_f, "categorical")},
)]
table_rows = []
for i in range(m):
    table_rows.append({"label": labels[i], "n": float(res["sizes"][i]) if res.get("sizes") is not None else None, "stat": float(stat[i]),
                       "center": float(center[i]), "lcl": float(lcl[i]), "ucl": float(ucl[i]), "rules": ", ".join(map(str, viol_rules[i]))})
tables = [{
    "key": "points", "title": "Points and limits",
    "columns": [{"key": "label", "label": "Subgroup", "type": "string"}, {"key": "n", "label": "n", "type": "number"},
                {"key": "stat", "label": "Statistic", "type": "number"}, {"key": "center", "label": "Center", "type": "number"},
                {"key": "lcl", "label": "LCL", "type": "number"}, {"key": "ucl", "label": "UCL", "type": "number"},
                {"key": "rules", "label": "Rules broken", "type": "string"}],
    "rows": table_rows,
}]

# %% Result
sizes_arr = np.asarray(res["sizes"], dtype=float)
values = {
    "chart": chart, "chart_label": label, "n_subgroups": m, "mean_size": float(np.mean(sizes_arr)),
    "center": float(center[0]), "sigma": float(res["sigma"]),
    "stat": list(map(float, stat)), "lcl": list(map(float, lcl)), "ucl": list(map(float, ucl)),
    "violations": violations, "violation_rules": [",".join(map(str, r)) for r in viol_rules if r], "n_signals": len(violations),
    "sec_stat": list(map(float, sec["stat"])) if sec else None, "sec_center": float(sec["center"][0]) if sec else None,
    "sec_lcl": list(map(float, sec["lcl"])) if sec else None, "sec_ucl": list(map(float, sec["ucl"])) if sec else None,
    "sec_violations": sec_viol,
    "cusum_pos": list(map(float, res["pos"])) if chart == "cusum" else None,
    "cusum_neg": list(map(float, res["neg"])) if chart == "cusum" else None,
}
rule_names = {"basic": "points beyond the limits", "western_electric": "Western Electric rules", "nelson": "Nelson rules"}
summary = f"{label} chart of {value_col}: {m} {'subgroups' if np.mean(sizes_arr) != 1 else 'points'}; "
summary += f"{len(violations)} signal{'s' if len(violations) != 1 else ''} ({rule_names[rules] if chart not in ('cusum', 'ewma') else 'beyond the limits'})." if violations else "no signals."
notes = [f"σ estimated from {'the first ' + str(phase1) + ' subgroups (phase I)' if 0 < phase1 < m else 'all subgroups'}."]
if chart in ("xbar_r", "xbar_s", "imr"):
    notes.append({"xbar_r": "σ = mean(R / d2) (qcc UWAVE-R).", "xbar_s": "σ = mean(S / c4) (qcc UWAVE-SD).", "imr": "σ = mean moving range / 1.128."}[chart])
cs.publish({
    "title": f"{label} control chart",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(x),
    "summary": summary,
    "statistics": [
        {"key": "center", "label": "Center", "value": float(center[0])},
        {"key": "sigma", "label": "σ", "value": float(res["sigma"])},
        {"key": "n_subgroups", "label": "Subgroups", "value": m, "format": "integer"},
        {"key": "n_signals", "label": "Signals", "value": len(violations), "format": "integer"},
    ],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": notes,
    "values": values,
})

The center is 19.2, and sigma is 4.38.

Check yourself

What is the upper limit, at three sigma? Give two decimals.

Show the answer

Answer: 32.31

19.174 + 3 × √19.174 = 19.174 + 13.136 = 32.31.

08

Check your understanding

Checkpoint

Check yourself

A p chart with 5,000 items per day flags most days, yet nothing seems to have changed. What should you try?

Show the answer

Answer: b

Large samples make binomial limits very tight. Laney p′ tests against the variation the process really shows.

Check yourself

A u chart uses limits at 2.5 sigma instead of 3. What should you expect?

Show the answer

Answer: a

Tighter limits trade one error for the other. On the circuit data, such a chart flags more points than the c chart did, though sizes also vary there, so the counts aren't directly comparable.

09

Try it

In the app

In the Quality studio, choose Process monitoring, and on the Control chart step pick the chart type. p, np, c, u and Laney p′ are all in the list, and the Sample size role takes your sizes.

10

Recap

Recap
  • Defective items use p or np. Defects on an item use c or u.
  • Use p or u when sample sizes vary.
  • An improvement is a signal too, so set new limits afterwards.
  • With large samples, check for overdispersion and consider Laney p′.

Concepts in this lesson