Multiplex Curves and Censored Values
Every Luminex concentration comes from reading an MFI back through a standard curve, and the curve holds only between its lowest and highest acceptable standards. This page fits a five-parameter logistic curve per analyte, sets the limits of quantification, and flags the samples outside them instead of extrapolating. It then asks what the values below the limit do to a group comparison, first on the synthetic plate and then on a real cytokine table.
Choose the entry point that matches your input. The calibration example and the real cohort answer different questions and use different datasets.
| Starting data or question | Entry point | What the example establishes |
|---|---|---|
| Raw MFI, bead counts and standards | Read the plate, then fit each curve | The synthetic truth allows a check of concentration recovery and limits |
| The effect of values outside the limits | Compare four substitutions | The same synthetic samples produce different comparisons under different substitutions |
| Concentrations from a published study | Read the real cohort | The example examines reported zeros and group comparisons without refitting the original calibration |
Read the plate
Section titled “Read the plate”The rows below 35 beads go, and the two wells of each sample average into one Median FI.
# drc attaches MASS, so load it before dplyr to keep dplyr's select().suppressPackageStartupMessages({ library(drc) library(dplyr) library(ggplot2) library(readr) library(tidyr)})
options(width = 110)data_dir <- "/opt/data/luminex_synthetic"plate <- read_csv( file.path(data_dir, "luminex_plate_export.csv"), show_col_types = FALSE)sample_sheet <- read_csv( file.path(data_dir, "luminex_sample_sheet.csv"), show_col_types = FALSE)truth <- read_csv( file.path(data_dir, "luminex_truth_concentrations.csv"), show_col_types = FALSE)analytes <- unique(plate$Analyte)
# Rows below 35 beads are dropped, as on the QC page.kept <- filter(plate, `Bead Count` >= 35)cat(sprintf("rows kept: %d of %d\n", nrow(kept), nrow(plate)))
# One value per sample and analyte: the mean Median FI of its kept wells.means <- kept |> group_by(Sample, Analyte) |> summarise( mfi = mean(`Median FI`), wells = n(), dilution = first(`Dilution Factor`), .groups = "drop" )cat(sprintf( "sample and analyte pairs left with one well: %d\n", sum(means$wells == 1)))print(as.data.frame(count(sample_sheet, group)), row.names = FALSE)metrics <- list(rows_kept = nrow(kept), single_well = sum(means$wells == 1))rows kept: 507 of 516sample and analyte pairs left with one well: 9 group n Control 16 Patient 16import jsonimport pathlibimport re
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom matplotlib.lines import Line2Dfrom scipy import statsfrom scipy.optimize import least_squares
DATA_DIR = pathlib.Path("/opt/data/luminex_synthetic")plate = pd.read_csv(DATA_DIR / "luminex_plate_export.csv")sample_sheet = pd.read_csv(DATA_DIR / "luminex_sample_sheet.csv")truth = pd.read_csv(DATA_DIR / "luminex_truth_concentrations.csv")analytes = list(plate["Analyte"].unique())
# Rows below 35 beads are dropped, as on the QC page.kept = plate[plate["Bead Count"] >= 35]print(f"rows kept: {len(kept)} of {len(plate)}")
# One value per sample and analyte: the mean Median FI of its kept wells.means = kept.groupby(["Sample", "Analyte"], as_index=False).agg( mfi=("Median FI", "mean"), wells=("Median FI", "size"), dilution=("Dilution Factor", "first"),)single_well = int((means["wells"] == 1).sum())print(f"sample and analyte pairs left with one well: {single_well}")print(sample_sheet["group"].value_counts().sort_index().to_string())metrics = {"rows_kept": len(kept), "single_well": single_well}rows kept: 507 of 516sample and analyte pairs left with one well: 9groupControl 16Patient 16Nine sample and analyte pairs are left with one well, and the 32 samples split into 16 Control and 16 Patient.
Fit one curve per analyte
Section titled “Fit one curve per analyte”drc’s LL.5() is the five-parameter curve of
Ritz et al. 2015,
c + (d - c) / (1 + exp(b * (log(x) - log(e))))^f. Here c is the MFI at zero, d the MFI at
saturation, b the slope, e the position of the rise and f the asymmetry. The noise on this
plate grows with the signal, so both tabs fit the log of the MFI, which weighs each standard
by its relative error, and both start from the same values.
#' Evaluate the drc LL.5 curve.#'#' @param conc Concentrations in pg/mL.#' @param p Named parameters b, c, d, e and f.#' @return The MFI that the curve predicts.FivePl <- function(conc, p) { p[["c"]] + (p[["d"]] - p[["c"]]) / (1 + exp(p[["b"]] * (log(conc) - log(p[["e"]]))))^p[["f"]]}
#' Fit the five-parameter curve to the log of the MFI.#'#' bcVal = 0 log-transforms both sides, so each standard counts by its#' relative error. The start values are written out so that the Python#' tab starts from the same point.#'#' @param standards A data frame with the columns conc and mfi.#' @return A list with p, the parameters b, c, d, e and f, and shift, the#' largest change that the Nelder-Mead pass made, in percent.FitFivePl <- function(standards) { start <- c( -1, min(standards$mfi), max(standards$mfi), median(standards$conc), 1 ) first <- drm( mfi ~ conc, data = standards, fct = LL.5(), bcVal = 0, start = start, control = drmc(relTol = 1e-12, maxIt = 5000) ) # BFGS can stop short where the curve is flat. A Nelder-Mead pass from # its estimates finishes the search. final <- drm( mfi ~ conc, data = standards, fct = LL.5(), bcVal = 0, start = coef(first), control = drmc(method = "Nelder-Mead", relTol = 1e-15, maxIt = 20000) ) list( p = setNames(coef(final), c("b", "c", "d", "e", "f")), shift = 100 * max(abs(coef(final) / coef(first) - 1)) )}
params <- list()fit_rows <- list()for (analyte in analytes) { standards <- kept |> filter(startsWith(Sample, "Std"), Analyte == analyte) |> transmute(conc = 10000 / `Dilution Factor`, mfi = `Median FI`) fit <- FitFivePl(standards) p <- fit$p params[[analyte]] <- p rss <- sum((log(standards$mfi) - log(FivePl(standards$conc, p)))^2) fit_rows[[analyte]] <- data.frame( analyte = analyte, t(p), rss = rss, polish_pct = round(fit$shift, 3) )}fit_table <- bind_rows(fit_rows)print(fit_table, row.names = FALSE, digits = 4)
# The generator's curve: a is the MFI at zero, d the MFI at saturation.curves <- read_csv( file.path(data_dir, "luminex_truth_curves.csv"), show_col_types = FALSE)ends <- fit_table |> select(analyte, c, d) |> left_join(select(curves, analyte, true_c = a, true_d = d), by = "analyte")print(as.data.frame(mutate(ends, c = round(c, 1), d = round(d))), row.names = FALSE)
for (i in seq_len(nrow(fit_table))) { key <- gsub("-", "_", tolower(fit_table$analyte[i])) for (name in c("b", "c", "d", "e", "f", "rss")) { metrics[[paste0(name, "_", key)]] <- fit_table[[name]][i] }} analyte b c d e f rss polish_pct IL-6 -0.5135 31.11 35353 341.8 2.7396 0.07200 0.804 IL-8 -1.1314 31.52 26447 1366.2 0.8438 0.05032 0.101 TNF-alpha -1.1280 16.07 18166 844.8 0.9590 0.06212 0.026 IL-10 -0.9399 39.70 14911 370.2 1.1046 0.01832 0.001 IFN-gamma -0.9502 37.79 19783 1714.4 1.0508 0.04191 0.051 IL-1beta -1.1069 18.71 17872 686.0 1.0287 0.08776 0.011 analyte c d true_c true_d IL-6 31.1 35353 22 24000 IL-8 31.5 26447 30 28000 TNF-alpha 16.1 18166 18 19000 IL-10 39.7 14911 25 16000 IFN-gamma 37.8 19783 35 21000 IL-1beta 18.7 17872 20 18500def five_pl(conc, params): """Evaluate the drc LL.5 curve.
Args: conc: Concentrations in pg/mL. params: The parameters b, c, d, e and f.
Returns: The MFI that the curve predicts. """ b, c, d, e, f = params return c + (d - c) / (1 + np.exp(b * (np.log(conc) - np.log(e)))) ** f
def log_residuals(params, conc, mfi): """Residuals of the curve on the log scale of the MFI.
Args: params: The parameters b, c, d, e and f. conc: Concentrations of the standards. mfi: Median FI of the standards.
Returns: log(mfi) minus the log of the curve. """ return np.log(mfi) - np.log(five_pl(conc, params))
def fit_five_pl(conc, mfi): """Fit the five-parameter curve to the log of the MFI.
The start values are the ones the R tab writes out.
Args: conc: Concentrations of the standards. mfi: Median FI of the standards.
Returns: The fitted parameters b, c, d, e and f as an array. """ start = [-1, mfi.min(), mfi.max(), np.median(conc), 1] fit = least_squares(log_residuals, start, args=(conc, mfi), xtol=1e-15, ftol=1e-15, gtol=1e-15) return fit.x
params = {}fit_rows = []for analyte in analytes: rows = kept[(kept["Analyte"] == analyte) & kept["Sample"].str.startswith("Std")] conc = 10000 / rows["Dilution Factor"].to_numpy() mfi = rows["Median FI"].to_numpy() params[analyte] = fit_five_pl(conc, mfi) rss = float(np.sum(log_residuals(params[analyte], conc, mfi) ** 2)) fit_rows.append([analyte, *params[analyte], rss])fit_table = pd.DataFrame( fit_rows, columns=["analyte", "b", "c", "d", "e", "f", "rss"])print(fit_table.to_string(index=False, float_format="{:.4g}".format))
# The generator's curve: a is the MFI at zero, d the MFI at saturation.curves = pd.read_csv(DATA_DIR / "luminex_truth_curves.csv").set_index( "analyte")ends = fit_table.set_index("analyte")[["c", "d"]].round({"c": 1, "d": 0})ends["true_c"] = curves["a"]ends["true_d"] = curves["d"]print(ends.to_string())
for _, row in fit_table.iterrows(): key = row["analyte"].lower().replace("-", "_") for name in ["b", "c", "d", "e", "f", "rss"]: metrics[f"{name}_{key}"] = float(row[name]) analyte b c d e f rss IL-6 -0.5135 31.11 3.535e+04 341.8 2.74 0.072 IL-8 -1.131 31.52 2.645e+04 1366 0.8438 0.05032TNF-alpha -1.128 16.07 1.817e+04 844.8 0.959 0.06212 IL-10 -0.9399 39.7 1.491e+04 370.2 1.105 0.01832IFN-gamma -0.9502 37.79 1.978e+04 1714 1.051 0.04191 IL-1beta -1.107 18.71 1.787e+04 686 1.029 0.08776 c d true_c true_danalyteIL-6 31.1 35353.0 22 24000IL-8 31.5 26447.0 30 28000TNF-alpha 16.1 18166.0 18 19000IL-10 39.7 14911.0 25 16000IFN-gamma 37.8 19783.0 35 21000IL-1beta 18.7 17872.0 20 18500The fitted ends stray where the standards stop short of an asymptote. No IL-10 standard reaches the floor, and its bottom c comes out at 39.7 against a true 25. The top IL-6 standards sit where the curve flattens, and d lands at 35353 against a true 24000. On a surface that flat, drc’s default BFGS search stops early, so the R tab finishes with a Nelder-Mead pass, which moved IL-6 by up to 0.804%. After it, the gate finds every parameter equal across the two languages within a relative 1e-5.
Back-calculate the standards and set the limits
Section titled “Back-calculate the standards and set the limits”The back-calculation inverts the curve, and an MFI outside the interval from c to d has no inverse. Each standard’s recovery is its back-calculated concentration over the nominal one. ICH M10 accepts a standard of a ligand binding assay within 20% of nominal, or 25% at the LLOQ and the ULOQ, and moves a limit to the next acceptable standard when an end standard fails. M10 excludes biomarkers, but the FDA guidance on biomarker assays of April 2026 makes it the starting point for them, as Experimental design explains.
#' Turn an MFI into a concentration with a fitted five-parameter curve.#'#' @param mfi Median FI values.#' @param p Parameters from FitFivePl.#' @return Concentrations in pg/mL. NA where the MFI is outside the two#' asymptotes, where the curve has no inverse.BackCalculate <- function(mfi, p) { conc <- rep(NA_real_, length(mfi)) inside <- mfi > p[["c"]] & mfi < p[["d"]] ratio <- ((p[["d"]] - p[["c"]]) / (mfi[inside] - p[["c"]]))^(1 / p[["f"]]) conc[inside] <- p[["e"]] * (ratio - 1)^(1 / p[["b"]]) conc}
standards <- means |> filter(startsWith(Sample, "Std")) |> mutate(nominal = 10000 / dilution, back = NA_real_)for (analyte in analytes) { rows <- standards$Analyte == analyte standards$back[rows] <- BackCalculate(standards$mfi[rows], params[[analyte]])}standards <- mutate(standards, recovery = 100 * back / nominal)recovery_table <- standards |> select(Analyte, Sample, recovery) |> pivot_wider(names_from = Sample, values_from = recovery) |> arrange(match(Analyte, analytes))recovery_view <- as.data.frame(recovery_table)recovery_view[-1] <- round(recovery_view[-1], 1)print(recovery_view, row.names = FALSE)
# The lowest and the highest standard within 25% of nominal set the# limits. Standards between them should sit within 20%.limits <- standards |> group_by(Analyte) |> summarise( lloq = min(nominal[abs(recovery - 100) <= 25]), uloq = max(nominal[abs(recovery - 100) <= 25]), inner_over_20 = sum( nominal > lloq & nominal < uloq & abs(recovery - 100) > 20 ), .groups = "drop" ) |> arrange(match(Analyte, analytes))print(as.data.frame(mutate(limits, lloq = round(lloq, 4))), row.names = FALSE)
for (i in seq_len(nrow(limits))) { key <- gsub("-", "_", tolower(limits$Analyte[i])) metrics[[paste0("lloq_", key)]] <- limits$lloq[i] metrics[[paste0("uloq_", key)]] <- limits$uloq[i]} Analyte Std1 Std2 Std3 Std4 Std5 Std6 Std7 Std8 IL-6 88.1 114.9 99.5 97.8 97.6 107.3 89.5 116.8 IL-8 82.5 114.5 95.7 98.2 103.1 104.1 91.6 107.8 TNF-alpha 82.2 115.1 95.0 102.6 101.5 95.1 105.7 98.4 IL-10 122.2 99.9 95.4 103.8 98.9 97.0 102.5 98.3 IFN-gamma 98.3 102.5 98.5 101.3 98.8 103.4 94.8 106.4 IL-1beta 57.6 144.9 95.9 96.4 104.2 101.1 95.5 109.4 Analyte lloq uloq inner_over_20 IL-6 0.6104 10000 0 IL-8 0.6104 10000 0 TNF-alpha 0.6104 10000 0 IL-10 0.6104 10000 0 IFN-gamma 0.6104 10000 0 IL-1beta 0.6104 625 0def back_calculate(mfi, params): """Turn an MFI into a concentration with a fitted five-parameter curve.
Args: mfi: Median FI values. params: The parameters from fit_five_pl.
Returns: Concentrations in pg/mL. NaN where the MFI is outside the two asymptotes, where the curve has no inverse. """ b, c, d, e, f = params mfi = np.asarray(mfi, dtype=float) conc = np.full(mfi.shape, np.nan) inside = (mfi > c) & (mfi < d) ratio = ((d - c) / (mfi[inside] - c)) ** (1 / f) conc[inside] = e * (ratio - 1) ** (1 / b) return conc
def quantification_limits(group): """Find the LLOQ and the ULOQ from the standards of one analyte.
The lowest and the highest standard within 25% of nominal set the limits. Standards between them should sit within 20%.
Args: group: The standards of one analyte, with nominal and recovery.
Returns: A Series with lloq, uloq and inner_over_20. """ error = (group["recovery"] - 100).abs() passing = group.loc[error <= 25, "nominal"] lloq, uloq = passing.min(), passing.max() inner = (group["nominal"] > lloq) & (group["nominal"] < uloq) return pd.Series({"lloq": lloq, "uloq": uloq, "inner_over_20": int((inner & (error > 20)).sum())})
standards = means[means["Sample"].str.startswith("Std")].copy()standards["nominal"] = 10000 / standards["dilution"]standards["back"] = np.nanfor analyte in analytes: rows = standards["Analyte"] == analyte standards.loc[rows, "back"] = back_calculate( standards.loc[rows, "mfi"], params[analyte] )standards["recovery"] = 100 * standards["back"] / standards["nominal"]recovery_table = standards.pivot( index="Analyte", columns="Sample", values="recovery").reindex(analytes)print(recovery_table.round(1).to_string())
limits = pd.DataFrame( {analyte: quantification_limits(group) for analyte, group in standards.groupby("Analyte")}).T.reindex(analytes)limits["inner_over_20"] = limits["inner_over_20"].astype(int)print(limits.round({"lloq": 4}).to_string())
for analyte, row in limits.iterrows(): key = analyte.lower().replace("-", "_") metrics[f"lloq_{key}"] = float(row["lloq"]) metrics[f"uloq_{key}"] = float(row["uloq"])Sample Std1 Std2 Std3 Std4 Std5 Std6 Std7 Std8AnalyteIL-6 88.1 114.9 99.5 97.8 97.6 107.3 89.5 116.8IL-8 82.5 114.5 95.7 98.2 103.1 104.1 91.6 107.8TNF-alpha 82.2 115.1 95.0 102.6 101.5 95.1 105.7 98.4IL-10 122.2 99.9 95.4 103.8 98.9 97.0 102.5 98.3IFN-gamma 98.3 102.5 98.5 101.3 98.8 103.4 94.8 106.4IL-1beta 57.6 144.9 95.9 96.4 104.2 101.1 95.5 109.4 lloq uloq inner_over_20IL-6 0.6104 10000.0 0IL-8 0.6104 10000.0 0TNF-alpha 0.6104 10000.0 0IL-10 0.6104 10000.0 0IFN-gamma 0.6104 10000.0 0IL-1beta 0.6104 625.0 0Every curve recovers Std8 within 25%, so every LLOQ is 0.6104 pg/mL. The top is less tidy. IL-1beta misses with both top standards, 57.6% and 144.9%, so its ULOQ drops to Std3 at 625 pg/mL. Near the top of a curve, a few percent of noise in MFI moves the concentration by tens of percent. M10 would reject the two IL-1beta standards and refit, which this page skips, since no IL-1beta sample reads above 625 pg/mL.
Flag the samples outside the limits
Section titled “Flag the samples outside the limits”A sample is < LLOQ when its concentration falls below the LLOQ or its MFI sits at or below
c, and > ULOQ in the mirror case. A flagged value gets no number.
status_levels <- c("< LLOQ", "in range", "> ULOQ")samples <- means |> filter(startsWith(Sample, "Sample_")) |> left_join(limits, by = "Analyte") |> mutate(extrapolated = NA_real_, bottom = NA_real_, top = NA_real_)for (analyte in analytes) { rows <- samples$Analyte == analyte p <- params[[analyte]] samples$extrapolated[rows] <- BackCalculate(samples$mfi[rows], p) samples$bottom[rows] <- p[["c"]] samples$top[rows] <- p[["d"]]}# A value outside the limits is reported as a flag, never as a number.samples <- samples |> mutate( status = case_when( mfi <= bottom | extrapolated < lloq ~ "< LLOQ", mfi >= top | extrapolated > uloq ~ "> ULOQ", TRUE ~ "in range" ), status = factor(status, levels = status_levels), conc = if_else(status == "in range", extrapolated, NA_real_) ) |> left_join( select(truth, Sample = sample, Analyte = analyte, group, true = true_concentration_pg_ml, position = position_vs_standards), by = c("Sample", "Analyte") )status_table <- samples |> count(Analyte, status, .drop = FALSE) |> pivot_wider(names_from = status, values_from = n) |> arrange(match(Analyte, analytes))print(as.data.frame(status_table), row.names = FALSE)cat("true position against the flag, all analytes:\n")print(table(samples$position, samples$status))
for (i in seq_len(nrow(status_table))) { key <- gsub("-", "_", tolower(status_table$Analyte[i])) metrics[[paste0("below_", key)]] <- status_table$`< LLOQ`[i] metrics[[paste0("in_range_", key)]] <- status_table$`in range`[i] metrics[[paste0("above_", key)]] <- status_table$`> ULOQ`[i]} Analyte < LLOQ in range > ULOQ IL-6 0 32 0 IL-8 0 31 1 TNF-alpha 0 32 0 IL-10 3 29 0 IFN-gamma 0 32 0 IL-1beta 2 30 0true position against the flag, all analytes:
< LLOQ in range > ULOQ above_top 0 2 1 below_bottom 4 1 0 within 1 183 0STATUS_LEVELS = ["< LLOQ", "in range", "> ULOQ"]samples = means[means["Sample"].str.startswith("Sample_")].merge( limits, left_on="Analyte", right_index=True)samples["extrapolated"] = np.nansamples["bottom"] = np.nansamples["top"] = np.nanfor analyte in analytes: rows = samples["Analyte"] == analyte b, c, d, e, f = params[analyte] samples.loc[rows, "extrapolated"] = back_calculate( samples.loc[rows, "mfi"], params[analyte] ) samples.loc[rows, "bottom"] = c samples.loc[rows, "top"] = d# A value outside the limits is reported as a flag, never as a number.below = (samples["mfi"] <= samples["bottom"]) | ( samples["extrapolated"] < samples["lloq"])above = (samples["mfi"] >= samples["top"]) | ( samples["extrapolated"] > samples["uloq"])samples["status"] = np.select([below, above], ["< LLOQ", "> ULOQ"], default="in range")samples["status"] = pd.Categorical(samples["status"], categories=STATUS_LEVELS)samples["conc"] = samples["extrapolated"].where( samples["status"] == "in range")samples = samples.merge( truth.rename(columns={ "sample": "Sample", "analyte": "Analyte", "true_concentration_pg_ml": "true", "position_vs_standards": "position", })[["Sample", "Analyte", "group", "true", "position"]], on=["Sample", "Analyte"],)status_table = pd.crosstab(samples["Analyte"], samples["status"], dropna=False).reindex(analytes)print(status_table.to_string())print("true position against the flag, all analytes:")print(pd.crosstab(samples["position"], samples["status"], dropna=False).to_string())
for analyte, row in status_table.iterrows(): key = analyte.lower().replace("-", "_") metrics[f"below_{key}"] = int(row["< LLOQ"]) metrics[f"in_range_{key}"] = int(row["in range"]) metrics[f"above_{key}"] = int(row["> ULOQ"])status < LLOQ in range > ULOQAnalyteIL-6 0 32 0IL-8 0 31 1TNF-alpha 0 32 0IL-10 3 29 0IFN-gamma 0 32 0IL-1beta 2 30 0true position against the flag, all analytes:status < LLOQ in range > ULOQpositionabove_top 0 2 1below_bottom 4 1 0within 1 183 0Six values carry a flag. Against the truth, 183 values from within the standards read in range and one reads below the LLOQ. The flags catch four of the five values below the bottom standard, and one of the three above the top.
Compare with the truth
Section titled “Compare with the truth”The truth is known, so the errors of the in-range values measure the curve, and the flagged values show what extrapolation would have reported.
in_range <- samples |> filter(status == "in range") |> mutate(error = 100 * (conc / true - 1)) |> group_by(Analyte) |> summarise( n = n(), median_abs_error = median(abs(error)), max_abs_error = max(abs(error)), .groups = "drop" ) |> arrange(match(Analyte, analytes))in_range_view <- as.data.frame(in_range)errors <- c("median_abs_error", "max_abs_error")in_range_view[errors] <- round(in_range_view[errors], 2)print(in_range_view, row.names = FALSE)
# What extrapolation would have reported for the flagged values, and the# samples whose true value lies outside the standards.outside <- samples |> filter(status != "in range" | position != "within") |> select(Sample, Analyte, group, position, status, mfi, extrapolated, true) |> arrange(match(Analyte, analytes), Sample) |> mutate( mfi = round(mfi, 2), extrapolated = round(extrapolated, 2), true = round(true, 2) )print(as.data.frame(outside), row.names = FALSE)
for (i in seq_len(nrow(in_range))) { key <- gsub("-", "_", tolower(in_range$Analyte[i])) metrics[[paste0("median_abs_error_", key)]] <- in_range$median_abs_error[i]} Analyte n median_abs_error max_abs_error IL-6 32 9.63 66.92 IL-8 31 5.21 23.40 TNF-alpha 32 2.61 12.33 IL-10 29 8.82 29.12 IFN-gamma 32 7.30 22.85 IL-1beta 30 9.34 141.05 Sample Analyte group position status mfi extrapolated true Sample_09 IL-6 Patient above_top in range 21913.50 8591.22 15000.00 Sample_23 IL-6 Patient above_top in range 22615.10 9924.98 30000.00 Sample_24 IL-8 Control above_top > ULOQ 26119.90 56331.17 18000.00 Sample_18 IL-10 Patient below_bottom < LLOQ 38.45 NA 0.30 Sample_20 IL-10 Control below_bottom < LLOQ 31.35 NA 0.15 Sample_27 IL-10 Patient below_bottom < LLOQ 31.35 NA 0.20 Sample_02 IL-1beta Patient within < LLOQ 21.50 0.31 1.08 Sample_03 IL-1beta Control below_bottom in range 28.80 0.96 0.40 Sample_27 IL-1beta Patient below_bottom < LLOQ 22.80 0.44 0.25inside = samples[samples["status"] == "in range"].copy()inside["abs_error"] = (100 * (inside["conc"] / inside["true"] - 1)).abs()in_range = inside.groupby("Analyte").agg( n=("abs_error", "size"), median_abs_error=("abs_error", "median"), max_abs_error=("abs_error", "max"),).reindex(analytes)print(in_range.round(2).to_string())
# What extrapolation would have reported for the flagged values, and the# samples whose true value lies outside the standards.outside = samples[(samples["status"] != "in range") | (samples["position"] != "within")]outside = outside.assign( order=outside["Analyte"].map(analytes.index)).sort_values(["order", "Sample"])columns = ["Sample", "Analyte", "group", "position", "status", "mfi", "extrapolated", "true"]print(outside[columns].round({"mfi": 2, "extrapolated": 2, "true": 2}) .to_string(index=False))
for analyte, row in in_range.iterrows(): key = analyte.lower().replace("-", "_") metrics[f"median_abs_error_{key}"] = float(row["median_abs_error"]) n median_abs_error max_abs_errorAnalyteIL-6 32 9.63 66.92IL-8 31 5.21 23.40TNF-alpha 32 2.61 12.33IL-10 29 8.82 29.12IFN-gamma 32 7.30 22.85IL-1beta 30 9.34 141.05 Sample Analyte group position status mfi extrapolated trueSample_09 IL-6 Patient above_top in range 21913.50 8591.22 15000.00Sample_23 IL-6 Patient above_top in range 22615.10 9924.98 30000.00Sample_24 IL-8 Control above_top > ULOQ 26119.90 56331.15 18000.00Sample_18 IL-10 Patient below_bottom < LLOQ 38.45 NaN 0.30Sample_20 IL-10 Control below_bottom < LLOQ 31.35 NaN 0.15Sample_27 IL-10 Patient below_bottom < LLOQ 31.35 NaN 0.20Sample_02 IL-1beta Patient within < LLOQ 21.50 0.31 1.08Sample_03 IL-1beta Control below_bottom in range 28.80 0.96 0.40Sample_27 IL-1beta Patient below_bottom < LLOQ 22.80 0.44 0.25The median error of the in-range values runs from 2.61% for TNF-alpha to 9.63% for IL-6, and the worst errors sit at the ends. Sample_23, true 30,000 pg/mL, reads in range for IL-6 at 9924.98, and Sample_09, true 15,000, at 8591.22. On the flat top their MFI looks like that of a sample just under 10,000 pg/mL, so no flag fires. The flagged IL-8 sample would have been extrapolated to 56,331 pg/mL, more than three times its true 18,000, and the three IL-10 samples below the fitted c of 39.7 have no value to extrapolate at all. At the IL-1beta LLOQ, noise pushes values both ways: Sample_02, true 1.08 pg/mL, reads 0.31 and is flagged, while Sample_03, true 0.40, reads 0.96 and passes.
Plot the curves
Section titled “Plot the curves”Each panel draws the fitted curve, the true curve dashed, the standards, and every sample at its true concentration and measured MFI.
grid <- 10^seq(-1.5, 4.7, length.out = 200)lines <- bind_rows(lapply(analytes, function(analyte) { true_p <- filter(curves, analyte == .env$analyte) # The generator writes its 5PL as d + (a - d) / (1 + (x / c)^b)^g. true_mfi <- true_p$d + (true_p$a - true_p$d) / (1 + (grid / true_p$c)^true_p$b)^true_p$g bind_rows( data.frame(Analyte = analyte, conc = grid, mfi = FivePl(grid, params[[analyte]]), curve = "fitted 5PL"), data.frame(Analyte = analyte, conc = grid, mfi = true_mfi, curve = "true curve") )}))lines$Analyte <- factor(lines$Analyte, levels = analytes)band <- mutate(limits, Analyte = factor(Analyte, levels = analytes))points <- bind_rows( transmute(standards, Analyte, conc = nominal, mfi, kind = "standard"), transmute( samples, Analyte, conc = true, mfi, kind = if_else(status == "in range", "sample in range", "sample flagged") )) |> mutate(Analyte = factor(Analyte, levels = analytes))
curve_plot <- ggplot() + geom_rect( data = band, aes(xmin = lloq, xmax = uloq, ymin = 1, ymax = 1e6), fill = "#f0efec" ) + geom_line(data = lines, aes(conc, mfi, linetype = curve), colour = "#52514e", linewidth = 0.6) + geom_point(data = points, aes(conc, mfi, colour = kind), size = 1.8) + scale_colour_manual( values = c( standard = "#0b0b0b", `sample in range` = "#2a78d6", `sample flagged` = "#eb6834" ), breaks = c("standard", "sample in range", "sample flagged") ) + scale_linetype_manual(values = c(`fitted 5PL` = "solid", `true curve` = "dashed")) + scale_x_log10(labels = scales::label_comma()) + scale_y_log10(labels = scales::label_comma()) + facet_wrap(~Analyte, ncol = 3) + # The band runs past the panel, and the panel shows 12 to 40,000. coord_cartesian(ylim = c(12, 40000)) + labs( x = "Concentration, pg/mL (samples at their true value)", y = "Median FI", colour = NULL, linetype = NULL, title = "Gray band: LLOQ to ULOQ" ) + # Fix the legend order. With both titles set to NULL, ggplot2 can put the # two legends in either order from one R session to the next. guides( linetype = guide_legend(order = 1), colour = guide_legend(order = 2) ) + theme_minimal(base_size = 10) + theme(panel.grid.minor = element_blank(), legend.position = "bottom")dir.create("outputs", showWarnings = FALSE)ggsave( "outputs/luminex-curves-censoring_fits_r.png", curve_plot, width = 9, height = 5.6, dpi = 120, bg = "white")
grid = 10 ** np.linspace(-1.5, 4.7, 200)colors = {"standard": "#0b0b0b", "sample in range": "#2a78d6", "sample flagged": "#eb6834"}
figure, axes = plt.subplots(2, 3, figsize=(9, 5.6), sharex=True, layout="constrained")for ax, analyte in zip(axes.flat, analytes): true_p = curves.loc[analyte] # The generator writes its 5PL as d + (a - d) / (1 + (x / c)^b)^g. true_mfi = true_p["d"] + (true_p["a"] - true_p["d"]) / ( 1 + (grid / true_p["c"]) ** true_p["b"] ) ** true_p["g"] limit = limits.loc[analyte] ax.axvspan(limit["lloq"], limit["uloq"], color="#f0efec", lw=0) ax.plot(grid, five_pl(grid, params[analyte]), color="#52514e", lw=1) ax.plot(grid, true_mfi, color="#52514e", lw=1, ls="--") std = standards[standards["Analyte"] == analyte] ax.scatter(std["nominal"], std["mfi"], s=14, color=colors["standard"]) smp = samples[samples["Analyte"] == analyte] flagged = smp["status"] != "in range" ax.scatter(smp.loc[~flagged, "true"], smp.loc[~flagged, "mfi"], s=14, color=colors["sample in range"]) ax.scatter(smp.loc[flagged, "true"], smp.loc[flagged, "mfi"], s=14, color=colors["sample flagged"]) ax.set_xscale("log") ax.set_yscale("log") ax.set_title(analyte, fontsize=10) ax.spines[["top", "right"]].set_visible(False)handles = [Line2D([], [], color="#52514e", label="fitted 5PL"), Line2D([], [], color="#52514e", ls="--", label="true curve")]handles += [Line2D([], [], color=color, marker="o", ls="", label=label) for label, color in colors.items()]figure.legend(handles=handles, loc="outside lower center", ncol=5, frameon=False)axes[1, 1].set_xlabel("Concentration, pg/mL (samples at their true value)")for ax in axes[:, 0]: ax.set_ylabel("Median FI")figure.suptitle("Gray band: LLOQ to ULOQ", x=0.02, ha="left")pathlib.Path("outputs").mkdir(exist_ok=True)figure.savefig("outputs/luminex-curves-censoring_fits_python.png", dpi=120)
The fitted and true curves overlap inside the band and part outside it, which is where any extrapolated value would come from.
Control against Patient, four ways to fill the gaps
Section titled “Control against Patient, four ways to fill the gaps”The code compares the groups with a Welch t-test on log10 concentrations under five rules: the true values, dropping flagged values, and replacing a value below the LLOQ with LLOQ/2, LLOQ/sqrt(2) or the LLOQ. A value above the ULOQ takes the ULOQ under the three replacement rules. The ratio is the Patient geometric mean over the Control one.
rules <- c("truth", "drop", "LLOQ/2", "LLOQ/sqrt(2)", "LLOQ")divisors <- c(`LLOQ/2` = 2, `LLOQ/sqrt(2)` = sqrt(2), LLOQ = 1)
#' Fill the censored values of one analyte under one rule.#'#' @param rows The samples of one analyte, with status, conc, true, lloq#' and uloq.#' @param rule One of the rules: truth, drop, LLOQ/2, LLOQ/sqrt(2), LLOQ.#' @return Concentrations, NA where the rule drops the value. Values#' above the ULOQ take the ULOQ under every substitution rule.FillCensored <- function(rows, rule) { if (rule == "truth") { return(rows$true) } value <- rows$conc if (rule == "drop") { return(value) } value[rows$status == "> ULOQ"] <- rows$uloq[1] value[rows$status == "< LLOQ"] <- rows$lloq[1] / divisors[[rule]] value}
tests <- list()for (analyte in analytes) { rows <- filter(samples, Analyte == analyte) for (rule in rules) { value <- FillCensored(rows, rule) keep <- !is.na(value) patient <- log10(value[keep & rows$group == "Patient"]) control <- log10(value[keep & rows$group == "Control"]) welch <- t.test(patient, control) tests[[length(tests) + 1]] <- data.frame( Analyte = analyte, rule = rule, censored = sum(rows$status != "in range"), ratio = 10^(mean(patient) - mean(control)), p = welch$p.value ) }}tests <- bind_rows(tests)p_table <- tests |> select(Analyte, censored, rule, p) |> pivot_wider(names_from = rule, values_from = p)print(as.data.frame(p_table), row.names = FALSE, digits = 3)ratio_table <- tests |> filter(censored > 0) |> select(Analyte, rule, ratio) |> pivot_wider(names_from = rule, values_from = ratio)ratio_view <- as.data.frame(ratio_table)ratio_view[-1] <- round(ratio_view[-1], 3)print(ratio_view, row.names = FALSE)
for (i in seq_len(nrow(tests))) { key <- paste0( gsub("-", "_", tolower(tests$Analyte[i])), "_", gsub("[^a-z0-9]+", "_", tolower(tests$rule[i])) ) metrics[[paste0("welch_p_", key)]] <- tests$p[i]} Analyte censored truth drop LLOQ/2 LLOQ/sqrt(2) LLOQ IL-6 0 1.34e-04 8.81e-05 8.81e-05 8.81e-05 8.81e-05 IL-8 1 5.17e-01 5.67e-01 5.86e-01 5.86e-01 5.86e-01 TNF-alpha 0 2.20e-06 2.40e-06 2.40e-06 2.40e-06 2.40e-06 IL-10 3 4.72e-01 6.27e-01 4.48e-01 4.51e-01 4.56e-01 IFN-gamma 0 1.47e-01 1.33e-01 1.33e-01 1.33e-01 1.33e-01 IL-1beta 2 8.91e-01 5.16e-01 5.81e-01 6.55e-01 7.47e-01 Analyte truth drop LLOQ/2 LLOQ/sqrt(2) LLOQ IL-8 0.713 1.159 0.765 0.765 0.765 IL-10 0.691 0.834 0.694 0.709 0.725 IL-1beta 0.957 1.168 0.838 0.875 0.913RULES = ["truth", "drop", "LLOQ/2", "LLOQ/sqrt(2)", "LLOQ"]DIVISORS = {"LLOQ/2": 2, "LLOQ/sqrt(2)": np.sqrt(2), "LLOQ": 1}
def fill_censored(rows, rule): """Fill the censored values of one analyte under one rule.
Args: rows: The samples of one analyte, with status, conc, true, lloq and uloq. rule: One of RULES.
Returns: Concentrations as an array, NaN where the rule drops the value. Values above the ULOQ take the ULOQ under every substitution rule. """ if rule == "truth": return rows["true"].to_numpy() value = rows["conc"].to_numpy().copy() if rule == "drop": return value status = rows["status"].to_numpy() value[status == "> ULOQ"] = rows["uloq"].iloc[0] value[status == "< LLOQ"] = rows["lloq"].iloc[0] / DIVISORS[rule] return value
tests = []for analyte in analytes: rows = samples[samples["Analyte"] == analyte] is_patient = (rows["group"] == "Patient").to_numpy() for rule in RULES: value = fill_censored(rows, rule) keep = ~np.isnan(value) patient = np.log10(value[keep & is_patient]) control = np.log10(value[keep & ~is_patient]) welch = stats.ttest_ind(patient, control, equal_var=False) tests.append({ "Analyte": analyte, "rule": rule, "censored": int((rows["status"] != "in range").sum()), "ratio": 10 ** (patient.mean() - control.mean()), "p": float(welch.pvalue), })tests = pd.DataFrame(tests)p_table = tests.pivot(index=["Analyte", "censored"], columns="rule", values="p")[RULES].reindex(analytes, level=0)print(p_table.to_string(float_format="{:.3g}".format))ratio_table = tests[tests["censored"] > 0].pivot( index="Analyte", columns="rule", values="ratio")[RULES]ratio_table = ratio_table.reindex( [a for a in analytes if a in ratio_table.index])print(ratio_table.round(3).to_string())
for _, row in tests.iterrows(): rule_key = re.sub("[^a-z0-9]+", "_", row["rule"].lower()) key = f"{row['Analyte'].lower().replace('-', '_')}_{rule_key}" metrics[f"welch_p_{key}"] = row["p"]rule truth drop LLOQ/2 LLOQ/sqrt(2) LLOQAnalyte censoredIL-6 0 0.000134 8.81e-05 8.81e-05 8.81e-05 8.81e-05IL-8 1 0.517 0.567 0.586 0.586 0.586TNF-alpha 0 2.2e-06 2.4e-06 2.4e-06 2.4e-06 2.4e-06IL-10 3 0.472 0.627 0.448 0.451 0.456IFN-gamma 0 0.147 0.133 0.133 0.133 0.133IL-1beta 2 0.891 0.516 0.581 0.655 0.747rule truth drop LLOQ/2 LLOQ/sqrt(2) LLOQAnalyteIL-8 0.713 1.159 0.765 0.765 0.765IL-10 0.691 0.834 0.694 0.709 0.725IL-1beta 0.957 1.168 0.838 0.875 0.913IL-6 and TNF-alpha differ by design and carry no flags, so the rules agree. The other four share one median across the groups, and no rule finds a difference, but the rules move the estimate. Dropping the one flagged IL-8 value, a high Control sample, turns the true ratio of 0.713 into 1.159. For IL-1beta the ratio goes from 0.957 in the truth to 1.168 after dropping and to between 0.838 and 0.913 under the replacements, while p runs from 0.516 to 0.747. Dropping does the most damage, because censoring removes one end of a group, never values at random.
Real data with the censoring already done
Section titled “Real data with the censoring already done”Neyton et al. 2024 deposited plasma cytokine concentrations of patients with severe COVID-19, with and without dexamethasone, on Zenodo under CC0. Their README says the multiplex analytes were read on a MAGPIX and analyzed in xPONENT, while some analytes were measured by singleplex ELISA instead. It says values outside the limit of detection were replaced with a third of the lower limit of the standard curve for Luminex and half of it for ELISA, without naming the ELISA analytes, and that the groups were compared with Wilcoxon rank-sum tests at a BH-adjusted p below 0.1. No curve or limit can be recovered from the table.
Read the dexamethasone table
Section titled “Read the dexamethasone table”The code reads the untreated patients from the README, counts missing values and zeros by group, and checks whether the smallest positive value of an analyte repeats, as a constant floor would make it.
dex_dir <- "/opt/data/dex_cytokine"dex <- read_tsv(file.path(dex_dir, "dex_cytokine.tsv"), show_col_types = FALSE)# The README names the patients who did not receive dexamethasone.readme <- readLines(file.path(dex_dir, "README.md"))no_dex_line <- grep("did not receive dexamethasone:", readme, value = TRUE)no_dex <- regmatches(no_dex_line, gregexpr("MVIR1-HS[0-9]+", no_dex_line))[[1]]cat(sprintf( "patients: %d, analytes: %d, without dexamethasone: %d, found: %d\n", nrow(dex), ncol(dex) - 1, length(no_dex), sum(dex$`Patient id` %in% no_dex)))long <- dex |> pivot_longer(-`Patient id`, names_to = "analyte", values_to = "conc") |> mutate(group = if_else(`Patient id` %in% no_dex, "no dex", "dex"))
census <- long |> group_by(analyte) |> summarise( na_dex = sum(is.na(conc) & group == "dex"), na_no_dex = sum(is.na(conc) & group == "no dex"), zero_dex = sum(conc == 0 & group == "dex", na.rm = TRUE), zero_no_dex = sum(conc == 0 & group == "no dex", na.rm = TRUE), smallest = min(conc[conc > 0], na.rm = TRUE), at_smallest = sum(conc == smallest, na.rm = TRUE), .groups = "drop" )censored <- filter(census, na_dex + na_no_dex + zero_dex + zero_no_dex > 0)print(as.data.frame(censored), row.names = FALSE, digits = 4)cat(sprintf( "analytes whose smallest positive value repeats: %d of %d\n", sum(census$at_smallest > 1), nrow(census)))cat(sprintf( "cells that log2 turns into -Inf: %d\n", sum(is.infinite(log2(long$conc)), na.rm = TRUE)))
metrics$dex_na <- sum(is.na(long$conc))metrics$dex_zeros <- sum(long$conc == 0, na.rm = TRUE)metrics$dex_smallest_repeats <- sum(census$at_smallest > 1)patients: 38, analytes: 18, without dexamethasone: 15, found: 15 analyte na_dex na_no_dex zero_dex zero_no_dex smallest at_smallest IFN-gamma 9 0 12 0 0.6759 1 PAI-1 1 0 2 2 1.1940 1 Protein C 0 0 1 0 40.5221 1analytes whose smallest positive value repeats: 0 of 18cells that log2 turns into -Inf: 17DEX_DIR = pathlib.Path("/opt/data/dex_cytokine")dex = pd.read_csv(DEX_DIR / "dex_cytokine.tsv", sep="\t")# The README names the patients who did not receive dexamethasone.readme = (DEX_DIR / "README.md").read_text()no_dex_line = next(line for line in readme.splitlines() if "did not receive dexamethasone:" in line)no_dex = re.findall(r"MVIR1-HS[0-9]+", no_dex_line)found = int(dex["Patient id"].isin(no_dex).sum())print( f"patients: {len(dex)}, analytes: {dex.shape[1] - 1}, " f"without dexamethasone: {len(no_dex)}, found: {found}")long = dex.melt(id_vars="Patient id", var_name="analyte", value_name="conc")long["group"] = np.where(long["Patient id"].isin(no_dex), "no dex", "dex")
def census_row(group): """Count the missing, zero and smallest values of one analyte.
Args: group: The rows of one analyte, with conc and group.
Returns: A Series of counts and the smallest positive value. """ is_dex = group["group"] == "dex" missing = group["conc"].isna() zero = group["conc"] == 0 smallest = group.loc[group["conc"] > 0, "conc"].min() return pd.Series({ "na_dex": int((missing & is_dex).sum()), "na_no_dex": int((missing & ~is_dex).sum()), "zero_dex": int((zero & is_dex).sum()), "zero_no_dex": int((zero & ~is_dex).sum()), "smallest": smallest, "at_smallest": int((group["conc"] == smallest).sum()), })
census = pd.DataFrame( {name: census_row(group) for name, group in long.groupby("analyte")}).Tflagged = census[census[["na_dex", "na_no_dex", "zero_dex", "zero_no_dex"]].sum(axis=1) > 0]print(flagged.to_string(float_format="{:.4g}".format))repeats = int((census["at_smallest"] > 1).sum())print( "analytes whose smallest positive value repeats: " f"{repeats} of {len(census)}")with np.errstate(divide="ignore"): minus_inf = int(np.isneginf(np.log2(long["conc"])).sum())print(f"cells that log2 turns into -Inf: {minus_inf}")
metrics["dex_na"] = int(long["conc"].isna().sum())metrics["dex_zeros"] = int((long["conc"] == 0).sum())metrics["dex_smallest_repeats"] = repeatspatients: 38, analytes: 18, without dexamethasone: 15, found: 15 na_dex na_no_dex zero_dex zero_no_dex smallest at_smallestIFN-gamma 9 0 12 0 0.6759 1PAI-1 1 0 2 2 1.194 1Protein C 0 0 1 0 40.52 1analytes whose smallest positive value repeats: 0 of 18cells that log2 turns into -Inf: 17All 15 README IDs are among the 38 patients. No smallest positive value repeats, though a floor that changed between plates would not repeat either. The table holds 17 exact zeros instead, 12 in IFN-gamma, 4 in PAI-1 and 1 in Protein C. All 12 IFN-gamma zeros and all 9 of its missing values, which the README calls measurements not done, fall in the dexamethasone group. The README’s PCA drops IFN-gamma for its missing values and log2-transforms the rest, which turns the five PAI-1 and Protein C zeros into minus infinity, and it does not say how it handled them.
Wilcoxon tests with BH adjustment
Section titled “Wilcoxon tests with BH adjustment”Ties need a decision. Since R 4.6.0, wilcox.test() computes an exact conditional p value
with ties, as the R NEWS
records, while older R and SciPy use the normal approximation with a continuity correction.
Both tabs use the older rule so that the languages agree, and the R tab prints the 4.6
default as p_r46.
wilcox_rows <- list()for (name in unique(long$analyte)) { rows <- filter(long, analyte == name, !is.na(conc)) treated <- rows$conc[rows$group == "dex"] untreated <- rows$conc[rows$group == "no dex"] # Exact without ties, and the normal approximation with a continuity # correction when values tie, as R did before 4.6.0 and as SciPy does. tied <- anyDuplicated(c(treated, untreated)) > 0 test <- wilcox.test(treated, untreated, exact = !tied) # Since R 4.6.0 the default is an exact conditional test with ties. r46 <- wilcox.test(treated, untreated) wilcox_rows[[name]] <- data.frame( analyte = name, n_dex = length(treated), n_no_dex = length(untreated), median_dex = median(treated), median_no_dex = median(untreated), W = unname(test$statistic), p = test$p.value, method = if (tied) "normal" else "exact", p_r46 = r46$p.value )}wilcox_table <- bind_rows(wilcox_rows) |> mutate( q = p.adjust(p, method = "BH"), q_r46 = p.adjust(p_r46, method = "BH") ) |> arrange(p)print(wilcox_table, row.names = FALSE, digits = 3)cat(sprintf( "analytes with BH q below 0.1: %d of %d, with the R 4.6 default: %d\n", sum(wilcox_table$q < 0.1), nrow(wilcox_table), sum(wilcox_table$q_r46 < 0.1)))
for (i in seq_len(nrow(wilcox_table))) { key <- gsub("[^a-z0-9]+", "_", tolower(wilcox_table$analyte[i])) metrics[[paste0("wilcox_w_", key)]] <- wilcox_table$W[i] metrics[[paste0("wilcox_p_", key)]] <- wilcox_table$p[i] metrics[[paste0("wilcox_q_", key)]] <- wilcox_table$q[i]}metrics$wilcox_q_below_0_1 <- sum(wilcox_table$q < 0.1) analyte n_dex n_no_dex median_dex median_no_dex W p method p_r46 q q_r46 IL-6 23 15 1.23e+01 2.29e+02 29 1.95e-05 normal 2.78e-06 0.000351 0.00005 IFN-gamma 14 15 0.00e+00 8.95e+00 29 6.21e-04 normal 2.84e-04 0.005590 0.00256 IL-10 23 15 1.24e+01 5.99e+00 272 3.11e-03 normal 2.29e-03 0.018657 0.01375 RAGE 23 15 7.30e+03 4.31e+03 231 8.33e-02 exact 8.33e-02 0.374627 0.37463 TNF R1 23 15 3.68e+03 2.82e+03 218 1.81e-01 exact 1.81e-01 0.567685 0.56795 IL-18 23 15 4.51e+02 6.20e+02 130 2.10e-01 normal 2.10e-01 0.567685 0.56795 IL-8 23 15 1.04e+01 1.80e+01 131 2.21e-01 normal 2.21e-01 0.567685 0.56795 ICAM-1 23 15 6.53e+05 5.47e+05 205 3.44e-01 exact 3.44e-01 0.639913 0.63991 VEGF 23 15 2.90e+01 3.50e+01 141 3.55e-01 normal 3.55e-01 0.639913 0.63991 SP-D 23 15 1.81e+04 2.47e+04 142 3.75e-01 exact 3.75e-01 0.639913 0.63991 Ang-2 23 15 4.81e+03 4.88e+03 143 3.91e-01 exact 3.91e-01 0.639913 0.63991 MMP-8 23 15 4.02e+03 8.16e+03 147 4.60e-01 exact 4.60e-01 0.690040 0.69004 Thrombomodulin 23 15 6.33e+03 7.95e+03 153 5.75e-01 exact 5.75e-01 0.740289 0.74029 Ang-1 23 15 6.28e+03 6.51e+03 191 5.95e-01 exact 5.95e-01 0.740289 0.74029 IP-10 23 15 6.62e+02 8.51e+02 157 6.58e-01 exact 6.58e-01 0.740289 0.74029 Protein C 23 15 8.56e+01 8.61e+01 188 6.58e-01 exact 6.58e-01 0.740289 0.74029 PAI-1 22 15 9.19e+00 1.03e+01 175 7.69e-01 normal 7.66e-01 0.813937 0.81096 TREM-1 23 15 3.79e+02 3.83e+02 173 1.00e+00 exact 1.00e+00 1.000000 1.00000analytes with BH q below 0.1: 3 of 18, with the R 4.6 default: 3def wilcoxon_row(name, rows): """Run the two-sided Wilcoxon rank-sum test on one analyte.
The test is exact without ties and uses the normal approximation with a continuity correction when values tie, as R's wilcox.test.
Args: name: The analyte. rows: The rows of the analyte, without missing values.
Returns: A dict with the group sizes and medians, W, p and the method. """ treated = rows.loc[rows["group"] == "dex", "conc"].to_numpy() untreated = rows.loc[rows["group"] == "no dex", "conc"].to_numpy() values = np.concatenate([treated, untreated]) tied = len(np.unique(values)) < len(values) method = "asymptotic" if tied else "exact" test = stats.mannwhitneyu(treated, untreated, alternative="two-sided", method=method, use_continuity=True) return { "analyte": name, "n_dex": len(treated), "n_no_dex": len(untreated), "median_dex": np.median(treated), "median_no_dex": np.median(untreated), "W": test.statistic, "p": test.pvalue, "method": "normal" if tied else "exact", }
measured = long.dropna(subset=["conc"])wilcox_table = pd.DataFrame( [wilcoxon_row(name, rows) for name, rows in measured.groupby("analyte")])wilcox_table["q"] = stats.false_discovery_control(wilcox_table["p"])wilcox_table = wilcox_table.sort_values("p", kind="stable")print(wilcox_table.to_string(index=False, float_format="{:.3g}".format))q_below = int((wilcox_table["q"] < 0.1).sum())print(f"analytes with BH q below 0.1: {q_below} of {len(wilcox_table)}")
for _, row in wilcox_table.iterrows(): key = re.sub("[^a-z0-9]+", "_", row["analyte"].lower()) metrics[f"wilcox_w_{key}"] = float(row["W"]) metrics[f"wilcox_p_{key}"] = float(row["p"]) metrics[f"wilcox_q_{key}"] = float(row["q"])metrics["wilcox_q_below_0_1"] = q_below analyte n_dex n_no_dex median_dex median_no_dex W p method q IL-6 23 15 12.3 229 29 1.95e-05 normal 0.000351 IFN-gamma 14 15 0 8.95 29 0.000621 normal 0.00559 IL-10 23 15 12.4 5.99 272 0.00311 normal 0.0187 RAGE 23 15 7.3e+03 4.31e+03 231 0.0833 exact 0.375 TNF R1 23 15 3.68e+03 2.82e+03 218 0.181 exact 0.568 IL-18 23 15 451 620 130 0.21 normal 0.568 IL-8 23 15 10.4 18 131 0.221 normal 0.568 ICAM-1 23 15 6.53e+05 5.47e+05 205 0.344 exact 0.64 VEGF 23 15 29 35 141 0.355 normal 0.64 SP-D 23 15 1.81e+04 2.47e+04 142 0.375 exact 0.64 Ang-2 23 15 4.81e+03 4.88e+03 143 0.391 exact 0.64 MMP-8 23 15 4.02e+03 8.16e+03 147 0.46 exact 0.69Thrombomodulin 23 15 6.33e+03 7.95e+03 153 0.575 exact 0.74 Ang-1 23 15 6.28e+03 6.51e+03 191 0.595 exact 0.74 IP-10 23 15 662 851 157 0.658 exact 0.74 Protein C 23 15 85.6 86.1 188 0.658 exact 0.74 PAI-1 22 15 9.19 10.3 175 0.769 normal 0.814 TREM-1 23 15 379 383 173 1 exact 1analytes with BH q below 0.1: 3 of 18Three analytes pass a q below 0.1. IL-6 is lower with dexamethasone, a median of 12.3 pg/mL against 229, IFN-gamma is lower too, and IL-10 is higher, 12.4 against 5.99. The R 4.6 default gives smaller p values for tied analytes, 2.78e-06 instead of 1.95e-05 for IL-6, and passes the same three. The IFN-gamma dexamethasone median is 0, since 12 of the 14 measured values in that group are zeros.
What the zeros do to the test
Section titled “What the zeros do to the test”Any value below the smallest measured one gives the zeros the same ranks. The code replaces each zero with half the smallest positive value and tests again.
# Any value below the smallest measured one gives the zeros the same# ranks, so W and p cannot move. Half the smallest value is one choice.changes <- list()for (name in c("IFN-gamma", "PAI-1", "Protein C")) { rows <- filter(long, analyte == name, !is.na(conc)) filled <- if_else(rows$conc == 0, min(rows$conc[rows$conc > 0]) / 2, rows$conc) test <- wilcox.test( filled[rows$group == "dex"], filled[rows$group == "no dex"], exact = anyDuplicated(filled) == 0 ) before <- filter(wilcox_table, analyte == name) changes[[name]] <- data.frame( analyte = name, zeros = sum(rows$conc == 0), W_change = unname(test$statistic) - before$W, p_change = test$p.value - before$p )}print(bind_rows(changes), row.names = FALSE) analyte zeros W_change p_change IFN-gamma 12 0 0 PAI-1 4 0 0 Protein C 1 0 0# Any value below the smallest measured one gives the zeros the same# ranks, so W and p cannot move. Half the smallest value is one choice.changes = []for name in ["IFN-gamma", "PAI-1", "Protein C"]: rows = measured[measured["analyte"] == name].copy() smallest = rows.loc[rows["conc"] > 0, "conc"].min() zeros = int((rows["conc"] == 0).sum()) rows["conc"] = rows["conc"].where(rows["conc"] > 0, smallest / 2) after = wilcoxon_row(name, rows) before = wilcox_table[wilcox_table["analyte"] == name].iloc[0] changes.append({"analyte": name, "zeros": zeros, "W_change": after["W"] - before["W"], "p_change": after["p"] - before["p"]})print(pd.DataFrame(changes).to_string(index=False)) analyte zeros W_change p_changeIFN-gamma 12 0.0 0.0 PAI-1 4 0.0 0.0Protein C 1 0.0 0.0W and p do not move, because a rank test ignores the replacement value. The ties stay, and the test reads the twelve IFN-gamma zeros as equal and below every other patient, which is all the assay can say about them. A t-test on log values or a fold change would depend on the replacement, as the synthetic plate showed.
Plot the three analytes below q = 0.1
Section titled “Plot the three analytes below q = 0.1”A log axis cannot hold a zero, so each zero is a cross at a third of the smallest positive value of its analyte.
hits <- wilcox_table$analyte[wilcox_table$q < 0.1]plot_data <- long |> filter(analyte %in% hits, !is.na(conc)) |> group_by(analyte) |> # Zeros cannot sit on a log axis. Draw them at a third of the smallest # positive value of the analyte, with their own marker. mutate( zero = conc == 0, shown = if_else(zero, min(conc[conc > 0]) / 3, conc) ) |> ungroup() |> mutate( analyte = factor(analyte, levels = hits), group = factor(group, levels = c("no dex", "dex")) )# Name each panel with its BH q value.panel_names <- with( filter(wilcox_table, analyte %in% hits), setNames(sprintf("%s, BH q = %.2g", analyte, q), analyte))plot_data$analyte <- factor( panel_names[as.character(plot_data$analyte)], levels = panel_names[hits])
dex_plot <- ggplot(plot_data, aes(group, shown)) + geom_point( aes(shape = zero, colour = group), size = 2, position = position_jitter(width = 0.15, height = 0, seed = 1) ) + stat_summary(fun = median, geom = "crossbar", width = 0.4, linewidth = 0.3, colour = "#52514e") + scale_y_log10(labels = scales::label_comma()) + scale_colour_manual(values = c(`no dex` = "#2a78d6", dex = "#eb6834"), guide = "none") + scale_shape_manual(values = c(`FALSE` = 16, `TRUE` = 4), labels = c("measured", "exact zero in the table")) + facet_wrap(~analyte, scales = "free_y") + labs(x = NULL, y = "Concentration, pg/mL", shape = NULL, title = paste("Bar: group median.", "Zeros drawn at a third of the smallest value")) + theme_minimal(base_size = 10) + theme(panel.grid.minor = element_blank(), legend.position = "bottom")ggsave( "outputs/luminex-curves-censoring_dex_r.png", dex_plot, width = 9, height = 4, dpi = 120, bg = "white")jsonlite::write_json( metrics, "outputs/luminex_curves_metrics_r.json", auto_unbox = TRUE, digits = NA)
hits = list(wilcox_table.loc[wilcox_table["q"] < 0.1, "analyte"])group_colors = {"no dex": "#2a78d6", "dex": "#eb6834"}rng = np.random.default_rng(1)
figure, axes = plt.subplots(1, 3, figsize=(9, 4), layout="constrained")for ax, name in zip(axes, hits): rows = measured[measured["analyte"] == name] floor = rows.loc[rows["conc"] > 0, "conc"].min() / 3 for position, group in enumerate(group_colors): values = rows.loc[rows["group"] == group, "conc"].to_numpy() # Zeros cannot sit on a log axis. Draw them at a third of the # smallest positive value of the analyte, with their own marker. shown = np.where(values == 0, floor, values) x = position + rng.uniform(-0.15, 0.15, len(values)) zero = values == 0 ax.scatter(x[~zero], shown[~zero], s=16, color=group_colors[group]) ax.scatter(x[zero], shown[zero], s=24, marker="x", color=group_colors[group]) ax.hlines(np.median(shown), position - 0.2, position + 0.2, color="#52514e", lw=1.5) q = wilcox_table.loc[wilcox_table["analyte"] == name, "q"].iloc[0] ax.set_title(f"{name}\nBH q = {q:.2g}", fontsize=10) ax.set_yscale("log") ax.set_xticks([0, 1], list(group_colors)) ax.spines[["top", "right"]].set_visible(False)axes[0].set_ylabel("Concentration, pg/mL")figure.legend( handles=[Line2D([], [], color="#52514e", marker="o", ls="", label="measured"), Line2D([], [], color="#52514e", marker="x", ls="", label="exact zero in the table")], loc="outside lower center", ncol=2, frameon=False,)figure.suptitle( "Bar: group median. Zeros drawn at a third of the smallest value", x=0.02, ha="left",)figure.savefig("outputs/luminex-curves-censoring_dex_python.png", dpi=120)pathlib.Path("outputs/luminex_curves_metrics_python.json").write_text( json.dumps(metrics, indent=2) + "\n")
How this step fails
Section titled “How this step fails”Extrapolation reports a number the plate cannot support, and a flat top hides samples above the range entirely. A sample that reads near the top standard deserves a dilution and a second run, which M10 asks for samples above the ULOQ.
Dropping censored values removes one end of a group, and a fixed fraction of the LLOQ shifts means and fold changes by an amount you chose. A table of concentrations alone hides its censoring. The dexamethasone table carries no limits and no flags, so you can count its censored values only where they happen to be zero.
The code is in benchtoinsights-code/guides/proteomics/luminex-curves-censoring/, and its
parity.json compares the fitted parameters, the flags, the test statistics and the BH
values of the two languages.
Data reference
Section titled “Data reference”Neyton, Patel, Sarma and Fragiadakis, 2024 deposited the real cytokine table under CC0. Their deposit documents the different substitutions for Luminex and ELISA values and the meaning of NA. The synthetic plate remains a separate teaching fixture.
Scientific references
Section titled “Scientific references”The drc package by Ritz and Streibig fits dose-response models in R.
Further reading
Section titled “Further reading”The man/LL.5.Rd reference in the drc 4.0-0 source package defines the five parameter logistic function and its asymmetry parameter. It provides the equation behind each fitted analyte curve.
The Neyton, Patel, Sarma, and Fragiadakis data deposit explains how the published table substitutes values outside assay limits and distinguishes them from measurements that were not performed. Read those rules before comparing the real table with this lesson’s synthetic plate.