D.1 Analysis Scripts
D.1 Analysis Scripts
Purpose. The multi-line scripts referenced from the technique chapters, gathered in one place and in the order they are run. Short shell commands stay inline in the module that uses them; anything longer lives here. Each section states the input format it expects and carries no data of its own — they are templates to point at your own exported files.
Background and principle
Scripts are kept here rather than in the protocol modules for three reasons: a protocol reads badly when interrupted by sixty lines of code; someone running an analysis wants the steps contiguous rather than scattered across a chapter; and code needs maintaining independently of the text around it.
How to use these
All of them run in base R [R Core Team, 2024]; where a figure is drawn, the code is given in base graphics, though the same data reshaped will go straight into ggplot2 [Wickham, 2016] if you prefer it.
They are worked skeletons, not a package. Each assumes particular file names and a particular experimental layout, both of which will differ for you. Read them, adapt the names and the design matrix, and check intermediate objects as you go rather than running them end to end.
Record the versions. An analysis is reproducible only if the package versions are known; capture the session information alongside the results and keep it with the record (Lab Record).
D.1.1 Pooled CRISPR screen pipeline
Three scripts, run in order, taking a library reference file and per-sample count files through to a ranked gene list. They follow on from the demultiplexing and trimming commands in Screen Analysis, which are shell one-liners and are given there.
Step 1 — build the library reference table
Collapses the supplier’s library file to unique guide sequences, records how many genes each sequence targets, and assigns a stable identifier. Guides that occur more than once, or that target more than one gene, would otherwise be double-counted.
# Base R throughout, one step per line library(edgeR) # Load the supplier’s library file and keep the three columns that matter, # renaming them to something readable as we go raw.library <- read.table("reference.library.txt", header = TRUE) data <- data.frame( UID = raw.library$id_UID, Gene = raw.library$gene, Sequence = raw.library$seq ) # Reduce to unique sequences and give each a stable key unique.sequences <- unique(data$Sequence) sorted.sequences <- sort(unique.sequences) dbs <- data.frame(ID = seq_along(sorted.sequences), Sequence = sorted.sequences) rownames(dbs) <- dbs$ID # Join every gene assignment back onto its unique sequence dst <- merge(dbs, data) dst <- dst[order(dst$ID), ] # Accumulate the gene names and identifiers hit by each sequence dbs$Genes.Number <- 0 dbs$Genes.Names <- "" dbs$Genes.UID <- "" N <- nrow(dst) for (i in 1:N) { if (i %% 1000 == 0) print(i * 100.0 / N, digits = 5) key <- dst[i, "ID"] dbs[key, "Genes.Names"] <- paste(dbs[key, "Genes.Names"], dst[i, "Gene"], sep = "+") dbs[key, "Genes.UID"] <- paste(dbs[key, "Genes.UID"], dst[i, "UID"], sep = "+") dbs[key, "Genes.Number"] <- dbs[key, "Genes.Number"] + 1 } dbs$Genes.Names <- substring(dbs$Genes.Names, 2) dbs$Genes.UID <- substring(dbs$Genes.UID, 2) # Collapse duplicates within each concatenated list. # Written as a loop rather than an apply so each step is visible: split the # string on "+", drop repeats, sort, and join it back together. rewrite <- function(x) { parts <- unlist(strsplit(x, "\\+")) unique.parts <- unique(parts) sorted.parts <- sort(unique.parts) paste(sorted.parts, collapse = "+") } for (i in seq_len(nrow(dbs))) { dbs$Genes.Names[i] <- rewrite(dbs$Genes.Names[i]) dbs$Genes.UID[i] <- rewrite(dbs$Genes.UID[i]) } # Sanity check: does the count of names match the recorded number? # Mismatches are expected where sub-library identifiers are local. # Count the entries in each concatenated list: separators plus one. # lengths(strsplit(...)) is base R and needs no extra package. n.UID <- lengths(strsplit(dbs$Genes.UID, "\\+")) n.Names <- lengths(strsplit(dbs$Genes.Names, "\\+")) index.UID <- which(n.UID != dbs$Genes.Number) index.Names <- which(n.Names != dbs$Genes.Number) dbs[index.UID, ] write.table(dbs, file = "dbs.txt", sep = "\t", row.names = FALSE, quote = FALSE)
Step 2 — count reads per guide
Run once per trimmed sample file. Takes reads of fixed structure and counts occurrences of each reference guide. The positional arguments are the important ones: they must match where the guide sits in the trimmed read, which is why the trimming step is checked by eye first.
library(edgeR) counts <- processAmplicons( readfile = "sample_trimmed.fastq", barcodefile = "barcode.txt", barcodeStart = 1, barcodeEnd = 2, hairpinfile = "sgRNA.txt", hairpinStart = 35, hairpinEnd = 54, # guide position in the read allowShifting = TRUE, shiftingBase = 1, allowMismatch = TRUE, barcodeMismatchBase = 0, # strict on the sample barcode hairpinMismatchBase = 1, # tolerant on the guide allowShiftedMismatch = FALSE) write.table(counts$counts, file = "sample_counts.txt", col.names = FALSE, sep = "\t", quote = FALSE)
The two mismatch settings are deliberately different
barcodeMismatchBase = 0 is strict: a misread barcode should send a read to no sample rather than to the wrong one, because a misassigned read is worse than a lost one.
hairpinMismatchBase = 1 is tolerant: a single sequencing error in the guide should not discard an otherwise good read, and with 20-nucleotide guides designed to be distinguishable, one mismatch does not create ambiguity.
Step 3 — differential abundance
Loads the per-sample counts, filters, attaches the reference table, aggregates guides to genes, normalises and tests using edgeR [Robinson et al., 2009], whose negative-binomial model and empirical-Bayes moderation of dispersion are what make inference possible from the two or three replicates a screen usually has. Assumes a sample annotation file listing sample, replicate and identifier.
library(edgeR); library(Glimma) # Experiment design: one row per sample, columns Sample / Replica / ID sample.anno <- read.csv("SampleAnnotation.csv") # Read the per-sample count files into a DGE object my.samples <- c("reference.replica-1.txt", "reference.replica-2.txt", "selected.replica-1.txt", "selected.replica-2.txt") dge <- readDGE(my.samples, group = sample.anno$Sample, labels = sample.anno$ID, header = FALSE) # Order by sequence so rows align with the reference table counts <- as.data.frame(dge$counts) row.order <- order(rownames(counts)) counts <- counts[row.order, ] # Filter: keep guides above a CPM threshold in at least n samples. # Both numbers are judgement calls -- state them in the methods. keep <- rowSums(cpm(counts) >= 0.5) >= 5 counts <- counts[keep, ] # Attach the reference table from step 1, filtered identically db <- read.table("dbs.txt", sep = "\t", header = TRUE) db <- db[keep, ] counts$Sequence <- rownames(counts) counts <- merge(counts, db, sort = FALSE) # Guides hitting several genes contribute fractionally to each sample.cols <- sample.anno$ID counts[, sample.cols] <- counts[, sample.cols] / counts$Genes.Number # Aggregate guides to genes by mean count. # aggregate() is base R: the formula reads "every other column, grouped by # Genes.Names", and FUN says what to do within each group. to.aggregate <- counts[, c("Genes.Names", sample.cols)] means <- aggregate(. ~ Genes.Names, data = to.aggregate, FUN = mean) rownames(means) <- means$Genes.Names means$Genes.Names <- NULL # Build the DGE object and the design matrix dge <- DGEList(counts = means, genes = rownames(means), group = sample.anno$Sample) design <- model.matrix(~ 0 + group, data = dge$samples) colnames(design) <- substring(colnames(design), 6) # Normalise for depth AND composition -- see the module’s caution dge <- calcNormFactors(dge) # Inspect before testing: replicates should cluster by treatment plotMDS(dge, method = "bcv", col = as.numeric(factor(sample.anno$Sample))) legend("topright", levels(factor(sample.anno$Sample)), col = 1:2, pch = 20) # Estimate dispersion, fit, and test selected against reference dge <- estimateDisp(dge, design) fit <- glmQLFit(dge, design) contr <- makeContrasts(Selection - Reference, levels = design) results <- glmQLFTest(fit, contrast = contr) topTags(results, n = 50) write.csv(topTags(results, n = Inf)$table, file = "screen_hits.csv") # Keep the versions with the result writeLines(capture.output(sessionInfo()), "sessionInfo.txt")
Sample annotation file
A three-column table, one row per sample, saved as SampleAnnotation.csv:
| Sample | Replica | ID |
| Reference | 1 | R1 |
| Reference | 2 | R2 |
| Selection | 1 | S1 |
| Selection | 2 | S2 |
Extend it with further columns — batch, donor, timepoint — and add them to the model matrix where the design requires it. This file is what makes the analysis reproducible: it is the only record of which count file is which arm.
D.1.2 Interpolating a linear standard curve
Fits a straight line to a set of known standards and interpolates unknowns from it — the arithmetic behind fluorometric nucleic acid quantification and any other assay whose response really is linear across the range used (Quantifying Nucleic Acids).
Note. For an immunoassay — ELISA, bead array, anything with an antibody in it — the response is sigmoid rather than linear, and this model is the wrong one. Use the four-parameter logistic in §D.1.5 instead.
library(ggplot2) # plots only; the data steps are base R # One row per well: Sample, Fluorescence, and Concentration (known for # standards, NA for unknowns) data <- read.csv("standards_and_samples.csv") # Fit on the standards only -- the rows where a concentration is known is.standard <- !is.na(data$Concentration) data.model <- data[is.standard, ] # Always look at the standards before fitting -- a curve that is not # linear over the range used needs transforming or truncating ggplot(data.model, aes(x = Fluorescence, y = Concentration)) + geom_point(colour = "blue", size = 2) model <- lm(Concentration ~ Fluorescence, data = data.model) summary(model) # Interpolate every well, standards included, as a check data$Predicted <- round(predict(model, newdata = data), 3) # Plot fitted line against the standards ggplot(data, aes(x = Fluorescence)) + geom_line(aes(y = Predicted), colour = "red") + geom_point(aes(y = Concentration), colour = "blue", size = 2) + labs(title = "Standard curve", x = "Fluorescence", y = "Concentration") output <- data.frame(Sample = data$Sample, Predicted = data$Predicted) write.csv(output, file = "predicted_concentrations.csv", row.names = FALSE)
Do not extrapolate
The model is valid only across the range the standards covered. A sample reading above the top standard is not quantified by this fit — it is diluted and re-read. Predicted values outside the standard range should be flagged rather than reported, and the same caution applies to every plate assay in this book.
This is the one rule that survives a change of model: it applies just as strictly to the logistic fits in §D.1.5, where the curve flattens at both ends and a reading in either plateau carries almost no information about concentration.
D.1.3 Reading a NanoDrop export: spectra and concentration
Takes a spectrophotometer export, plots each sample’s full spectrum, and returns concentration together with the two purity ratios — the arithmetic behind Quantifying Nucleic Acids and Protein Concentration.
Input format
One row per sample, one column per wavelength, exported as CSV or tab-separated. The column names below are the ones this script expects; rename yours to match, or change the script — the export format differs between instrument software versions and between vendors, and that is the single commonest reason a script like this fails on the first run.
| Column | Contents |
| Sample | sample identifier |
| A230, A260, A280, A320 | absorbance at those wavelengths |
| X220 …X350 | one column per nm, for the spectrum plot |
If your export writes decimals with a comma, pass dec = "," to read.csv; if it carries a multi-line instrument header, skip it with skip =.
library(ggplot2) # plots only; every data step below is base R raw <- read.csv("nanodrop_export.csv", check.names = FALSE) ## Look at what was actually imported before doing anything to it. str(raw) head(raw) ## ------------------------------------------------- step 1. baseline correction ## A320 should read zero for a clean sample: neither nucleic acid nor protein ## absorbs there, so any signal is light scattered by particulates or a dirty ## pedestal. Subtracting it removes that offset from every other wavelength. baseline <- raw$A320 A230 <- raw$A230 - baseline A260 <- raw$A260 - baseline A280 <- raw$A280 - baseline ## Flag samples where the baseline was not near zero: their readings are ## suspect however good the ratios look. scatter.flag <- baseline > 0.02 ## ------------------------------------------------- step 2. concentration ## Beer-Lambert: A = epsilon * c * l. For a 1 mm pathlength instrument the ## conventional factors below already fold the pathlength in, so A260 is ## multiplied by the factor directly. Pick the one matching what is in the ## tube -- using the dsDNA factor on an RNA sample overestimates by a quarter. factor.dsDNA <- 50 # ng/uL per unit A260 factor.ssDNA <- 33 factor.RNA <- 40 conc.dsDNA <- A260 * factor.dsDNA conc.RNA <- A260 * factor.RNA ## ------------------------------------------------- step 3. purity ratios ratio.260.280 <- A260 / A280 ratio.260.230 <- A260 / A230 ## ------------------------------------------------- step 4. quality flags ## An absorbance above about 1.0 on a short pathlength is outside the linear ## range of most instruments: dilute and re-read rather than trusting it. ## The ratio thresholds are conventional, not absolute. saturated <- A260 > 1.0 pure.260280 <- ratio.260.280 > 1.8 & ratio.260.280 < 2.1 pure.260230 <- ratio.260.230 > 2.0 ## ------------------------------------------------- step 5. assemble the report ## Build the table column by column, so it is obvious what each one is. report <- data.frame( Sample = raw$Sample, A260 = round(A260, 3), A280 = round(A280, 3), conc.ng.per.uL = round(conc.dsDNA, 1), ratio.260.280 = round(ratio.260.280, 2), ratio.260.230 = round(ratio.260.230, 2), saturated = saturated, scatter = scatter.flag, pure.260280 = pure.260280, pure.260230 = pure.260230 ) print(report) write.csv(report, "nanodrop_quantified.csv", row.names = FALSE) ## ------------------------------------------------- step 6. protein, if relevant ## A280 has no universal conversion factor: it depends on how many tryptophan ## and tyrosine residues the protein has. For a protein of known sequence, ## use its own extinction coefficient. epsilon in M^-1 cm^-1, MW in g/mol, ## pathlength in cm. protein.mg.per.ml <- function(A280, epsilon, MW, pathlength = 0.1) { molar.concentration <- A280 / (epsilon * pathlength) # mol/L molar.concentration * MW / 1000 # mg/mL } ## Example call -- substitute the values for your protein: ## protein.mg.per.ml(A280 = 0.42, epsilon = 34000, MW = 27000) ## ------------------------------------------------- step 7. plot the spectra ## Always look at the curve, not just the number. A clean nucleic acid ## spectrum peaks at 260 and troughs near 230; a peak shifted towards 230, or ## a rising tail below 240, means contamination the ratios only hint at. ## Find the per-wavelength columns (named X220, X221, ... in the export). wavelength.columns <- grep("^X[0-9]+$", names(raw), value = TRUE) ## Reshape wide to long, one row per sample per wavelength. reshape() is in ## base R; the arguments are verbose but nothing is hidden. spectra <- reshape( raw[, c("Sample", wavelength.columns)], direction = "long", varying = wavelength.columns, v.names = "A", timevar = "nm", times = as.numeric(sub("^X", "", wavelength.columns)), idvar = "Sample" ) ggplot(spectra, aes(x = nm, y = A, group = Sample)) + geom_line() + geom_vline(xintercept = c(230, 260, 280), linetype = "dashed", colour = "grey50") + facet_wrap(~ Sample) + labs(x = "wavelength (nm)", y = "absorbance")
What the ratios do and do not tell you
260/280 reports protein or phenol carry-over in a nucleic acid preparation, and is the more reliable of the two. Roughly 1.8 for DNA and 2.0 for RNA; below that, protein is present.
260/230 reports guanidine, phenol, EDTA and carbohydrate. It is noisier because A230 is small, so a low ratio on a dilute sample may mean nothing at all — check the absolute A230 before acting on it.
Neither ratio reports integrity. A completely degraded RNA sample gives perfect ratios, because the nucleotides absorb whether or not they are still joined together. Integrity needs a gel or a capillary trace (Assessing RNA Integrity).
D.1.4 Fitting a dose–response curve
A general four- or five-parameter log-logistic fit with model selection, effective-dose estimation and the diagnostic plots that decide whether the fit can be believed. The fitting, model comparison and effective-dose machinery all come from the drc package [Ritz et al., 2015]. This is the arithmetic behind a killing curve (Endpoint Cytotoxicity), a kill curve for selection (Kill Curve) and any titration with a sigmoid response.
Input format
Two columns. Dose is the concentration or ratio on the \(x\)-axis; Response is whatever was measured. One row per well, replicates as separate rows — do not average replicates before fitting, because the fit uses the spread to estimate confidence intervals.
Add a third column, Group, when several conditions are to be compared on the same axes.
library(drc) # the fitting library(ggplot2) # the plots data <- read.csv("dose_response.csv") # columns: Dose, Response [, Group] str(data) ## ------------------------------------------------- step 1. look before fitting ## A zero dose cannot be placed on a log axis. Substitute a value below the ## lowest real dose FOR PLOTTING ONLY -- never for fitting, where drc handles ## the untreated control correctly on its own. positive.doses <- data$Dose[data$Dose > 0] plot.floor <- min(positive.doses) / 10 data$Dose.plot <- data$Dose data$Dose.plot[data$Dose == 0] <- plot.floor ggplot(data, aes(x = Dose.plot, y = Response)) + geom_point(colour = "blue", size = 2) + scale_x_log10() + labs(x = "dose (log scale)", y = "response") ## ------------------------------------------------- step 2. fit the curve ## LL.4 has four parameters: ## b slope at the midpoint ## c lower asymptote (bottom) ## d upper asymptote (top) ## e ED50 ## LL.5 adds f, an asymmetry parameter. Start with LL.4: the extra parameter ## is only justified if the data are genuinely asymmetric AND there are enough ## points to constrain it. model <- drm(Response ~ Dose, data = data, fct = LL.4()) summary(model) ## ------------------------------------------------- step 3. is it the right model? ## Compare candidate models by information criterion. The LOWEST value wins, ## but a difference of a point or two is not evidence -- prefer the simpler ## model when they are close. candidates <- list(LL.3(), LL.5(), W1.4(), W2.4()) mselect(model, candidates, sorted = "IC") ## ------------------------------------------------- step 4. check the residuals ## Residuals must scatter without pattern. A U-shape means the model is the ## wrong shape; a funnel means variance grows with the response, and the fit ## should be weighted. Do this before reading any parameter. fitted.values <- fitted(model) residual.values <- residuals(model) diagnostics <- data.frame(Fitted = fitted.values, Residual = residual.values) ggplot(diagnostics, aes(x = Fitted, y = Residual)) + geom_point() + geom_hline(yintercept = 0, colour = "red") ## ------------------------------------------------- step 5. the numbers ## Effective doses with confidence intervals. The INTERVAL matters more than ## the estimate: a wide one means the curve is not constrained where it counts, ## usually because there are no points near that part of the curve. ED(model, c(10, 50, 90), interval = "delta") ## ------------------------------------------------- step 6. comparing conditions ## Fitting both groups in one model, then testing whether their ED50 values ## differ, is the question a pair of curves is usually being asked. if ("Group" %in% names(data)) { grouped.model <- drm(Response ~ Dose, curveid = Group, data = data, fct = LL.4()) summary(grouped.model) EDcomp(grouped.model, c(50, 50)) } ## ------------------------------------------------- step 7. draw the fitted curve ## Predict at 200 evenly log-spaced doses so the line is smooth. dose.grid <- 10^seq(from = log10(plot.floor), to = log10(max(data$Dose)), length.out = 200) curve.data <- data.frame(Dose = dose.grid) curve.data$Response <- predict(model, newdata = curve.data) ggplot(data, aes(x = Dose.plot, y = Response)) + geom_point(colour = "blue", size = 3, shape = 1) + geom_line(data = curve.data, aes(x = Dose, y = Response), colour = "red") + scale_x_log10() + labs(x = "dose (log scale)", y = "response")
The slope at the midpoint, done correctly
It is tempting to read steepness off the fitted \(b\) parameter. For a symmetric curve (LL.4, or LL.5 with \(f = 1\)) the gradient at the inflection is available in closed form. For an asymmetric LL.5 fit the inflection point is not \(e\), and the gradient there is not what a formula written for the symmetric case returns.
Differentiate numerically instead — it is two lines, it is correct for any model drc can fit, and it cannot silently disagree with the curve that was actually fitted:
slope.at <- function(model, x, h = 1e-6) { just.above <- predict(model, data.frame(Dose = x * (1 + h))) just.below <- predict(model, data.frame(Dose = x * (1 - h))) rise <- just.above - just.below run <- 2 * x * h rise / run } ed50 <- ED(model, 50, display = FALSE)[1] slope.at(model, ed50)
D.1.5 Back-calculating concentrations from a bead array
Fits a four-parameter logistic to the standard series of each analyte in a multiplexed bead array and interpolates the unknowns — the analysis that turns MFI from a cytometry file into a concentration (Bead Array).
Input format
One row per bead population per well, after the cytometry files have been gated and the per-population median exported.
| Column | Contents |
| Sample | well or sample identifier |
| Analyte | which bead population, e.g. IFN-\(\gamma \) |
| MFI | median fluorescence of that population |
| Concentration | known value for standards, NA for unknowns |
Gating and export happen upstream in the cytometry software or in an R flow-cytometry package; this script begins from the exported medians.
library(drc) # the fitting library(ggplot2) # the plots data <- read.csv("cba_medians.csv") str(data) ## Each bead population is its own assay with its own standard curve. Fitting ## them together would be wrong: dynamic range and background differ between ## analytes even on the same plate. So work through them one at a time. analytes <- unique(data$Analyte) print(analytes) ## Somewhere to collect the per-analyte results and the fitted models. all.results <- NULL all.models <- list() for (this.analyte in analytes) { message("---- fitting ", this.analyte) ## --------------------------------------------- step 1. split out one analyte rows <- data$Analyte == this.analyte analyte.data <- data[rows, ] ## --------------------------------------------- step 2. the standards only ## Standards are the rows with a known concentration. A zero-concentration ## blank cannot go into a log-scale fit, so it is excluded here and used ## separately as the background reading. is.standard <- !is.na(analyte.data$Concentration) & analyte.data$Concentration > 0 standards <- analyte.data[is.standard, ] if (nrow(standards) < 4) { warning("too few standards for ", this.analyte, " -- skipping") next } ## --------------------------------------------- step 3. fit the standard curve ## Four-parameter logistic: bottom, top, slope, EC50. Let drc handle the ## concentration axis rather than log-transforming by hand. model <- drm(MFI ~ Concentration, data = standards, fct = LL.4()) all.models[[this.analyte]] <- model print(summary(model)) ## --------------------------------------------- step 4. the working range ## Anything outside the standards is not a measurement. Record the limits ## now so every sample can be checked against them. lowest.standard.MFI <- min(standards$MFI) highest.standard.MFI <- max(standards$MFI) ## --------------------------------------------- step 5. back-calculate ## Interpolation is the INVERSE of the fitted curve. ED(type = "absolute") ## does this using the model that was actually fitted, which is safer than ## writing the algebra out: a hand-written inverse has to match the exact ## parameterisation the package used, and returns nonsense when it does not. predicted <- rep(NA_real_, nrow(analyte.data)) for (i in seq_len(nrow(analyte.data))) { this.MFI <- analyte.data$MFI[i] ## The solver fails for readings off the end of the curve; catch that ## rather than letting the loop stop. attempt <- try( ED(model, this.MFI, type = "absolute", display = FALSE), silent = TRUE ) if (!inherits(attempt, "try-error")) { predicted[i] <- attempt[1] } } analyte.data$Predicted <- predicted ## --------------------------------------------- step 6. flag out-of-range range.flag <- rep("in range", nrow(analyte.data)) range.flag[analyte.data$MFI < lowest.standard.MFI] <- "below lowest standard" range.flag[analyte.data$MFI > highest.standard.MFI] <- "above highest standard" analyte.data$Range.flag <- range.flag ## --------------------------------------------- step 7. collect all.results <- rbind(all.results, analyte.data) } ## ------------------------------------------------- step 8. recovery check ## Put the standards back through their own curve. They should return their ## known concentrations to roughly 80-120 percent. A standard that does not ## recover is a standard to drop; several that do not is a curve to refit. is.standard.row <- !is.na(all.results$Concentration) & all.results$Concentration > 0 recovery <- all.results[is.standard.row, ] recovery$Recovery.pct <- round(100 * recovery$Predicted / recovery$Concentration, 1) print(recovery[, c("Analyte", "Concentration", "Predicted", "Recovery.pct")]) ## ------------------------------------------------- step 9. look at the curves standards.only <- all.results[is.standard.row, ] ggplot(standards.only, aes(x = Concentration, y = MFI)) + geom_point(colour = "blue", size = 2) + scale_x_log10() + facet_wrap(~ Analyte, scales = "free_y") + labs(x = "standard concentration (log scale)", y = "MFI") write.csv(all.results, "cba_concentrations.csv", row.names = FALSE)
Why a straight line is the wrong model here
An immunoassay standard curve is sigmoid, not linear: it flattens at the top as capture sites saturate and at the bottom into background. Fitting a line through the middle of it works over perhaps one order of magnitude and fails silently outside that — and the samples that matter are usually the ones near the ends.
Use the linear model in §D.1.2 only where the relationship is genuinely linear over the whole range used, as in fluorometric nucleic acid quantification. For anything with an antibody in it, fit the four-parameter logistic above.
One further trap: a curve fitted in linear concentration and a curve fitted in \(\log _{10}\) concentration need different parameterisations. Mixing them — passing raw concentrations to a model whose midpoint parameter is a logarithm — produces a fit that plots through the points and returns meaningless parameters. Let the package handle the transformation, and read the midpoint back with ED() rather than off the coefficient table.
D.1.6 Fitting an ITC binding isotherm
Takes integrated injection heats and fits them, either descriptively or thermodynamically — and the distinction between those two matters more than the code (ITC).
Input format
The integrated heats exported by the instrument software, one row per injection: MolarRatio (ligand to macromolecule in the cell) and NDH, the normalised heat per mole of injectant. Baseline correction and peak integration happen in the instrument software first; this begins from the integrated values.
library(ggplot2) # plots only; the fitting below is base R (nls) itc <- read.csv("itc_integrated.csv") # columns: MolarRatio, NDH str(itc) ggplot(itc, aes(x = MolarRatio, y = NDH)) + geom_point(colour = "blue", size = 2) + labs(x = "molar ratio", y = "kcal per mole of injectant") ## ---------------------------------------------------------------- one-site model ## Wiseman isotherm, fitted by non-linear least squares. Parameters: ## dH enthalpy change (kcal/mol) ## Ka association constant (1/M); K_D = 1/Ka ## n stoichiometry (sites per macromolecule) ## Mt is the macromolecule concentration in the cell, in M -- YOU supply it, ## and an error here propagates directly into n. Mt <- 20e-6 wiseman <- function(ratio, n, Ka, dH, Mt) { r <- 1 / (Ka * Mt) Xr <- ratio / n dH * (0.5 + (1 - Xr - r) / (2 * sqrt((1 + Xr + r)^2 - 4 * Xr))) } fit <- nls(NDH ~ wiseman(MolarRatio, n, Ka, dH, Mt), data = itc, start = list(n = 1, Ka = 1e6, dH = -10), control = nls.control(maxiter = 200)) summary(fit) params <- coef(fit) KD <- 1 / params["Ka"] # in M dG <- -1.987e-3 * 298.15 * log(params["Ka"]) # kcal/mol at 25 C dS <- (params["dH"] - dG) / 298.15 c(n = params["n"], KD_M = KD, dH = params["dH"], dG = dG, TdS = 298.15 * dS) ## ---------------------------------------------------------------- the fitted curve grid <- data.frame(MolarRatio = seq(0, max(itc$MolarRatio), length.out = 200)) grid$NDH <- predict(fit, newdata = grid) ggplot(itc, aes(x = MolarRatio, y = NDH)) + geom_point(colour = "blue", size = 3, shape = 1) + geom_line(data = grid, colour = "red") + labs(x = "molar ratio", y = "kcal per mole of injectant")
A sigmoid fit is a shape, not thermodynamics
An ITC isotherm looks sigmoid, and a log-logistic curve (§D.1.4) will fit it and return a midpoint and a slope. That is a perfectly reasonable thing to do for visualisation, or to compare the shape of two titrations.
It does not give you thermodynamics. \(\Delta H\), \(K_a\) and \(n\) are the parameters of a binding model, and only a binding model returns them. A log-logistic ED50 is not a dissociation constant, and its slope parameter is not a stoichiometry — they are curve descriptors that happen to have the right shape. Fitting the wrong one and reporting the parameters under thermodynamic names is how an ITC experiment gets misreported.
Use the log-logistic when the question is “do these two titrations look different”. Use the Wiseman model above, or the instrument’s own fitting routine, when the question is “what is the affinity”. And recall that the \(c\) value decides whether the second question is answerable at all from the data you have (Figure 11.2).
D.1.7 Tidying a chromatography export into one table
Turns the multi-curve export written by FPLC control software into a single tidy table that R can read and plot. The transformation is not specific to any instrument or to any purification — it applies to any export in which each curve carries its own \(x\)-axis column (Protein Affinity Chromatography, Size Exclusion).
Input format, and why it is not a table
Open a chromatogram export and the header looks wrong, because it is:
ml,Cond,ml,%-Cond,ml,Conc B,ml,System flow,…,ml,UV,…
Every curve comes as a pair of columns — its own volume axis, then its own values — and the file is as many columns wide as twice the number of curves. A typical run exports eighteen curves in thirty-six columns.
The reason is sampling rate. Each detector records at whatever interval suits it, so the curves do not share time points and cannot share an \(x\)-axis. In one ordinary run the UV trace held 51,276 points, conductivity 25,637, concentration of buffer B 5,126, and the fraction marks just 34. The file is therefore not one table of 51,276 rows; it is eighteen independent tables printed side by side, padded with blanks to the length of the longest.
This matters because of what it does to a naive import. read.csv() will accept the file happily — it silently renames the repeated columns ml, ml.1, ml.2 and so on — and you will have a data frame that looks fine and is wrong. Row 400 of the UV column and row 400 of the Conc B column are measurements at different volumes. Plotting one against the other, or filtering rows by the first ml column, produces a figure that is quietly meaningless. Nothing errors.
The fix is to key every curve on its own volume column and then join all of them on that key, so that the result has one volume column and one column per curve, with a missing value wherever a given curve was not sampled at that volume. That is a relational operation on a large, irregular table, which is why it is done in SQLite rather than in a spreadsheet or by hand: the join is indexed, it runs in seconds on a file of this size, and the intermediate tables stay available for inspection if the result looks wrong.
The algorithm in four moves
Import the raw file as a single all-text table. Nothing is assumed about types, because a raw export contains numbers, empty strings, text labels and nulls in the same column. SQLite numbers the repeated ml headers for you — ml_1, ml_3, ml_5 — which is convenient, since those are exactly the key columns.
Split into one two-column table per curve, discarding the padding rows where that curve has no value. Each table now holds only the points that curve actually recorded.
Join them one at a time onto the first with a full outer join on the volume key, coalescing the key so that a volume present in the incoming curve but absent from the accumulated table is carried in rather than dropped. Index each key column before joining or the run takes minutes instead of seconds.
Export as CSV. The result has \(N/2 + 1\) columns and as many rows as there are distinct volumes across all curves — more rows than any single curve contains, most cells empty, and every value on the row that belongs to its own volume.
-- transform.sql -- run as: sqlite3 transform.db < transform.sql -- Precondition: data_input.csv in the working directory, an even number of -- columns, odd columns the volume key, even columns the values. -- Postcondition: data_output.csv, one key column plus one column per curve. .import --csv data_input.csv data .header on .mode column PRAGMA table_info( data ); -- confirm the column names SQLite assigned SELECT COUNT( * ) FROM data; -- ---------------------------------------------------------------- split -- One table per curve. The WHERE clause drops the padding: rows where this -- particular curve recorded nothing. Name each table after its key column so -- the numbering stays traceable through the joins below. CREATE TABLE data_01 AS SELECT ml_1, "Cond" FROM data WHERE ml_1 IS NOT NULL AND ml_1 != ’’; CREATE TABLE data_03 AS SELECT ml_3, "%-Cond" FROM data WHERE ml_3 IS NOT NULL AND ml_3 != ’’; CREATE TABLE data_05 AS SELECT ml_5, "Conc B" FROM data WHERE ml_5 IS NOT NULL AND ml_5 != ’’; CREATE TABLE data_25 AS SELECT ml_25, "UV" FROM data WHERE ml_25 IS NOT NULL AND ml_25 != ’’; -- ... one CREATE TABLE per curve, continuing to the last column pair. -- ---------------------------------------------------------------- index -- Not optional at this size. Without an index each join is a table scan. CREATE INDEX ind_01 ON data_01 ( ml_1 ); CREATE INDEX ind_03 ON data_03 ( ml_3 ); CREATE INDEX ind_05 ON data_05 ( ml_5 ); CREATE INDEX ind_25 ON data_25 ( ml_25 ); -- ... one per curve. -- ---------------------------------------------------------------- join -- Accumulate onto the first table, three statements per curve: -- join on the key, carry the incoming key where the accumulated one is -- null, then drop the now-redundant incoming key column. -- Intermediate tables are deliberately not dropped, so that a result that -- looks wrong can be traced back to the join that broke it. CREATE TABLE data_0103 AS SELECT * FROM data_01 FULL OUTER JOIN data_03 ON ml_1 = ml_3; UPDATE data_0103 SET ml_1 = ml_3 WHERE ml_1 IS NULL; ALTER TABLE data_0103 DROP COLUMN ml_3; SELECT * FROM data_0103 LIMIT 30; -- eyeball it before continuing CREATE TABLE data_0105 AS SELECT * FROM data_0103 FULL OUTER JOIN data_05 ON ml_1 = ml_5; UPDATE data_0105 SET ml_1 = ml_5 WHERE ml_1 IS NULL; ALTER TABLE data_0105 DROP COLUMN ml_5; -- ... repeat for every remaining curve, each onto the previous result. -- ---------------------------------------------------------------- export SELECT COUNT( * ) FROM data_0135; -- expect more rows than any one curve .mode csv .output data_output.csv SELECT * FROM data_0135; .output stdout .shell rm transform.db -- the database is disposable .quit
Adapting it to your own export
The script above is written out longhand rather than generated in a loop, and that is a deliberate trade: it is verbose, but every step is visible and any one of them can be run on its own when a join misbehaves.
To adapt it, run the PRAGMA table_info( data ) line first and read off the key column names SQLite assigned. Then write one CREATE TABLE, one CREATE INDEX and one three-line join block per curve, numbered to match. The value column names are quoted because exports contain spaces, percent signs and hyphens in headers; keep the quoting and do not rename them yet — renaming is easier in R, where it can be done reproducibly alongside the analysis.
If your export has an odd number of columns, or a shared axis for some curves and separate axes for others, the precondition does not hold and the split step needs adjusting before anything else will work. Check the header first.
Processing a folder of runs
One shell loop applies the transformation to every export in a directory, writing a prefixed output and a log for each, so that a batch of runs is prepared in one command and each one’s console output is kept for diagnosis.
#!/bin/zsh # transform.zsh -- apply transform.sql to every CSV in the working directory. # Precondition: transform.sql and the exports are in the working directory, # and each export meets the transform.sql precondition. # Postcondition: sql_<name>.csv and sql_<name>.csv.log for each input. FILENAME_IN="data_input.csv" FILENAME_OUT="data_output.csv" FILENAME_PREFIX="sql_" for FILE in *.csv; do # skip files this script has already produced [[ "$FILE" == ${FILENAME_PREFIX}* ]] && continue echo "Processing: $FILE (details in [$FILENAME_PREFIX$FILE.log])" cp "$FILE" "$FILENAME_IN" sqlite3 transform.db < transform.sql &> "$FILENAME_PREFIX$FILE.log" cp "$FILENAME_OUT" "$FILENAME_PREFIX$FILE" rm "$FILENAME_IN" "$FILENAME_OUT" done
Critical step. The loop copies each input to a fixed working name and deletes it afterwards, so it must not be run in a directory holding anything called data_input.csv or data_output.csv that you need. Run it on copies, never on the only copy of an instrument export.
Reading the tidied file in R
library(ggplot2) chrom <- read.csv("sql_run001.csv", check.names = FALSE) str(chrom) names(chrom)[1] <- "ml" chrom$ml <- as.numeric(chrom$ml) ## ---------------------------------------------------------------- separate the ## Two of the columns are not curves and should be pulled out before anything ## else, because they are sparse text and will otherwise be treated as data. ## Run Log -- timestamped method events (a few hundred rows) ## Fraction -- the collector’s tube marks (a few dozen rows) runlog <- chrom[!is.na(chrom$"Run Log") & chrom$"Run Log" != "", c("ml", "Run Log")] fracs <- chrom[!is.na(chrom$"Fraction") & chrom$"Fraction" != "", c("ml", "Fraction")] ## ---------------------------------------------------------------- one curve ## Each curve is dense in its own rows and empty in everyone else’s, so drop ## the empty rows per curve rather than dropping incomplete rows globally -- ## na.omit() on the whole frame would leave almost nothing. uv <- chrom[!is.na(chrom$UV), c("ml", "UV")] uv$UV <- as.numeric(uv$UV) ggplot(uv, aes(ml, UV)) + geom_line() + geom_vline(data = fracs, aes(xintercept = ml), colour = "grey70", linewidth = 0.2) + labs(x = "volume (mL)", y = "absorbance at 280 nm (mAU)") ## ---------------------------------------------------------------- two curves ## To draw UV and %B on one figure, do NOT merge them on ml -- they were never ## sampled at the same volumes. Keep them as separate series and let the plot ## place each on its own x values; scale the second to the first axis. concb <- chrom[!is.na(chrom$"Conc B"), c("ml", "Conc B")] names(concb)[2] <- "ConcB" concb$ConcB <- as.numeric(concb$ConcB) scale_factor <- max(uv$UV, na.rm = TRUE) / 100 ggplot() + geom_line(data = uv, aes(ml, UV)) + geom_line(data = concb, aes(ml, ConcB * scale_factor), colour = "red", linetype = "dashed") + scale_y_continuous( name = "absorbance at 280 nm (mAU)", sec.axis = sec_axis(~ . / scale_factor, name = "buffer B (%)")) + labs(x = "volume (mL)") ## ---------------------------------------------------------------- peak volume ## Integrating the UV peak needs the trapezoid on the curve’s own spacing, ## which is why the per-curve subset above matters -- the spacing is uneven. peak <- uv[uv$ml >= 20 & uv$ml <= 26, ] area <- sum(diff(peak$ml) * (head(peak$UV, -1) + tail(peak$UV, -1)) / 2) area # mAU * mL
Two traps in the joined output
The volume key is not unique, so the join can duplicate rows. A curve that recorded two values at the same volume — which happens at the start of a run, and happens badly in the run log, where several events share a timestamp — fans out against every match in the accumulated table. In an ordinary run this inflated 51,276 curve points to 75,322 output rows, a few hundred of them duplicates. It is harmless for plotting a single curve, because the duplicates carry identical values, and it is not harmless if you count rows or average them. Pull the run log out first, as above, and the problem largely disappears with it.
Do not fill the gaps by interpolation without asking what the column is. Carrying the last value forward is defensible for a slowly varying instrument reading such as conductivity or system pressure. It is wrong for Fraction, which is an event mark rather than a continuous quantity — interpolating it invents tube boundaries that never existed and will shift which fractions you believe a peak fell into. Treat sparse columns as events, dense columns as curves, and decide per column rather than per file.
Validation and limitations
These scripts are written for clarity rather than for speed or generality. The loop in the screen pipeline is slow on a genome-scale library and could be vectorised; its aggregation step takes a simple mean where a purpose-built screen tool would use a rank-based method (Screen Analysis). They are a documented, working route rather than a recommended best practice, and anyone comfortable in R should improve them for their own use.
None of them has been run against your data, and none carries any. Every input format above is a stated convention, not a standard — instrument exports vary between vendors and between software versions, so the first run will almost always need the column names changed. Check the shape of the imported object before fitting anything to it.
The fitted models are also only as good as their diagnostics. A curve that passes through the points is not evidence the model is right; residual structure, confidence-interval width and recovery of the standards are what decide that, which is why each section includes them rather than stopping at the fit.