Skip to content

Can the process meet the specification?

Compare a stable process with its specification using Cp, Cpk, Pp and Ppk, and read their intervals and assumptions.

Applied ~12 min10 steps

What runs in CodeSplash

You will be able to

  • Compute Cp and Cpk, and say what each one ignores
  • Tell within-subgroup capability from overall performance
  • Check stability and normality before trusting parts per million

Read first

01

Stability first

Read

CapabilityProcess capabilityHow the spread and center of a stable process compare with its specification limits. compares what a process does with what the customer needs. It only makes sense for a stable process. If the process is shifting around, today's capability says little about tomorrow's.

So run the control chart first. Then:

Cp=USL−LSL6σ^,Cpk=min⁡ ⁣(USL−μ^3σ^,  μ^−LSL3σ^)C_p = \frac{\text{USL} - \text{LSL}}{6\hat\sigma}, \qquad C_{pk} = \min\!\left(\frac{\text{USL} - \hat\mu}{3\hat\sigma},\; \frac{\hat\mu - \text{LSL}}{3\hat\sigma}\right)
02

Compute Cp

Checkpoint

Piston rings have limits of 73.9573.95 and 74.0574.05 mm. The within-subgroup standard deviation is 0.01007.

Check yourself

What is Cp? Give two decimals.

Show the answer

Answer: 1.65492707221618

(74.05 − 73.95) / (6 × 0.01007) = 0.10 / 0.0604 = 1.65. The specification is about 1.65 times as wide as the process spread.

03

Which is lower?

Predict

Predict first

The mean of these rings is 74.004, slightly above the 74 mm target. How does Cpk compare with Cp?

Cpk equals CpCpk is lowerCpk is higher
Reveal

Cpk is 1.54, against Cp 1.65. Cp asks whether the process could fit if it were centered. Cpk measures how close it comes to the nearer limit, as it actually runs. Cpk can never exceed Cp.

04

Short-term and overall

In the app
Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)Recorded · Python and R agreeRecorded 2026-11-17 · 29 values compared
R

Cpk = 1.54, Ppk = 1.35; about 25 parts per million expected outside the specifications.

Cpk
1.536
Ppk
1.355
σ within
0.0101
σ overall
0.0114

Plots

Capability of Diameter (mm)Does the process fit inside its specification limits, and how much falls outside?
View data
Normal (overall σ)xDiameter (mm)
6.367e-673.94074.030
8.533e-673.94174.002
1.140e-573.94174.019
1.520e-573.94273.992
2.020e-573.94274.008
2.677e-573.94373.995
3.539e-573.94473.992
4.664e-573.94474.001
6.130e-573.94574.011
8.034e-573.94574.004
0.000173.94673.988
0.000173.94774.024
0.000273.94774.021
0.000273.94874.005
0.000373.94874.002
0.000473.94974.002
0.000573.95073.996
0.000673.95073.993
0.000873.95174.015
0.001073.95174.009
0.001373.95273.992
0.001773.95374.007
0.002173.95374.015
0.002673.95473.989
0.003373.95474.014
0.004273.95574.009
0.005273.95673.994
0.006573.95673.997
0.008173.95773.985
0.010073.95773.993
0.012473.95873.995
0.015273.95974.006
0.018773.95973.994
0.023073.96074
0.028173.96174.005
0.034273.96173.985
0.041673.96274.003
0.050473.96273.993
0.061073.96374.015
0.073573.96473.988
0.088473.96474.008
0.105973.96573.995
0.126673.96574.009
0.150973.96674.005
0.179473.96774.004
0.212773.96773.998
0.251473.96874
0.296473.96873.990
0.348473.96974.007
0.408473.97073.995
0.477573.97073.994
0.556673.97173.998
0.647073.97173.994
0.750173.97273.995
0.867173.97373.990
0.999773.97374.004
1.14973.97474
1.31773.97474.007
1.50673.97574
1.71773.97673.996

First 60 of 200 rows.

Capability indices

IndexValue95% CI lower95% CI upper
Cp (within)1.6551.4921.817
Cpk (within)1.5361.3781.693
Cpl1.774——
Cpu1.536——
Pp (overall)1.4601.3161.603
Ppk (overall)1.3551.2141.495
Ppl1.565——
Ppu1.355——
Cpm1.392——

Parts per million outside the specifications

BasisPPM
Expected (within σ)2.095
Expected (overall σ)25.490
Observed0
  • Within σ: mean(R / d2). Overall σ: sample SD.
  • Cpk CI: Bissell (1990); Cp/Pp CI: χ².
The exact R script · R R version 4.5.1 (2025-06-13)
# Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.capability 1.0.1 · spec aa4ccbb51190e88f
# 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_capability(): twin of codesplash.quality.capability (qcc conventions)

# Classic equivalent: q <- qcc::qcc(qcc::qcc.groups(x, sample), type = "xbar", plot = FALSE);
# qcc::process.capability(q, spec.limits = c(LSL, USL), target = T)

# %% 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)

# %% Data and specifications
value_col <- "Diameter (mm)"
subgroup_col <- "Sample"
x_raw <- as.numeric(df[[value_col]])
lsl <- 73.95; usl <- 74.05; target <- 74
if (is.null(lsl) && is.null(usl)) stop("Set at least one specification limit (LSL or USL).", call. = FALSE)
if (!is.null(lsl) && !is.null(usl) && usl <= lsl) stop("USL must be above LSL.", call. = FALSE)
cs_check_rows(length(x_raw), 2, "A capability analysis")  # the spread needs two values that differ (registry/errors.yaml)
cs_check_not_constant(x_raw, value_col)
conf <- 0.95
transform <- "none"
lam <- NULL
lam_hat <- NULL
x <- x_raw
spec <- list(lsl = lsl, usl = usl, target = target)
if (transform == "boxcox") {
  if (any(x_raw <= 0) || any(vapply(spec, function(v) !is.null(v) && v <= 0, TRUE)))
    stop("Box–Cox needs positive values and positive specification limits.", call. = FALSE)
  lam <- NULL
  if (is.null(lam)) {
    # lambda maximizes a flat profile likelihood; like Minitab, use it rounded (here to 0.001) so the
    # transformation - and every index - is identical in R and Python.
    lam_hat <- cs_spc_boxcox_lambda(x_raw)
    lam <- floor(lam_hat * 1000 + 0.5) / 1000
  }
  x <- cs_spc_boxcox(x_raw, lam)
  spec <- lapply(spec, function(v) if (!is.null(v)) cs_spc_boxcox(v, lam) else NULL)
}
labels <- if (!is.null(subgroup_col)) as.character(df[[subgroup_col]]) else NULL
groups <- cs_spc_subgroups(x, labels, NULL)$groups
ws <- cs_spc_within_sigma(groups, "auto")
res <- cs_spc_capability(x, ws$sigma, spec$lsl, spec$usl, spec$target, conf)
sw_p <- if (length(x) >= 3 && length(x) <= 5000) stats::shapiro.test(x)$p.value else NaN

# %% Tables and chart
ci_row <- function(key, label) list(index = label, value = res[[key]], low = res[[paste0(key, "_low")]], high = res[[paste0(key, "_high")]])
tables <- list(
  list(key = "indices", title = "Capability indices",
       columns = list(list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number"),
                      list(key = "low", label = sprintf("%.0f%% CI lower", 100 * conf), type = "number"),
                      list(key = "high", label = sprintf("%.0f%% CI upper", 100 * conf), type = "number")),
       rows = list(ci_row("cp", "Cp (within)"), ci_row("cpk", "Cpk (within)"), list(index = "Cpl", value = res$cpl), list(index = "Cpu", value = res$cpu),
                   ci_row("pp", "Pp (overall)"), ci_row("ppk", "Ppk (overall)"), list(index = "Ppl", value = res$ppl), list(index = "Ppu", value = res$ppu),
                   list(index = "Cpm", value = res$cpm))),
  list(key = "ppm", title = "Parts per million outside the specifications",
       columns = list(list(key = "basis", label = "Basis", type = "string"), list(key = "ppm", label = "PPM", type = "number")),
       rows = list(list(basis = "Expected (within σ)", ppm = res$ppm_within), list(basis = "Expected (overall σ)", ppm = res$ppm_overall),
                   list(basis = "Observed", ppm = res$ppm_observed))))
specs <- Filter(Negate(is.null), list(lsl = lsl, usl = usl, target = target))
if (transform == "none") {
  lo_x <- min(c(x, unlist(specs))); hi_x <- max(c(x, unlist(specs)))
  pad <- 0.1 * (hi_x - lo_x)
  gx <- seq(lo_x - pad, hi_x + pad, length.out = 200)
  charts <- list(cs_chart(
    "capability", "capability-histogram", sprintf("Capability of %s", value_col),
    list(value = cs_col(value_col, x), fit_x = cs_col("x", gx), fit_density = cs_col("Normal (overall σ)", stats::dnorm(gx, res$mean, res$sd_overall))),
    controls = list(lsl = lsl, usl = usl, target = target)))
} else {
  charts <- list(cs_chart(
    "capability", "capability-histogram", sprintf("Capability of %s (Box–Cox, λ = %.3f)", value_col, lam),
    list(value = cs_col(paste(value_col, "(transformed)"), x)),
    controls = list(lsl = spec$lsl, usl = spec$usl, target = spec$target)))
}

# %% Result
keys <- c("n", "mean", "sd_within", "sd_overall", "cp", "cpk", "cpl", "cpu", "pp", "ppk", "ppl", "ppu", "cpm",
          "cp_low", "cp_high", "cpk_low", "cpk_high", "pp_low", "pp_high", "ppk_low", "ppk_high", "ppm_within", "ppm_overall", "ppm_observed")
values <- res[keys]
values["lambda"] <- list(lam)  # keep the key when NULL (no transformation)
values["lambda_hat"] <- list(lam_hat)
values$sw_p <- sw_p
values$ppm_overall_round <- round(res$ppm_overall)
values$n_subgroups <- length(groups)
if (is.finite(sw_p) && sw_p < 0.05)
  warnings <- c(warnings, sprintf("The %svalues depart from normality (Shapiro–Wilk p = %s); expected PPM may be off — consider the Box–Cox option.",
                                  if (!is.null(lam)) "transformed " else "", format(signif(sw_p, 3))))
summary <- if (is.finite(res$cpk)) sprintf("Cpk = %s, Ppk = %s", cs_fmt_num(res$cpk, 2), cs_fmt_num(res$ppk, 2)) else "Capability"
summary <- paste0(summary, sprintf("; about %s parts per million expected outside the specifications.", format(round(res$ppm_overall), big.mark = ",")))
cs_publish(list(
  method = "spc.capability",
  methodVersion = "1.0.1",
  title = "Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)",
  engine = cs_engine_info("stats", "codesplashr"),
  n = res$n,
  summary = summary,
  statistics = list(list(key = "cpk", label = "Cpk", value = res$cpk), list(key = "ppk", label = "Ppk", value = res$ppk),
                    list(key = "sd_within", label = "σ within", value = ws$sigma), list(key = "sd_overall", label = "σ overall", value = res$sd_overall)),
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = c(sprintf("Within σ: %s. Overall σ: sample SD.", ws$method), "Cpk CI: Bissell (1990); Cp/Pp CI: χ².",
            if (!is.null(lam)) sprintf("Box–Cox λ = %.4f; data and specification limits transformed.", lam)),
  values = values
))
Python

Cpk = 1.54, Ppk = 1.35; about 25 parts per million expected outside the specifications.

Cpk
1.536
Ppk
1.355
σ within
0.0101
σ overall
0.0114

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

Capability indices

IndexValue95% CI lower95% CI upper
Cp (within)1.6551.4921.817
Cpk (within)1.5361.3781.693
Cpl1.774——
Cpu1.536——
Pp (overall)1.4601.3161.603
Ppk (overall)1.3551.2141.495
Ppl1.565——
Ppu1.355——
Cpm1.392——

Parts per million outside the specifications

BasisPPM
Expected (within σ)2.095
Expected (overall σ)25.490
Observed0
  • Within σ: mean(R / d2). Overall σ: sample SD.
  • Cpk CI: Bissell (1990); Cp/Pp CI: χ².
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.capability 1.0.1 · spec aa4ccbb51190e88f
# 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
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.quality import capability as cap  # twin of codesplashr::cs_spc_capability (qcc conventions)
from codesplash.quality import spc

# Classic equivalent in R: qcc::process.capability(qcc(groups, type = "xbar"), spec.limits = c(LSL, USL)).

# %% 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)

# %% Data and specifications
value_col = "Diameter (mm)"
subgroup_col = "Sample"
x_raw = df[value_col].to_numpy(dtype=float)
lsl, usl, target = 73.95, 74.05, 74
if lsl is None and usl is None:
    raise ValueError("Set at least one specification limit (LSL or USL).")
if lsl is not None and usl is not None and usl <= lsl:
    raise ValueError("USL must be above LSL.")
cs.check_rows(len(x_raw), 2, "A capability analysis")  # the spread needs two values that differ (registry/errors.yaml)
check_not_constant(x_raw, value_col)
conf = 0.95
transform = "none"
lam = None
lam_hat = None
x = x_raw
spec = {"lsl": lsl, "usl": usl, "target": target}
if transform == "boxcox":
    if np.any(x_raw <= 0) or any(v is not None and v <= 0 for v in spec.values()):
        raise ValueError("Box–Cox needs positive values and positive specification limits.")
    lam = None
    if lam is None:
        # λ maximizes a flat profile likelihood; like Minitab, use it rounded (here to 0.001) so the
        # transformation — and every index — is identical in Python and R.
        lam_hat = cap.boxcox_lambda(x_raw)
        lam = float(np.floor(lam_hat * 1000 + 0.5) / 1000)
    x = cap.boxcox(x_raw, lam)
    spec = {k: (float(cap.boxcox(np.array([v]), lam)[0]) if v is not None else None) for k, v in spec.items()}

labels = [str(v) for v in df[subgroup_col]] if subgroup_col else None
groups, _ = spc.subgroups(x, labels, None)
sw, sw_method = cap.within_sigma(groups, "auto")
res = cap.indices(x, sw, spec["lsl"], spec["usl"], spec["target"], conf)
sw_p = float(stats.shapiro(x).pvalue) if 3 <= len(x) <= 5000 else float("nan")

# %% Tables and chart
def r(key, label):
    lo, hi = res.get(f"{key}_low"), res.get(f"{key}_high")
    return {"index": label, "value": res[key], "low": lo, "high": hi}

tables = [{
    "key": "indices", "title": "Capability indices",
    "columns": [{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
                {"key": "low", "label": f"{conf:.0%} CI lower", "type": "number"}, {"key": "high", "label": f"{conf:.0%} CI upper", "type": "number"}],
    "rows": [r("cp", "Cp (within)"), r("cpk", "Cpk (within)"), {"index": "Cpl", "value": res["cpl"]}, {"index": "Cpu", "value": res["cpu"]},
             r("pp", "Pp (overall)"), r("ppk", "Ppk (overall)"), {"index": "Ppl", "value": res["ppl"]}, {"index": "Ppu", "value": res["ppu"]},
             {"index": "Cpm", "value": res["cpm"]}],
}, {
    "key": "ppm", "title": "Parts per million outside the specifications",
    "columns": [{"key": "basis", "label": "Basis", "type": "string"}, {"key": "ppm", "label": "PPM", "type": "number"}],
    "rows": [{"basis": "Expected (within σ)", "ppm": res["ppm_within"]}, {"basis": "Expected (overall σ)", "ppm": res["ppm_overall"]},
             {"basis": "Observed", "ppm": res["ppm_observed"]}],
}]
charts = []
if transform == "none":
    lo_x = min([float(np.min(x))] + [v for v in (lsl, usl, target) if v is not None])
    hi_x = max([float(np.max(x))] + [v for v in (lsl, usl, target) if v is not None])
    pad = 0.1 * (hi_x - lo_x)
    gx = np.linspace(lo_x - pad, hi_x + pad, 200)
    charts.append(cs.chart(
        "capability", "capability-histogram", f"Capability of {value_col}",
        {"value": cs.col(value_col, x.tolist()),
         "fit_x": cs.col("x", gx.tolist()),
         "fit_density": cs.col("Normal (overall σ)", stats.norm.pdf(gx, res["mean"], res["sd_overall"]).tolist())},
        controls={"lsl": lsl, "usl": usl, "target": target},
    ))
else:
    charts.append(cs.chart(
        "capability", "capability-histogram", f"Capability of {value_col} (Box–Cox, λ = {lam:.3f})",
        {"value": cs.col(f"{value_col} (transformed)", x.tolist())},
        controls={"lsl": spec["lsl"], "usl": spec["usl"], "target": spec["target"]},
    ))

# %% Result
values = {k: res[k] for k in ("n", "mean", "sd_within", "sd_overall", "cp", "cpk", "cpl", "cpu", "pp", "ppk", "ppl", "ppu", "cpm",
                              "cp_low", "cp_high", "cpk_low", "cpk_high", "pp_low", "pp_high", "ppk_low", "ppk_high",
                              "ppm_within", "ppm_overall", "ppm_observed")}
values.update({"lambda": lam, "lambda_hat": lam_hat, "sw_p": sw_p, "ppm_overall_round": round(res["ppm_overall"]), "n_subgroups": len(groups)})
warnings = list(warnings)
if np.isfinite(sw_p) and sw_p < 0.05:
    warnings.append(f"The {'transformed ' if lam is not None else ''}values depart from normality (Shapiro–Wilk p = {sw_p:.3g}); expected PPM may be off — consider the Box–Cox option.")
summary = f"Cpk = {cs.fmt_num(res['cpk'], 2)}, Ppk = {cs.fmt_num(res['ppk'], 2)}" if np.isfinite(res["cpk"]) else "Capability"
summary += f"; about {round(res['ppm_overall']):,} parts per million expected outside the specifications."
cs.publish({
    "title": "Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)",
    "engine": cs.engine_info("numpy", "scipy"),
    "n": res["n"],
    "summary": summary,
    "statistics": [
        {"key": "cpk", "label": "Cpk", "value": res["cpk"]}, {"key": "ppk", "label": "Ppk", "value": res["ppk"]},
        {"key": "sd_within", "label": "σ within", "value": sw}, {"key": "sd_overall", "label": "σ overall", "value": res["sd_overall"]},
    ],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": [f"Within σ: {sw_method}. Overall σ: sample SD.", "Cpk CI: Bissell (1990); Cp/Pp CI: χ²."]
    + ([f"Box–Cox λ = {lam:.4f}; data and specification limits transformed."] if lam is not None else []),
    "values": values,
})

Cp and Cpk use within-subgroup variation, 0.0101. Pp and Ppk use the overall standard deviation, 0.0114, which includes movement between subgroups.

Here Ppk is 1.35. A gap like this says the process could do better if it stayed put. You saw why on the chart: it drifts late on.

Cpm, at 1.39, also penalizes distance from the target.

05

Parts per million

Predict

Predict first

Each index implies an expected share of rings outside the limits. Which estimate of parts per million will be larger: within-subgroup or overall?

Within gives moreOverall gives moreThey match
Reveal

Overall: 25 per million, against 2.1 from within-subgroup variation. Observed, in 200 rings: 0. So few rings can't confirm a rate that small, and the estimates lean on the normal tails.

06

Benchmarks and uncertainty

Read

A common benchmark is Cpk≥1.33C_{pk} \ge 1.33. With tighter limits of 73.9773.97 and 74.0374.03 mm, Cpk falls to 0.880, and the process no longer meets it.

A Cpk is an estimate. The rings give an interval from 1.38 to 1.69, even with 200 measurements. Don't treat a value barely over a benchmark as a pass. Check the interval.

07

Skewed data

In the app

Indices and parts per million assume a normal distribution. The Nile's annual flow, used here as a demonstration, is skewed, so a Box–Cox transformation comes first.

Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)Recorded · Python and R agreeRecorded 2026-11-17 · 29 values compared · largest relative difference 1.9e-8
R

Cpk = 1.40, Ppk = 0.99; about 1,545 parts per million expected outside the specifications.

Cpk
1.398
Ppk
0.9905
σ within
1.629
σ overall
2.300

Plots

Capability of Flow (Box–Cox, λ = 0.370)Does the process fit inside its specification limits, and how much falls outside?
View data
Flow (transformed)
33.606
34.080
31.633
34.659
34.080
34.080
29.547
34.887
36.416
33.844
32.050
31.260
33.486
32.037
32.371
31.593
34.314
29.341
31.566
33.844
33.365
34.659
33.963
35.112
35.223
34.773
32.498
33.365
28.966
29.940
30.422
27.713
31.327
29.839
27.826
31.003
27.681
32.371
32.749
31.712
29.810
28.225
23.336
29.708
27.842
33.606
33.365
29.824
28.814
29.665
28.875
30.011
30.282
30.253
27.778
30.011
28.506
29.296
32.624
28.738

First 60 of 100 rows.

Capability indices

IndexValue95% CI lower95% CI upper
Cp (within)1.6011.3781.823
Cpk (within)1.3981.1931.604
Cpl1.803——
Cpu1.398——
Pp (overall)1.1340.97611.291
Ppk (overall)0.99050.83791.143
Ppl1.277——
Ppu0.9905——
Cpm———

Parts per million outside the specifications

BasisPPM
Expected (within σ)13.668
Expected (overall σ)1545.10
Observed0
  • Within σ: mean moving range / d2(2). Overall σ: sample SD.
  • Cpk CI: Bissell (1990); Cp/Pp CI: χ².
  • Box–Cox λ = 0.3700; data and specification limits transformed.
The exact R script · R R version 4.5.1 (2025-06-13)
# Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.capability 1.0.1 · spec 9996137bffe0bf65
# Dataset: q1_nile (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_capability(): twin of codesplash.quality.capability (qcc conventions)

# Classic equivalent: q <- qcc::qcc(qcc::qcc.groups(x, sample), type = "xbar", plot = FALSE);
# qcc::process.capability(q, spec.limits = c(LSL, USL), target = T)

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

# %% Data and specifications
value_col <- "Flow"
subgroup_col <- NULL
x_raw <- as.numeric(df[[value_col]])
lsl <- 400; usl <- 1500; target <- NULL
if (is.null(lsl) && is.null(usl)) stop("Set at least one specification limit (LSL or USL).", call. = FALSE)
if (!is.null(lsl) && !is.null(usl) && usl <= lsl) stop("USL must be above LSL.", call. = FALSE)
cs_check_rows(length(x_raw), 2, "A capability analysis")  # the spread needs two values that differ (registry/errors.yaml)
cs_check_not_constant(x_raw, value_col)
conf <- 0.95
transform <- "boxcox"
lam <- NULL
lam_hat <- NULL
x <- x_raw
spec <- list(lsl = lsl, usl = usl, target = target)
if (transform == "boxcox") {
  if (any(x_raw <= 0) || any(vapply(spec, function(v) !is.null(v) && v <= 0, TRUE)))
    stop("Box–Cox needs positive values and positive specification limits.", call. = FALSE)
  lam <- NULL
  if (is.null(lam)) {
    # lambda maximizes a flat profile likelihood; like Minitab, use it rounded (here to 0.001) so the
    # transformation - and every index - is identical in R and Python.
    lam_hat <- cs_spc_boxcox_lambda(x_raw)
    lam <- floor(lam_hat * 1000 + 0.5) / 1000
  }
  x <- cs_spc_boxcox(x_raw, lam)
  spec <- lapply(spec, function(v) if (!is.null(v)) cs_spc_boxcox(v, lam) else NULL)
}
labels <- if (!is.null(subgroup_col)) as.character(df[[subgroup_col]]) else NULL
groups <- cs_spc_subgroups(x, labels, NULL)$groups
ws <- cs_spc_within_sigma(groups, "auto")
res <- cs_spc_capability(x, ws$sigma, spec$lsl, spec$usl, spec$target, conf)
sw_p <- if (length(x) >= 3 && length(x) <= 5000) stats::shapiro.test(x)$p.value else NaN

# %% Tables and chart
ci_row <- function(key, label) list(index = label, value = res[[key]], low = res[[paste0(key, "_low")]], high = res[[paste0(key, "_high")]])
tables <- list(
  list(key = "indices", title = "Capability indices",
       columns = list(list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number"),
                      list(key = "low", label = sprintf("%.0f%% CI lower", 100 * conf), type = "number"),
                      list(key = "high", label = sprintf("%.0f%% CI upper", 100 * conf), type = "number")),
       rows = list(ci_row("cp", "Cp (within)"), ci_row("cpk", "Cpk (within)"), list(index = "Cpl", value = res$cpl), list(index = "Cpu", value = res$cpu),
                   ci_row("pp", "Pp (overall)"), ci_row("ppk", "Ppk (overall)"), list(index = "Ppl", value = res$ppl), list(index = "Ppu", value = res$ppu),
                   list(index = "Cpm", value = res$cpm))),
  list(key = "ppm", title = "Parts per million outside the specifications",
       columns = list(list(key = "basis", label = "Basis", type = "string"), list(key = "ppm", label = "PPM", type = "number")),
       rows = list(list(basis = "Expected (within σ)", ppm = res$ppm_within), list(basis = "Expected (overall σ)", ppm = res$ppm_overall),
                   list(basis = "Observed", ppm = res$ppm_observed))))
specs <- Filter(Negate(is.null), list(lsl = lsl, usl = usl, target = target))
if (transform == "none") {
  lo_x <- min(c(x, unlist(specs))); hi_x <- max(c(x, unlist(specs)))
  pad <- 0.1 * (hi_x - lo_x)
  gx <- seq(lo_x - pad, hi_x + pad, length.out = 200)
  charts <- list(cs_chart(
    "capability", "capability-histogram", sprintf("Capability of %s", value_col),
    list(value = cs_col(value_col, x), fit_x = cs_col("x", gx), fit_density = cs_col("Normal (overall σ)", stats::dnorm(gx, res$mean, res$sd_overall))),
    controls = list(lsl = lsl, usl = usl, target = target)))
} else {
  charts <- list(cs_chart(
    "capability", "capability-histogram", sprintf("Capability of %s (Box–Cox, λ = %.3f)", value_col, lam),
    list(value = cs_col(paste(value_col, "(transformed)"), x)),
    controls = list(lsl = spec$lsl, usl = spec$usl, target = spec$target)))
}

# %% Result
keys <- c("n", "mean", "sd_within", "sd_overall", "cp", "cpk", "cpl", "cpu", "pp", "ppk", "ppl", "ppu", "cpm",
          "cp_low", "cp_high", "cpk_low", "cpk_high", "pp_low", "pp_high", "ppk_low", "ppk_high", "ppm_within", "ppm_overall", "ppm_observed")
values <- res[keys]
values["lambda"] <- list(lam)  # keep the key when NULL (no transformation)
values["lambda_hat"] <- list(lam_hat)
values$sw_p <- sw_p
values$ppm_overall_round <- round(res$ppm_overall)
values$n_subgroups <- length(groups)
if (is.finite(sw_p) && sw_p < 0.05)
  warnings <- c(warnings, sprintf("The %svalues depart from normality (Shapiro–Wilk p = %s); expected PPM may be off — consider the Box–Cox option.",
                                  if (!is.null(lam)) "transformed " else "", format(signif(sw_p, 3))))
summary <- if (is.finite(res$cpk)) sprintf("Cpk = %s, Ppk = %s", cs_fmt_num(res$cpk, 2), cs_fmt_num(res$ppk, 2)) else "Capability"
summary <- paste0(summary, sprintf("; about %s parts per million expected outside the specifications.", format(round(res$ppm_overall), big.mark = ",")))
cs_publish(list(
  method = "spc.capability",
  methodVersion = "1.0.1",
  title = "Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)",
  engine = cs_engine_info("stats", "codesplashr"),
  n = res$n,
  summary = summary,
  statistics = list(list(key = "cpk", label = "Cpk", value = res$cpk), list(key = "ppk", label = "Ppk", value = res$ppk),
                    list(key = "sd_within", label = "σ within", value = ws$sigma), list(key = "sd_overall", label = "σ overall", value = res$sd_overall)),
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = c(sprintf("Within σ: %s. Overall σ: sample SD.", ws$method), "Cpk CI: Bissell (1990); Cp/Pp CI: χ².",
            if (!is.null(lam)) sprintf("Box–Cox λ = %.4f; data and specification limits transformed.", lam)),
  values = values
))
Python

Cpk = 1.40, Ppk = 0.99; about 1,545 parts per million expected outside the specifications.

Cpk
1.398
Ppk
0.9905
σ within
1.629
σ overall
2.300

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

Capability indices

IndexValue95% CI lower95% CI upper
Cp (within)1.6011.3781.823
Cpk (within)1.3981.1931.604
Cpl1.803——
Cpu1.398——
Pp (overall)1.1340.97611.291
Ppk (overall)0.99050.83791.143
Ppl1.277——
Ppu0.9905——
Cpm———

Parts per million outside the specifications

BasisPPM
Expected (within σ)13.668
Expected (overall σ)1545.10
Observed0
  • Within σ: mean moving range / d2(2). Overall σ: sample SD.
  • Cpk CI: Bissell (1990); Cp/Pp CI: χ².
  • Box–Cox λ = 0.3700; data and specification limits transformed.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spc.capability 1.0.1 · spec 9996137bffe0bf65
# Dataset: q1_nile (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
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.quality import capability as cap  # twin of codesplashr::cs_spc_capability (qcc conventions)
from codesplash.quality import spc

# Classic equivalent in R: qcc::process.capability(qcc(groups, type = "xbar"), spec.limits = c(LSL, USL)).

# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_nile.parquet", columns=["Flow"])
n_input = len(df)
df = df.dropna(subset=["Flow"])  # 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, ["Flow"])  # infinite values stop the run (registry/errors.yaml)

# %% Data and specifications
value_col = "Flow"
subgroup_col = None
x_raw = df[value_col].to_numpy(dtype=float)
lsl, usl, target = 400, 1500, None
if lsl is None and usl is None:
    raise ValueError("Set at least one specification limit (LSL or USL).")
if lsl is not None and usl is not None and usl <= lsl:
    raise ValueError("USL must be above LSL.")
cs.check_rows(len(x_raw), 2, "A capability analysis")  # the spread needs two values that differ (registry/errors.yaml)
check_not_constant(x_raw, value_col)
conf = 0.95
transform = "boxcox"
lam = None
lam_hat = None
x = x_raw
spec = {"lsl": lsl, "usl": usl, "target": target}
if transform == "boxcox":
    if np.any(x_raw <= 0) or any(v is not None and v <= 0 for v in spec.values()):
        raise ValueError("Box–Cox needs positive values and positive specification limits.")
    lam = None
    if lam is None:
        # λ maximizes a flat profile likelihood; like Minitab, use it rounded (here to 0.001) so the
        # transformation — and every index — is identical in Python and R.
        lam_hat = cap.boxcox_lambda(x_raw)
        lam = float(np.floor(lam_hat * 1000 + 0.5) / 1000)
    x = cap.boxcox(x_raw, lam)
    spec = {k: (float(cap.boxcox(np.array([v]), lam)[0]) if v is not None else None) for k, v in spec.items()}

labels = [str(v) for v in df[subgroup_col]] if subgroup_col else None
groups, _ = spc.subgroups(x, labels, None)
sw, sw_method = cap.within_sigma(groups, "auto")
res = cap.indices(x, sw, spec["lsl"], spec["usl"], spec["target"], conf)
sw_p = float(stats.shapiro(x).pvalue) if 3 <= len(x) <= 5000 else float("nan")

# %% Tables and chart
def r(key, label):
    lo, hi = res.get(f"{key}_low"), res.get(f"{key}_high")
    return {"index": label, "value": res[key], "low": lo, "high": hi}

tables = [{
    "key": "indices", "title": "Capability indices",
    "columns": [{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
                {"key": "low", "label": f"{conf:.0%} CI lower", "type": "number"}, {"key": "high", "label": f"{conf:.0%} CI upper", "type": "number"}],
    "rows": [r("cp", "Cp (within)"), r("cpk", "Cpk (within)"), {"index": "Cpl", "value": res["cpl"]}, {"index": "Cpu", "value": res["cpu"]},
             r("pp", "Pp (overall)"), r("ppk", "Ppk (overall)"), {"index": "Ppl", "value": res["ppl"]}, {"index": "Ppu", "value": res["ppu"]},
             {"index": "Cpm", "value": res["cpm"]}],
}, {
    "key": "ppm", "title": "Parts per million outside the specifications",
    "columns": [{"key": "basis", "label": "Basis", "type": "string"}, {"key": "ppm", "label": "PPM", "type": "number"}],
    "rows": [{"basis": "Expected (within σ)", "ppm": res["ppm_within"]}, {"basis": "Expected (overall σ)", "ppm": res["ppm_overall"]},
             {"basis": "Observed", "ppm": res["ppm_observed"]}],
}]
charts = []
if transform == "none":
    lo_x = min([float(np.min(x))] + [v for v in (lsl, usl, target) if v is not None])
    hi_x = max([float(np.max(x))] + [v for v in (lsl, usl, target) if v is not None])
    pad = 0.1 * (hi_x - lo_x)
    gx = np.linspace(lo_x - pad, hi_x + pad, 200)
    charts.append(cs.chart(
        "capability", "capability-histogram", f"Capability of {value_col}",
        {"value": cs.col(value_col, x.tolist()),
         "fit_x": cs.col("x", gx.tolist()),
         "fit_density": cs.col("Normal (overall σ)", stats.norm.pdf(gx, res["mean"], res["sd_overall"]).tolist())},
        controls={"lsl": lsl, "usl": usl, "target": target},
    ))
else:
    charts.append(cs.chart(
        "capability", "capability-histogram", f"Capability of {value_col} (Box–Cox, λ = {lam:.3f})",
        {"value": cs.col(f"{value_col} (transformed)", x.tolist())},
        controls={"lsl": spec["lsl"], "usl": spec["usl"], "target": spec["target"]},
    ))

# %% Result
values = {k: res[k] for k in ("n", "mean", "sd_within", "sd_overall", "cp", "cpk", "cpl", "cpu", "pp", "ppk", "ppl", "ppu", "cpm",
                              "cp_low", "cp_high", "cpk_low", "cpk_high", "pp_low", "pp_high", "ppk_low", "ppk_high",
                              "ppm_within", "ppm_overall", "ppm_observed")}
values.update({"lambda": lam, "lambda_hat": lam_hat, "sw_p": sw_p, "ppm_overall_round": round(res["ppm_overall"]), "n_subgroups": len(groups)})
warnings = list(warnings)
if np.isfinite(sw_p) and sw_p < 0.05:
    warnings.append(f"The {'transformed ' if lam is not None else ''}values depart from normality (Shapiro–Wilk p = {sw_p:.3g}); expected PPM may be off — consider the Box–Cox option.")
summary = f"Cpk = {cs.fmt_num(res['cpk'], 2)}, Ppk = {cs.fmt_num(res['ppk'], 2)}" if np.isfinite(res["cpk"]) else "Capability"
summary += f"; about {round(res['ppm_overall']):,} parts per million expected outside the specifications."
cs.publish({
    "title": "Process capability (Cp, Cpk, Pp, Ppk, Cpm, PPM)",
    "engine": cs.engine_info("numpy", "scipy"),
    "n": res["n"],
    "summary": summary,
    "statistics": [
        {"key": "cpk", "label": "Cpk", "value": res["cpk"]}, {"key": "ppk", "label": "Ppk", "value": res["ppk"]},
        {"key": "sd_within", "label": "σ within", "value": sw}, {"key": "sd_overall", "label": "σ overall", "value": res["sd_overall"]},
    ],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": [f"Within σ: {sw_method}. Overall σ: sample SD.", "Cpk CI: Bissell (1990); Cp/Pp CI: χ²."]
    + ([f"Box–Cox λ = {lam:.4f}; data and specification limits transformed."] if lam is not None else []),
    "values": values,
})

After transforming with λ≈0.37\lambda \approx 0.37, Shapiro–Wilk gives p = .099, and Ppk is 0.991. Limits are transformed too, so read the indices on that scale.

08

Check your understanding

Checkpoint

Check yourself

A process has Cpk = 1.6, but its control chart shows repeated shifts. What do you report?

Show the answer

Answer: b

Capability describes a stable process. An unstable one has no single capability to report.

Check yourself

Cp = 1.6 and Cpk = 0.9. What is the most direct improvement?

Show the answer

Answer: a

Cp shows the spread would fit. The gap to Cpk comes from being off center, which is often easier to fix than variation.

Check yourself

Which pair uses overall variation, including movement between subgroups?

Show the answer

Answer: b

The "P" indices use the overall standard deviation, so they describe long-term performance.

09

Do it

In the app

In the Quality studio, choose Process monitoring and open the Capability step. It starts from your chart's dataset and columns, such as {{value}} by {{subgroup}}. Specification limits come from the customer or the design, never from the data.

Python
import pandas as pd

df = pd.read_csv("pistonrings.csv")
x = df["Diameter (mm)"]
lsl, usl = 73.95, 74.05

ranges = df.groupby("Sample")["Diameter (mm)"].agg(lambda s: s.max() - s.min())
sigma_within = ranges.mean() / 2.326   # d2 for subgroups of 5

cp = (usl - lsl) / (6 * sigma_within)
cpk = min(usl - x.mean(), x.mean() - lsl) / (3 * sigma_within)
ppk = min(usl - x.mean(), x.mean() - lsl) / (3 * x.std())
print(round(cp, 3), round(cpk, 3), round(ppk, 3))
R
df <- read.csv("pistonrings.csv", check.names = FALSE)
x <- df[["Diameter (mm)"]]
lsl <- 73.95; usl <- 74.05

ranges <- tapply(x, df$Sample, function(s) max(s) - min(s))
sigma_within <- mean(ranges) / 2.326  # d2 for subgroups of 5

cp <- (usl - lsl) / (6 * sigma_within)
cpk <- min(usl - mean(x), mean(x) - lsl) / (3 * sigma_within)
ppk <- min(usl - mean(x), mean(x) - lsl) / (3 * sd(x))
round(c(cp = cp, cpk = cpk, ppk = ppk), 3)
10

Recap

Recap
  • Check stability first. Capability describes a stable process.
  • Cp ignores centering, and Cpk doesn't.
  • Pp and Ppk use overall variation, and the gap shows how much the process moves.
  • Read the interval, and check normality before you trust parts per million.

Concepts in this lesson