The ELISA Standard Curve
A plate reader measures how much light each well absorbs, not how much protein it holds. A dilution series of a known standard on the same plate gives the curve that converts one into the other. This page fits that curve to one real plate, compares a four and a five parameter logistic model, and back-calculates fifteen samples and a control.
The plate
Section titled “The plate”The data are the example files of ELISAtools
0.1.8, the package that Feng et al. 2019
wrote to correct the shift between ELISA kit lots. Three SoftMax Pro text exports hold
five 96-well plates in two batches, and this page uses plate 1 of Batch1, Assay_2.txt.
Columns 1 to 3 hold eight standards in triplicate, from 3,000 pg/mL down in two-fold steps
to 46.875 pg/mL, then a 0 pg/mL blank. Fifteen samples and one control fill columns 4 to
11. The optical density, OD, is the 450 nm read minus a 620 nm reference read that corrects
for flaws in the plate itself.
The R tab reads the plate with loadData(), which takes the ODs from the export and the
name of each well from an annotation file that ships with the package. The Python tab
parses the export itself, including the groups where SoftMax Pro records which sample sits
in which well.
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]
# loadData() reads design.txt, each SoftMax export it lists and the# annotation file of each plate. It prints its progress with cat().progress <- capture.output( batches <- loadData(file.path(elisa_dir, "design.txt")))plate_1 <- batches[["Batch1"]]@runs[[1]]@plates[[1]]
# ELISAtools keeps standards and unknowns in two tables. Its OD is the# 450 nm read minus the 620 nm read.ann_std <- plate_1@data.stdann_unknown <- plate_1@data.unknownann_wells <- data.frame( well = paste0(plate_rows[c(ann_std$row, ann_unknown$row)], c(ann_std$col, ann_unknown$col)), ann_id = c(ann_std$ID, ann_unknown$ID), od = c(ann_std$OD, ann_unknown$OD))cat(sprintf("ELISAtools read %d wells: %d standard, %d unknown\n", nrow(ann_wells), nrow(ann_std), nrow(ann_unknown)))
#' Print the OD of each well as an 8 x 12 plate grid.#'#' @param wells A data frame with well and od columns.#' @return NULL, invisibly. A well that is not in the table prints a dot.PrintPlateGrid <- function(wells) { cat(sprintf("%-2s%s\n", "", paste(sprintf("%6d", 1:12), collapse = ""))) for (row in plate_rows) { od <- wells$od[match(paste0(row, 1:12), wells$well)] cells <- ifelse(is.na(od), " .", sprintf("%6.3f", od)) cat(sprintf("%-2s%s\n", row, paste(cells, collapse = ""))) } invisible(NULL)}
PrintPlateGrid(ann_wells)
# Write every digit, so that the Python tab can compare the ODs exactly.dir.create("outputs", showWarnings = FALSE)write.csv(transform(ann_wells, od = sprintf("%.17g", od)), "outputs/elisa-standard-curve_wells_r.csv", row.names = FALSE)ELISAtools read 72 wells: 24 standard, 48 unknown 1 2 3 4 5 6 7 8 9 10 11 12A 2.204 2.661 2.417 . . . . . . . . .B 1.376 1.587 1.429 0.046 0.042 0.038 0.096 0.078 0.092 0.110 0.098 .C 0.653 0.903 0.743 0.039 0.038 0.038 0.104 0.110 0.114 0.091 0.068 .D 0.369 0.463 0.432 0.057 0.037 0.039 0.069 0.063 0.082 0.073 0.079 .E 0.178 0.227 0.246 0.041 0.038 0.038 0.074 0.076 0.080 0.085 0.088 .F 0.105 0.136 0.122 0.042 0.042 0.044 0.059 0.061 0.069 0.081 0.939 .G 0.059 0.053 0.062 0.064 0.056 0.058 0.096 0.100 0.099 0.906 0.877 .H 0.028 0.037 0.024 . . . . . . . . .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.
import jsonimport pathlib
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport scipy.optimizeimport scipy.stats
ELISA_DIR = pathlib.Path("/opt/data/elisa")PLATE_ROWS = "ABCDEFGH"
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.
A block starts at a "Plate:" line. The next line names the 96 wells, and each data line holds an empty field, the temperature and one value per well. The first data line is the 450 nm read and the second is the 620 nm reference read.
Args: path: Path to the SoftMax Pro text export.
Returns: A list with one DataFrame per plate: well, od_450, od_620 and od, the 450 nm value minus the 620 nm value. """ 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)]]) plate = pd.DataFrame( {"well": wells, "od_450": reads[0], "od_620": reads[1]} ) plate["od"] = plate["od_450"] - plate["od_620"] plates.append(plate) return plates
def read_softmax_layout(path): """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.
Args: path: Path to a SoftMax Pro text export.
Returns: A DataFrame with one row per well: plate, group, sample, well, the concentration in pg/mL for a standard, whether SoftMax masked the well, and an id in the style of ELISAtools, s1 to s8 for the standards. """ 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) layout["id"] = np.where( layout["group"] == "Standards", "s" + layout["sample"], np.where(layout["group"] == "Control", "Control", layout["sample"]), ) return layout
def print_plate_grid(wells): """Print the OD of each well as an 8 x 12 plate grid.
Args: wells: A DataFrame with well and od columns. A well that is not in the table prints a dot. """ od_by_well = wells.set_index("well")["od"] print(" " + "".join(f"{column:6d}" for column in range(1, 13))) for row in PLATE_ROWS: cells = [] for column in range(1, 13): od = od_by_well.get(f"{row}{column}") cells.append(" ." if od is None else f"{od:6.3f}") print(f"{row:<2}" + "".join(cells))
plates = read_softmax_plates(ELISA_DIR / "Assay_2.txt")plate_1 = plates[0]layout = read_softmax_layout(ELISA_DIR / "Assay_2.txt")layout = layout[layout["plate"] == 1]wells = layout.merge(plate_1[["well", "od"]], on="well")print(f"SoftMax export: {len(plates)} plate block, {len(plate_1)} wells " f"read, {len(wells)} named by the groups")print_plate_grid(wells)
# R runs first and writes the wells that ELISAtools read.r_wells = pd.read_csv("outputs/elisa-standard-curve_wells_r.csv")both = wells.merge(r_wells, on="well", suffixes=("", "_r"))od_gap = np.abs(both["od"] - both["od_r"]).max()print(f"wells shared with the ELISAtools read in R: {len(both)} of " f"{len(r_wells)}; largest OD difference {od_gap:g}")SoftMax export: 1 plate block, 96 wells read, 72 named by the groups 1 2 3 4 5 6 7 8 9 10 11 12A 2.204 2.661 2.417 . . . . . . . . .B 1.376 1.587 1.429 0.046 0.042 0.038 0.096 0.078 0.092 0.110 0.098 .C 0.653 0.903 0.743 0.039 0.038 0.038 0.104 0.110 0.114 0.091 0.068 .D 0.369 0.463 0.432 0.057 0.037 0.039 0.069 0.063 0.082 0.073 0.079 .E 0.178 0.227 0.246 0.041 0.038 0.038 0.074 0.076 0.080 0.085 0.088 .F 0.105 0.136 0.122 0.042 0.042 0.044 0.059 0.061 0.069 0.081 0.939 .G 0.059 0.053 0.062 0.064 0.056 0.058 0.096 0.100 0.099 0.906 0.877 .H 0.028 0.037 0.024 . . . . . . . . .wells shared with the ELISAtools read in R: 72 of 72; largest OD difference 0The Python parser found the same 72 wells as ELISAtools, with an OD difference of 0, and the dots are wells that neither file assigns. Every well in columns 4 to 11 reads 0.114 or less, except F11, G10 and G11 near 0.9.
Which well holds which sample
Section titled “Which well holds which sample”The annotation file and the SoftMax groups both name the 72 wells. The code lists each SoftMax triplicate with the IDs the annotation gives its wells.
#' 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, sample, well,#' the concentration in pg/mL for a standard, whether SoftMax masked the#' well, and an id in the style of ELISAtools, s1 to s8 for the standards.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", layout$sample) ) layout}
#' Join the distinct annotation IDs of one triplicate.#'#' @param ids The ELISAtools IDs of the wells of one SoftMax sample.#' @return The sorted distinct IDs joined with a plus sign.JoinIds <- function(ids) { paste(sort(unique(ids)), collapse = "+")}
#' 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)}
layout <- ReadSoftMaxLayout(file.path(elisa_dir, "Assay_2.txt"))layout <- layout[layout$plate == 1, ]wells <- merge(layout, ann_wells, by = "well")cat(sprintf("wells in both layouts: %d\n", nrow(wells)))
# A triplicate agrees when the annotation gives its three wells one ID.ann_ids <- tapply(wells$ann_id, wells$id, JoinIds)same_wells <- !grepl("+", ann_ids, fixed = TRUE)renamed <- same_wells & tolower(ann_ids) != tolower(names(ann_ids))cat(sprintf("triplicates with the same three wells: %d of %d\n", sum(same_wells), length(ann_ids)))cat(sprintf(" of these, under another name: %d\n", sum(renamed)))cat("triplicates that the annotation splits:\n")for (id in names(ann_ids)[!same_wells]) { split_wells <- wells[wells$id == id, ] cat(sprintf(" %-8s %-12s annotation: %s\n", id, paste(split_wells$well, collapse = " "), paste(split_wells$ann_id, collapse = " ")))}ann_control <- ann_wells[ann_wells$ann_id == "Control", ]cat(sprintf("annotation Control %s: OD %s, CV %.1f%%\n", paste(ann_control$well, collapse = " "), paste(sprintf("%.3f", ann_control$od), collapse = " "), CvPercent(ann_control$od)))for (group in unique(wells$group)) { masked <- sort(wells$well[wells$masked & wells$group == group]) if (length(masked) == 0) masked <- "none" cat(sprintf("SoftMax masked in %s: %s\n", group, paste(masked, collapse = " ")))}wells in both layouts: 72triplicates with the same three wells: 20 of 24 of these, under another name: 9triplicates that the annotation splits: Control F11 G10 G11 annotation: Control P14 Control P12 C11 D10 D11 annotation: P15 P13 P15 P14 E10 E11 F10 annotation: P14 Control P14 P15 B10 B11 C10 annotation: P13 P15 P13annotation Control E11 F11 G11: OD 0.088 0.939 0.877, CV 74.7%SoftMax masked in Standards: C1 E1 F1 G2SoftMax masked in Unk_Dilution: B6 D4 D9 E4SoftMax masked in Control: nonedef read_annotation(path, plate_name="plate 1"): """Read the ID of each well from an ELISAtools annotation file.
Args: path: Path to the annotation file, for example AnExp_2plate.txt. plate_name: The name after "Plate:" of the block to read.
Returns: A DataFrame with the columns well and ann_id. """ lines = read_lines(path) start = next(i for i, line in enumerate(lines) if line.split("\t")[:2] == ["Plate:", plate_name]) 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 annotation IDs of one triplicate.
Args: ids: The ELISAtools IDs of the wells of one SoftMax sample.
Returns: The sorted distinct IDs joined with a plus sign. """ return "+".join(sorted(set(ids)))
def cv_percent(values): """Coefficient of variation in percent.
Args: values: A pandas Series.
Returns: 100 times the sample standard deviation over the mean. """ return 100 * values.std() / values.mean()
annotation = read_annotation(ELISA_DIR / "AnExp_2plate.txt")wells = wells.merge(annotation, on="well")print(f"wells in both layouts: {len(wells)}")
# A triplicate agrees when the annotation gives its three wells one ID.ann_ids = wells.groupby("id")["ann_id"].agg(join_ids)same_wells = ~ann_ids.str.contains("+", regex=False)renamed = same_wells & (ann_ids.str.lower() != ann_ids.index.str.lower())print(f"triplicates with the same three wells: {same_wells.sum()} of " f"{len(ann_ids)}")print(f" of these, under another name: {renamed.sum()}")print("triplicates that the annotation splits:")for sample_id in sorted(ann_ids.index[~same_wells]): split = wells[wells["id"] == sample_id].sort_values("well") print(f" {sample_id:<8} {' '.join(split['well']):<12} annotation: " f"{' '.join(split['ann_id'])}")ann_control = wells[wells["ann_id"] == "Control"].sort_values("well")ods = " ".join(f"{od:.3f}" for od in ann_control["od"])print(f"annotation Control {' '.join(ann_control['well'])}: OD {ods}, " f"CV {cv_percent(ann_control['od']):.1f}%")for group in wells["group"].unique(): masked = wells.loc[wells["masked"] & (wells["group"] == group), "well"] print(f"SoftMax masked in {group}: {' '.join(sorted(masked)) or 'none'}")wells in both layouts: 72triplicates with the same three wells: 20 of 24 of these, under another name: 9triplicates that the annotation splits: Control F11 G10 G11 annotation: Control P14 Control P12 C11 D10 D11 annotation: P15 P13 P15 P14 E10 E11 F10 annotation: P14 Control P14 P15 B10 B11 C10 annotation: P13 P15 P13annotation Control E11 F11 G11: OD 0.088 0.939 0.877, CV 74.7%SoftMax masked in Standards: C1 E1 F1 G2SoftMax masked in Unk_Dilution: B6 D4 D9 E4SoftMax masked in Control: noneTwenty of the 24 triplicates hold the same three wells in both files, though 9 of them carry another name: the sample SoftMax calls P2 is P4 in the annotation. The four split triplicates are worse. SoftMax groups columns 10 and 11 across each row, B10, B11 and C10 for P15, while the annotation groups them down each column. Read through the annotation, the Control takes well E11 at 0.088 next to two wells near 0.9, for a CV of 74.7%, and a CV like that points at the layout before it points at the pipette. This page takes the layout from the SoftMax groups, the record the plate reader software kept with the data.
SoftMax also masked 8 wells and left them out of its own means. ELISAtools reads them like any other well, and so does this page.
The standards and the blank
Section titled “The standards and the blank”standards <- wells[wells$group == "Standards", ]level_od <- aggregate(od ~ conc, data = standards, FUN = mean)level_sd <- aggregate(od ~ conc, data = standards, FUN = sd)levels <- data.frame( conc = level_od$conc, mean_od = level_od$od, sd_od = level_sd$od, cv_pct = 100 * level_sd$od / level_od$od)levels <- levels[order(-levels$conc), ]cat(sprintf("%9s %8s %7s %6s\n", "pg/mL", "mean OD", "SD", "CV %"))cat(sprintf("%9.3f %8.4f %7.4f %6.1f\n", levels$conc, levels$mean_od, levels$sd_od, levels$cv_pct), sep = "")blank_od <- standards$od[standards$conc == 0] pg/mL mean OD SD CV % 3000.000 2.4276 0.2284 9.4 1500.000 1.4640 0.1094 7.5 750.000 0.7666 0.1266 16.5 375.000 0.4216 0.0478 11.3 187.500 0.2172 0.0353 16.2 93.750 0.1210 0.0154 12.7 46.875 0.0579 0.0045 7.8 0.000 0.0296 0.0070 23.6standards = wells[wells["group"] == "Standards"]levels = (standards.groupby("conc")["od"].agg(["mean", "std"]) .sort_index(ascending=False))levels["cv"] = 100 * levels["std"] / levels["mean"]print(f"{'pg/mL':>9} {'mean OD':>8} {'SD':>7} {'CV %':>6}")for conc, level in levels.iterrows(): print(f"{conc:9.3f} {level['mean']:8.4f} {level['std']:7.4f} " f"{level['cv']:6.1f}")blank_od = standards.loc[standards["conc"] == 0, "od"] pg/mL mean OD SD CV % 3000.000 2.4276 0.2284 9.4 1500.000 1.4640 0.1094 7.5 750.000 0.7666 0.1266 16.5 375.000 0.4216 0.0478 11.3 187.500 0.2172 0.0353 16.2 93.750 0.1210 0.0154 12.7 46.875 0.0579 0.0045 7.8 0.000 0.0296 0.0070 23.6The blank is the 0 pg/mL standard, with a mean OD of 0.0296 and a CV of 23.6%. Kit
protocols subtract it from every well, and
ICH M10
leaves it out of the fit, as the
experimental design page explains. This page
keeps it in the fit at 0 pg/mL. A log-logistic curve equals its lower asymptote c at
zero concentration, so the blank wells inform c directly, while subtraction only shifts
c and adds the noise of three wells to every other well. M10 also asks for data near
both asymptotes before a 4PL or 5PL, and here the blank is the only data near the lower
one, since the lowest standard still reads 0.0579.
The standards halve at every step, so on a log axis the seven nonzero levels sit at equal distances and each one pins a different stretch of the curve. On a linear axis, 46.875, 93.75, 187.5 and 375 pg/mL crowd into the first eighth of the range. Binding responds to ratios of concentration, and a two-fold pipetting error spans the same distance on a log axis at both ends of the series. That is why the logistic models below take log concentration as their input.
Four or five parameters
Section titled “Four or five parameters”drc fits the log-logistic models of
Ritz et al. 2015. The four parameter
model, LL.4, is
f(x) = c + (d - c) / (1 + exp(b * (log(x) - log(e))))where c is the OD at zero concentration, d the OD at infinite concentration, e the
concentration halfway between them, and b the slope, negative for a rising curve. The
five parameter LL.5 raises the denominator to a power f, so the curve can approach its
two plateaus at different speeds. The Python tab writes the same functions for
scipy.optimize.curve_fit.
# The blank wells stay in the fit at 0 pg/mL, where the curve equals c.cat(sprintf("fit on %d wells, %d levels\n", nrow(standards), length(unique(standards$conc))))
# The default BFGS search stops early on a flat 5PL surface.# Nelder-Mead with a tight tolerance reaches the SciPy minimum.fit_control <- drmc(method = "Nelder-Mead", relTol = 1e-15, maxIt = 1e5)fit_4pl <- drm(od ~ conc, data = standards, control = fit_control, fct = LL.4(names = c("b", "c", "d", "e")))fit_5pl <- drm(od ~ conc, data = standards, control = fit_control, fct = LL.5(names = c("b", "c", "d", "e", "f")))
#' Summarize one drc fit in a named vector.#'#' @param fit A fitted drc model.#' @return The estimates, the residual standard error, the AIC and the#' p value of the lack-of-fit test against one mean per standard level.SummarizeFit <- function(fit) { estimates <- coef(fit) names(estimates) <- sub(":\\(Intercept\\)$", "", names(estimates)) c(estimates, rse = summary(fit)$rseMat[1, "rse"], aic = AIC(fit), lof_p = modelFit(fit)[2, "p value"])}
summary_4pl <- SummarizeFit(fit_4pl)summary_5pl <- SummarizeFit(fit_5pl)cat(sprintf("%-6s %12s %12s\n", "", "4PL", "5PL"))for (row in c("b", "c", "d", "e", "f", "rse", "aic", "lof_p")) { left <- if (row == "f") "1 (fixed)" else format(summary_4pl[[row]], digits = 6) cat(sprintf("%-6s %12s %12s\n", row, left, format(summary_5pl[[row]], digits = 6)))}nested <- anova(fit_4pl, fit_5pl, details = FALSE)cat(sprintf("F test, 5PL against 4PL: F = %.3f, p = %.3f\n", nested[2, "F value"], nested[2, "p value"]))
# drc takes standard errors from the Hessian; curve_fit in the Python tab# uses the Jacobian, so the two differ in the third digit.se_4pl <- sqrt(diag(vcov(fit_4pl)))cat(sprintf("4PL d = %.2f OD, SE %.2f; top standard mean OD %.3f\n", summary_4pl[["d"]], se_4pl[3], max(levels$mean_od)))cat(sprintf("4PL e = %.0f pg/mL, SE %.0f; top standard %.0f pg/mL\n", summary_4pl[["e"]], se_4pl[4], max(levels$conc)))cat(sprintf("correlation of d and e: %.3f\n", cov2cor(vcov(fit_4pl))[3, 4]))cat(sprintf("4PL c = %.4f OD; blank mean %.4f, SD %.4f\n", summary_4pl[["c"]], mean(blank_od), sd(blank_od)))fit on 24 wells, 8 levels 4PL 5PLb -1.1035 -5.0205c 0.028969 0.0185076d 5.98569 2.70756e 4283.17 2860.53f 1 (fixed) 0.189317rse 0.0924526 0.0944911aic -40.5575 -38.7417lof_p 0.990053 0.983573F test, 5PL against 4PL: F = 0.146, p = 0.7064PL d = 5.99 OD, SE 2.65; top standard mean OD 2.4284PL e = 4283 pg/mL, SE 3056; top standard 3000 pg/mLcorrelation of d and e: 0.9984PL c = 0.0290 OD; blank mean 0.0296, SD 0.0070def ll5(conc, b, c, d, e, f): """Evaluate the drc LL.5 model.
f(x) = c + (d - c) / (1 + exp(b (log x - log e)))^f. With b < 0 the curve rises, and at x = 0 it equals c, as in drc.
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 of the 4PL. f: Asymmetry. f = 1 gives the 4PL.
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 ** f
def ll4(conc, b, c, d, e): """Evaluate the drc LL.4 model, the LL.5 model with f = 1.
Args: conc: Concentrations in pg/mL, a NumPy array. b: Slope. c: Lower asymptote. d: Upper asymptote. e: Inflection concentration.
Returns: The model ODs, a NumPy array. """ return ll5(conc, b, c, d, e, 1.0)
def fit_curve(model, conc, od, n_params): """Fit LL.4 or LL.5 by least squares and summarize the fit.
Args: model: ll4 or ll5. conc: Standard concentrations, a NumPy array. od: Standard ODs, a NumPy array. n_params: 4 or 5.
Returns: A dict with the estimates, their standard errors, the residual sum of squares, the residual standard error, the AIC as drc computes it, the p value of the lack-of-fit test against one mean per level, and the correlation of d and e. """ start = [-1.0, od.min(), od.max(), np.median(conc[conc > 0]), 1.0] lower = [-np.inf, -np.inf, -np.inf, 1e-9, 1e-9] params, cov = scipy.optimize.curve_fit( model, conc, od, p0=start[:n_params], bounds=(lower[:n_params], np.inf), method="trf", xtol=1e-15, ftol=1e-15, gtol=1e-15, max_nfev=100000, ) n_obs = len(od) rss = float(np.sum((od - model(conc, *params)) ** 2)) # drc uses the Gaussian log-likelihood with the variance RSS / n. log_lik = -n_obs / 2 * (np.log(2 * np.pi * rss / n_obs) + 1) # Pure error: the scatter of each level around its own mean. level_means = pd.Series(od).groupby(conc).transform("mean").to_numpy() pure_ss = float(np.sum((od - level_means) ** 2)) pure_df = n_obs - len(np.unique(conc)) lof_df = n_obs - n_params - pure_df lof_f = ((rss - pure_ss) / lof_df) / (pure_ss / pure_df) names = "bcdef"[:n_params] summary = dict(zip(names, params)) summary.update({f"se_{name}": se for name, se in zip(names, np.sqrt(np.diag(cov)))}) summary.update({ "rss": rss, "rse": np.sqrt(rss / (n_obs - n_params)), "aic": -2 * log_lik + 2 * (n_params + 1), "lof_p": scipy.stats.f.sf(lof_f, lof_df, pure_df), "cor_de": cov[2, 3] / np.sqrt(cov[2, 2] * cov[3, 3]), }) return summary
# The blank wells stay in the fit at 0 pg/mL, where the curve equals c.conc = standards["conc"].to_numpy()od = standards["od"].to_numpy()print(f"fit on {len(od)} wells, {len(np.unique(conc))} levels")fit_4pl = fit_curve(ll4, conc, od, 4)fit_5pl = fit_curve(ll5, conc, od, 5)print(f"{'':6} {'4PL':>12} {'5PL':>12}")for row in ["b", "c", "d", "e", "f", "rse", "aic", "lof_p"]: left = f"{fit_4pl[row]:.6g}" if row in fit_4pl else "1 (fixed)" print(f"{row:<6} {left:>12} {fit_5pl[row]:>12.6g}")df_5pl = len(od) - 5f_value = (fit_4pl["rss"] - fit_5pl["rss"]) / (fit_5pl["rss"] / df_5pl)print(f"F test, 5PL against 4PL: F = {f_value:.3f}, " f"p = {scipy.stats.f.sf(f_value, 1, df_5pl):.3f}")
# curve_fit takes standard errors from the Jacobian; drc in the R tab# uses the Hessian, so the two differ in the third digit.print(f"4PL d = {fit_4pl['d']:.2f} OD, SE {fit_4pl['se_d']:.2f}; " f"top standard mean OD {levels['mean'].max():.3f}")print(f"4PL e = {fit_4pl['e']:.0f} pg/mL, SE {fit_4pl['se_e']:.0f}; " f"top standard {conc.max():.0f} pg/mL")print(f"correlation of d and e: {fit_4pl['cor_de']:.3f}")print(f"4PL c = {fit_4pl['c']:.4f} OD; blank mean {blank_od.mean():.4f}, " f"SD {blank_od.std():.4f}")fit on 24 wells, 8 levels 4PL 5PLb -1.1035 -5.0205c 0.028969 0.0185076d 5.98569 2.70756e 4283.17 2860.53f 1 (fixed) 0.189317rse 0.0924526 0.0944911aic -40.5575 -38.7417lof_p 0.990053 0.983573F test, 5PL against 4PL: F = 0.146, p = 0.7064PL d = 5.99 OD, SE 2.64; top standard mean OD 2.4284PL e = 4283 pg/mL, SE 3042; top standard 3000 pg/mLcorrelation of d and e: 0.9984PL c = 0.0290 OD; blank mean 0.0296, SD 0.0070The fifth parameter buys nothing here. The residual standard error rises once the extra
degree of freedom is paid for, the 4PL has the lower AIC, and the F test of the nested
pair gives p = 0.706. The lack-of-fit test, lof_p, asks whether a curve misses the eight
level means by more than the replicates scatter, and both curves pass it with ease. This
page uses the 4PL.
Its asymptotes lie beyond the data. The 4PL puts d at 5.99 OD, more than twice the 2.428
of the top standard, and e at 4,283 pg/mL, above the top standard of 3,000. The OD still
climbs from 1.464 to 2.428 across the last doubling, so the plate never shows its upper
plateau and the fit can only extrapolate one. That is why d and e correlate at 0.998:
the standards fix the curve inside their range and leave its course above it open. The 5PL
reads the same data as a curve that flattens early, with d at 2.70756. Do not report d
or e as properties of the assay. At the bottom, the blank holds c at 0.0290.
The optimum is flat, which explains the comment at the top of the R tab. With its default search, drc stops short of the 5PL minimum. Nelder-Mead with a tight tolerance reaches it, and the two languages then print the same six significant digits.
Back-calculated concentrations
Section titled “Back-calculated concentrations”The 4PL inverts in closed form, x = e * ((d - c) / (y - c) - 1)^(1 / b), for any OD
between c and d. Each well gets a concentration, and each sample reports the mean and
the CV of its three wells.
#' 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}
unknowns <- wells[wells$group != "Standards", ]unknowns$conc_well <- Inverse4pl(unknowns$od, summary_4pl)cat(sprintf("sample wells outside the curve: %d of %d\n", sum(is.na(unknowns$conc_well)), nrow(unknowns)))
back_calc <- merge( aggregate(cbind(od, conc_well) ~ id, data = unknowns, FUN = mean), aggregate(cbind(cv_od = od, cv_conc = conc_well) ~ id, data = unknowns, FUN = CvPercent))back_calc$wells <- tapply(unknowns$well, unknowns$id, paste, collapse = " ")[back_calc$id]back_calc <- back_calc[match(c(paste0("P", 1:15), "Control"), back_calc$id), ]lowest_std <- min(levels$conc[levels$conc > 0])back_calc$below_lowest <- back_calc$conc_well < lowest_std
cat(sprintf("%-8s %-12s %7s %8s %6s %6s\n", "sample", "wells", "mean OD", "pg/mL", "CV OD", "CV pg"))cat(sprintf("%-8s %-12s %7.4f %8.2f %6.1f %6.1f%s\n", back_calc$id, back_calc$wells, back_calc$od, back_calc$conc_well, back_calc$cv_od, back_calc$cv_conc, ifelse(back_calc$below_lowest, " below lowest standard", "")), sep = "")cat(sprintf("samples below the lowest standard, %.3f pg/mL: %d of 15\n", lowest_std, sum(back_calc$below_lowest[1:15])))sample wells outside the curve: 0 of 48sample wells mean OD pg/mL CV OD CV pgP1 B4 B5 B6 0.0418 16.36 9.7 28.9 below lowest standardP2 E4 E5 E6 0.0388 12.94 5.5 19.6 below lowest standardP3 C4 C5 C6 0.0383 12.31 2.0 7.6 below lowest standardP4 F4 F5 F6 0.0425 17.29 2.3 6.5 below lowest standardP5 D4 D5 D6 0.0443 19.11 25.2 66.3 below lowest standardP6 G4 G5 G6 0.0593 35.90 6.6 11.7 below lowest standardP7 D7 D8 D9 0.0711 48.45 14.0 21.5P8 B7 B8 B9 0.0884 66.36 10.5 14.4P9 E7 E8 E9 0.0765 54.19 4.1 6.0P10 C7 C8 C9 0.1090 87.30 4.7 5.9P11 F7 F8 F9 0.0629 39.80 8.3 13.9 below lowest standardP12 C11 D10 D11 0.0730 50.45 7.3 11.0P13 G7 G8 G9 0.0985 76.67 2.1 2.7P14 E10 E11 F10 0.0849 62.84 4.3 5.9P15 B10 B11 C10 0.0999 78.06 9.5 12.2Control F11 G10 G11 0.9072 873.27 3.4 3.7samples below the lowest standard, 46.875 pg/mL: 7 of 15def 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). """ 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)
unknowns = wells[wells["group"] != "Standards"].copy()unknowns["conc_well"] = inverse_4pl(unknowns["od"].to_numpy(), fit_4pl)print(f"sample wells outside the curve: " f"{unknowns['conc_well'].isna().sum()} of {len(unknowns)}")
back_calc = unknowns.groupby("id").agg( wells=("well", " ".join), od=("od", "mean"), conc_well=("conc_well", "mean"), cv_od=("od", cv_percent), cv_conc=("conc_well", cv_percent),)back_calc = back_calc.loc[[f"P{n}" for n in range(1, 16)] + ["Control"]]lowest_std = conc[conc > 0].min()back_calc["below_lowest"] = back_calc["conc_well"] < lowest_stdprint(f"{'sample':<8} {'wells':<12} {'mean OD':>7} {'pg/mL':>8} " f"{'CV OD':>6} {'CV pg':>6}")for sample_id, row in back_calc.iterrows(): note = " below lowest standard" if row["below_lowest"] else "" print(f"{sample_id:<8} {row['wells']:<12} {row['od']:7.4f} " f"{row['conc_well']:8.2f} {row['cv_od']:6.1f} " f"{row['cv_conc']:6.1f}{note}")print(f"samples below the lowest standard, {lowest_std:.3f} pg/mL: " f"{back_calc['below_lowest'].iloc[:15].sum()} of 15")sample wells outside the curve: 0 of 48sample wells mean OD pg/mL CV OD CV pgP1 B4 B5 B6 0.0418 16.36 9.7 28.9 below lowest standardP2 E4 E5 E6 0.0388 12.94 5.5 19.6 below lowest standardP3 C4 C5 C6 0.0383 12.31 2.0 7.6 below lowest standardP4 F4 F5 F6 0.0425 17.29 2.3 6.5 below lowest standardP5 D4 D5 D6 0.0443 19.11 25.2 66.3 below lowest standardP6 G4 G5 G6 0.0593 35.90 6.6 11.7 below lowest standardP7 D7 D8 D9 0.0711 48.45 14.0 21.5P8 B7 B8 B9 0.0884 66.36 10.5 14.4P9 E7 E8 E9 0.0765 54.19 4.1 6.0P10 C7 C8 C9 0.1090 87.30 4.7 5.9P11 F7 F8 F9 0.0629 39.80 8.3 13.9 below lowest standardP12 C11 D10 D11 0.0730 50.45 7.3 11.0P13 G7 G8 G9 0.0985 76.67 2.1 2.7P14 E10 E11 F10 0.0849 62.84 4.3 5.9P15 B10 B11 C10 0.0999 78.06 9.5 12.2Control F11 G10 G11 0.9072 873.27 3.4 3.7samples below the lowest standard, 46.875 pg/mL: 7 of 15The Control comes back at 873.27 pg/mL with a CV of 3.7%. The samples are another story. Seven of the fifteen land below the lowest standard, where the curve runs almost flat into the blank and a small spread in OD becomes a large spread in concentration: P1 has a CV of 9.7% in OD and 28.9% in concentration. The curve returns a number for these samples, but no standard backs it, and the next page sets the limit of quantification that decides whether to report them.
P5 fails in a different way. Its CV of 66.3% comes from one well, D4, at 0.057 against 0.037 and 0.039, and D4 is one of the wells SoftMax masked.
The curve and the samples on it
Section titled “The curve and the samples on it”grid <- data.frame(conc = 10^seq(log10(5), 4, length.out = 300))curves <- rbind( data.frame(grid, model = "4PL", od = predict(fit_4pl, newdata = grid)), data.frame(grid, model = "5PL", od = predict(fit_5pl, newdata = grid)))std_points <- standards[standards$conc > 0, ]placed <- back_calcplaced$kind <- ifelse(placed$id == "Control", "Control", "sample")
#' Draw the standards, the two fits and the samples on a log axis.#'#' @param title The panel title.#' @param xlim,ylim Optional axis limits for a zoomed panel.#' @return A ggplot object.CurvePanel <- function(title, xlim = NULL, ylim = NULL) { ggplot() + geom_hline(yintercept = mean(blank_od), linetype = "dotted", colour = "grey40") + geom_line(data = curves, aes(conc, od, linetype = model), colour = "grey20") + geom_point(data = std_points, aes(conc, od), shape = 21, fill = "white", size = 2) + geom_point(data = placed, aes(conc_well, od, colour = kind), size = 2.2) + scale_colour_manual(values = c(Control = "#c44e52", sample = "#4c72b0")) + scale_x_log10() + coord_cartesian(xlim = xlim, ylim = ylim) + labs(x = "concentration, pg/mL", y = "OD 450 - 620 nm", title = title, colour = NULL, linetype = NULL) + # 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(colour = guide_legend(order = 1), linetype = guide_legend(order = 2)) + theme_bw(base_size = 10)}
figure <- CurvePanel("full range") + CurvePanel("low end, where the samples are", c(5, 250), c(0, 0.15)) + plot_layout(guides = "collect")ggsave("outputs/elisa-standard-curve_plate1_r.png", figure, width = 9, height = 3.8, dpi = 120)
# The gate compares these values with the Python tab.metrics <- c( list( n_wells = nrow(wells), n_standard_wells = nrow(standards), n_unknown_wells = nrow(unknowns), n_split_triplicates = sum(!same_wells), n_renamed_triplicates = sum(renamed), n_masked = sum(wells$masked), n_below_lowest = sum(back_calc$below_lowest), od_sum = sum(wells$od) ), setNames(as.list(summary_4pl), paste0("fit4_", names(summary_4pl))), setNames(as.list(summary_5pl), paste0("fit5_", names(summary_5pl))), setNames(as.list(back_calc$conc_well), paste0("conc_", back_calc$id)), setNames(as.list(back_calc$cv_conc), paste0("cv_", back_calc$id)))jsonlite::write_json(metrics, "outputs/elisa-standard-curve_metrics_r.json", auto_unbox = TRUE, digits = NA)
grid = np.geomspace(5, 10000, 300)nonzero = standards[standards["conc"] > 0]samples = back_calc.drop(index="Control")figure, axes = plt.subplots(1, 2, figsize=(9, 3.8))for axis, title in zip(axes, ["full range", "low end, where the samples are"]): axis.axhline(blank_od.mean(), color="grey", linestyle=":", label="blank mean") axis.plot(grid, ll4(grid, *[fit_4pl[k] for k in "bcde"]), color="0.15", label="4PL") axis.plot(grid, ll5(grid, *[fit_5pl[k] for k in "bcdef"]), color="0.15", linestyle="--", label="5PL") axis.scatter(nonzero["conc"], nonzero["od"], facecolor="white", edgecolor="black", zorder=3, label="standards") axis.scatter(samples["conc_well"], samples["od"], color="#4c72b0", zorder=4, label="samples") axis.scatter(back_calc.loc[["Control"], "conc_well"], back_calc.loc[["Control"], "od"], color="#c44e52", zorder=4, label="Control") axis.set_xscale("log") axis.set_xlabel("concentration, pg/mL") axis.set_ylabel("OD 450 - 620 nm") axis.set_title(title, fontsize=10)axes[1].set_xlim(5, 250)axes[1].set_ylim(0, 0.15)axes[0].legend(fontsize=8, frameon=False)figure.tight_layout()figure.savefig("outputs/elisa-standard-curve_plate1_python.png", dpi=120)
# The gate compares these values with the R tab.metrics = { "n_wells": len(wells), "n_standard_wells": len(standards), "n_unknown_wells": len(unknowns), "n_split_triplicates": int((~same_wells).sum()), "n_renamed_triplicates": int(renamed.sum()), "n_masked": int(wells["masked"].sum()), "n_below_lowest": int(back_calc["below_lowest"].sum()), "od_sum": float(wells["od"].sum()),}for name, fit in [("fit4", fit_4pl), ("fit5", fit_5pl)]: for key in ["b", "c", "d", "e", "f", "rse", "aic", "lof_p"]: if key in fit: metrics[f"{name}_{key}"] = float(fit[key])for sample_id, row in back_calc.iterrows(): metrics[f"conc_{sample_id}"] = float(row["conc_well"]) metrics[f"cv_{sample_id}"] = float(row["cv_conc"])pathlib.Path("outputs/elisa-standard-curve_metrics_python.json").write_text( json.dumps(metrics, indent=2) + "\n")
On the left, the 4PL keeps rising past the top standard while the 5PL levels off, and nothing on the plate says which one is right. On the right, where all fifteen samples sit, the two models part again below the lowest standard, so a sample there gets a different value from each model.
How this step fails
Section titled “How this step fails”- A wrong layout gives no error. A curve fitted to mislabeled standards, or a triplicate built from the wrong wells, still returns numbers, so check the annotation against the export before you fit.
- On a plate without a visible plateau,
dandeare extrapolations, and two models that fit equally well disagree on them. - A flat optimum lets two optimizers stop at different points. Tighten the tolerance until the estimates stop moving, and compare the residual sums of squares.
- A value outside the standards comes from the model, not from the sample.
The code for this page is in the companion repository under
guides/proteomics/elisa-standard-curve/.
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”The man/LL.4.Rd and man/LL.5.Rd references in the drc 4.0-0 source package define the four and five parameter logistic models. Their parameter definitions explain the symmetry difference between the two fitted curves.
The man/loadData.Rd reference in the ELISAtools 0.1.8 source package describes the package input structure. Use it alongside the SoftMax export to distinguish a measured well from its supplied annotation.