Skip to content

Outlier rules: IQR, z, MAD, Grubbs, GESD, Dixon and Tietjen–Moore

Seven rules for flagging extreme values, what each assumes, and why one outlier can hide another.

Applied ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Apply the IQR, z and modified z rules
  • Explain masking and why robust rules resist it
  • Choose among Grubbs, generalized ESD, Dixon and Tietjen–Moore

Read first

01

Three quick rules

Read

Tukey's fencesTukey's fencesFlags values below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR. They're the points a box plot draws on their own. flag values beyond Q1−1.5 IQRQ_1 - 1.5\,\text{IQR} or Q3+1.5 IQRQ_3 + 1.5\,\text{IQR}. They're what a box plot draws.

The z rule flags ∣x−xˉ∣/s>3|x - \bar x| / s > 3.

The modified zModified z-scoreA z-score built from the median and MAD, so the outliers it looks for can't hide by inflating the mean and SD. Flags beyond 3.5. replaces the mean and SD with the median and MAD, and flags ∣M∣>3.5|M| > 3.5:

M=0.6745 (x−median)MADM = \frac{0.6745\,(x - \text{median})}{\text{MAD}}
02

Which rules find both?

Predict

Predict first

A sample of 30 has two planted outliers. Which rule finds both?

The z ruleThe modified z ruleThey find the same
Reveal

The answer: The modified z rule

The modified z flags 2. The z rule flags 1. The outliers inflate the SD they're measured against, so one hides the other. This is masking.

03

Try masking yourself

Explore

Start with one planted outlier, then raise the count. Watch the z rule fall behind as the outliers inflate the SD, while the robust rules hold on.

AExplorable · Outlier detectors compared

Why do outliers hide from the z-score, and which rule finds them?

How many points will the z > 3 rule flag?

5
How sure?
20
1
8.0
IQR fences (1.5)z > 3Modified z > 3.5Grubbs (one point)Generalized ESD (up to 5)

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

04

Formal tests

Read

These give a p-value, and they assume the rest of the data are roughly normal. Check that first.

TestAnswersWatch for
GrubbsGrubbs' testTests whether the most extreme value is an outlier, assuming the rest is normal. It finds one outlier at a time.Is the most extreme value an outlier?one suspect only
Generalized ESDGeneralized ESD testExtends Grubbs to find up to k outliers at once, without one outlier hiding another (Rosner 1983).How many, up to a chosen limit?masking-resistant
Dixon's QDixon's Q testFor 3–30 values, compares the gap between the most extreme value and its neighbor with the range of the data.Is the extreme value far from its neighbor?small samples
Tietjen–MooreTietjen–Moore testTests whether exactly k extreme values are outliers by how much the spread shrinks when they are removed (E close to 0 → outliers).Are exactly kk values outliers?kk fixed in advance
05

Read the card

In the app

The method runs these side by side on one column.

OutliersRecorded · Python and R agreeRecorded 2026-11-17 · 44 values compared
R

Grubbs' G = 4.31, p < .001

Flagged (any rule)
2
Flagged by ≥ 2 rules
2
Grubbs p
< .001
Dixon p
< .001

Plots

reading: flagged vs not flaggedWhat do all the observations look like per group, next to the group mean and its uncertainty?
View data
Statusreading
Not flagged10.200
Not flagged9.800
Not flagged10.500
Not flagged10.100
Not flagged9.600
Not flagged10.900
Not flagged10.300
Not flagged9.900
Not flagged10
Not flagged10.400
Not flagged9.700
Not flagged10.600
Not flagged10.200
Not flagged9.500
Not flagged10.800
Not flagged10.100
Not flagged9.900
Not flagged10.300
Not flagged10
Not flagged10.700
Not flagged9.800
Not flagged10.200
Not flagged10.500
Not flagged9.400
Not flagged10.100
Flagged14.900
Not flagged10
Not flagged10.300
Flagged3.100
Not flagged10.200

Rules

RuleCriterionFlagged
Tukey fences (k = 1.5)outside [9.188, 11.09]2
z-score (|z| > 3)SD with n − 11
Modified z (|M| > 3.5)median and MAD (Iglewicz & Hoaglin)2
Grubbs' testG = 4.307, p = 1.389e-061
Generalized ESD (up to 3)α = 0.052
Dixon's Q testr22: Q = 0.8312, p = 0.0001 (lowest value)1
Tietjen–Moore (k = 2)k = 2: E = 0.0502, p = 0.00012

Flagged values

RowidreadingzModified zTukeyz ruleMod. zGrubbsESDDixonT–MRules
29r293.100−4.307−19.021truetruetruetruetruetruetrue4
26r2614.9002.98812.815truefalsetruefalsetruefalsetrue3

Generalized ESD steps

iValueRλ (critical)Outlier
13.1004.3072.908true
214.9004.7982.893true
310.9002.0162.876false
  • Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. Never delete automatically; compare results with and without flagged values (sensitivity analysis).
  • Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; Tietjen–Moore tests exactly k values chosen before looking at the data.
  • Dixon and Tietjen–Moore p-values are Monte-Carlo (9,999 normal samples, seed 1); they match in Python and R.
The exact R script · R R version 4.5.1 (2025-06-13)
# Outliers (univariate)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method outliers.univariate 2.0.1 · spec 7fa75b43dd4df169
# Dataset: s1_outliers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_outliers.parquet", col_select = c("reading", "id")))
n_input <- nrow(df)
df[["id"]] <- factor(df[["id"]], levels = c("r01", "r02", "r03", "r04", "r05", "r06", "r07", "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30"))  # stored level order
df <- df[stats::complete.cases(df[c("reading", "id")]), , 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("reading", "id"))  # infinite values stop the run (registry/errors.yaml)

# %% Rules
y <- "reading"
label <- "id"
if (!nzchar(label)) label <- NULL
group <- ""
if (!nzchar(group)) group <- NULL
x_all <- as.numeric(df[[y]])
rows_all <- as.integer(rownames(df))  # 1-based row numbers in the input
n <- length(x_all)
tukey_k <- 1.5
z_cut <- 3
modz_cut <- 3.5
alpha <- 0.05
gesd_k <- as.integer(3)
side <- "two_sided"  # two_sided, upper or lower (prespecified)
dixon_type <- "auto"
tm_k <- as.integer(2)
reps <- as.integer(9999)
seed <- as.integer(1)

num_or_null <- function(v) if (is.null(v) || length(v) == 0 || !is.finite(v)) NULL else v

# Every rule on one sample; `idx` maps positions in x to rows of df.
screen <- function(x, rows_in, idx) {
  n <- length(x)
  fences <- cs_tukey_fences(x, tukey_k)
  outer <- cs_tukey_fences(x, 3)
  flag_tukey <- x < fences[1] | x > fences[2]
  z <- cs_zscores(x)
  z_enabled <- n > 10  # with n <= 10, |z| can never exceed (n - 1) / sqrt(n)
  flag_z <- if (z_enabled) abs(z) > z_cut else rep(FALSE, n)
  mz <- cs_modified_z(x)
  flag_modz <- abs(mz) > modz_cut
  gr <- cs_grubbs(x, side)
  flag_grubbs <- rep(FALSE, n)
  grubbs_row <- NULL
  if (is.finite(gr$p) && gr$p < alpha) {
    pos <- if (gr$side == "lowest") which.min(x) else which.max(x)
    flag_grubbs[pos] <- TRUE
    grubbs_row <- rows_in[pos]
  }
  ge <- cs_gesd(x, gesd_k, alpha)
  flag_gesd <- rep(FALSE, n)
  if (nrow(ge$steps)) flag_gesd[ge$steps$row[ge$steps$outlier]] <- TRUE
  dx <- cs_dixon(x, dixon_type, side, reps, seed)
  flag_dixon <- rep(FALSE, n)
  if (is.finite(dx$p) && dx$p < alpha) flag_dixon[if (dx$side == "lowest") which.min(x) else which.max(x)] <- TRUE
  tm <- cs_tietjen_moore(x, tm_k, side, reps, seed)
  flag_tm <- rep(FALSE, n)
  if (is.finite(tm$p) && tm$p < alpha) flag_tm[tm$rows] <- TRUE
  count <- flag_tukey + flag_z + flag_modz + flag_gesd
  any_flag <- count > 0 | flag_grubbs | flag_dixon | flag_tm
  list(n = n, x = x, rows_in = rows_in, idx = idx, fences = fences, outer = outer, z = z, z_enabled = z_enabled, mz = mz,
       gr = gr, grubbs_row = grubbs_row, ge = ge, dx = dx, tm = tm, count = count, any = any_flag,
       flags = list(tukey = flag_tukey, z_rule = flag_z, modz_rule = flag_modz, grubbs = flag_grubbs, gesd = flag_gesd,
                    dixon = flag_dixon, tm = flag_tm))
}

if (is.null(group) && n < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "Outlier screening", min = 3, n = n)
if (n >= 1 && diff(range(x_all)) == 0) cs_error("CS_E_CONSTANT", column = y)  # no variation: SD and MAD are 0
if (!is.null(group)) {
  levels_g <- levels(df[[group]])
  g_all <- as.character(df[[group]])
  samples <- list()
  for (lv in levels_g) {
    m <- g_all == lv
    if (sum(m) < 3) {
      warnings <- c(warnings, sprintf("%s = %s has fewer than 3 values and was not screened.", group, lv))
      next
    }
    samples[[length(samples) + 1]] <- list(level = lv, s = screen(x_all[m], rows_all[m], which(m)))
  }
  if (!length(samples)) cs_error("CS_E_UNDEFINED", what = "Outlier screening", reason = sprintf("no group of %s has at least 3 values", group))
} else {
  samples <- list(list(level = NULL, s = screen(x_all, rows_all, seq_len(n))))
}

# %% Result
flagged <- list()
for (smp in samples) {
  s <- smp$s
  for (i in which(s$any)) {
    flagged[[length(flagged) + 1]] <- c(
      list(row = s$rows_in[i]), if (!is.null(group)) list(group = smp$level),
      if (!is.null(label)) list(label = as.character(df[[label]][s$idx[i]])),
      list(value = s$x[i], z = num_or_null(s$z[i]), modz = s$mz[i]),
      lapply(s$flags, function(f) f[i]), list(rules = s$count[i]))
  }
}
if (length(flagged)) {
  o <- order(-vapply(flagged, function(r) r$rules, numeric(1)), vapply(flagged, function(r) r$row, numeric(1)))
  flagged <- flagged[o]
}
any_rows <- sort(unlist(lapply(samples, function(smp) smp$s$rows_in[smp$s$any])))
n_any <- sum(vapply(samples, function(smp) sum(smp$s$any), numeric(1)))
n_cons <- sum(vapply(samples, function(smp) sum(smp$s$count >= 2), numeric(1)))
values <- list(n = n, mean = mean(x_all), sd = stats::sd(x_all), median = stats::median(x_all),
               n_flagged_any = n_any, n_consensus = n_cons, flagged_rows = I(as.integer(any_rows)),
               n_groups = if (is.null(group)) 0L else length(samples), mc_reps = reps, tm_k = tm_k)
single_keys <- c("tukey_low", "tukey_high", "outer_low", "outer_high", "n_tukey", "n_tukey_outer", "n_z", "z_enabled", "max_abs_z",
                 "n_modz", "max_abs_modz", "grubbs_g", "grubbs_p", "grubbs_value", "grubbs_side", "grubbs_row", "gesd_n",
                 "dixon_type", "dixon_q", "dixon_p", "dixon_value", "dixon_side", "tm_e", "tm_p", "tm_side")
tables <- list()
if (is.null(group)) {
  s <- samples[[1]]$s
  x <- s$x; gr <- s$gr; ge <- s$ge; dx <- s$dx; tm <- s$tm; f <- s$flags
  values$tukey_low <- s$fences[1]
  values$tukey_high <- s$fences[2]
  values$outer_low <- s$outer[1]
  values$outer_high <- s$outer[2]
  values$n_tukey <- sum(f$tukey)
  values$n_tukey_outer <- sum(x < s$outer[1] | x > s$outer[2])
  values$n_z <- sum(f$z_rule)
  values$z_enabled <- s$z_enabled
  values["max_abs_z"] <- list(if (s$z_enabled) max(abs(s$z), na.rm = TRUE) else NULL)
  values$n_modz <- sum(f$modz_rule)
  values$max_abs_modz <- max(abs(s$mz))
  values$grubbs_g <- gr$g
  values$grubbs_p <- gr$p
  values$grubbs_value <- gr$value
  values$grubbs_side <- gr$side
  values["grubbs_row"] <- list(s$grubbs_row)
  values$gesd_n <- ge$n_outliers
  values["dixon_type"] <- list(if (is.finite(dx$q)) dx$type else NULL)
  values["dixon_q"] <- list(num_or_null(dx$q))
  values["dixon_p"] <- list(num_or_null(dx$p))
  values["dixon_value"] <- list(num_or_null(dx$value))
  values["dixon_side"] <- list(if (nzchar(dx$side)) dx$side else NULL)
  values["tm_e"] <- list(num_or_null(tm$e))
  values["tm_p"] <- list(num_or_null(tm$p))
  values["tm_side"] <- list(if (nzchar(tm$side)) tm$side else NULL)
  for (j in seq_len(nrow(ge$steps))) {
    values[[sprintf("gesd_r[%d]", ge$steps$i[j])]] <- ge$steps$r[j]
    values[[sprintf("gesd_lambda[%d]", ge$steps$i[j])]] <- ge$steps$lambda[j]
    values[[sprintf("gesd_value[%d]", ge$steps$i[j])]] <- ge$steps$value[j]
  }
  dixon_crit <- if (is.finite(dx$q)) sprintf("%s: Q = %.4g, p = %.4g (%s value)", dx$type, dx$q, dx$p, dx$side) else "not used: Dixon's ratios cover 3–30 values"
  tm_crit <- if (is.finite(tm$e)) sprintf("k = %d: E = %.4g, p = %.4g", tm_k, tm$e, tm$p) else sprintf("not used: needs more than %d values", tm_k + 1)
  methods <- list(
    list(method = sprintf("Tukey fences (k = %s)", format(tukey_k)), criterion = sprintf("outside [%.4g, %.4g]", s$fences[1], s$fences[2]), flagged = sum(f$tukey)),
    list(method = sprintf("z-score (|z| > %s)", format(z_cut)), criterion = if (s$z_enabled) "SD with n − 1" else "not used: n ≤ 10", flagged = sum(f$z_rule)),
    list(method = sprintf("Modified z (|M| > %s)", format(modz_cut)), criterion = "median and MAD (Iglewicz & Hoaglin)", flagged = sum(f$modz_rule)),
    list(method = "Grubbs' test", criterion = sprintf("G = %.3f, p = %.4g", gr$g, gr$p), flagged = sum(f$grubbs)),
    list(method = sprintf("Generalized ESD (up to %d)", gesd_k), criterion = sprintf("α = %s", format(alpha)), flagged = sum(f$gesd)),
    list(method = "Dixon's Q test", criterion = dixon_crit, flagged = sum(f$dixon)),
    list(method = sprintf("Tietjen–Moore (k = %d)", tm_k), criterion = tm_crit, flagged = sum(f$tm))
  )
  tables[[length(tables) + 1]] <- list(key = "rules", title = "Rules", columns = list(
    list(key = "method", label = "Rule", type = "string"), list(key = "criterion", label = "Criterion", type = "string"),
    list(key = "flagged", label = "Flagged", type = "integer")), rows = methods)
} else {
  for (k in single_keys) values[k] <- list(NULL)
  grows <- list()
  for (smp in samples) {
    lv <- smp$level
    s <- smp$s
    values[[sprintf("n[%s]", lv)]] <- s$n
    values[[sprintf("n_flagged[%s]", lv)]] <- sum(s$any)
    values[[sprintf("tukey_low[%s]", lv)]] <- s$fences[1]
    values[[sprintf("tukey_high[%s]", lv)]] <- s$fences[2]
    values[sprintf("grubbs_p[%s]", lv)] <- list(num_or_null(s$gr$p))
    values[sprintf("dixon_p[%s]", lv)] <- list(num_or_null(s$dx$p))
    values[sprintf("tm_p[%s]", lv)] <- list(num_or_null(s$tm$p))
    grows[[length(grows) + 1]] <- list(group = lv, n = s$n, flagged = sum(s$any), tukey_low = s$fences[1], tukey_high = s$fences[2],
                                       grubbs_p = num_or_null(s$gr$p), gesd_n = s$ge$n_outliers, dixon_p = num_or_null(s$dx$p),
                                       tm_p = num_or_null(s$tm$p))
  }
  tables[[length(tables) + 1]] <- list(key = "groups", title = sprintf("Rules within each %s", group), columns = list(
    list(key = "group", label = group, type = "string"), list(key = "n", label = "n", type = "integer"),
    list(key = "flagged", label = "Flagged", type = "integer"), list(key = "tukey_low", label = "Lower fence", type = "number"),
    list(key = "tukey_high", label = "Upper fence", type = "number"), list(key = "grubbs_p", label = "Grubbs p", type = "p"),
    list(key = "gesd_n", label = "ESD outliers", type = "integer"), list(key = "dixon_p", label = "Dixon p", type = "p"),
    list(key = "tm_p", label = "Tietjen–Moore p", type = "p")), rows = grows)
}
flag_cols <- c(list(list(key = "row", label = "Row", type = "integer")),
               if (!is.null(group)) list(list(key = "group", label = group, type = "string")),
               if (!is.null(label)) list(list(key = "label", label = label, type = "string")),
               list(list(key = "value", label = y, type = "number"), list(key = "z", label = "z", type = "number"),
                    list(key = "modz", label = "Modified z", type = "number"), list(key = "tukey", label = "Tukey", type = "string"),
                    list(key = "z_rule", label = "z rule", type = "string"), list(key = "modz_rule", label = "Mod. z", type = "string"),
                    list(key = "grubbs", label = "Grubbs", type = "string"), list(key = "gesd", label = "ESD", type = "string"),
                    list(key = "dixon", label = "Dixon", type = "string"), list(key = "tm", label = "T–M", type = "string"),
                    list(key = "rules", label = "Rules", type = "integer")))
tables[[length(tables) + 1]] <- list(key = "flagged", title = "Flagged values", columns = flag_cols, rows = flagged)
if (is.null(group)) {
  s <- samples[[1]]$s
  gesd_rows <- if (nrow(s$ge$steps)) {
    steps <- s$ge$steps
    steps$row <- s$rows_in[steps$row]
    steps
  } else list()
  tables[[length(tables) + 1]] <- list(key = "gesd", title = "Generalized ESD steps",
    columns = list(list(key = "i", label = "i", type = "integer"), list(key = "value", label = "Value", type = "number"),
                   list(key = "r", label = "R", type = "number"), list(key = "lambda", label = "λ (critical)", type = "number"),
                   list(key = "outlier", label = "Outlier", type = "string")),
    rows = gesd_rows)
}
any_mask <- rep(FALSE, n)
for (smp in samples) any_mask[smp$s$idx[smp$s$any]] <- TRUE
chart_rows <- unique(round(seq(1, n, length.out = min(n, 5000))))
status <- ifelse(any_mask, "Flagged", "Not flagged")
small_n <- is.null(group) && !samples[[1]]$s$z_enabled
gr0 <- samples[[1]]$s$gr
cs_publish(list(
  method = "outliers.univariate",
  methodVersion = "2.0.1",
  title = "Outliers",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = paste0(sprintf("%s: %d of %d values flagged by at least one rule, %d by two or more", y, n_any, n, n_cons),
                   if (!is.null(group)) sprintf(" (each %s screened on its own).", group) else "."),
  apa = if (!is.null(group)) "" else sprintf("Grubbs' G = %s, %s", cs_fmt_num(gr0$g), cs_fmt_p(gr0$p)),
  statistics = c(list(list(key = "n_flagged_any", label = "Flagged (any rule)", value = n_any),
                      list(key = "n_consensus", label = "Flagged by ≥ 2 rules", value = n_cons)),
                 if (is.null(group)) list(list(key = "grubbs_p", label = "Grubbs p", value = gr0$p, format = "p"),
                                          list(key = "dixon_p", label = "Dixon p", value = values$dixon_p, format = "p"))),
  tables = tables,
  effectSizes = list(),
  assumptions = list(),
  warnings = c(warnings, if (small_n) list("With 10 or fewer values the z rule cannot flag anything; it is not used.")),
  notes = list(paste("Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values.",
                     "Never delete automatically; compare results with and without flagged values (sensitivity analysis)."),
               paste("Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values;",
                     "Tietjen–Moore tests exactly k values chosen before looking at the data."),
               sprintf("Dixon and Tietjen–Moore p-values are Monte-Carlo (%s normal samples, seed %d); they match in Python and R.",
                       format(reps, big.mark = ","), seed)),
  charts = list(cs_chart("values", "strip", sprintf("%s: flagged vs not flagged", y), list(
    y = cs_col(y, x_all[chart_rows]), group = cs_col("Status", status[chart_rows], levels = c("Not flagged", "Flagged"))),
    controls = list(interval = "none"))),
  values = values
))
Python

Grubbs' G = 4.31, p < .001

Flagged (any rule)
2
Flagged by ≥ 2 rules
2
Grubbs p
< .001
Dixon p
< .001

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

Rules

RuleCriterionFlagged
Tukey fences (k = 1.5)outside [9.188, 11.09]2
z-score (|z| > 3)SD with n − 11
Modified z (|M| > 3.5)median and MAD (Iglewicz & Hoaglin)2
Grubbs' testG = 4.307, p = 1.389e-061
Generalized ESD (up to 3)α = 0.052
Dixon's Q testr22: Q = 0.8312, p = 0.0001 (lowest value)1
Tietjen–Moore (k = 2)k = 2: E = 0.0502, p = 0.00012

Flagged values

RowidreadingzModified zTukeyz ruleMod. zGrubbsESDDixonT–MRules
29r293.100−4.307−19.021truetruetruetruetruetruetrue4
26r2614.9002.98812.815truefalsetruefalsetruefalsetrue3

Generalized ESD steps

iValueRλ (critical)Outlier
13.1004.3072.908true
214.9004.7982.893true
310.9002.0162.876false
  • Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. Never delete automatically; compare results with and without flagged values (sensitivity analysis).
  • Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; Tietjen–Moore tests exactly k values chosen before looking at the data.
  • Dixon and Tietjen–Moore p-values are Monte-Carlo (9,999 normal samples, seed 1); they match in Python and R.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Outliers (univariate)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method outliers.univariate 2.0.1 · spec 7fa75b43dd4df169
# Dataset: s1_outliers (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.stats import outliers as cso

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_outliers.parquet", columns=["reading", "id"])
n_input = len(df)
df["id"] = pd.Categorical(df["id"], categories=["r01", "r02", "r03", "r04", "r05", "r06", "r07", "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30"])  # stored level order
df = df.dropna(subset=["reading", "id"])  # listwise deletion over the analysis columns
df["id"] = df["id"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["reading", "id"])  # infinite values stop the run (registry/errors.yaml)

# %% Rules
y = "reading"
label = "id" or None
group = "" or None
x_all = df[y].to_numpy(dtype=float)
rows_all = (df.index.to_numpy() + 1).astype(int)  # 1-based row numbers in the input
n = x_all.size
tukey_k = 1.5
z_cut = 3
modz_cut = 3.5
alpha = 0.05
gesd_k = int(3)
side = "two_sided"  # two_sided, upper or lower (prespecified)
dixon_type = "auto"
tm_k = int(2)
reps = int(9999)
seed = int(1)


def screen(x, rows_in, idx):
    """Every rule on one sample; positions in the result index ``x`` (``idx`` maps them to ``df`` rows)."""
    n = x.size
    lo, hi = cso.tukey_fences(x, tukey_k)
    olo, ohi = cso.tukey_fences(x, 3.0)
    flag_tukey = (x < lo) | (x > hi)
    z = cso.zscores(x)
    z_enabled = n > 10  # with n ≤ 10, |z| can never exceed (n − 1)/√n
    flag_z = (np.abs(z) > z_cut) if z_enabled else np.zeros(n, bool)
    mz = cso.modified_z(x)
    flag_modz = np.abs(mz) > modz_cut
    gr = cso.grubbs(x, side)
    flag_grubbs = np.zeros(n, bool)
    grubbs_row = None
    if np.isfinite(gr["p"]) and gr["p"] < alpha:
        pos = int(np.argmin(x)) if gr["side"] == "lowest" else int(np.argmax(x))
        flag_grubbs[pos] = True
        grubbs_row = int(rows_in[pos])
    ge = cso.gesd(x, gesd_k, alpha)
    flag_gesd = np.zeros(n, bool)
    for st in ge["steps"]:
        if st["outlier"]:
            flag_gesd[st["row"]] = True
    dx = cso.dixon(x, dixon_type, side, reps, seed)
    flag_dixon = np.zeros(n, bool)
    if np.isfinite(dx["p"]) and dx["p"] < alpha:
        flag_dixon[int(np.argmin(x)) if dx["side"] == "lowest" else int(np.argmax(x))] = True
    tm = cso.tietjen_moore(x, tm_k, side, reps, seed)
    flag_tm = np.zeros(n, bool)
    if np.isfinite(tm["p"]) and tm["p"] < alpha:
        flag_tm[tm["rows"]] = True
    count = flag_tukey.astype(int) + flag_z.astype(int) + flag_modz.astype(int) + flag_gesd.astype(int)
    any_flag = (count > 0) | flag_grubbs | flag_dixon | flag_tm
    return {"n": n, "x": x, "rows_in": rows_in, "idx": idx, "lo": lo, "hi": hi, "olo": olo, "ohi": ohi, "z": z, "z_enabled": z_enabled,
            "mz": mz, "gr": gr, "grubbs_row": grubbs_row, "ge": ge, "dx": dx, "tm": tm, "count": count, "any": any_flag,
            "flags": {"tukey": flag_tukey, "z_rule": flag_z, "modz_rule": flag_modz, "grubbs": flag_grubbs, "gesd": flag_gesd,
                      "dixon": flag_dixon, "tm": flag_tm}}


def num(v):
    return None if v is None or not np.isfinite(v) else float(v)


if not group and n < 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Outlier screening", min=3, n=n)
if n >= 1 and np.ptp(x_all) == 0:  # no variation: SD and MAD are 0, so no rule can flag anything
    cs.cs_error("CS_E_CONSTANT", column=y)
if group:
    levels = [str(lv) for lv in df[group].cat.categories]
    g_all = df[group].astype(str).to_numpy()
    samples = []
    for lv in levels:
        m = g_all == lv
        if m.sum() < 3:
            warnings.append(f"{group} = {lv} has fewer than 3 values and was not screened.")
            continue
        samples.append((lv, screen(x_all[m], rows_all[m], np.flatnonzero(m))))
    if not samples:
        cs.cs_error("CS_E_UNDEFINED", what="Outlier screening", reason=f"no group of {group} has at least 3 values")
else:
    samples = [(None, screen(x_all, rows_all, np.arange(n)))]

# %% Result
flagged = []
for lv, s in samples:
    for i in np.flatnonzero(s["any"]):
        flagged.append({
            "row": int(s["rows_in"][i]), **({"group": lv} if group else {}),
            **({"label": str(df[label].iloc[int(s["idx"][i])])} if label else {}),
            "value": float(s["x"][i]), "z": num(s["z"][i]), "modz": float(s["mz"][i]),
            **{k: bool(f[i]) for k, f in s["flags"].items()}, "rules": int(s["count"][i]),
        })
flagged.sort(key=lambda r: (-r["rules"], r["row"]))
any_rows = sorted(int(r) for _, s in samples for r in s["rows_in"][s["any"]])
n_any = sum(int(s["any"].sum()) for _, s in samples)
n_cons = sum(int((s["count"] >= 2).sum()) for _, s in samples)
values = {"n": n, "mean": float(x_all.mean()), "sd": float(x_all.std(ddof=1)), "median": float(np.median(x_all)),
          "n_flagged_any": n_any, "n_consensus": n_cons, "flagged_rows": any_rows, "n_groups": len(samples) if group else 0,
          "mc_reps": reps, "tm_k": tm_k}
single_keys = ["tukey_low", "tukey_high", "outer_low", "outer_high", "n_tukey", "n_tukey_outer", "n_z", "z_enabled", "max_abs_z",
               "n_modz", "max_abs_modz", "grubbs_g", "grubbs_p", "grubbs_value", "grubbs_side", "grubbs_row", "gesd_n",
               "dixon_type", "dixon_q", "dixon_p", "dixon_value", "dixon_side", "tm_e", "tm_p", "tm_side"]
tables = []
if not group:
    s = samples[0][1]
    x, gr, ge, dx, tm, f = s["x"], s["gr"], s["ge"], s["dx"], s["tm"], s["flags"]
    values.update({
        "tukey_low": s["lo"], "tukey_high": s["hi"], "outer_low": s["olo"], "outer_high": s["ohi"],
        "n_tukey": int(f["tukey"].sum()), "n_tukey_outer": int(((x < s["olo"]) | (x > s["ohi"])).sum()),
        "n_z": int(f["z_rule"].sum()), "z_enabled": bool(s["z_enabled"]),
        "max_abs_z": float(np.nanmax(np.abs(s["z"]))) if s["z_enabled"] else None,
        "n_modz": int(f["modz_rule"].sum()), "max_abs_modz": float(np.max(np.abs(s["mz"]))),
        "grubbs_g": gr["g"], "grubbs_p": gr["p"], "grubbs_value": gr["value"], "grubbs_side": gr["side"], "grubbs_row": s["grubbs_row"],
        "gesd_n": int(ge["n_outliers"]),
        "dixon_type": dx["type"] if np.isfinite(dx["q"]) else None, "dixon_q": num(dx["q"]), "dixon_p": num(dx["p"]), "dixon_value": num(dx["value"]),
        "dixon_side": dx["side"] or None, "tm_e": num(tm["e"]), "tm_p": num(tm["p"]), "tm_side": tm["side"] or None,
    })
    for st in ge["steps"]:
        values[f"gesd_r[{st['i']}]"] = st["r"]
        values[f"gesd_lambda[{st['i']}]"] = st["lambda"]
        values[f"gesd_value[{st['i']}]"] = st["value"]
    dixon_crit = (f"{dx['type']}: Q = {dx['q']:.4g}, p = {dx['p']:.4g} ({dx['side']} value)" if np.isfinite(dx["q"])
                  else "not used: Dixon's ratios cover 3–30 values")
    tm_crit = (f"k = {tm_k}: E = {tm['e']:.4g}, p = {tm['p']:.4g}" if np.isfinite(tm["e"]) else f"not used: needs more than {tm_k + 1} values")
    methods = [
        {"method": f"Tukey fences (k = {tukey_k:g})", "criterion": f"outside [{s['lo']:.4g}, {s['hi']:.4g}]", "flagged": int(f["tukey"].sum())},
        {"method": f"z-score (|z| > {z_cut:g})", "criterion": "SD with n − 1" if s["z_enabled"] else "not used: n ≤ 10", "flagged": int(f["z_rule"].sum())},
        {"method": f"Modified z (|M| > {modz_cut:g})", "criterion": "median and MAD (Iglewicz & Hoaglin)", "flagged": int(f["modz_rule"].sum())},
        {"method": "Grubbs' test", "criterion": f"G = {gr['g']:.3f}, p = {gr['p']:.4g}", "flagged": int(f["grubbs"].sum())},
        {"method": f"Generalized ESD (up to {gesd_k})", "criterion": f"α = {alpha:g}", "flagged": int(f["gesd"].sum())},
        {"method": "Dixon's Q test", "criterion": dixon_crit, "flagged": int(f["dixon"].sum())},
        {"method": f"Tietjen–Moore (k = {tm_k})", "criterion": tm_crit, "flagged": int(f["tm"].sum())},
    ]
    tables.append({"key": "rules", "title": "Rules", "columns": [{"key": "method", "label": "Rule", "type": "string"},
                   {"key": "criterion", "label": "Criterion", "type": "string"}, {"key": "flagged", "label": "Flagged", "type": "integer"}],
                   "rows": methods})
else:
    for k in single_keys:
        values[k] = None
    grows = []
    for lv, s in samples:
        values[f"n[{lv}]"] = int(s["n"])
        values[f"n_flagged[{lv}]"] = int(s["any"].sum())
        values[f"tukey_low[{lv}]"] = s["lo"]
        values[f"tukey_high[{lv}]"] = s["hi"]
        values[f"grubbs_p[{lv}]"] = num(s["gr"]["p"])
        values[f"dixon_p[{lv}]"] = num(s["dx"]["p"])
        values[f"tm_p[{lv}]"] = num(s["tm"]["p"])
        grows.append({"group": lv, "n": int(s["n"]), "flagged": int(s["any"].sum()), "tukey_low": s["lo"], "tukey_high": s["hi"],
                      "grubbs_p": num(s["gr"]["p"]), "gesd_n": int(s["ge"]["n_outliers"]), "dixon_p": num(s["dx"]["p"]), "tm_p": num(s["tm"]["p"])})
    tables.append({"key": "groups", "title": f"Rules within each {group}", "columns": [
        {"key": "group", "label": group, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
        {"key": "flagged", "label": "Flagged", "type": "integer"}, {"key": "tukey_low", "label": "Lower fence", "type": "number"},
        {"key": "tukey_high", "label": "Upper fence", "type": "number"}, {"key": "grubbs_p", "label": "Grubbs p", "type": "p"},
        {"key": "gesd_n", "label": "ESD outliers", "type": "integer"}, {"key": "dixon_p", "label": "Dixon p", "type": "p"},
        {"key": "tm_p", "label": "Tietjen–Moore p", "type": "p"}], "rows": grows})
flag_cols = ([{"key": "row", "label": "Row", "type": "integer"}] + ([{"key": "group", "label": group, "type": "string"}] if group else [])
             + ([{"key": "label", "label": label, "type": "string"}] if label else []) + [
    {"key": "value", "label": y, "type": "number"}, {"key": "z", "label": "z", "type": "number"}, {"key": "modz", "label": "Modified z", "type": "number"},
    {"key": "tukey", "label": "Tukey", "type": "string"}, {"key": "z_rule", "label": "z rule", "type": "string"},
    {"key": "modz_rule", "label": "Mod. z", "type": "string"}, {"key": "grubbs", "label": "Grubbs", "type": "string"},
    {"key": "gesd", "label": "ESD", "type": "string"}, {"key": "dixon", "label": "Dixon", "type": "string"},
    {"key": "tm", "label": "T–M", "type": "string"}, {"key": "rules", "label": "Rules", "type": "integer"},
])
tables.append({"key": "flagged", "title": "Flagged values", "columns": flag_cols, "rows": flagged})
if not group:
    s = samples[0][1]
    tables.append({"key": "gesd", "title": "Generalized ESD steps",
                   "columns": [{"key": "i", "label": "i", "type": "integer"}, {"key": "value", "label": "Value", "type": "number"},
                               {"key": "r", "label": "R", "type": "number"}, {"key": "lambda", "label": "λ (critical)", "type": "number"},
                               {"key": "outlier", "label": "Outlier", "type": "string"}],
                   "rows": [{**st, "row": int(s["rows_in"][st["row"]])} for st in s["ge"]["steps"]]})
any_mask = np.zeros(n, bool)
for _, s in samples:
    any_mask[s["idx"][s["any"]]] = True
chart_rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
status = np.where(any_mask, "Flagged", "Not flagged")
small_n = (not group) and not samples[0][1]["z_enabled"]
gr0 = samples[0][1]["gr"]
cs.publish({
    "method": "outliers.univariate",
    "methodVersion": "2.0.1",
    "title": "Outliers",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": f"{y}: {n_any} of {n} values flagged by at least one rule, {n_cons} by two or more"
    + (f" (each {group} screened on its own)." if group else "."),
    "apa": "" if group else f"Grubbs' G = {cs.fmt_num(gr0['g'])}, {cs.fmt_p(gr0['p'])}",
    "statistics": [{"key": "n_flagged_any", "label": "Flagged (any rule)", "value": n_any},
                   {"key": "n_consensus", "label": "Flagged by ≥ 2 rules", "value": n_cons}]
    + ([] if group else [{"key": "grubbs_p", "label": "Grubbs p", "value": gr0["p"], "format": "p"},
                         {"key": "dixon_p", "label": "Dixon p", "value": values["dixon_p"], "format": "p"}]),
    "tables": tables,
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings + (["With 10 or fewer values the z rule cannot flag anything; it is not used."] if small_n else []),
    "notes": ["Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. "
              "Never delete automatically; compare results with and without flagged values (sensitivity analysis).",
              "Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; "
              "Tietjen–Moore tests exactly k values chosen before looking at the data.",
              f"Dixon and Tietjen–Moore p-values are Monte-Carlo ({reps:,} normal samples, seed {seed}); they match in Python and R."],
    "charts": [cs.chart("values", "strip", f"{y}: flagged vs not flagged", {
        "y": cs.col(y, x_all[chart_rows]), "group": cs.col("Status", status[chart_rows], levels=["Not flagged", "Flagged"])},
        controls={"interval": "none"})],
    "values": values,
})

Grubbs' test flags 3.10, with G=G = 4.31, p < .001. Generalized ESD finds 2. The rules agree on 2 values.

Outlier consensusWhich values look unusual, and do the common outlier rules agree?
View data
response_ms
324
139
268
374
184
376
341
154
131
240
364
420
156
188
414
251
232
252
284
323
363
238
326
178
224
201
167
223
198
198
179
164
375
278
191
229
189
134
524
146
106
232
222
244
238
179
304
193
217
267
400
264
101
209
332
204
243
526
293
322

First 60 of 405 rows.

06

Small samples and fixed counts

Explore

Dixon's Q needs few points. In a guide example with 10 values, Q=Q = 0.69, p = .001.

Tietjen–Moore tests a fixed number of suspects. Testing k=k = 2 values among 60 gives p < .001.

07

Outliers in a model

Read

An extreme value in one column may be ordinary given other columns. A person who is 2 m tall and weighs 110 kg isn't odd once you account for height.

For a fitted regression, the Bonferroni outlier test checks the largest studentized residual, correcting for having searched all rows. It's an output of linear regression, not of this method.

08

Check your understanding

Checkpoint

Check yourself

A column has Q1=10Q_1 = 10 and Q3=20Q_3 = 20. What is the upper Tukey fence? (Use the 1.5 multiplier.)

Show the answer

Answer: 35

IQR = 10, so 20 + 1.5 × 10.

Check yourself

Why can a z-score rule miss two large outliers?

Show the answer

Answer: a

The ruler stretches to accommodate the values it's measuring. A median and MAD barely move.

Check yourself

You don't know how many outliers a roughly normal column has, but you can name a maximum. Which test fits?

Show the answer

Answer: b

Grubbs handles one value and suffers masking when applied repeatedly. Generalized ESD takes an upper limit and is built for this.

Check yourself

What does Tietjen–Moore require that generalized ESD doesn't?

Show the answer

Answer: a

Choosing kk after looking at the data undoes the test's calibration. If you don't know kk, use generalized ESD.

Check yourself

Which check belongs to a fitted regression, not to a single column?

Show the answer

Answer: c

It asks whether a row is extreme given the model, correcting for having looked at every row.

09

Recap

Recap
  • Tukey and modified z are good screens, and they resist the masking that defeats the plain z rule.
  • Formal tests assume the rest of the data are roughly normal.
  • Use Grubbs for one suspect, generalized ESD for several, Dixon for small samples, and Tietjen–Moore when kk is known.

Concepts in this lesson