Relative expression from paired qPCR samples
A lower Cq means that a reaction crossed its threshold earlier. It does not, by itself, show that treatment increased gene expression: RNA input, reverse transcription, and assay behavior also affect the measurement. A relative expression analysis first compares the target with suitable reference genes, then compares the normalized measurements between biological samples.
Here each donor supplies a control sample and a stimulated sample. We retain that pairing through the analysis and estimate the stimulated-to-control expression ratio. The data are invented. The code and figures illustrate the calculation; they contain no evidence about a real gene or treatment.
Establish the assay before the calculation
Section titled “Establish the assay before the calculation”The comparative Cq method requires evidence that the target and reference assays have suitable, approximately equal amplification efficiencies. The base-two calculation below further assumes approximately twofold amplification per cycle. The file guide’s dilution series shows how an efficiency estimate comes from a standard curve.
If the assays have materially different efficiencies, a base-two fold change can be biased even when the Cq table is correct. Use an efficiency-aware model such as Pfaffl’s method, with efficiencies estimated for the assays and their uncertainty considered. Do not repair an unvalidated assay by changing the formula alone.
Reference genes need evidence of stability in the tissue, conditions, and
sample preparation under study. A familiar gene symbol does not establish
stability. Vandesompele and colleagues
describe selection and combination of multiple reference genes. Our REF_A
and REF_B labels have stable reference behavior by construction; this fixture
cannot select reference genes for a real experiment.
The MIQE 2.0 guidelines connect the analysis to sample preparation, assay validation, controls, and reporting. Check amplification and melt curves, contamination controls, and the assay’s quantifiable range before treating an exported Cq as a usable measurement.
Read the invented plate export
Section titled “Read the invented plate export”Download the paired well table and save it
beside your script as qpcr_paired_wells.csv. The fixture declares twelve
donors, two conditions, three assays, and three technical wells for each assay.
Each donor’s two conditions share a plate. The table also includes no-template
controls, identified by role = ntc.
The generator deliberately inserts an isolated undetermined well, a discordant
technical repeat, and one sample whose target wells are all undetermined.
These cases make the exclusion rules visible. Undetermined is missing
measurement information, not a measured Cq of zero or the final cycle number.
options(digits = 6)dir.create("outputs", showWarnings = FALSE)wells <- read.csv("qpcr_paired_wells.csv", na.strings = "Undetermined")key <- c("donor", "condition", "plate", "assay", "replicate")stopifnot(!anyDuplicated(wells[key]))stopifnot(all(is.na(wells$cq) | is.finite(wells$cq)))controls <- subset(wells, role == "ntc")samples <- subset(wells, role == "sample")stopifnot(nrow(controls) > 0, all(is.na(controls$cq)))donor_plate <- unique(samples[c("donor", "plate")])stopifnot(!anyDuplicated(donor_plate$donor))cat("Sample wells:", nrow(samples), "\n")cat("No-template control wells:", nrow(controls), "\n")cat("Undetermined sample wells:", sum(is.na(samples$cq)), "\n")Sample wells: 216No-template control wells: 18Undetermined sample wells: 4from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import stats
out = Path("outputs")out.mkdir(exist_ok=True)wells = pd.read_csv("qpcr_paired_wells.csv", na_values="Undetermined")key = ["donor", "condition", "plate", "assay", "replicate"]assert not wells.duplicated(key).any()assert (wells["cq"].isna() | np.isfinite(wells["cq"])).all()controls = wells.loc[wells["role"].eq("ntc")]samples = wells.loc[wells["role"].eq("sample")].copy()assert len(controls) > 0 and controls["cq"].isna().all()assert samples.groupby("donor")["plate"].nunique().eq(1).all()print(f"Sample wells: {len(samples)}")print(f"No-template control wells: {len(controls)}")print(f"Undetermined sample wells: {samples['cq'].isna().sum()}")Sample wells: 216No-template control wells: 18Undetermined sample wells: 4The no-template controls have no detected amplification in this invented export. A real control requires its amplification trace and assay-specific acceptance rule. An undetermined sample target can reflect low abundance, inhibition, or technical failure; the control result alone cannot distinguish those causes.
Apply a declared technical rule
Section titled “Apply a declared technical rule”For this lesson, an assay within a sample needs at least two detected wells and a Cq range no greater than 0.5 cycles. This is an illustrative rule fixed before the treatment comparison, not a universal qPCR cutoff. A laboratory must set its rule from assay repeatability and the concentration range it intends to quantify.
We reject the entire sample-assay measurement when its technical wells fail. We do not remove whichever well produces the desired treatment effect. A real discordant set needs investigation and, when feasible, a repeat measurement.
#' Summarize technical wells for one assay within one sample.#'#' @param assay_wells A data frame containing one sample and assay.#' @return One row with detected counts, a Cq mean, and an acceptance flag.SummarizeAssay <- function(assay_wells) { values <- assay_wells$cq[!is.na(assay_wells$cq)] n_detected <- length(values) spread <- if (n_detected > 0) diff(range(values)) else NA_real_ mean_cq <- if (n_detected > 0) mean(values) else NA_real_ accepted <- n_detected >= 2 && spread <= 0.5 data.frame(assay_wells[1, c("donor", "condition", "plate", "assay")], n_detected = n_detected, mean_cq = mean_cq, cq_range = spread, accepted = accepted)}
assay_key <- interaction(samples$donor, samples$condition, samples$plate, samples$assay, drop = TRUE)qc <- do.call(rbind, lapply(split(samples, assay_key), SummarizeAssay))rownames(qc) <- NULLqc <- qc[order(qc$donor, qc$condition, qc$assay), ]cat("Accepted sample-assay measurements:", sum(qc$accepted), "\n")print(qc[!qc$accepted, c("donor", "condition", "assay", "n_detected", "cq_range")], row.names = FALSE)write.csv(qc, "outputs/assay_qc_r.csv", row.names = FALSE)Accepted sample-assay measurements: 70 donor condition assay n_detected cq_range D07 stimulated TARGET 3 0.918 D12 stimulated TARGET 0 NAassay_key = ["donor", "condition", "plate", "assay"]qc = samples.groupby(assay_key, as_index=False).agg( n_detected=("cq", "count"), mean_cq=("cq", "mean"), cq_min=("cq", "min"), cq_max=("cq", "max"),)qc["cq_range"] = qc["cq_max"] - qc["cq_min"]qc["accepted"] = qc["n_detected"].ge(2) & qc["cq_range"].le(0.5)qc = qc.sort_values(["donor", "condition", "assay"])print(f"Accepted sample-assay measurements: {qc['accepted'].sum()}")columns = ["donor", "condition", "assay", "n_detected", "cq_range"]print(qc.loc[~qc["accepted"], columns].to_string(index=False))qc.to_csv(out / "assay_qc_python.csv", index=False)Accepted sample-assay measurements: 70donor condition assay n_detected cq_range D07 stimulated TARGET 3 0.918 D12 stimulated TARGET 0 NaNThe isolated undetermined reference well leaves two agreeing detected wells, so that sample-assay measurement remains usable under the stated rule. The other failures cannot provide a normalized target measurement for that sample. Keep their identities in the exclusion record.
Normalize within each sample
Section titled “Normalize within each sample”With equal twofold efficiencies, the geometric mean of two reference
quantities corresponds to their arithmetic mean on the Cq scale. These
expressions define the reference Cq and Delta Cq for sample s.
reference_cq[s] = (mean_cq[REF_A, s] + mean_cq[REF_B, s]) / 2delta_cq[s] = mean_cq[TARGET, s] - reference_cq[s]Each mean uses accepted technical wells. We require both reference assays and the target in each sample. A lower Delta Cq means more target expression relative to the reference signal.
accepted <- qc[qc$accepted, c("donor", "condition", "plate", "assay", "mean_cq")]sample_cq <- reshape(accepted, idvar = c("donor", "condition", "plate"), timevar = "assay", direction = "wide")required <- paste0("mean_cq.", c("TARGET", "REF_A", "REF_B"))sample_cq <- sample_cq[complete.cases(sample_cq[required]), ]sample_cq$reference_cq <- (sample_cq$mean_cq.REF_A + sample_cq$mean_cq.REF_B) / 2sample_cq$delta_cq <- sample_cq$mean_cq.TARGET - sample_cq$reference_cqpaired <- reshape(sample_cq[c("donor", "plate", "condition", "delta_cq")], idvar = c("donor", "plate"), timevar = "condition", direction = "wide")paired <- paired[complete.cases(paired), ]paired <- paired[order(paired$donor), ]paired$delta_delta_cq <- paired$delta_cq.stimulated - paired$delta_cq.controlpaired$log2_fold_change <- -paired$delta_delta_cqpaired$fold_change <- 2^paired$log2_fold_changeexcluded <- setdiff(unique(samples$donor), paired$donor)cat("Complete donor pairs:", nrow(paired), "\n")cat("Excluded donors:", paste(sort(excluded), collapse = ", "), "\n")print(paired[c("donor", "delta_delta_cq", "fold_change")], row.names = FALSE)write.csv(paired, "outputs/donor_results_r.csv", row.names = FALSE)Complete donor pairs: 10Excluded donors: D07, D12 donor delta_delta_cq fold_change D01 -1.324167 2.50388 D02 -0.857000 1.81127 D03 -1.444083 2.72090 D04 -1.748167 3.35931 D05 -0.974333 1.96473 D06 -1.096333 2.13811 D08 -1.523333 2.87454 D09 -1.540667 2.90929 D10 -1.675000 3.19319 D11 -0.760667 1.69427accepted = qc.loc[qc["accepted"]]sample_cq = accepted.pivot( index=["donor", "condition", "plate"], columns="assay", values="mean_cq").dropna(subset=["TARGET", "REF_A", "REF_B"])sample_cq["reference_cq"] = sample_cq[["REF_A", "REF_B"]].mean(axis=1)sample_cq["delta_cq"] = sample_cq["TARGET"] - sample_cq["reference_cq"]paired = sample_cq.reset_index().pivot( index=["donor", "plate"], columns="condition", values="delta_cq").dropna(subset=["control", "stimulated"]).sort_index()paired["delta_delta_cq"] = paired["stimulated"] - paired["control"]paired["log2_fold_change"] = -paired["delta_delta_cq"]paired["fold_change"] = 2.0 ** paired["log2_fold_change"]excluded = sorted(set(samples["donor"]) - set(paired.index.get_level_values(0)))print(f"Complete donor pairs: {len(paired)}")print(f"Excluded donors: {', '.join(excluded)}")print(paired.reset_index()[ ["donor", "delta_delta_cq", "fold_change"]].round(6).to_string(index=False))paired.to_csv(out / "donor_results_python.csv")Complete donor pairs: 10Excluded donors: D07, D12donor delta_delta_cq fold_change D01 -1.324167 2.503882 D02 -0.857000 1.811268 D03 -1.444083 2.720899 D04 -1.748167 3.359314 D05 -0.974333 1.964733 D06 -1.096333 2.138106 D08 -1.523333 2.874544 D09 -1.540667 2.909289 D10 -1.675000 3.193194 D11 -0.760667 1.694273Each surviving donor contributes one DeltaDelta Cq, calculated as stimulated
minus control. Therefore 2^(-DeltaDelta Cq) is the donor’s stimulated-to-control
ratio. A negative DeltaDelta Cq produces a ratio greater than one.
Complete-pair analysis excludes a donor when either condition lacks a usable target or reference measurement. If low target abundance causes those failures, the remaining donors can overrepresent higher expression. These results describe the retained pairs; a real study must investigate the missingness before extending that claim to all donors.
Estimate the paired effect on the Cq scale
Section titled “Estimate the paired effect on the Cq scale”The independent units are donors. We use a one-sample t-test of their DeltaDelta Cq values against zero, equivalent to a paired t-test of Delta Cq. Its interval assumes independent donors and approximately normal donor differences. The technical wells do not increase the number of independent observations.
Let m be the mean DeltaDelta Cq and [L, U] its confidence interval. The
estimated expression ratio is 2^(-m), with interval [2^(-U), 2^(-L)].
The endpoints reverse because the transformation decreases as DeltaDelta Cq
increases. This ratio is the geometric mean of the donor ratios, not their
arithmetic mean.
fit <- t.test(paired$delta_delta_cq, mu = 0)mean_difference <- mean(paired$delta_delta_cq)ci <- unname(fit$conf.int)ratio <- 2^(-mean_difference)ratio_ci <- 2^(-rev(ci))effect <- data.frame( n_pairs = nrow(paired), mean_delta_delta_cq = mean_difference, ci_low = ci[1], ci_high = ci[2], fold_change = ratio, fold_ci_low = ratio_ci[1], fold_ci_high = ratio_ci[2], t_statistic = unname(fit$statistic), p_value = fit$p.value)cat(sprintf("Mean DeltaDelta Cq: %.3f cycles\n", mean_difference))cat(sprintf("95%% interval: [%.3f, %.3f] cycles\n", ci[1], ci[2]))cat(sprintf("Geometric mean expression ratio: %.3f\n", ratio))cat(sprintf("95%% ratio interval: [%.3f, %.3f]\n", ratio_ci[1], ratio_ci[2]))cat(sprintf("Paired t-test: t = %.3f, df = %d, p = %.6g\n", fit$statistic, fit$parameter, fit$p.value))write.csv(effect, "outputs/effect_r.csv", row.names = FALSE)Mean DeltaDelta Cq: -1.294 cycles95% interval: [-1.545, -1.044] cyclesGeometric mean expression ratio: 2.45395% ratio interval: [2.062, 2.918]Paired t-test: t = -11.682, df = 9, p = 9.67823e-07differences = paired["delta_delta_cq"].to_numpy()fit = stats.ttest_1samp(differences, popmean=0)ci = fit.confidence_interval(confidence_level=0.95)mean_difference = differences.mean()ratio = 2.0 ** (-mean_difference)ratio_ci = 2.0 ** (-np.array([ci.high, ci.low]))effect = pd.DataFrame({ "n_pairs": [len(paired)], "mean_delta_delta_cq": [mean_difference], "ci_low": [ci.low], "ci_high": [ci.high], "fold_change": [ratio], "fold_ci_low": [ratio_ci[0]], "fold_ci_high": [ratio_ci[1]], "t_statistic": [fit.statistic], "p_value": [fit.pvalue],})print(f"Mean DeltaDelta Cq: {mean_difference:.3f} cycles")print(f"95% interval: [{ci.low:.3f}, {ci.high:.3f}] cycles")print(f"Geometric mean expression ratio: {ratio:.3f}")print(f"95% ratio interval: [{ratio_ci[0]:.3f}, {ratio_ci[1]:.3f}]")print(f"Paired t-test: t = {fit.statistic:.3f}, " f"df = {len(paired) - 1}, p = {fit.pvalue:.6g}")effect.to_csv(out / "effect_python.csv", index=False)Mean DeltaDelta Cq: -1.294 cycles95% interval: [-1.545, -1.044] cyclesGeometric mean expression ratio: 2.45395% ratio interval: [2.062, 2.918]Paired t-test: t = -11.682, df = 9, p = 9.67823e-07The interval estimates uncertainty across the retained donors under the model. It does not include uncertainty about reference gene stability or amplification efficiency. Those assumptions determine whether the expression ratio means what the calculation says.
Show donors and the estimated ratio
Section titled “Show donors and the estimated ratio”The paired plot preserves each donor’s measurements. The middle panel displays the donor differences used by the t-test. The final panel puts individual ratios beside their geometric mean and its interval on a logarithmic axis.
png("outputs/qpcr_paired_r.png", width = 1650, height = 650, res = 150)par(mfrow = c(1, 3), mar = c(4.5, 4.6, 3, 1))limits <- range(paired[c("delta_cq.control", "delta_cq.stimulated")])plot(c(1, 2), limits, type = "n", xaxt = "n", xlab = "", ylab = "Delta Cq", main = "Retained donor pairs")axis(1, at = c(1, 2), labels = c("Control", "Stimulated"))for (i in seq_len(nrow(paired))) { lines(c(1, 2), c(paired$delta_cq.control[i], paired$delta_cq.stimulated[i]), col = "#82959C")}points(rep(1, nrow(paired)), paired$delta_cq.control, pch = 16, col = "#28647C")points(rep(2, nrow(paired)), paired$delta_cq.stimulated, pch = 16, col = "#B65132")plot(seq_len(nrow(paired)), paired$delta_delta_cq, pch = 16, xaxt = "n", xlab = "Donor", ylab = "DeltaDelta Cq", ylim = range(c(0, paired$delta_delta_cq)), col = "#28647C", main = "Differences enter the test")axis(1, at = seq_len(nrow(paired)), labels = paired$donor, las = 2, cex.axis = 0.7)abline(h = 0, lty = 2, col = "#69797F")abline(h = mean_difference, col = "#B65132", lwd = 2)ratio_limits <- range(c(1, paired$fold_change, ratio_ci)) * c(0.85, 1.15)plot(paired$fold_change, seq_len(nrow(paired)), log = "x", pch = 16, xlim = ratio_limits, ylim = c(0, nrow(paired) + 1), yaxt = "n", xlab = "Stimulated / control expression", ylab = "", col = "#28647C", main = "Donor ratios and mean")axis(2, at = c(0, seq_len(nrow(paired))), labels = c("Mean", paired$donor), las = 1, cex.axis = 0.7)abline(v = 1, lty = 2, col = "#69797F")segments(ratio_ci[1], 0, ratio_ci[2], 0, col = "#B65132", lwd = 3)points(ratio, 0, pch = 18, cex = 1.4, col = "#B65132")invisible(dev.off())
fig, axes = plt.subplots(1, 3, figsize=(13, 4.6))for row in paired.itertuples(): axes[0].plot([0, 1], [row.control, row.stimulated], color="#82959c")axes[0].scatter(np.zeros(len(paired)), paired["control"], color="#28647c")axes[0].scatter(np.ones(len(paired)), paired["stimulated"], color="#b65132")axes[0].set(xticks=[0, 1], xticklabels=["Control", "Stimulated"], ylabel="Delta Cq", title="Retained donor pairs")positions = np.arange(len(paired))donors = paired.index.get_level_values("donor")axes[1].scatter(positions, differences, color="#28647c")axes[1].axhline(0, color="#69797f", linestyle="--")axes[1].axhline(mean_difference, color="#b65132")axes[1].set(xticks=positions, xticklabels=donors, xlabel="Donor", ylabel="DeltaDelta Cq", title="Differences enter the test")axes[1].tick_params(axis="x", labelrotation=90)axes[2].scatter(paired["fold_change"], positions + 1, color="#28647c")axes[2].errorbar(ratio, 0, xerr=[[ratio - ratio_ci[0]], [ratio_ci[1] - ratio]], fmt="D", color="#b65132", capsize=4)axes[2].axvline(1, color="#69797f", linestyle="--")axes[2].set(xscale="log", yticks=np.arange(len(paired) + 1), yticklabels=["Mean", *donors], xlabel="Stimulated / control expression", title="Donor ratios and mean")fig.tight_layout()fig.savefig(out / "qpcr_paired_python.png", dpi=150)plt.close(fig)
A p-value from these invented observations is a demonstration of a calculation. For a real experiment, report the assay and reference validation, the donor count after exclusions, the exclusion reasons, the effect scale, and its interval. Keep the raw well table so another analyst can recover each donor’s normalized measurement.
Scientific references
Section titled “Scientific references”Livak and Schmittgen, 2001 describe the comparative Cq method for relative gene expression.
Pfaffl, 2001 derives a relative expression model that incorporates target and reference amplification efficiencies.
Vandesompele and colleagues, 2002 describe reference gene selection and normalization with the geometric mean of multiple reference quantities.
Bustin and colleagues, 2025 revise the MIQE recommendations for qPCR design, assay validation, analysis, and reporting.
Further reading
Section titled “Further reading”The RDML MIQE checklist separates assay validation, control results, reference gene justification, and biological and technical replicates. Use these categories to document the evidence behind a Cq table.
The R t-test documentation and SciPy one-sample t-test reference define the mean-difference test and its confidence interval. The paired-samples lesson explains the same experimental unit using direct measurements from paired donors.