Limits, Replicates, and Plates
The standard curve page turned the ODs of one plate into concentrations. This page decides which of them to report, and whether five plates read in two batches agree. It sets the limits of each plate, flags replicates and compares curves and controls across batches. On the way it finds two standards swapped on plate 4.
Five plates and their layout
Section titled “Five plates and their layout”design.txt lists three SoftMax Pro exports: plate 1 in Assay_2.txt and plates 2 and 3
in Assay_3_and_4.txt, all in Batch1, then plates 4 and 5 in Assay_11_and_12.txt, in
Batch2. Both tabs take the layout from the SoftMax groups, as the standard curve page did,
and set it beside the ELISAtools annotation. The R tab hands the SoftMax layout to the
package’s own read.plates(), so the batch correction at the end runs on corrected
plates.
These assay exports and annotations come from Feng Feng’s ELISAtools 0.1.8 source package. The package supplies these examples under its MIT license. The fixture and license notice identifies the original files and this lesson’s derived results.
suppressPackageStartupMessages({ library(ELISAtools) library(drc) library(ggplot2) library(patchwork)})
elisa_dir <- "/opt/data/elisa"plate_rows <- LETTERS[1:8]
#' Read the well layout that the SoftMax Pro groups record.#'#' Each "Group:" block lists its samples with one well per row. The first#' row of a sample carries its name, and the rows after it leave the name#' blank.#'#' @param path Path to a SoftMax Pro text export.#' @return A data frame with one row per well: plate, group, well, the#' concentration in pg/mL for a standard, whether SoftMax masked the#' well, and an id: s1 to s8 for the standards, Blank for the diluent#' wells, Control, or the sample name.ReadSoftMaxLayout <- function(path) { lines <- sub("\r$", "", readLines(path, encoding = "latin1", warn = FALSE)) plate_of_line <- cumsum(startsWith(lines, "Plate:")) layout <- list() for (start in which(startsWith(lines, "Group:"))) { group <- trimws(sub("^Group:", "", strsplit(lines[start], "\t")[[1]][1])) wells_at <- match("Wells", strsplit(lines[start + 1], "\t")[[1]]) i <- start + 2 while (nzchar(trimws(lines[i])) && !startsWith(lines[i], "Group ")) { fields <- trimws(strsplit(lines[i], "\t")[[1]]) if (nzchar(fields[1])) { sample <- fields[1] conc <- if (group == "Standards") as.numeric(fields[2]) else NA } if (length(fields) >= wells_at && nzchar(fields[wells_at])) { layout[[length(layout) + 1]] <- data.frame( plate = plate_of_line[start], group = group, sample = sample, well = fields[wells_at], conc = conc, masked = any(fields == "Masked") ) } i <- i + 1 } } layout <- do.call(rbind, layout) layout$id <- ifelse( layout$group == "Standards", paste0("s", layout$sample), ifelse(layout$group == "Control", "Control", ifelse(layout$group == "Unknowns", "Blank", layout$sample)) ) layout[, c("plate", "group", "well", "conc", "masked", "id")]}
#' Turn the SoftMax layout of one plate into an ELISAtools annotation.#'#' @param layout The rows of ReadSoftMaxLayout() for one plate.#' @return A list with standards and unknowns tables, the structure that#' read.plates() expects.AnnotationFromLayout <- function(layout) { std <- layout$group == "Standards" rows <- match(substr(layout$well, 1, 1), plate_rows) cols <- as.integer(substring(layout$well, 2)) list( standards = data.frame(ID = layout$id[std], row = rows[std], col = cols[std], conc = layout$conc[std]), unknowns = data.frame(ID = layout$id[!std], row = rows[!std], col = cols[!std]) )}
#' List the wells of one elisa_plate as a data frame.#'#' @param plate An elisa_plate object.#' @return A data frame with well, id, conc and od.PlateWells <- function(plate) { std <- plate@data.std unknown <- plate@data.unknown data.frame( well = paste0(plate_rows[c(std$row, unknown$row)], c(std$col, unknown$col)), id = c(std$ID, unknown$ID), conc = c(std$conc, rep(NA, nrow(unknown))), od = c(std$OD, unknown$OD) )}
#' Join the distinct IDs of a set of wells.#'#' @param ids Character IDs, NA for a well that a file leaves out.#' @return The sorted distinct IDs joined with a plus sign.JoinIds <- function(ids) { paste(sort(unique(ifelse(is.na(ids), "none", ids))), collapse = "+")}
design <- read.delim(file.path(elisa_dir, "design.txt"))progress <- capture.output( batches <- loadData(file.path(elisa_dir, "design.txt")))
# Read each export again with read.plates() and the SoftMax layout, and# keep the ELISAtools annotation of every well beside it.fixed_runs <- list()plate_tables <- list()for (row in seq_len(nrow(design))) { layout <- ReadSoftMaxLayout(file.path(elisa_dir, design$FileName[row])) annotations <- lapply(split(layout, layout$plate), AnnotationFromLayout) run <- read.plates( fileName = file.path(elisa_dir, design$FileName[row]), annotations = annotations, num.plate = design$Num_Plate[row], batchID = design$Batch[row], expID = design$ExpID[row], date = design$Date[row] ) fixed_runs[[row]] <- run run_index <- sum(design$Batch[seq_len(row)] == design$Batch[row]) original <- batches[[design$Batch[row]]]@runs[[run_index]] for (k in seq_len(design$Num_Plate[row])) { ann <- PlateWells(original@plates[[k]])[, c("well", "id")] names(ann)[2] <- "ann_id" plate_layout <- layout[layout$plate == k, c("well", "group", "masked")] fixed <- merge(PlateWells(run@plates[[k]]), plate_layout, by = "well") plate_tables[[length(plate_tables) + 1]] <- data.frame( plate = length(plate_tables) + 1, batch = design$Batch[row], merge(fixed, ann, by = "well", all = TRUE) ) }}wells <- do.call(rbind, plate_tables)
cat(sprintf("%-5s %-6s %5s %9s %5s %7s %10s %6s\n", "plate", "batch", "wells", "std agree", "split", "renamed", "blank ann.", "masked"))audit <- list()details <- character(0)for (plate in unique(wells$plate)) { named <- wells[wells$plate == plate & !is.na(wells$id), ] ann_ids <- tapply(named$ann_id, named$id, JoinIds) is_std <- grepl("^s[0-9]$", names(ann_ids)) is_blank <- names(ann_ids) == "Blank" same <- !grepl("+", ann_ids, fixed = TRUE) audit[[plate]] <- data.frame( plate = plate, wells = nrow(named), std_agree = sum(is_std & ann_ids == names(ann_ids)), split = sum(!same & !is_blank), renamed = sum(same & !is_std & !is_blank & tolower(ann_ids) != tolower(names(ann_ids))), blank_annotated = sum(named$id == "Blank" & !is.na(named$ann_id)), masked = sum(named$masked) ) cat(sprintf("%-5d %-6s %5d %9s %5d %7d %10d %6d\n", plate, named$batch[1], nrow(named), sprintf("%d of 8", audit[[plate]]$std_agree), audit[[plate]]$split, audit[[plate]]$renamed, audit[[plate]]$blank_annotated, audit[[plate]]$masked)) odd <- names(ann_ids)[(!same & !is_blank) | (is_std & ann_ids != names(ann_ids))] odd <- c(odd, if (audit[[plate]]$blank_annotated > 0) "Blank") for (id in odd) { shown <- named[named$id == id & !is.na(named$ann_id), ] details <- c(details, sprintf( " plate %d: SoftMax %-7s %-12s annotation %s", plate, id, paste(shown$well, collapse = " "), paste(shown$ann_id, collapse = " ") )) }}audit <- do.call(rbind, audit)cat(details, sep = "\n")
# Write every digit, so that the Python tab can compare the ODs exactly.dir.create("outputs", showWarnings = FALSE)write.csv(transform(wells, od = sprintf("%.17g", od)), "outputs/elisa-limits-plates_wells_r.csv", row.names = FALSE)plate batch wells std agree split renamed blank ann. masked1 Batch1 72 8 of 8 4 9 0 82 Batch1 72 8 of 8 4 9 0 33 Batch1 72 8 of 8 4 9 0 04 Batch2 96 6 of 8 0 12 0 55 Batch2 96 8 of 8 0 11 3 1 plate 1: SoftMax Control F11 G10 G11 annotation Control P14 Control plate 1: SoftMax P12 C11 D10 D11 annotation P15 P13 P15 plate 1: SoftMax P14 E10 E11 F10 annotation P14 Control P14 plate 1: SoftMax P15 B10 B11 C10 annotation P13 P15 P13 plate 2: SoftMax Control F11 G10 G11 annotation Control P14 Control plate 2: SoftMax P12 C11 D10 D11 annotation P15 P13 P15 plate 2: SoftMax P14 E10 E11 F10 annotation P14 Control P14 plate 2: SoftMax P15 B10 B11 C10 annotation P13 P15 P13 plate 3: SoftMax Control F11 G10 G11 annotation Control P14 Control plate 3: SoftMax P12 C11 D10 D11 annotation P15 P13 P15 plate 3: SoftMax P14 E10 E11 F10 annotation P14 Control P14 plate 3: SoftMax P15 B10 B11 C10 annotation P13 P15 P13 plate 4: SoftMax s1 B1 B2 B3 annotation s2 s2 s2 plate 4: SoftMax s2 A1 A2 A3 annotation s1 s1 s1 plate 5: SoftMax Blank D4 D5 D6 annotation P3 P3 P3These assay exports and annotations come from Feng Feng’s ELISAtools 0.1.8 source package. The package supplies these examples under its MIT license. The fixture and license notice identifies the original files and this lesson’s derived results.
import jsonimport pathlib
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport scipy.optimize
ELISA_DIR = pathlib.Path("/opt/data/elisa")NOMINAL = {"s1": 3000, "s2": 1500, "s3": 750, "s4": 375, "s5": 187.5, "s6": 93.75, "s7": 46.875, "s8": 0}
def read_lines(path): """Read a SoftMax Pro or ELISAtools text file.
Args: path: Path to the file. The exports are Latin-1 with CRLF endings.
Returns: The lines without line endings. """ return path.read_text(encoding="latin-1").splitlines()
def read_softmax_plates(path): """Read the absorbance block of every plate in a SoftMax Pro export.
Args: path: Path to the SoftMax Pro text export.
Returns: A list with one DataFrame per plate: well and od, the 450 nm read minus the 620 nm read. """ lines = read_lines(path) plates = [] for start, line in enumerate(lines): if not line.startswith("Plate:"): continue wells = [well for well in lines[start + 1].split("\t")[2:] if well] reads = [] for data_line in lines[start + 2:]: if data_line.startswith("~End"): break fields = data_line.split("\t") if len(fields) > 2 and fields[1].strip(): reads.append([float(v) for v in fields[2:2 + len(wells)]]) od = np.array(reads[0]) - np.array(reads[1]) plates.append(pd.DataFrame({"well": wells, "od": od})) return plates
def read_softmax_layout(path): """Read the well layout that the SoftMax Pro groups record.
Args: path: Path to a SoftMax Pro text export.
Returns: A DataFrame with one row per well: plate, group, well, the concentration in pg/mL for a standard, whether SoftMax masked the well, and an id: s1 to s8 for the standards, Blank for the diluent wells, Control, or the sample name. """ lines = read_lines(path) rows = [] plate = 0 for start, line in enumerate(lines): if line.startswith("Plate:"): plate += 1 if not line.startswith("Group:"): continue group = line.split("\t")[0].removeprefix("Group:").strip() wells_at = lines[start + 1].split("\t").index("Wells") sample, conc = None, np.nan for row_line in lines[start + 2:]: if not row_line.strip() or row_line.startswith("Group "): break fields = [field.strip() for field in row_line.split("\t")] if fields[0]: sample = fields[0] conc = float(fields[1]) if group == "Standards" else np.nan if len(fields) > wells_at and fields[wells_at]: rows.append({ "plate": plate, "group": group, "sample": sample, "well": fields[wells_at], "conc": conc, "masked": "Masked" in fields, }) layout = pd.DataFrame(rows) ids = {"Control": "Control", "Unknowns": "Blank"} layout["id"] = np.where( layout["group"] == "Standards", "s" + layout["sample"], layout["group"].map(ids).fillna(layout["sample"]), ) return layout.drop(columns="sample")
def read_annotation(path, block): """Read the ID of each well from one block of an annotation file.
Args: path: Path to the ELISAtools annotation file. block: The position of the "Plate:" block, 1 for the first.
Returns: A DataFrame with the columns well and ann_id. """ lines = read_lines(path) starts = [i for i, line in enumerate(lines) if line.startswith("Plate:")] start = starts[block - 1] columns = lines[start + 1].split("\t")[1:] rows = [] for line in lines[start + 2:start + 10]: fields = line.split("\t") for column, ann_id in zip(columns, fields[1:]): if ann_id.strip(): rows.append({"well": f"{fields[0]}{column}", "ann_id": ann_id.strip()}) return pd.DataFrame(rows)
def join_ids(ids): """Join the distinct IDs of a set of wells.
Args: ids: A pandas Series of IDs, NaN for a well that a file leaves out.
Returns: The sorted distinct IDs joined with a plus sign. """ return "+".join(sorted(set(ids.fillna("none"))))
design = pd.read_csv(ELISA_DIR / "design.txt", sep="\t")tables = []for _, run in design.iterrows(): export = ELISA_DIR / run["FileName"] reads = read_softmax_plates(export) layout = read_softmax_layout(export) for k in range(1, run["Num_Plate"] + 1): plate = layout[layout["plate"] == k].drop(columns="plate") plate = plate.merge(reads[k - 1], on="well") annotation = read_annotation(ELISA_DIR / run["AnnotationFile"], k) plate = plate.merge(annotation, on="well", how="outer") plate.insert(0, "batch", run["Batch"]) plate.insert(0, "plate", len(tables) + 1) tables.append(plate)wells = pd.concat(tables, ignore_index=True)
print(f"{'plate':<5} {'batch':<6} {'wells':>5} {'std agree':>9} " f"{'split':>5} {'renamed':>7} {'blank ann.':>10} {'masked':>6}")audit = []details = []for plate, plate_wells in wells.groupby("plate"): named = plate_wells[plate_wells["id"].notna()] ann_ids = named.groupby("id")["ann_id"].agg(join_ids).sort_index() is_std = ann_ids.index.str.fullmatch(r"s[0-9]") is_blank = ann_ids.index == "Blank" same = ~ann_ids.str.contains("+", regex=False) row = { "plate": plate, "wells": len(named), "std_agree": int((is_std & (ann_ids == ann_ids.index)).sum()), "split": int((~same & ~is_blank).sum()), "renamed": int((same & ~is_std & ~is_blank & ( ann_ids.str.lower() != ann_ids.index.str.lower())).sum()), "blank_annotated": int(((named["id"] == "Blank") & named["ann_id"].notna()).sum()), "masked": int(named["masked"].sum()), } audit.append(row) print(f"{plate:<5} {named['batch'].iloc[0]:<6} {row['wells']:>5} " f"{row['std_agree']:>4} of 8 {row['split']:>5} " f"{row['renamed']:>7} {row['blank_annotated']:>10} " f"{row['masked']:>6}") odd = list(ann_ids.index[(~same & ~is_blank) | (is_std & (ann_ids != ann_ids.index))]) if row["blank_annotated"] > 0: odd.append("Blank") for sample_id in odd: shown = named[(named["id"] == sample_id) & named["ann_id"].notna()] shown = shown.sort_values("well") details.append( f" plate {plate}: SoftMax {sample_id:<7} " f"{' '.join(shown['well']):<12} annotation " f"{' '.join(shown['ann_id'])}" )audit = pd.DataFrame(audit)print("\n".join(details))
# R runs first and writes the wells it read through ELISAtools.r_wells = pd.read_csv("outputs/elisa-limits-plates_wells_r.csv")both = wells.merge(r_wells, on=["plate", "well"], suffixes=("", "_r"))od_gap = np.abs(both["od"] - both["od_r"]).max()print(f"wells shared with the R read: {len(both)} of {len(r_wells)}; " f"largest OD difference {od_gap:g}")plate batch wells std agree split renamed blank ann. masked1 Batch1 72 8 of 8 4 9 0 82 Batch1 72 8 of 8 4 9 0 33 Batch1 72 8 of 8 4 9 0 04 Batch2 96 6 of 8 0 12 0 55 Batch2 96 8 of 8 0 11 3 1 plate 1: SoftMax Control F11 G10 G11 annotation Control P14 Control plate 1: SoftMax P12 C11 D10 D11 annotation P15 P13 P15 plate 1: SoftMax P14 E10 E11 F10 annotation P14 Control P14 plate 1: SoftMax P15 B10 B11 C10 annotation P13 P15 P13 plate 2: SoftMax Control F11 G10 G11 annotation Control P14 Control plate 2: SoftMax P12 C11 D10 D11 annotation P15 P13 P15 plate 2: SoftMax P14 E10 E11 F10 annotation P14 Control P14 plate 2: SoftMax P15 B10 B11 C10 annotation P13 P15 P13 plate 3: SoftMax Control F11 G10 G11 annotation Control P14 Control plate 3: SoftMax P12 C11 D10 D11 annotation P15 P13 P15 plate 3: SoftMax P14 E10 E11 F10 annotation P14 Control P14 plate 3: SoftMax P15 B10 B11 C10 annotation P13 P15 P13 plate 4: SoftMax s1 B1 B2 B3 annotation s2 s2 s2 plate 4: SoftMax s2 A1 A2 A3 annotation s1 s1 s1 plate 5: SoftMax Blank D4 D5 D6 annotation P3 P3 P3wells shared with the R read: 408 of 408; largest OD difference 0The two layouts agree on the standards of four plates. On plate 4 they do not: SoftMax puts 3,000 pg/mL in row B and 1,500 pg/mL in row A, and the annotation says the opposite. Plates 1 to 3 repeat the regrouping of columns 10 and 11 that the standard curve page found, so the annotation’s Control on those plates includes a sample well. On plate 5, SoftMax records D4, D5 and D6 as blank wells with diluent only, and the annotation calls them sample P3. SoftMax also lists diluent wells on plates 4 and 5 that the annotation leaves out, which is why those plates name 96 wells instead of 72. The Python parser reads the same 408 wells as R, with an OD difference of 0.
The swapped standards on plate 4
Section titled “The swapped standards on plate 4”A swap of two standards does not stop a fit. Two checks catch it, run here on every plate under each layout: the mean OD must fall with every step down the dilution series, and the 4PL must not miss the standards by much more than on the other plates.
#' Mean OD of each standard level, highest concentration first.#'#' @param od ODs of the standard wells.#' @param conc Nominal concentrations of the same wells.#' @return Mean OD per level, ordered from the highest concentration.LevelMeans <- function(od, conc) { means <- tapply(od, conc, mean) means[order(-as.numeric(names(means)))]}
nominal <- c(s1 = 3000, s2 = 1500, s3 = 750, s4 = 375, s5 = 187.5, s6 = 93.75, s7 = 46.875, s8 = 0)# Nelder-Mead with a tight tolerance, as on the standard curve page.fit_control <- drmc(method = "Nelder-Mead", relTol = 1e-15, maxIt = 1e5)defect <- list()cat(sprintf("%-5s %-24s %-24s\n", "plate", "annotation", "SoftMax"))for (plate in unique(wells$plate)) { ann_std <- wells[wells$plate == plate & grepl("^s", wells$ann_id), ] fix_std <- wells[wells$plate == plate & wells$group %in% "Standards", ] ann_conc <- nominal[ann_std$ann_id] ann_fit <- drm(ann_std$od ~ ann_conc, fct = LL.4(), control = fit_control) fix_fit <- drm(od ~ conc, data = fix_std, fct = LL.4(), control = fit_control) defect[[plate]] <- data.frame( plate = plate, ann_mono = all(diff(LevelMeans(ann_std$od, ann_conc)) < 0), fix_mono = all(diff(LevelMeans(fix_std$od, fix_std$conc)) < 0), ann_rse = summary(ann_fit)$rseMat[1, "rse"], fix_rse = summary(fix_fit)$rseMat[1, "rse"] ) cat(sprintf("%-5d %-24s %-24s\n", plate, sprintf("%s, RSE %.4f", ifelse(defect[[plate]]$ann_mono, "monotone", "NOT"), defect[[plate]]$ann_rse), sprintf("%s, RSE %.4f", ifelse(defect[[plate]]$fix_mono, "monotone", "NOT"), defect[[plate]]$fix_rse)))}defect <- do.call(rbind, defect)top <- wells[wells$plate == 4 & wells$group %in% "Standards" & wells$conc >= 1500, ]cat("plate 4, top two standards:\n")cat(sprintf(" %-3s SoftMax %4.0f pg/mL, annotation %s, OD %.3f\n", top$well, top$conc, top$ann_id, top$od), sep = "")plate annotation SoftMax1 monotone, RSE 0.0925 monotone, RSE 0.09252 monotone, RSE 0.0463 monotone, RSE 0.04633 monotone, RSE 0.0750 monotone, RSE 0.07504 NOT, RSE 0.2325 monotone, RSE 0.04705 monotone, RSE 0.1028 monotone, RSE 0.1028plate 4, top two standards: A1 SoftMax 1500 pg/mL, annotation s1, OD 1.882 A2 SoftMax 1500 pg/mL, annotation s1, OD 1.899 A3 SoftMax 1500 pg/mL, annotation s1, OD 1.833 B1 SoftMax 3000 pg/mL, annotation s2, OD 2.513 B2 SoftMax 3000 pg/mL, annotation s2, OD 2.349 B3 SoftMax 3000 pg/mL, annotation s2, OD 2.328def ll4(conc, b, c, d, e): """Evaluate the drc LL.4 model.
Args: conc: Concentrations in pg/mL, a NumPy array. b: Slope. A negative value gives a rising curve. c: Lower asymptote, the OD at zero concentration. d: Upper asymptote. e: Inflection concentration.
Returns: The model ODs, a NumPy array. """ with np.errstate(divide="ignore", over="ignore"): core = 1.0 + np.exp(b * (np.log(conc) - np.log(e))) return c + (d - c) / core
def fit_4pl(conc, od): """Fit the drc LL.4 model by least squares.
Args: conc: Standard concentrations, a NumPy array. od: Standard ODs, a NumPy array.
Returns: A dict with b, c, d, e and the residual standard error rse. """ start = [-1.0, od.min(), od.max(), np.median(conc[conc > 0])] params, _ = scipy.optimize.curve_fit( ll4, conc, od, p0=start, bounds=([-np.inf, -np.inf, -np.inf, 1e-9], np.inf), method="trf", xtol=1e-15, ftol=1e-15, gtol=1e-15, max_nfev=100000, ) rss = np.sum((od - ll4(conc, *params)) ** 2) fit = dict(zip("bcde", params)) fit["rse"] = float(np.sqrt(rss / (len(od) - 4))) return fit
def is_monotone(od, conc): """Check that the mean OD falls with every step down the standards.
Args: od: ODs of the standard wells, a pandas Series. conc: Nominal concentrations of the same wells, a pandas Series.
Returns: True when the mean OD strictly decreases with concentration. """ means = od.groupby(conc.to_numpy()).mean().sort_index(ascending=False) return bool((np.diff(means.to_numpy()) < 0).all())
defect = []print(f"{'plate':<5} {'annotation':<24} {'SoftMax':<24}")for plate, plate_wells in wells.groupby("plate"): ann_std = plate_wells[plate_wells["ann_id"].str.match("s", na=False)] fix_std = plate_wells[plate_wells["group"] == "Standards"] ann_conc = ann_std["ann_id"].map(NOMINAL) ann_fit = fit_4pl(ann_conc.to_numpy(), ann_std["od"].to_numpy()) fix_fit = fit_4pl(fix_std["conc"].to_numpy(), fix_std["od"].to_numpy()) row = { "plate": plate, "ann_mono": is_monotone(ann_std["od"], ann_conc), "fix_mono": is_monotone(fix_std["od"], fix_std["conc"]), "ann_rse": ann_fit["rse"], "fix_rse": fix_fit["rse"], } defect.append(row) left = "monotone" if row["ann_mono"] else "NOT" right = "monotone" if row["fix_mono"] else "NOT" print(f"{plate:<5} {left + ', RSE ' + format(row['ann_rse'], '.4f'):<24} " f"{right + ', RSE ' + format(row['fix_rse'], '.4f'):<24}")defect = pd.DataFrame(defect)top = wells[(wells["plate"] == 4) & (wells["group"] == "Standards") & (wells["conc"] >= 1500)].sort_values("well")print("plate 4, top two standards:")for _, well in top.iterrows(): print(f" {well['well']:<3} SoftMax {well['conc']:4.0f} pg/mL, " f"annotation {well['ann_id']}, OD {well['od']:.3f}")plate annotation SoftMax1 monotone, RSE 0.0925 monotone, RSE 0.09252 monotone, RSE 0.0463 monotone, RSE 0.04633 monotone, RSE 0.0750 monotone, RSE 0.07504 NOT, RSE 0.2325 monotone, RSE 0.04705 monotone, RSE 0.1028 monotone, RSE 0.1028plate 4, top two standards: A1 SoftMax 1500 pg/mL, annotation s1, OD 1.882 A2 SoftMax 1500 pg/mL, annotation s1, OD 1.899 A3 SoftMax 1500 pg/mL, annotation s1, OD 1.833 B1 SoftMax 3000 pg/mL, annotation s2, OD 2.513 B2 SoftMax 3000 pg/mL, annotation s2, OD 2.349 B3 SoftMax 3000 pg/mL, annotation s2, OD 2.328Under the annotation, plate 4 fails the first check: its wells labeled 3,000 pg/mL read 1.833 to 1.899, below the 2.328 to 2.513 of its wells labeled 1,500. The fit still converges without a warning, and only its residual standard error, 0.2325 against 0.0470 under the SoftMax layout, gives it away. The other four plates fit the same under both layouts. The evidence for the fix sits in the export, whose Standards group lists B1 to B3 at 3,000 pg/mL and A1 to A3 at 1,500. Correct the layout, never the ODs.
LOD, LLOQ and ULOQ
Section titled “LOD, LLOQ and ULOQ”The limit of detection, LOD, is the lowest concentration a plate tells apart from the blank. This page takes the mean OD of the three blank wells plus three standard deviations and reads that OD off the plate’s 4PL.
The lower and upper limits of quantification, LLOQ and ULOQ, come from the standards. For ligand binding assays, ICH M10 asks that the back-calculated standards stay within 20% of nominal in accuracy and precision, and within 25% at the LLOQ and ULOQ. M10 leaves biomarkers out of its scope, but the FDA guidance on biomarker assays names it the starting point for them, as the experimental design page explains. The code keeps the widest run of consecutive levels whose mean recovery and CV pass at 20%, or at 25% for the two end levels.
#' Back-calculate concentrations from a 4PL in the drc parameterization.#'#' @param od Optical densities.#' @param pars Named vector with b, c, d and e.#' @return Concentrations in pg/mL, NA where the OD is outside (c, d).Inverse4pl <- function(od, pars) { ratio <- (pars[["d"]] - pars[["c"]]) / (od - pars[["c"]]) - 1 conc <- pars[["e"]] * ratio^(1 / pars[["b"]]) conc[od <= pars[["c"]] | od >= pars[["d"]]] <- NA conc}
#' Coefficient of variation in percent.#'#' @param x Numeric values.#' @return 100 times the standard deviation over the mean.CvPercent <- function(x) { 100 * sd(x) / mean(x)}
#' Find the widest run of standard levels that meets the M10 rule.#'#' Inside the run, each level needs a mean recovery within 80 to 120% and a#' CV of at most 20%. The two end levels may reach 75 to 125% and 25%.#'#' @param levels A data frame with conc, recovery and cv, one row per#' nonzero level, sorted by conc.#' @return A vector with the LLOQ and the ULOQ in pg/mL, NA if no run#' passes.QuantRange <- function(levels) { inner <- abs(levels$recovery - 100) <= 20 & levels$cv <= 20 edge <- abs(levels$recovery - 100) <= 25 & levels$cv <= 25 inner[is.na(inner)] <- FALSE edge[is.na(edge)] <- FALSE best <- c(NA, NA) width <- -1 for (lo in seq_len(nrow(levels))) { for (hi in lo:nrow(levels)) { middle <- if (hi - lo > 1) inner[(lo + 1):(hi - 1)] else TRUE if (edge[lo] && edge[hi] && all(middle) && hi - lo > width) { best <- c(levels$conc[lo], levels$conc[hi]) width <- hi - lo } } } best}
fits <- list()limits <- list()level_tables <- list()for (plate in unique(wells$plate)) { std <- wells[wells$plate == plate & wells$group %in% "Standards", ] fit <- drm(od ~ conc, data = std, control = fit_control, fct = LL.4(names = c("b", "c", "d", "e"))) pars <- setNames(coef(fit), c("b", "c", "d", "e")) fits[[plate]] <- pars # LOD: the mean of the blank plus 3 SD, read off the curve. blank <- std$od[std$conc == 0] diluent <- wells$od[wells$plate == plate & wells$id %in% "Blank"] lod_diluent <- NA if (length(diluent) > 0) { lod_diluent <- Inverse4pl(mean(diluent) + 3 * sd(diluent), pars) } # Recovery and CV of the back-calculated standards, level by level. std <- std[std$conc > 0, ] std$back <- Inverse4pl(std$od, pars) levels <- data.frame( conc = sort(unique(std$conc)), recovery = 100 * tapply(std$back, std$conc, mean) / sort(unique(std$conc)), cv = tapply(std$back, std$conc, CvPercent) ) level_tables[[plate]] <- data.frame(plate = plate, levels) quant <- QuantRange(levels) limits[[plate]] <- data.frame( plate = plate, lod = Inverse4pl(mean(blank) + 3 * sd(blank), pars), lod_diluent = lod_diluent, n_diluent = length(diluent), lloq = quant[1], uloq = quant[2], n_levels = sum(levels$conc >= quant[1] & levels$conc <= quant[2]) )}fits <- do.call(rbind, fits)limits <- do.call(rbind, limits)level_tables <- do.call(rbind, level_tables)
#' Print one value per standard level and plate.#'#' @param tables The level tables of all plates.#' @param column The column to print.#' @return NULL, invisibly.PrintLevelTable <- function(tables, column) { plates <- sort(unique(tables$plate)) cat(sprintf("%9s%s\n", "pg/mL", paste(sprintf("%9s", paste("plate", plates)), collapse = ""))) for (conc in sort(unique(tables$conc))) { values <- tables[tables$conc == conc, ] values <- values[order(values$plate), column] cat(sprintf("%9.3f%s\n", conc, paste(sprintf("%9.1f", values), collapse = ""))) } invisible(NULL)}
cat("recovery %:\n")PrintLevelTable(level_tables, "recovery")cat("CV %:\n")PrintLevelTable(level_tables, "cv")cat(sprintf("%-5s %8s %9s %10s %8s %8s %6s\n", "plate", "LOD", "LOD dil.", "n diluent", "LLOQ", "ULOQ", "levels"))cat(sprintf("%-5d %8.2f %9s %10d %8.3f %8.0f %6d\n", limits$plate, limits$lod, ifelse(is.na(limits$lod_diluent), "-", sprintf("%.2f", limits$lod_diluent)), limits$n_diluent, limits$lloq, limits$uloq, limits$n_levels), sep = "")recovery %: pg/mL plate 1 plate 2 plate 3 plate 4 plate 5 46.875 73.5 90.0 103.5 104.0 90.8 93.750 105.8 83.0 95.1 102.1 92.7 187.500 102.7 95.0 102.0 105.1 91.8 375.000 103.4 103.5 100.5 101.8 100.4 750.000 97.2 103.6 99.7 94.7 109.9 1500.000 101.0 97.9 100.6 104.7 93.8 3000.000 100.4 100.5 100.5 99.2 104.2CV %: pg/mL plate 1 plate 2 plate 3 plate 4 plate 5 46.875 14.3 7.0 8.3 8.4 4.8 93.750 15.4 6.1 3.4 7.2 10.3 187.500 17.6 10.7 13.6 8.9 19.3 375.000 11.8 14.2 18.5 3.2 10.2 750.000 17.8 10.1 18.4 5.0 4.7 1500.000 9.2 8.6 13.1 3.6 11.1 3000.000 14.5 4.1 11.5 15.0 24.8plate LOD LOD dil. n diluent LLOQ ULOQ levels1 26.35 - 0 93.750 3000 62 16.52 - 0 46.875 3000 73 7.04 - 0 46.875 3000 74 19.36 9.63 24 46.875 3000 75 18.66 9.98 27 46.875 3000 7def inverse_4pl(od, fit): """Back-calculate concentrations from a 4PL in the drc parameterization.
Args: od: Optical densities, a NumPy array. fit: A dict with the 4PL parameters b, c, d and e.
Returns: Concentrations in pg/mL, NaN where the OD is outside (c, d). """ od = np.asarray(od, dtype=float) inside = (od > fit["c"]) & (od < fit["d"]) ratio = (fit["d"] - fit["c"]) / np.where(inside, od - fit["c"], 1) - 1 return np.where(inside, fit["e"] * ratio ** (1 / fit["b"]), np.nan)
def cv_percent(values): """Coefficient of variation in percent, NaN if any value is missing.
Args: values: A pandas Series.
Returns: 100 times the sample standard deviation over the mean. """ values = values.to_numpy(dtype=float) return 100 * np.std(values, ddof=1) / np.mean(values)
def strict_mean(values): """Mean that stays NaN when any value is missing, as R's mean() does.
Args: values: A pandas Series.
Returns: The mean, or NaN. """ return float(np.mean(values.to_numpy(dtype=float)))
def quant_range(levels): """Find the widest run of standard levels that meets the M10 rule.
Inside the run, each level needs a mean recovery within 80 to 120% and a CV of at most 20%. The two end levels may reach 75 to 125% and 25%.
Args: levels: A DataFrame with conc, recovery and cv, one row per nonzero level, sorted by conc.
Returns: A tuple with the LLOQ and the ULOQ in pg/mL, NaN if no run passes. """ error = (levels["recovery"] - 100).abs().to_numpy() cv = levels["cv"].to_numpy() inner = (error <= 20) & (cv <= 20) edge = (error <= 25) & (cv <= 25) conc = levels["conc"].to_numpy() best, width = (np.nan, np.nan), -1 for lo in range(len(levels)): for hi in range(lo, len(levels)): middle = inner[lo + 1:hi].all() if edge[lo] and edge[hi] and middle and hi - lo > width: best, width = (conc[lo], conc[hi]), hi - lo return best
fits = {}limits = []level_tables = []for plate, plate_wells in wells.groupby("plate"): std = plate_wells[plate_wells["group"] == "Standards"] fit = fit_4pl(std["conc"].to_numpy(), std["od"].to_numpy()) fits[plate] = fit # LOD: the mean of the blank plus 3 SD, read off the curve. blank = std.loc[std["conc"] == 0, "od"] diluent = plate_wells.loc[plate_wells["id"] == "Blank", "od"] lod_diluent = np.nan if len(diluent) > 0: lod_diluent = inverse_4pl(diluent.mean() + 3 * diluent.std(), fit) # Recovery and CV of the back-calculated standards, level by level. std = std[std["conc"] > 0].copy() std["back"] = inverse_4pl(std["od"], fit) levels = std.groupby("conc")["back"].agg([strict_mean, cv_percent]) levels = levels.reset_index() levels.columns = ["conc", "mean", "cv"] levels["recovery"] = 100 * levels["mean"] / levels["conc"] levels.insert(0, "plate", plate) level_tables.append(levels) lloq, uloq = quant_range(levels) limits.append({ "plate": plate, "lod": float(inverse_4pl(blank.mean() + 3 * blank.std(), fit)), "lod_diluent": float(lod_diluent), "n_diluent": len(diluent), "lloq": lloq, "uloq": uloq, "n_levels": int(levels["conc"].between(lloq, uloq).sum()), })limits = pd.DataFrame(limits)level_tables = pd.concat(level_tables)
def print_level_table(tables, column): """Print one value per standard level and plate.
Args: tables: The level tables of all plates. column: The column to print. """ wide = tables.pivot(index="conc", columns="plate", values=column) print(f"{'pg/mL':>9}" + "".join(f"{'plate ' + str(p):>9}" for p in wide.columns)) for conc, values in wide.iterrows(): print(f"{conc:9.3f}" + "".join(f"{v:9.1f}" for v in values))
print("recovery %:")print_level_table(level_tables, "recovery")print("CV %:")print_level_table(level_tables, "cv")print(f"{'plate':<5} {'LOD':>8} {'LOD dil.':>9} {'n diluent':>10} " f"{'LLOQ':>8} {'ULOQ':>8} {'levels':>6}")for row in limits.itertuples(): lod_dil = "-" if np.isnan(row.lod_diluent) else f"{row.lod_diluent:.2f}" print(f"{row.plate:<5} {row.lod:8.2f} {lod_dil:>9} {row.n_diluent:>10} " f"{row.lloq:8.3f} {row.uloq:8.0f} {row.n_levels:>6}")recovery %: pg/mL plate 1 plate 2 plate 3 plate 4 plate 5 46.875 73.5 90.0 103.5 104.0 90.8 93.750 105.8 83.0 95.1 102.1 92.7 187.500 102.7 95.0 102.0 105.1 91.8 375.000 103.4 103.5 100.5 101.8 100.4 750.000 97.2 103.6 99.7 94.7 109.9 1500.000 101.0 97.9 100.6 104.7 93.8 3000.000 100.4 100.5 100.5 99.2 104.2CV %: pg/mL plate 1 plate 2 plate 3 plate 4 plate 5 46.875 14.3 7.0 8.3 8.4 4.8 93.750 15.4 6.1 3.4 7.2 10.3 187.500 17.6 10.7 13.6 8.9 19.3 375.000 11.8 14.2 18.5 3.2 10.2 750.000 17.8 10.1 18.4 5.0 4.7 1500.000 9.2 8.6 13.1 3.6 11.1 3000.000 14.5 4.1 11.5 15.0 24.8plate LOD LOD dil. n diluent LLOQ ULOQ levels1 26.35 - 0 93.750 3000 62 16.52 - 0 46.875 3000 73 7.04 - 0 46.875 3000 74 19.36 9.63 24 46.875 3000 75 18.66 9.98 27 46.875 3000 7Plate 1 is the one plate that loses a level. Its 46.875 pg/mL standard back-calculates to 73.5% of nominal, outside even the 25% allowed at an end, so its LLOQ rises to 93.75 pg/mL and its range keeps 6 levels, the minimum M10 accepts. The other four plates keep all 7 levels from 46.875 to 3,000 pg/mL, and plate 5 keeps its top standard only at the edge, with a CV of 24.8%.
The LOD rests on three wells, and it moves with their scatter, from 7.04 pg/mL on plate 3 to 26.35 pg/mL on plate 1. Plates 4 and 5 also carry 24 and 27 diluent wells. Taken as the blank, they give an LOD of 9.63 and 9.98 pg/mL, about half the value from the three blank standards on the same plates. When you design a plate, give the blank more wells.
Samples in range and replicate flags
Section titled “Samples in range and replicate flags”Each sample takes a status from the mean of its back-calculated wells: below the LOD,
below the LLOQ, in range, or above the ULOQ. A well whose OD sits at or below c has no
concentration, and its sample counts as below the LOD. Inside the range, a triplicate CV
above 20%, the M10 limit for standards, raises a flag.
unknowns <- wells[wells$group %in% c("Unk_Dilution", "Control"), ]unknowns$back <- NAfor (plate in unique(unknowns$plate)) { rows <- unknowns$plate == plate unknowns$back[rows] <- Inverse4pl(unknowns$od[rows], fits[plate, ])}cat(sprintf("sample wells with an OD at or below c: %d of %d\n", sum(is.na(unknowns$back)), nrow(unknowns)))samples <- aggregate(cbind(od, back) ~ plate + batch + id + group, data = unknowns, FUN = mean, na.action = na.pass)samples <- merge(samples, aggregate( cbind(cv_od = od, cv_back = back) ~ plate + id, data = unknowns, FUN = CvPercent, na.action = na.pass))samples <- merge(samples, aggregate(masked ~ plate + id, data = unknowns, FUN = any))samples <- merge(samples, limits[, c("plate", "lod", "lloq", "uloq")])samples$status <- ifelse( is.na(samples$back) | samples$back < samples$lod, "below LOD", ifelse(samples$back < samples$lloq, "below LLOQ", ifelse(samples$back > samples$uloq, "above ULOQ", "in range")))samples$flag <- samples$status == "in range" & samples$cv_back > 20patients <- samples[samples$group == "Unk_Dilution", ]status_levels <- c("below LOD", "below LLOQ", "in range", "above ULOQ")counts <- table(patients$plate, factor(patients$status, status_levels))cat(sprintf("%-5s%s\n", "plate", paste(sprintf("%11s", status_levels), collapse = "")))for (plate in rownames(counts)) { cat(sprintf("%-5s%s\n", plate, paste(sprintf("%11d", counts[plate, ]), collapse = "")))}cat(sprintf("in range: %d of %d samples\n", sum(patients$status == "in range"), nrow(patients)))cat(sprintf("in-range triplicates with a CV above 20%%: %d\n", sum(samples$flag)))for (i in which(samples$flag)) { cat(sprintf(" plate %d %-4s %6.1f pg/mL, CV %4.1f%%, masked well: %s\n", samples$plate[i], samples$id[i], samples$back[i], samples$cv_back[i], ifelse(samples$masked[i], "yes", "no")))}cat(sprintf("triplicates with a masked well: %d, of which in range: %d\n", sum(samples$masked), sum(samples$masked & samples$status == "in range")))sample wells with an OD at or below c: 8 of 237plate below LOD below LLOQ in range above ULOQ1 5 10 0 02 0 6 9 03 0 5 10 04 6 5 4 05 0 6 8 0in range: 31 of 74 samplesin-range triplicates with a CV above 20%: 1 plate 2 P7 93.5 pg/mL, CV 40.4%, masked well: yestriplicates with a masked well: 10, of which in range: 3unknowns = wells[wells["group"].isin(["Unk_Dilution", "Control"])].copy()unknowns["back"] = np.nanfor plate, fit in fits.items(): rows = unknowns["plate"] == plate unknowns.loc[rows, "back"] = inverse_4pl(unknowns.loc[rows, "od"], fit)print(f"sample wells with an OD at or below c: " f"{unknowns['back'].isna().sum()} of {len(unknowns)}")samples = unknowns.groupby(["plate", "batch", "id", "group"]).agg( od=("od", "mean"), back=("back", strict_mean), cv_od=("od", cv_percent), cv_back=("back", cv_percent), masked=("masked", "any"),).reset_index()samples = samples.merge(limits[["plate", "lod", "lloq", "uloq"]])samples["status"] = np.select( [samples["back"].isna() | (samples["back"] < samples["lod"]), samples["back"] < samples["lloq"], samples["back"] > samples["uloq"]], ["below LOD", "below LLOQ", "above ULOQ"], default="in range",)samples["flag"] = (samples["status"] == "in range") & ( samples["cv_back"] > 20)patients = samples[samples["group"] == "Unk_Dilution"]status_levels = ["below LOD", "below LLOQ", "in range", "above ULOQ"]counts = (patients.groupby("plate")["status"].value_counts() .unstack(fill_value=0).reindex(columns=status_levels, fill_value=0))print(f"{'plate':<5}" + "".join(f"{level:>11}" for level in status_levels))for plate, row in counts.iterrows(): print(f"{plate:<5}" + "".join(f"{count:11d}" for count in row))in_range = (patients["status"] == "in range").sum()print(f"in range: {in_range} of {len(patients)} samples")print(f"in-range triplicates with a CV above 20%: {samples['flag'].sum()}")for _, row in samples[samples["flag"]].iterrows(): masked = "yes" if row["masked"] else "no" print(f" plate {row['plate']} {row['id']:<4} {row['back']:6.1f} pg/mL, " f"CV {row['cv_back']:4.1f}%, masked well: {masked}")masked_in_range = samples["masked"] & (samples["status"] == "in range")print(f"triplicates with a masked well: {samples['masked'].sum()}, " f"of which in range: {masked_in_range.sum()}")sample wells with an OD at or below c: 8 of 237plate below LOD below LLOQ in range above ULOQ1 5 10 0 02 0 6 9 03 0 5 10 04 6 5 4 05 0 6 8 0in range: 31 of 74 samplesin-range triplicates with a CV above 20%: 1 plate 2 P7 93.5 pg/mL, CV 40.4%, masked well: yestriplicates with a masked well: 10, of which in range: 3Only 31 of the 74 samples fall inside the quantifiable range. Plate 1 has none, since every sample on it reads below its LLOQ of 93.75 pg/mL, and 5 of its 15 fall below the LOD. Report such a sample as below the limit, not as the number the curve returns. The Luminex curves page shows what that choice does to a group comparison.
Ten triplicates hold a well that SoftMax masked, and 3 of them are in range. Only one of those breaks the CV rule, P7 on plate 2 at 40.4%. The other two pass with the masked well included, so the analyst who masked them was stricter than the rule.
Plates and batches
Section titled “Plates and batches”The same Control sits on all five plates, so it measures plate and batch effects. The table sets it beside the 4PL of each plate.
control <- samples[samples$id == "Control", ]control <- control[order(control$plate), ]cat(sprintf("%-5s %-6s %7s %7s %5s %6s %8s %5s\n", "plate", "batch", "b", "c", "d", "e", "Control", "CV %"))cat(sprintf("%-5d %-6s %7.4f %7.4f %5.2f %6.0f %8.1f %5.1f\n", control$plate, control$batch, fits[, "b"], fits[, "c"], fits[, "d"], fits[, "e"], control$back, control$cv_back), sep = "")by_batch <- tapply(control$back, control$batch, mean)cat(sprintf("Control mean by batch: %s\n", paste(names(by_batch), sprintf("%.1f", by_batch), collapse = ", ")))cat(sprintf("Control CV across the five plates: %.1f%%\n", CvPercent(control$back)))
#' Evaluate a 4PL in the drc parameterization.#'#' @param conc Concentrations in pg/mL.#' @param pars Named vector with b, c, d and e.#' @return The model ODs.Curve4pl <- function(conc, pars) { pars[["c"]] + (pars[["d"]] - pars[["c"]]) / (1 + exp(pars[["b"]] * (log(conc) - log(pars[["e"]]))))}
grid <- 10^seq(log10(30), log10(4000), length.out = 200)curves <- list()for (plate in seq_len(nrow(fits))) { curves[[plate]] <- data.frame( plate = plate, batch = control$batch[plate], conc = grid, od = Curve4pl(grid, fits[plate, ]) )}curves <- do.call(rbind, curves)std_wells <- wells[wells$group %in% "Standards" & wells$conc > 0, ]level_points <- aggregate(od ~ plate + batch + conc, data = std_wells, FUN = mean)swapped <- wells[wells$plate == 4 & wells$ann_id %in% c("s1", "s2"), ]swapped <- aggregate(od ~ ann_id, data = swapped, FUN = mean)swapped$conc <- nominal[swapped$ann_id]batch_colours <- c(Batch1 = "#4c72b0", Batch2 = "#dd8452")
curve_panel <- ggplot() + geom_line(data = curves, aes(conc, od, colour = batch, group = factor(plate))) + geom_point(data = level_points, aes(conc, od, colour = batch), size = 1.6) + geom_point(data = swapped, aes(conc, od), shape = 4, size = 3, stroke = 1.2) + annotate("text", x = 1500, y = 2.62, label = "plate 4 as annotated", hjust = 1, size = 3) + scale_x_log10() + scale_colour_manual(values = batch_colours) + labs(x = "concentration, pg/mL", y = "OD 450 - 620 nm", colour = NULL, title = "4PL of each plate, SoftMax layout") + theme_bw(base_size = 10)
placed <- samples[!is.na(samples$back), ]placed$kind <- ifelse(placed$id == "Control", "Control", "sample")range_panel <- ggplot() + geom_segment(data = limits, aes(x = lloq, xend = uloq, y = plate, yend = plate), linewidth = 5, colour = "grey85") + geom_point(data = limits, aes(lod, plate), shape = 124, size = 6) + geom_point(data = placed, aes(back, plate, colour = kind), size = 1.6, position = position_jitter(width = 0, height = 0.15, seed = 1)) + scale_x_log10() + scale_y_reverse(breaks = 1:5) + scale_colour_manual(values = c(Control = "#c44e52", sample = "grey30")) + labs(x = "back-calculated concentration, pg/mL", y = "plate", colour = NULL, title = "LOD (bar), LLOQ to ULOQ (band)") + theme_bw(base_size = 10)
ggsave("outputs/elisa-limits-plates_plates_r.png", curve_panel + range_panel, width = 10, height = 4, dpi = 120)
# The gate compares these values with the Python tab.metrics <- list( n_in_range = sum(patients$status == "in range"), n_samples = nrow(patients), n_flagged = sum(samples$flag), n_masked_triplicates = sum(samples$masked), n_wells_below_c = sum(is.na(unknowns$back)), control_cv_plates = CvPercent(control$back))for (plate in seq_len(nrow(fits))) { values <- c( unlist(audit[plate, -1]), ann_mono = defect$ann_mono[plate], ann_rse = defect$ann_rse[plate], fix_rse = defect$fix_rse[plate], fits[plate, ], unlist(limits[plate, -1]), od_sum = sum(wells$od[wells$plate == plate & !is.na(wells$id)]), control = control$back[plate], control_cv = control$cv_back[plate], counts[as.character(plate), ] ) names(values) <- paste0(gsub(" ", "_", names(values)), "_p", plate) metrics <- c(metrics, as.list(values))}jsonlite::write_json(metrics, "outputs/elisa-limits-plates_metrics_r.json", auto_unbox = TRUE, digits = NA)plate batch b c d e Control CV %1 Batch1 -1.1035 0.0290 5.99 4283 873.3 3.72 Batch1 -0.9688 0.0030 5.30 4395 714.6 11.53 Batch1 -1.1712 0.0231 3.76 2536 682.7 1.94 Batch2 -1.2168 0.0518 3.18 1200 473.8 7.65 Batch2 -0.9217 0.0187 4.37 2627 577.1 9.8Control mean by batch: Batch1 756.8, Batch2 525.4Control CV across the five plates: 22.6%
control = samples[samples["id"] == "Control"].sort_values("plate")fit_table = pd.DataFrame(fits).Tprint(f"{'plate':<5} {'batch':<6} {'b':>7} {'c':>7} {'d':>5} {'e':>6} " f"{'Control':>8} {'CV %':>5}")for (_, row), (_, fit) in zip(control.iterrows(), fit_table.iterrows()): print(f"{row['plate']:<5} {row['batch']:<6} {fit['b']:7.4f} " f"{fit['c']:7.4f} {fit['d']:5.2f} {fit['e']:6.0f} " f"{row['back']:8.1f} {row['cv_back']:5.1f}")by_batch = control.groupby("batch")["back"].mean()print("Control mean by batch: " + ", ".join(f"{batch} {mean:.1f}" for batch, mean in by_batch.items()))print(f"Control CV across the five plates: " f"{cv_percent(control['back']):.1f}%")
colours = {"Batch1": "#4c72b0", "Batch2": "#dd8452"}grid = np.geomspace(30, 4000, 200)figure, (curve_axis, range_axis) = plt.subplots(1, 2, figsize=(10, 4))standards = wells[(wells["group"] == "Standards") & (wells["conc"] > 0)]for plate, fit in fits.items(): batch = control.loc[control["plate"] == plate, "batch"].iloc[0] curve_axis.plot(grid, ll4(grid, *[fit[k] for k in "bcde"]), color=colours[batch]) means = standards[standards["plate"] == plate].groupby("conc")["od"] curve_axis.scatter(means.mean().index, means.mean(), s=12, color=colours[batch])swapped = wells[(wells["plate"] == 4) & wells["ann_id"].isin(["s1", "s2"])]swapped = swapped.groupby("ann_id")["od"].mean()curve_axis.scatter(swapped.index.map(NOMINAL), swapped, marker="x", s=60, color="black", label="plate 4 as annotated")for batch, colour in colours.items(): curve_axis.plot([], [], color=colour, label=batch)curve_axis.set_xscale("log")curve_axis.set_xlabel("concentration, pg/mL")curve_axis.set_ylabel("OD 450 - 620 nm")curve_axis.set_title("4PL of each plate, SoftMax layout", fontsize=10)curve_axis.legend(fontsize=8, frameon=False)
placed = samples[samples["back"].notna()]jitter = np.random.default_rng(1).uniform(-0.15, 0.15, len(placed))for _, row in limits.iterrows(): range_axis.plot([row["lloq"], row["uloq"]], [row["plate"]] * 2, color="0.85", linewidth=8, solid_capstyle="butt") range_axis.plot([row["lod"]] * 2, [row["plate"] - 0.3, row["plate"] + 0.3], color="black")is_control = (placed["id"] == "Control").to_numpy()range_axis.scatter(placed["back"][~is_control], placed["plate"][~is_control] + jitter[~is_control], s=12, color="0.2", zorder=3, label="sample")range_axis.scatter(placed["back"][is_control], placed["plate"][is_control], s=16, color="#c44e52", zorder=3, label="Control")range_axis.set_xscale("log")range_axis.invert_yaxis()range_axis.set_yticks(range(1, 6))range_axis.set_xlabel("back-calculated concentration, pg/mL")range_axis.set_ylabel("plate")range_axis.set_title("LOD (bar), LLOQ to ULOQ (band)", fontsize=10)range_axis.legend(fontsize=8, frameon=False, loc="lower right")figure.tight_layout()figure.savefig("outputs/elisa-limits-plates_plates_python.png", dpi=120)
# The gate compares these values with the R tab.metrics = { "n_in_range": int(in_range), "n_samples": len(patients), "n_flagged": int(samples["flag"].sum()), "n_masked_triplicates": int(samples["masked"].sum()), "n_wells_below_c": int(unknowns["back"].isna().sum()), "control_cv_plates": float(cv_percent(control["back"])),}for plate in fits: values = audit.set_index("plate").loc[plate].to_dict() values.update(defect.set_index("plate").loc[plate].to_dict()) values.update({k: fits[plate][k] for k in "bcde"}) values.update(limits.set_index("plate").loc[plate].to_dict()) named = wells[(wells["plate"] == plate) & wells["id"].notna()] values["od_sum"] = named["od"].sum() row = control[control["plate"] == plate].iloc[0] values.update({"control": row["back"], "control_cv": row["cv_back"]}) values.update(counts.loc[plate].to_dict()) values.pop("fix_mono") for key, value in values.items(): metrics[f"{key.replace(' ', '_')}_p{plate}"] = float(value)pathlib.Path("outputs/elisa-limits-plates_metrics_python.json").write_text( json.dumps(metrics, indent=2) + "\n")plate batch b c d e Control CV %1 Batch1 -1.1035 0.0290 5.99 4283 873.3 3.72 Batch1 -0.9688 0.0030 5.30 4395 714.6 11.53 Batch1 -1.1712 0.0231 3.76 2536 682.7 1.94 Batch2 -1.2168 0.0518 3.18 1200 473.8 7.65 Batch2 -0.9217 0.0187 4.37 2627 577.1 9.8Control mean by batch: Batch1 756.8, Batch2 525.4Control CV across the five plates: 22.6%
The Batch2 curves sit above the Batch1 curves over most of the range, and plate 4 bends
early, with e at 1,200 pg/mL where the other plates sit between 2,536 and 4,395. A plate
that gives more OD for the same concentration reads every sample lower, and the Control
drops from a mean of 756.8 pg/mL in Batch1 to 525.4 in Batch2. Within a plate its CV stays
between 1.9% and 11.5%, but across the five plates it reaches 22.6%. That is the problem
ELISAtools was written for: the standard curve moved between batches and took every
sample with it.
The ELISAtools batch correction, in R only
Section titled “The ELISAtools batch correction, in R only”ELISAtools has no Python counterpart.
Feng et al. 2019 fit one reference 5PL
shape to the standards of every plate and give each plate a shift factor S along the log
concentration axis. runFit() fixes the two asymptotes at the lowest and highest standard
OD of all plates and adds a tenth of the lowest nonzero standard to every concentration,
so that the blank fits on a log axis. predictAll() reads each sample off its plate’s
shifted curve, then multiplies it by exp(S) for the mean S of its batch.
# Rebuild the two batches from the runs read with the SoftMax layout.fixed_batches <- list()for (batch_id in unique(design$Batch)) { runs <- fixed_runs[design$Batch == batch_id] range_ods <- sapply(runs, slot, "range.ODs") batch <- elisa_batch() batch@batchID <- batch_id batch@runs <- runs batch@num.runs <- length(runs) batch@range.ODs <- c(min(range_ods[1, ]), max(range_ods[2, ])) fixed_batches[[batch_id]] <- batch}
# One 5PL shape for every plate, from the start values of the package# tutorial. Each plate moves along log concentration by its S factor.start <- c(xmid = 7.2, scal = 0.5, g = 0.015)fit_log <- capture.output( fixed_batches <- runFit(pars = start, batches = fixed_batches, refBatch.ID = 1, model = "5pl"))fixed_batches <- predictAll(fixed_batches)shared <- fixed_batches[[1]]@parscat(sprintf("shared 5PL: %s\n", paste(names(shared), sprintf("%.4f", shared), collapse = ", ")))cat(sprintf("%-5s %-6s %7s %8s %8s %10s\n", "plate", "batch", "S", "batch S", "Control", "corrected"))plate <- 0corrected <- data.frame()for (batch in fixed_batches) { for (run in batch@runs) { for (eplate in run@plates) { plate <- plate + 1 means <- eplate@mdata.unknown ctrl <- means[means$ID == "Control", ] corrected <- rbind(corrected, data.frame( plate = plate, raw = ctrl$conc_pred, bc = ctrl$conc_pred.bc )) cat(sprintf("%-5d %-6s %7.4f %8.4f %8.1f %10.1f\n", plate, batch@batchID, eplate@normFactor, batch@normFactor, ctrl$conc_pred, ctrl$conc_pred.bc)) } }}cat(sprintf("Control CV across plates: %.1f%% before, %.1f%% after\n", CvPercent(corrected$raw), CvPercent(corrected$bc)))shared 5PL: a 0.0192, d 2.6608, xmid 7.9966, scal 0.3444, g 0.3085plate batch S batch S Control corrected1 Batch1 0.0960 0.0047 807.5 811.42 Batch1 0.0000 0.0047 744.4 747.93 Batch1 -0.0817 0.0047 694.1 697.44 Batch2 0.4187 0.3460 516.3 729.85 Batch2 0.2732 0.3460 653.4 923.5Control CV across plates: 16.0% before, 11.4% afterBatch2 gets a mean S of 0.3460, and the Control CV across plates falls from 16.0% to 11.4%. The correction overshoots on plate 5, whose Control moves from 653.4 to 923.5 pg/mL, above every Batch1 plate. It assumes that each sample moved with the standards of its batch, which fits a change of kit lot but not a plate with an error of its own. The uncorrected Control of plate 1 reads 807.5 rather than the 873.3 pg/mL of the 4PL table, because one shape with fixed asymptotes now serves all five plates.
How this step fails
Section titled “How this step fails”- A swapped standard still gives a converged fit. Check that the mean OD falls at every step, and compare the annotation with the export before you fit.
- An LOD from three blank wells moves with their scatter, more than three-fold across these five plates.
- A batch correction moves every sample of a batch at once. It needs a control on every plate to check it, and it cannot repair the error of a single plate.
The code for this page is in the companion repository under
guides/proteomics/elisa-limits-plates/.
Scientific references
Section titled “Scientific references”The ELISAtools package by Feng supplies ELISA data analysis with batch correction.
The drc package by Ritz and Streibig fits dose-response models in R.
Further reading
Section titled “Further reading”Feng and colleagues, 2019, describe shifts between ELISA kit lots and the batch correction implemented in ELISAtools. Compare their study design with the five plates and two batches examined here. The man/loadData.Rd reference in the ELISAtools 0.1.8 source package explains how its design file connects plates, annotations, and batches.
The ICH M10 guideline describes validation of ligand binding assays, including calibration and quality controls. Read its intended regulatory scope before treating a diagnostic rule from this teaching example as an assay acceptance limit.