GQuality & process · spc.control_chart
Control chart (X̄–R, X̄–S, I–MR, p, np, c, u, Laney p′, CUSUM, EWMA)
Is the process stable, or are there signals of special-cause variation?
Shewhart, CUSUM and EWMA control charts for measurements (subgroups or individuals) and for counts of nonconforming units or defects, with phase I limits from the first subgroups and Western Electric or Nelson run rules. Limits and constants follow qcc, so R users can check the numbers with the classic package.
A real result
Example “Xbar r phase1”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
X̄–R chart of Diameter (mm): 40 subgroups; 5 signals (Western Electric rules).
- Center
- 74.001
- σ
- 0.0098
- Subgroups
- 40
- Signals
- 5
Plots
View data
| Center | Chart | Subgroup | LCL | Rules | UCL | Statistic | Signal |
|---|---|---|---|---|---|---|---|
| 74.001 | X̄ | 1 | 73.988 | 74.014 | 74.010 | false | |
| 74.001 | X̄ | 2 | 73.988 | 74.014 | 74.001 | false | |
| 74.001 | X̄ | 3 | 73.988 | 74.014 | 74.008 | false | |
| 74.001 | X̄ | 4 | 73.988 | 74.014 | 74.003 | false | |
| 74.001 | X̄ | 5 | 73.988 | 74.014 | 74.003 | false | |
| 74.001 | X̄ | 6 | 73.988 | 74.014 | 73.996 | false | |
| 74.001 | X̄ | 7 | 73.988 | 74.014 | 74 | false | |
| 74.001 | X̄ | 8 | 73.988 | 74.014 | 73.997 | false | |
| 74.001 | X̄ | 9 | 73.988 | 74.014 | 74.004 | false | |
| 74.001 | X̄ | 10 | 73.988 | 74.014 | 73.998 | false | |
| 74.001 | X̄ | 11 | 73.988 | 74.014 | 73.994 | false | |
| 74.001 | X̄ | 12 | 73.988 | 74.014 | 74.001 | false | |
| 74.001 | X̄ | 13 | 73.988 | 74.014 | 73.998 | false | |
| 74.001 | X̄ | 14 | 73.988 | 74.014 | 73.990 | false | |
| 74.001 | X̄ | 15 | 73.988 | 74.014 | 74.006 | false | |
| 74.001 | X̄ | 16 | 73.988 | 74.014 | 73.997 | false | |
| 74.001 | X̄ | 17 | 73.988 | 74.014 | 74.001 | false | |
| 74.001 | X̄ | 18 | 73.988 | 74.014 | 74.007 | false | |
| 74.001 | X̄ | 19 | 73.988 | 74.014 | 73.998 | false | |
| 74.001 | X̄ | 20 | 73.988 | 74.014 | 74.009 | false | |
| 74.001 | X̄ | 21 | 73.988 | 74.014 | 74.000 | false | |
| 74.001 | X̄ | 22 | 73.988 | 74.014 | 74.002 | false | |
| 74.001 | X̄ | 23 | 73.988 | 74.014 | 74.002 | false | |
| 74.001 | X̄ | 24 | 73.988 | 74.014 | 74.005 | false | |
| 74.001 | X̄ | 25 | 73.988 | 74.014 | 73.998 | false | |
| 74.001 | X̄ | 26 | 73.988 | 74.014 | 74.009 | false | |
| 74.001 | X̄ | 27 | 73.988 | 74.014 | 74.002 | false | |
| 74.001 | X̄ | 28 | 73.988 | 74.014 | 73.992 | false | |
| 74.001 | X̄ | 29 | 73.988 | 74.014 | 74.004 | false | |
| 74.001 | X̄ | 30 | 73.988 | 74.014 | 73.997 | false | |
| 74.001 | X̄ | 31 | 73.988 | 74.014 | 74.007 | false | |
| 74.001 | X̄ | 32 | 73.988 | 74.014 | 74.006 | false | |
| 74.001 | X̄ | 33 | 73.988 | 74.014 | 73.998 | false | |
| 74.001 | X̄ | 34 | 73.988 | 74.014 | 74.011 | false | |
| 74.001 | X̄ | 35 | 73.988 | 2,3 | 74.014 | 74.013 | true |
| 74.001 | X̄ | 36 | 73.988 | 74.014 | 74.004 | false | |
| 74.001 | X̄ | 37 | 73.988 | 1,2 | 74.014 | 74.017 | true |
| 74.001 | X̄ | 38 | 73.988 | 1,2,3 | 74.014 | 74.020 | true |
| 74.001 | X̄ | 39 | 73.988 | 1,2,3 | 74.014 | 74.023 | true |
| 74.001 | X̄ | 40 | 73.988 | 2,3 | 74.014 | 74.013 | true |
| 0.0228 | R | 1 | 0 | 0.0481 | 0.0380 | false | |
| 0.0228 | R | 2 | 0 | 0.0481 | 0.0190 | false | |
| 0.0228 | R | 3 | 0 | 0.0481 | 0.0360 | false | |
| 0.0228 | R | 4 | 0 | 0.0481 | 0.0220 | false | |
| 0.0228 | R | 5 | 0 | 0.0481 | 0.0260 | false | |
| 0.0228 | R | 6 | 0 | 0.0481 | 0.0240 | false | |
| 0.0228 | R | 7 | 0 | 0.0481 | 0.0120 | false | |
| 0.0228 | R | 8 | 0 | 0.0481 | 0.0300 | false | |
| 0.0228 | R | 9 | 0 | 0.0481 | 0.0140 | false | |
| 0.0228 | R | 10 | 0 | 0.0481 | 0.0170 | false | |
| 0.0228 | R | 11 | 0 | 0.0481 | 0.0080 | false | |
| 0.0228 | R | 12 | 0 | 0.0481 | 0.0110 | false | |
| 0.0228 | R | 13 | 0 | 0.0481 | 0.0290 | false | |
| 0.0228 | R | 14 | 0 | 0.0481 | 0.0390 | false | |
| 0.0228 | R | 15 | 0 | 0.0481 | 0.0160 | false | |
| 0.0228 | R | 16 | 0 | 0.0481 | 0.0210 | false | |
| 0.0228 | R | 17 | 0 | 0.0481 | 0.0260 | false | |
| 0.0228 | R | 18 | 0 | 0.0481 | 0.0180 | false | |
| 0.0228 | R | 19 | 0 | 0.0481 | 0.0210 | false | |
| 0.0228 | R | 20 | 0 | 0.0481 | 0.0200 | false |
First 60 of 80 rows.
Points and limits
| Subgroup | n | Statistic | Center | LCL | UCL | Rules broken |
|---|---|---|---|---|---|---|
| 1 | 5 | 74.010 | 74.001 | 73.988 | 74.014 | |
| 2 | 5 | 74.001 | 74.001 | 73.988 | 74.014 | |
| 3 | 5 | 74.008 | 74.001 | 73.988 | 74.014 | |
| 4 | 5 | 74.003 | 74.001 | 73.988 | 74.014 | |
| 5 | 5 | 74.003 | 74.001 | 73.988 | 74.014 | |
| 6 | 5 | 73.996 | 74.001 | 73.988 | 74.014 | |
| 7 | 5 | 74 | 74.001 | 73.988 | 74.014 | |
| 8 | 5 | 73.997 | 74.001 | 73.988 | 74.014 | |
| 9 | 5 | 74.004 | 74.001 | 73.988 | 74.014 | |
| 10 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 11 | 5 | 73.994 | 74.001 | 73.988 | 74.014 | |
| 12 | 5 | 74.001 | 74.001 | 73.988 | 74.014 | |
| 13 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 14 | 5 | 73.990 | 74.001 | 73.988 | 74.014 | |
| 15 | 5 | 74.006 | 74.001 | 73.988 | 74.014 | |
| 16 | 5 | 73.997 | 74.001 | 73.988 | 74.014 | |
| 17 | 5 | 74.001 | 74.001 | 73.988 | 74.014 | |
| 18 | 5 | 74.007 | 74.001 | 73.988 | 74.014 | |
| 19 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 20 | 5 | 74.009 | 74.001 | 73.988 | 74.014 | |
| 21 | 5 | 74.000 | 74.001 | 73.988 | 74.014 | |
| 22 | 5 | 74.002 | 74.001 | 73.988 | 74.014 | |
| 23 | 5 | 74.002 | 74.001 | 73.988 | 74.014 | |
| 24 | 5 | 74.005 | 74.001 | 73.988 | 74.014 | |
| 25 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 26 | 5 | 74.009 | 74.001 | 73.988 | 74.014 | |
| 27 | 5 | 74.002 | 74.001 | 73.988 | 74.014 | |
| 28 | 5 | 73.992 | 74.001 | 73.988 | 74.014 | |
| 29 | 5 | 74.004 | 74.001 | 73.988 | 74.014 | |
| 30 | 5 | 73.997 | 74.001 | 73.988 | 74.014 | |
| 31 | 5 | 74.007 | 74.001 | 73.988 | 74.014 | |
| 32 | 5 | 74.006 | 74.001 | 73.988 | 74.014 | |
| 33 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 34 | 5 | 74.011 | 74.001 | 73.988 | 74.014 | |
| 35 | 5 | 74.013 | 74.001 | 73.988 | 74.014 | 2, 3 |
| 36 | 5 | 74.004 | 74.001 | 73.988 | 74.014 | |
| 37 | 5 | 74.017 | 74.001 | 73.988 | 74.014 | 1, 2 |
| 38 | 5 | 74.020 | 74.001 | 73.988 | 74.014 | 1, 2, 3 |
| 39 | 5 | 74.023 | 74.001 | 73.988 | 74.014 | 1, 2, 3 |
| 40 | 5 | 74.013 | 74.001 | 73.988 | 74.014 | 2, 3 |
- σ estimated from the first 25 subgroups (phase I).
- σ = mean(R / d2) (qcc UWAVE-R).
X̄–R chart of Diameter (mm): 40 subgroups; 5 signals (Western Electric rules).
- Center
- 74.001
- σ
- 0.0098
- Subgroups
- 40
- Signals
- 5
To keep this page light, the plots are shown once, under the R tab.
Points and limits
| Subgroup | n | Statistic | Center | LCL | UCL | Rules broken |
|---|---|---|---|---|---|---|
| 1 | 5 | 74.010 | 74.001 | 73.988 | 74.014 | |
| 2 | 5 | 74.001 | 74.001 | 73.988 | 74.014 | |
| 3 | 5 | 74.008 | 74.001 | 73.988 | 74.014 | |
| 4 | 5 | 74.003 | 74.001 | 73.988 | 74.014 | |
| 5 | 5 | 74.003 | 74.001 | 73.988 | 74.014 | |
| 6 | 5 | 73.996 | 74.001 | 73.988 | 74.014 | |
| 7 | 5 | 74 | 74.001 | 73.988 | 74.014 | |
| 8 | 5 | 73.997 | 74.001 | 73.988 | 74.014 | |
| 9 | 5 | 74.004 | 74.001 | 73.988 | 74.014 | |
| 10 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 11 | 5 | 73.994 | 74.001 | 73.988 | 74.014 | |
| 12 | 5 | 74.001 | 74.001 | 73.988 | 74.014 | |
| 13 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 14 | 5 | 73.990 | 74.001 | 73.988 | 74.014 | |
| 15 | 5 | 74.006 | 74.001 | 73.988 | 74.014 | |
| 16 | 5 | 73.997 | 74.001 | 73.988 | 74.014 | |
| 17 | 5 | 74.001 | 74.001 | 73.988 | 74.014 | |
| 18 | 5 | 74.007 | 74.001 | 73.988 | 74.014 | |
| 19 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 20 | 5 | 74.009 | 74.001 | 73.988 | 74.014 | |
| 21 | 5 | 74.000 | 74.001 | 73.988 | 74.014 | |
| 22 | 5 | 74.002 | 74.001 | 73.988 | 74.014 | |
| 23 | 5 | 74.002 | 74.001 | 73.988 | 74.014 | |
| 24 | 5 | 74.005 | 74.001 | 73.988 | 74.014 | |
| 25 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 26 | 5 | 74.009 | 74.001 | 73.988 | 74.014 | |
| 27 | 5 | 74.002 | 74.001 | 73.988 | 74.014 | |
| 28 | 5 | 73.992 | 74.001 | 73.988 | 74.014 | |
| 29 | 5 | 74.004 | 74.001 | 73.988 | 74.014 | |
| 30 | 5 | 73.997 | 74.001 | 73.988 | 74.014 | |
| 31 | 5 | 74.007 | 74.001 | 73.988 | 74.014 | |
| 32 | 5 | 74.006 | 74.001 | 73.988 | 74.014 | |
| 33 | 5 | 73.998 | 74.001 | 73.988 | 74.014 | |
| 34 | 5 | 74.011 | 74.001 | 73.988 | 74.014 | |
| 35 | 5 | 74.013 | 74.001 | 73.988 | 74.014 | 2, 3 |
| 36 | 5 | 74.004 | 74.001 | 73.988 | 74.014 | |
| 37 | 5 | 74.017 | 74.001 | 73.988 | 74.014 | 1, 2 |
| 38 | 5 | 74.020 | 74.001 | 73.988 | 74.014 | 1, 2, 3 |
| 39 | 5 | 74.023 | 74.001 | 73.988 | 74.014 | 1, 2, 3 |
| 40 | 5 | 74.013 | 74.001 | 73.988 | 74.014 | 2, 3 |
- σ estimated from the first 25 subgroups (phase I).
- σ = mean(R / d2) (qcc UWAVE-R).
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Xbar r phase1q1_pistonrings · subgroup: Sample · value: Diameter (mm)
- Xbar s nelsonq1_pistonrings · value: Diameter (mm)
- Imr nileq1_nile · value: Flow
- P chartq1_orangejuice · size: Size · value: Nonconforming
- Np chartq1_orangejuice · size: Size · value: Nonconforming
- Laneyq1_orangejuice · size: Size · value: Nonconforming
- C chartq1_circuit · value: Defects
- U chartq1_circuit · size: Units · value: Defects
In the guides
Where it sits in the decision guides
- Statistical optimization (regression, response surface) · DS & ML Decision Guide · Optimize / decide
What you need
- Measurement or countnumeric · 1 column
- Variables charts: the measurement. p/np/Laney charts: nonconforming units per sample; c/u charts: defects per sample.
- Subgroupcategorical / numeric / temporal · 0–1 column
- Rows with the same value form a subgroup (in order of first appearance). For attribute charts, counts in the same subgroup are added up.
- Sample sizenumeric · 0–1 column
- Units inspected per sample (p, np, u and Laney p′ charts).
Choices you make
hypothesis
- Chartdefault imr
Chart type: depends on whether you have measurements (subgroups or individuals), proportions or counts of defects.
- X̄–R (subgroup means and ranges) — Tracks subgroup means and ranges; the classic chart for small subgroups of about 2 to 9.
- X̄–S (subgroup means and SDs) — Tracks subgroup means and SDs; better for larger subgroups of about 10 or more.
- I–MR (individuals and moving ranges)(default) — Tracks single values and the change between them; pick it when each subgroup is one measurement.
- p (proportion nonconforming) — Tracks the share of defective units; handles subgroups of different sizes.
- np (number nonconforming, equal samples) — Tracks the count of defective units; use it when every sample is the same size.
- Laney p′ (overdispersed proportions) — A p chart with limits widened for overdispersion; pick it for very large samples, where p limits flag too much.
- c (defects per unit) — Tracks defect counts; use it when each inspected unit is the same size.
- u (defects per unit, varying units) — Tracks defects per unit; use it when the amount inspected varies.
- CUSUM (small sustained shifts) — Adds up deviations from target; catches small sustained shifts sooner than an X̄ or I chart.
- EWMA (small shifts) — Tracks a weighted running mean; catches small gradual shifts and tolerates non-normal data.
options
- Subgroup size (consecutive rows)default —
Without a subgroup column, groups of this many consecutive rows form the subgroups.
- Phase I subgroupsdefault 0
Estimate the center and limits from the first m subgroups (0 = all) and monitor the rest against them.
- Run rulesdefault western_electric
Run rules that flag unusual patterns besides points beyond the limits.
- Beyond the limits only — Flags only points beyond the limits; the fewest false alarms and the least sensitive.
- Western Electric (rules 1–4)(default) — Adds run rules 1–4; catches shifts and runs, so it's the usual choice.
- Nelson (rules 1–8) — Adds rules 1–8, including trends and oscillation; the most sensitive, with more false alarms.
- Limits at ± k σdefault 3
Control limits are placed this many standard deviations from the center line (3 is standard).
- Target (CUSUM / EWMA center)default —
Center for CUSUM and EWMA charts. Empty uses the process mean.
- CUSUM decision interval h (σ units)default 5
CUSUM signals when the cumulative sum passes h standard deviations. Larger h gives fewer false alarms.
- CUSUM shift to detect (σ units)default 1
Size of shift the CUSUM is tuned to detect, in standard deviations.
- EWMA weight λdefault 0.2
Weight on the newest point in the EWMA. Smaller λ detects small shifts; larger reacts faster.
What it reports
- chart
- Code for the chart drawn, such as imr (individuals and moving ranges), xbar_r, p, c, cusum or ewma.
- n_subgroups
- How many independent units the analysis used; it sets precision and power.
- center
- A process plotted over time with limits set by its own variation, to separate routine noise from real signals.
- sigma
- The distance between two distributions' average kernel embeddings; zero when they are equal.
- stat
- A single number that summarizes how far your data are from what H₀ predicts.
- lcl
- A process plotted over time with limits set by its own variation, to separate routine noise from real signals.
- ucl
- A process plotted over time with limits set by its own variation, to separate routine noise from real signals.
- violations
- A process plotted over time with limits set by its own variation, to separate routine noise from real signals.
- violation_rules
- A process plotted over time with limits set by its own variation, to separate routine noise from real signals.
- n_signals
- How many independent units the analysis used; it sets precision and power.
- chart_label
- Which control chart was drawn, e.g. X̄–R, p, c or CUSUM.
- mean_size
- Mean number of measurements per subgroup; 1 means individual values.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses numpy, pandas, codesplash; R uses nanoparquet, codesplashr.
Default traps between the two languages
- qcc's conventions in both engines (UWAVE-R / UWAVE-SD / MR σ, tabulated d2 and d3); the twin also gives phase I/II limits and Nelson rules, which qcc does not.
The exact script CodeSplash ran for example “Xbar r phase1” · 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 464d5d0e05631d71
# Dataset: q1_pistonrings (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_pistonrings.parquet", columns=["Diameter (mm)", "Sample"])
n_input = len(df)
df = df.dropna(subset=["Diameter (mm)", "Sample"]) # 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, ["Diameter (mm)", "Sample"]) # infinite values stop the run (registry/errors.yaml)
# %% Subgroups
chart = "xbar_r"
value_col = "Diameter (mm)"
subgroup_col = "Sample"
size_col = None
phase1 = int(25)
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 exact script CodeSplash ran for example “Xbar r phase1” · 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 464d5d0e05631d71
# Dataset: q1_pistonrings (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_pistonrings.parquet", col_select = c("Diameter (mm)", "Sample")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Diameter (mm)", "Sample")]), , 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("Diameter (mm)", "Sample")) # infinite values stop the run (registry/errors.yaml)
# %% Subgroups
chart <- "xbar_r"
value_col <- "Diameter (mm)"
subgroup_col <- "Sample"
size_col <- NULL
phase1 <- as.integer(25)
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
))
Sources
- Montgomery, D. C. (2013). Introduction to statistical quality control (7th ed.). Wiley.
- Scrucca, L. (2004). qcc: An R package for quality control charting and statistical process control. R News, 4(1), 11–17.
- Nelson, L. S. (1984). The Shewhart control chart — tests for special causes. Journal of Quality Technology, 16, 237–239.
- Laney, D. B. (2002). Improved control charts for attributes. Quality Engineering, 14, 531–537.
From the CodeSplash method registry · spc.control_chart v1.0.1.