Level 1 · Foundations · Topic 6 of 6

Experimental design and statistics essentials

Replicates, controls, confounders, p-values, effect sizes and multiple testing, with simulations you can run and a real batch effect to find.

  • About 90 minutes
  • 7 code cells · 4 checked exercises
  • 10-question check
  • Runs in your browser

What you will learn

  • Identify the experimental unit, and tell biological replicates from technical replicates and pseudoreplication.
  • Explain how randomisation, blocking and balanced designs protect against confounding and batch effects.
  • Describe uncertainty with standard errors and confidence intervals, including the bootstrap.
  • Explain what a p-value is and is not, and run t-tests and permutation tests.
  • Relate effect size, sample size and power, and explain why low power exaggerates the effects that are found.
  • Control false discoveries when testing thousands of genes, and use Python to find a batch effect in real RNA-seq data.

Before you start: Topic 1.5, especially counts per million and fold changes. Basic Python from the earlier code labs. No previous statistics is needed: everything is built from simulations and real data, in your browser.

Why this matters for bioinformatics

Every result a bioinformatics pipeline produces rests on an experiment and on statistics. A sequencer cannot rescue an experiment in which every treated sample was processed on a different day from every control, and no algorithm can rescue one with too few replicates. In genomics the statistics also has to cope with scale: a single RNA-seq experiment tests thousands of genes at once, and a test that is right 95% of the time will be wrong hundreds of times.

Batch effects are a well-documented example. Measurements change with laboratory conditions, reagent lots and the people doing the work, and when those differences line up with the groups being compared they can lead to wrong conclusions. The decisions that prevent this, such as how many replicates to collect and which samples to process together, are made before any data exist. This topic covers those decisions and the statistics that come after them: confidence intervals, p-values, power and multiple testing.

Designing an experiment: units, replicates and controls

The experimental unit is the smallest thing to which a treatment is applied independently: a mouse, a culture flask, a patient. The number of units, not the number of measurements, is the sample size that statistics cares about.

  • Biological replicates are independent units: different animals, separately grown cultures, different people. They capture the natural variation that a result must hold up against.
  • Technical replicates are repeated measurements of the same unit, such as sequencing one library on two lanes. They measure the noise of the method, but say nothing about whether a result holds in another animal.
  • Pseudoreplication is treating measurements that are not independent as if they were: counting 100 cells from 2 mice as 100 replicates, or two lanes of one library as two samples. It makes results look far more certain than they are. In one survey of a single issue of Nature Neuroscience, 12% of papers had pseudoreplication and a further 36% were suspected of it.
Three animals, each sampled and measured once, are three biological replicates. One animal sampled once and measured three times gives three technical replicates but a sample size of one. Sixty cells from two animals are still a sample size of two: treating the cells as independent is pseudoreplication.
Swipe sideways to see the whole figure. Biological replicates are independent units; technical replicates are repeated measurements of one unit. Here there are 3 biological replicates per group, whatever the number of measurements. Open full size

Controls, randomisation, blocking and blinding

  • Controls show what happens without the treatment. A negative control receives everything except the treatment itself, such as the solvent a drug is dissolved in or a non-targeting RNA in a knockdown experiment; a positive control shows that the method can detect an effect at all.
  • Randomisation decides by chance which unit gets which treatment, and in which order samples are processed, so that unknown differences are spread evenly between the groups.
  • Blocking groups similar units and compares treatments within each group: if only four samples fit in a sequencing run, put two treated and two controls in every run, rather than all the treated samples in one.
  • Blinding keeps the person measuring or scoring from knowing which group a sample belongs to.

How many replicates?

Enough to detect the effect you care about, which a power calculation can estimate (below). For RNA-seq, an experiment with 48 replicates per group gave a direct answer: with three replicates, most analysis tools found only 20% to 40% of the genes that 42 clean replicates showed to change, though they found more than 85% of those changing more than four-fold. The authors recommended at least six biological replicates, and at least twelve when it matters to find genes with small changes.

Confounding and batch effects

A confounder is a variable that is linked both to the groups being compared and to the outcome, so that its effect cannot be separated from the effect of interest. In laboratory work the usual confounders are batch effects: technical differences between groups of samples processed separately, such as the day of RNA extraction, a reagent lot, the person, the sequencing run or the library preparation method.

Batch effects are not a problem in themselves; every laboratory has them. They become a problem when they line up with the groups. If all treated samples are sequenced in one run and all controls in another, every difference between the runs is added to the treatment effect, and no analysis can take it out again. If each run contains both conditions, the batch can be measured and allowed for.

Left: the seven samples of the real pasilla experiment, arranged by condition and library type. Untreated samples are both single-end (untreated1 and 2) and paired-end (untreated3 and 4); knockdown samples are single-end (treated1) and paired-end (treated2 and 3). Right: the same seven samples in a confounded design, in which all untreated samples are single-end and all knockdown samples paired-end.
Swipe sideways to see the whole figure. Left: the real pasilla experiment. Both library types appear in both conditions, so the batch and the treatment can be told apart. Right: a confounded design with the same seven samples, in which library type and treatment always change together. Open full size

Before testing anything, look at the data. Principal component analysis (PCA) finds the directions in which the samples differ most. For the pasilla samples, the first principal component, 52% of the variation among the 500 most variable genes, separates the knockdown samples from the untreated ones. The second, 32%, separates single-end from paired-end libraries: the library type is a real batch effect, about as large as a biological signal. You will reproduce this in the code lab.

Variation and uncertainty: standard errors and confidence intervals

Two different numbers describe spread, and they are easy to confuse:

  • The standard deviation (SD) describes how much individual values vary. It does not shrink as you collect more data.
  • The standard error (SE) describes how uncertain an estimate, such as a mean, is. For a mean it is SD / √n, so it shrinks as the sample grows: four times as many units halve it.

A 95% confidence interval is a range computed from the data by a method that, over many repeated experiments, would contain the true value 95% of the time. It shows how precisely an effect has been measured, which a p-value alone does not. Intervals can be calculated from formulas or by the bootstrap: resampling the units with replacement many times, recalculating the estimate each time and taking the middle 95% of the results.

An example from topic 1.4: 30 of the 216 alleles carried by the 108 Yoruba people (YRI) in the 1000 Genomes Project are the sickle-cell allele, a frequency of 13.9%. Its 95% confidence interval is about 10% to 19%. A survey of 108 people pins the frequency down only roughly. When you bootstrap, resample the 108 people, not the 216 alleles: the person is the unit that was sampled.

Hypothesis tests and p-values

A hypothesis test starts from a null hypothesis, usually that there is no difference between the groups. A test statistic measures how far the data are from what the null hypothesis predicts. For two means, the t statistic is the difference divided by its standard error. The null distribution describes the values the statistic would take if the null hypothesis, and the test’s assumptions, were true.

The p-value is the probability, under that null distribution, of a test statistic at least as extreme as the one observed. A small p-value means the data would be surprising if there were no difference.

The t distribution with 5 degrees of freedom, which the t statistic follows when two groups of 3 and 4 samples come from the same normal distribution. An observed t of 2.6 leaves 2.4% of the distribution beyond it, and another 2.4% lies beyond −2.6, so the two-sided p-value is 0.048.
Swipe sideways to see the whole figure. The t distribution with 5 degrees of freedom, the null distribution of the t statistic for comparing two groups of 3 and 4 samples. An observed t of 2.6 leaves 2.4% of the distribution beyond it on each side: a two-sided p-value of 0.048. Open full size
  • The t-test was published in 1908 by William Gosset, a chemist at the Guinness brewery in Dublin, under the pen name “Student”. It assumes roughly normal data; Welch’s version drops the assumption that the two groups have equal variances and is a sensible default.
  • Permutation tests make almost no assumptions. If the treatment had no effect, the group labels are arbitrary, so shuffle them every possible way, recompute the difference each time and ask how unusual the real one is. With few samples there are few shuffles: 4 untreated and 3 treated samples can be split in only 35 ways, so no permutation test can give a p-value below 1/35, about 0.029.

What a p-value does not tell you

In 2016 the American Statistical Association published six principles for using p-values. Three are worth memorising:

  • A p-value is not the probability that the null hypothesis is true, nor the probability that the data were produced by chance alone.
  • Conclusions should not rest only on whether a p-value passes a threshold such as 0.05.
  • A p-value does not measure the size of an effect or how important it is.

With enough samples a tiny, biologically meaningless difference becomes “significant”; with too few, a large and real one may not. Always report the effect size and its confidence interval alongside the p-value.

Effect sizes, power and sample size

An effect size says how big a difference is: a difference in means, a fold change, or a standardised effect such as Cohen’s d, the difference divided by the standard deviation. A test can go wrong in two ways:

A two-by-two table of the truth against the test result. With no real effect, a non-significant result is correct and a significant one is a type I error, a false positive, with probability alpha. With a real effect, a non-significant result is a type II error, a false negative, with probability beta, and a significant one is correct, with probability 1 minus beta: the power.
Swipe sideways to see the whole figure. The four possible outcomes of a test. The false positive rate is set by the significance threshold; the false negative rate depends on the effect size, the noise and the sample size. Open full size

The power of an experiment is the probability that it detects an effect of a given size, if the effect is real. It rises with the effect size and the number of replicates, and falls as noise increases. For a t-test at the 0.05 threshold, detecting a difference of one standard deviation with 80% power takes 17 samples per group; half a standard deviation takes 64. With 3 samples per group the power for a one-standard-deviation difference is only 16%.

Low power has a second, less obvious cost. When a small study does reach significance, it is usually because the noise happened to push the estimate upwards, so the significant results of underpowered studies overestimate the true effect. With 4 samples per group and a true difference of half a standard deviation, the experiments that reach significance overestimate it about three-fold on average; with 30 per group, by about 40%. Low power also lowers the chance that a significant result reflects a true effect at all, one reason why many published findings fail to replicate.

Interactive

Run a thousand experiments

Each run simulates 1,000 experiments that compare two groups drawn from normal distributions, and tests each with Welch’s t-test. Set the true difference to zero to see false positives; increase the sample size to see power grow. The coloured bars are the experiments that reached p < 0.05.

Testing thousands of genes at once

A 5% false positive rate is reasonable for a single test, but an RNA-seq analysis runs one test per gene. With 7,908 expressed genes and no real changes at all, about 395 genes would still reach p < 0.05. There are two main ways to control this:

  • The family-wise error rate (FWER) is the probability of even one false positive. The Bonferroni correction controls it by testing each gene at 0.05 divided by the number of tests. It is very strict: in the pasilla experiment only 8 genes pass.
  • The false discovery rate (FDR) is the expected proportion of false positives among the genes called significant. The Benjamini–Hochberg procedure (1995) controls it; its adjusted p-values are often loosely called q-values. At an FDR of 10%, 481 pasilla genes pass: on average, fewer than one in ten of them should be false discoveries.

Genome-scale studies almost always use the FDR, because finding most of the real changes at the cost of a known, small proportion of false ones is a better trade than finding almost none.

A histogram of the p-values of 7,908 expressed genes. 1,530 genes fall in the first bar, below 0.05, against about 395 expected per bar if no gene changed. The rest of the histogram is a nearly flat floor of about 290 genes per bar, made mostly of genes that do not change.
Swipe sideways to see the whole figure. p-values from Welch’s t-test for the 7,908 expressed genes in the pasilla experiment, knockdown against untreated, calculated from the hosted count table. Genes that do not change give p-values spread evenly between 0 and 1; real changes pile up near 0. Open full size

A p-value histogram is the first plot to make after testing many features. A flat histogram with a peak near zero is healthy: the flat part, here about 290 genes per bar, comes mostly from genes that do not change, which suggests that roughly three-quarters of the genes are unaffected. A histogram that rises towards 1, or has bumps in the middle, warns that the test’s assumptions do not fit the data.

Good statistical practice

  • Plan before you collect. Write down the question, the experimental unit, the groups, the batches, the planned comparisons and the test before the data arrive.
  • Look at the data first. Plot distributions and a PCA, check for outliers and batch effects, and check the assumptions of the test you intend to use.
  • Report everything. The number of units per group, the test, effect sizes with confidence intervals, exact p-values, the number of tests and the correction used.
  • Avoid forking paths. Trying analyses until one gives p < 0.05 (p-hacking) or presenting an unexpected finding as if it had been the hypothesis all along (HARKing) makes p-values meaningless.
  • Use models made for the data. RNA-seq counts are better analysed with methods built for them, such as DESeq2 and edgeR, which model counts directly, share information between genes and can include batch in the model. You will use them in Level 4; the ideas in this topic are what they are built on.

Code lab: simulations and a real experiment

Each box below is Python that runs in your browser: press Run (or Ctrl + Enter). The first box downloads Python and the SciPy library, which takes a little longer than usual; after that, runs are quick. Your edits are saved in this browser until you press Reset.

The first two boxes use simulated data, where the truth is known. The rest use real data: the 1000 Genomes genotypes from topic 1.4 and the pasilla RNA-seq counts. Boxes marked Exercise are checked automatically, with a hint and a worked solution.

Example

p-values when nothing is going on

Simulate 10,000 experiments in which both groups come from the same distribution, so the null hypothesis is true by construction, and look at the p-values the t-test gives.

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

rng = np.random.default_rng(2026)
experiments, n = 10000, 4
a = rng.normal(loc=10, scale=1, size=(experiments, n))     # group A: 4 samples per experiment
b = rng.normal(loc=10, scale=1, size=(experiments, n))     # group B: the same distribution, so no real difference
p = stats.ttest_ind(a, b, axis=1).pvalue                   # one t-test per experiment

print(f"{experiments:,} experiments with no real difference")
print(f"p < 0.05 in {np.mean(p < 0.05):.1%} of them; p < 0.01 in {np.mean(p < 0.01):.1%}")

plt.figure(figsize=(6.4, 3))
plt.hist(p, bins=20, range=(0, 1), color="#97a3b6")
plt.axhline(experiments / 20, color="#b3261e", linestyle="--", linewidth=1)
plt.xlabel("p-value")
plt.ylabel("experiments")
plt.title("When the null hypothesis is true, p-values are uniform")
plt.show()
What you should see

About 5% of the experiments give p < 0.05 and about 1% give p < 0.01, although nothing is different between the groups. When the null hypothesis is true, every p-value between 0 and 1 is equally likely, so the histogram is flat. That is what the 0.05 threshold means: 1 in 20 tests of a true null hypothesis will be “significant”.

Exercise

Measure power by simulation

Write simulated_power: simulate experiments in which group B is shifted by effect standard deviations, test each one and return the fraction with p < 0.05. Compare your answers with the exact formula.

import math
import numpy as np
from scipy import stats

rng = np.random.default_rng(7)

def exact_power(n, effect):
    """Power of a two-sided t-test at 0.05, from the noncentral t distribution."""
    df = 2 * n - 2
    shift = effect * math.sqrt(n / 2)
    critical = stats.t.ppf(0.975, df)
    return stats.nct.sf(critical, df, shift) + stats.nct.cdf(-critical, df, shift)

def simulated_power(n, effect, experiments=4000):
    """Fraction of simulated experiments (n samples per group, true difference = effect SDs) with p < 0.05."""
    return 0.0     # TODO: draw a and b as in the previous box, but with b centred on effect instead of 0

print("n per group   simulated   exact formula")
for n in (3, 4, 6, 10, 17, 25):
    print(f"{n:>11}   {simulated_power(n, 1.0):>9.3f}   {exact_power(n, 1.0):>13.3f}")
print()
print(f"With no real difference, {simulated_power(10, 0.0):.1%} of experiments are significant: the false positive rate")
Example

A confidence interval three ways

Estimate the frequency of the sickle-cell allele in the Yoruba sample (YRI) of the 1000 Genomes Project, and its 95% confidence interval: from a simple formula, from the Wilson formula and by bootstrapping the people.

Data: 1kGP_high_coverage_chr11_5225001-5230000.vcf.gz integrated_call_samples_v3.20130502.ALL.panel

import gzip
import numpy as np
from scipy import stats

population = {}
with open("integrated_call_samples_v3.20130502.ALL.panel") as handle:
    next(handle)
    for line in handle:
        sample, pop = line.split("\t")[:2]
        population[sample] = pop
with gzip.open("1kGP_high_coverage_chr11_5225001-5230000.vcf.gz", "rt") as handle:
    for line in handle:
        if line.startswith("#CHROM"):
            samples = line.rstrip("\n").split("\t")[9:]
        elif not line.startswith("#"):
            fields = line.rstrip("\n").split("\t")
            if fields[1] == "5227002" and fields[4] == "A":          # the sickle-cell allele
                genotypes = dict(zip(samples, fields[9:]))

copies = np.array([genotypes[s].count("1") for s in samples if population.get(s) == "YRI"])   # 0, 1 or 2 per person
k, n = copies.sum(), 2 * len(copies)
estimate = k / n
print(f"{len(copies)} people, {k} sickle-cell alleles out of {n}: frequency {estimate:.3f}")

se = np.sqrt(estimate * (1 - estimate) / n)                       # standard error of a proportion
print(f"Simple formula, estimate ± 1.96 SE: {estimate - 1.96 * se:.3f} to {estimate + 1.96 * se:.3f}")
wilson = stats.binomtest(k, n).proportion_ci(method="wilson")
print(f"Wilson interval:                    {wilson.low:.3f} to {wilson.high:.3f}")

rng = np.random.default_rng(1)
boot = [rng.choice(copies, size=len(copies)).sum() / n for _ in range(10000)]    # resample people
low, high = np.percentile(boot, [2.5, 97.5])
print(f"Bootstrap over the people:          {low:.3f} to {high:.3f}")
What you should see

All three methods agree that the frequency, 0.139, is known only to within about 4 to 5 percentage points either way: roughly 0.10 to 0.19. The simple formula is symmetric and can misbehave for rare alleles, the Wilson interval is a better formula for proportions, and the bootstrap needs no formula at all. The bootstrap resamples whole people because people, not alleles, were sampled.

Example

Look before you test: a PCA of the pasilla samples

Principal component analysis of the 500 most variable genes. NumPy’s singular value decomposition finds the directions in which the samples differ most.

Data: pasilla_gene_counts.tsv pasilla_sample_annotation.csv

import csv
import numpy as np
import matplotlib.pyplot as plt

with open("pasilla_gene_counts.tsv") as handle:
    samples = handle.readline().rstrip("\n").split("\t")[1:]
    genes, rows = [], []
    for line in handle:
        fields = line.rstrip("\n").split("\t")
        genes.append(fields[0])
        rows.append([int(x) for x in fields[1:]])
counts = np.array(rows, dtype=float)                 # 14,599 genes x 7 samples
cpm = counts / counts.sum(axis=0) * 1e6              # counts per million: correct for library size

library_type = {}
with open("pasilla_sample_annotation.csv") as handle:
    for row in csv.DictReader(handle):
        library_type[row["file"].removesuffix("fb")] = row["type"]      # treated1fb -> treated1

log_cpm = np.log2(cpm + 1)
top = np.argsort(log_cpm.var(axis=1))[::-1][:500]            # the 500 most variable genes
x = log_cpm[top].T - log_cpm[top].T.mean(axis=0)              # samples x genes, centred
u, s, vt = np.linalg.svd(x, full_matrices=False)
scores = u * s
explained = s ** 2 / np.sum(s ** 2)
print(f"PC1 explains {explained[0]:.1%} of the variation, PC2 {explained[1]:.1%}")
for name, (pc1, pc2) in zip(samples, scores[:, :2]):
    print(f"  {name:<11} {library_type[name]:<12} PC1 {pc1:6.1f}  PC2 {pc2:6.1f}")

plt.figure(figsize=(5.2, 4))
for name, (pc1, pc2) in zip(samples, scores[:, :2]):
    plt.scatter(pc1, pc2, s=90, color="#0b7a6e" if name.startswith("untreated") else "#c4600a",
                marker="o" if library_type[name] == "single-read" else "s")
    plt.annotate(name, (pc1, pc2), textcoords="offset points", xytext=(6, 6), fontsize=8)
plt.xlabel(f"PC1 ({explained[0]:.0%})")
plt.ylabel(f"PC2 ({explained[1]:.0%})")
plt.title("Colour: condition. Shape: library type")
plt.show()
What you should see

PC1 (51.8%) separates the knockdown samples from the untreated ones. PC2 (32.0%) separates the three single-end libraries from the four paired-end ones, whatever their condition. (Which side of zero a group falls on is arbitrary: only the separation matters.) The library type is a real, large batch effect. Because both types occur in both conditions, it can be estimated and allowed for; had the types followed the conditions, it would have been inseparable from the knockdown.

Exercise

An exact permutation test

Is pasilla really lower in the knockdown samples? Try every way of labelling 3 of the 7 samples as “treated”, compute the difference in means for each, and find the fraction at least as extreme as the real one.

Data: pasilla_gene_counts.tsv

import itertools
import numpy as np
from scipy import stats

with open("pasilla_gene_counts.tsv") as handle:
    samples = handle.readline().rstrip("\n").split("\t")[1:]
    genes, rows = [], []
    for line in handle:
        fields = line.rstrip("\n").split("\t")
        genes.append(fields[0])
        rows.append([int(x) for x in fields[1:]])
counts = np.array(rows, dtype=float)                 # 14,599 genes x 7 samples
cpm = counts / counts.sum(axis=0) * 1e6              # counts per million: correct for library size

log_cpm = np.log2(cpm[genes.index("FBgn0261552")] + 1)      # the pasilla gene, on a log scale
untreated, treated = [0, 1, 2, 3], [4, 5, 6]                # column indices of the two groups
observed = log_cpm[treated].mean() - log_cpm[untreated].mean()
print("pasilla, log2(CPM + 1):", np.round(log_cpm, 2))
print(f"Observed difference, knockdown minus untreated: {observed:.3f}")

differences = []
# TODO: for every combination of 3 sample indices (itertools.combinations(range(7), 3)), treat them as the
#       "treated" group and the other 4 as "untreated", and append the difference in mean log_cpm
p_value = 0.0      # TODO: fraction of differences whose absolute value is >= abs(observed)

print(f"{len(differences)} ways to choose which 3 of the 7 samples are 'treated'")
print(f"Permutation p-value: {p_value:.4f}  (the smallest possible is 1/{len(differences)} = {1 / len(differences):.4f})")
welch = stats.ttest_ind(log_cpm[treated], log_cpm[untreated], equal_var=False)
print(f"Welch's t-test p-value: {welch.pvalue:.4f}  (assumes the values follow normal distributions)")
Exercise

Control the false discovery rate

Test every expressed gene with Welch’s t-test (given), then write the Benjamini–Hochberg procedure: sort the p-values, multiply the i-th smallest by m / i, make the results non-decreasing from the largest down, cap them at 1 and put them back in the original order.

Data: pasilla_gene_counts.tsv

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

with open("pasilla_gene_counts.tsv") as handle:
    samples = handle.readline().rstrip("\n").split("\t")[1:]
    genes, rows = [], []
    for line in handle:
        fields = line.rstrip("\n").split("\t")
        genes.append(fields[0])
        rows.append([int(x) for x in fields[1:]])
counts = np.array(rows, dtype=float)                 # 14,599 genes x 7 samples
cpm = counts / counts.sum(axis=0) * 1e6              # counts per million: correct for library size

expressed = (cpm >= 1).sum(axis=1) >= 3              # keep genes with at least 1 CPM in 3 or more samples
log_cpm = np.log2(cpm[expressed] + 1)
names = [g for g, keep in zip(genes, expressed) if keep]
untreated, treated = log_cpm[:, :4], log_cpm[:, 4:]

# One Welch t-test per gene, all at once
p = stats.ttest_ind(treated, untreated, axis=1, equal_var=False).pvalue
m = len(p)
print(f"{m:,} genes tested")
print(f"p < 0.05: {np.sum(p < 0.05):,} genes; about {0.05 * m:,.0f} would get there by chance if nothing changed")
print(f"Bonferroni (p < 0.05 / {m:,}): {np.sum(p < 0.05 / m)} genes")

def benjamini_hochberg(p):
    """Benjamini-Hochberg adjusted p-values (q-values), in the same order as p."""
    return np.ones_like(p)     # TODO

q = benjamini_hochberg(p)
print(f"Benjamini-Hochberg, FDR < 0.10: {np.sum(q < 0.10)} genes; FDR < 0.05: {np.sum(q < 0.05)}")
print(f"pasilla itself: p = {p[names.index('FBgn0261552')]:.4f}, q = {q[names.index('FBgn0261552')]:.3f}")

plt.figure(figsize=(6.4, 3))
plt.hist(p, bins=20, range=(0, 1), color="#0b7a6e")
plt.axhline(m / 20, color="#b3261e", linestyle="--", linewidth=1, label="expected if no gene changed")
plt.xlabel("p-value")
plt.ylabel("genes")
plt.legend()
plt.title("p-values for 7,908 genes, pasilla knockdown vs untreated")
plt.show()

Check your understanding

Ten questions. Score 70% or more to complete this part of the topic. You can retake it as often as you like.

1You culture cells from 3 mice per group and sequence each culture twice. How many biological replicates per group are there?
2All treated samples are sequenced on Monday and all controls on Friday. What is the main problem?
3Which statement about the standard error of a mean is true?
4A test gives p = 0.03. Which interpretation is correct?
5With 4 samples in one group and 3 in the other, what is the smallest p-value an exact permutation test can give?
6What is statistical power?
7Why do significant results from small studies tend to overestimate effects?
8You test 10,000 genes, none of which really changes. About how many will have p < 0.05?
9What does controlling the false discovery rate at 10% mean?
10Your p-value histogram is flat with a peak near 0. What does this suggest?

Mini project: how a batch changes an apparent effect

In the pasilla experiment, some samples were sequenced single-end and others paired-end. Use that real batch to see what an unbalanced design does to a comparison.

  1. Keep genes with a mean of at least 10 counts per million and work on the log scale (given).
  2. Write log_fold_change(group_a, group_b): the mean log2 expression of group b minus that of group a, for every gene.
  3. Compare three pairs of groups: untreated samples sequenced in different ways, which differ only in the batch; treated against untreated within the same library type, a fair comparison; and treated paired-end against untreated single-end, in which the treatment and the batch change together.
Exercise

Batch and biology

Data: pasilla_gene_counts.tsv

import numpy as np
with open("pasilla_gene_counts.tsv") as handle:
    samples = handle.readline().rstrip("\n").split("\t")[1:]
    genes, rows = [], []
    for line in handle:
        fields = line.rstrip("\n").split("\t")
        genes.append(fields[0])
        rows.append([int(x) for x in fields[1:]])
counts = np.array(rows, dtype=float)                 # 14,599 genes x 7 samples
cpm = counts / counts.sum(axis=0) * 1e6              # counts per million: correct for library size

expressed = cpm.mean(axis=1) >= 10                   # genes with a mean of at least 10 CPM
log_cpm = np.log2(cpm[expressed] + 1)
names = [g for g, keep in zip(genes, expressed) if keep]
column = {name: i for i, name in enumerate(samples)}

untreated_single = ["untreated1", "untreated2"]      # sequenced single-end
untreated_paired = ["untreated3", "untreated4"]      # sequenced paired-end
treated_paired = ["treated2", "treated3"]            # sequenced paired-end
print(len(names), "genes with a mean of at least 10 CPM")

def log_fold_change(group_a, group_b):
    """Mean log2(CPM + 1) of group_b minus that of group_a, for every gene. Groups are lists of sample names."""
    return np.zeros(len(names))     # TODO: use column[name] to find each sample's column in log_cpm

batch = log_fold_change(untreated_single, untreated_paired)     # same condition, different library type
fair = log_fold_change(untreated_paired, treated_paired)        # different condition, same library type
confounded = log_fold_change(untreated_single, treated_paired)  # different condition AND library type

two_fold = lambda lfc: np.abs(lfc) > 1
print(f"Batch only (no treatment difference): {two_fold(batch).sum()} genes change more than 2-fold")
print(f"Fair comparison, same library type:   {two_fold(fair).sum()} genes")
print(f"Confounded comparison:                {two_fold(confounded).sum()} genes")
spurious = two_fold(confounded) & ~two_fold(fair)
missed = two_fold(fair) & ~two_fold(confounded)
print(f"  {spurious.sum()} of them are not 2-fold changes in the fair comparison, and it misses {missed.sum()} that are")
print(f"Agreement between the fair and confounded estimates: r = {np.corrcoef(fair, confounded)[0, 1]:.3f}")
i = names.index("FBgn0261552")
print(f"pasilla: fair {fair[i]:.2f}, confounded {confounded[i]:.2f}")

Go further

  • Repeat the comparisons with genes of at least 1 CPM in 3 samples. Do low-expressed genes make the batch problem better or worse?
  • Make an MA plot: the mean log2 expression of each gene against its fold change, for the fair and the confounded comparison.
  • Use statsmodels to fit, for each of a few genes, a linear model with both condition and library type, and compare the condition effect with the simple difference in means.
  • Simulate a balanced and a confounded design yourself: add a batch effect to simulated data and see how often each design finds a difference that is not there.

Summary and further reading

Key takeaways

  • The experimental unit sets the sample size. Biological replicates measure biological variation; technical replicates only measure the method, and counting them as independent is pseudoreplication.
  • Randomise, block and balance. A batch that lines up with the groups is a confounder that no analysis can remove; a batch spread across the groups can be estimated and allowed for.
  • The standard deviation describes the data, the standard error the estimate. A confidence interval shows how precisely an effect has been measured; the bootstrap resamples units to estimate one.
  • A p-value is the probability of data at least this extreme if the null hypothesis were true. It is not the probability that the hypothesis is true, and it does not measure effect size.
  • Power depends on effect size, noise and sample size. Underpowered studies miss real effects and exaggerate the ones they find.
  • Testing thousands of genes produces hundreds of false positives at p < 0.05. Control the false discovery rate, for example with Benjamini–Hochberg, and check the p-value histogram.

Key terms

Data used on this page

References and further reading

  1. Leek JT, et al. Tackling the widespread and critical impact of batch effects in high-throughput data. Nature Reviews Genetics 11, 733–739 (2010). doi:10.1038/nrg2825
  2. Lazic SE. The problem of pseudoreplication in neuroscientific studies: is it affecting your analysis? BMC Neuroscience 11, 5 (2010). doi:10.1186/1471-2202-11-5
  3. Blainey P, Krzywinski M, Altman N. Replication. Nature Methods 11, 879–880 (2014). doi:10.1038/nmeth.3091
  4. Schurch NJ, et al. How many biological replicates are needed in an RNA-seq experiment and which differential expression tool should you use? RNA 22, 839–851 (2016). doi:10.1261/rna.053959.115
  5. Student. The probable error of a mean. Biometrika 6, 1–25 (1908). doi:10.1093/biomet/6.1.1
  6. Wilson EB. Probable inference, the law of succession, and statistical inference. Journal of the American Statistical Association 22, 209–212 (1927). doi:10.1080/01621459.1927.10502953
  7. Efron B. Bootstrap methods: another look at the jackknife. The Annals of Statistics 7, 1–26 (1979). doi:10.1214/aos/1176344552
  8. Wasserstein RL, Lazar NA. The ASA statement on p-values: context, process, and purpose. The American Statistician 70, 129–133 (2016). doi:10.1080/00031305.2016.1154108
  9. Krzywinski M, Altman N. Significance, P values and t-tests. Nature Methods 10, 1041–1042 (2013). doi:10.1038/nmeth.2698
  10. Krzywinski M, Altman N. Power and sample size. Nature Methods 10, 1139–1140 (2013). doi:10.1038/nmeth.2738
  11. Button KS, et al. Power failure: why small sample size undermines the reliability of neuroscience. Nature Reviews Neuroscience 14, 365–376 (2013). doi:10.1038/nrn3475
  12. Halsey LG, et al. The fickle P value generates irreproducible results. Nature Methods 12, 179–185 (2015). doi:10.1038/nmeth.3288
  13. Benjamini Y, Hochberg Y. Controlling the false discovery rate: a practical and powerful approach to multiple testing. Journal of the Royal Statistical Society B 57, 289–300 (1995). doi:10.1111/j.2517-6161.1995.tb02031.x
  14. Storey JD, Tibshirani R. Statistical significance for genomewide studies. PNAS 100, 9440–9445 (2003). doi:10.1073/pnas.1530509100
  15. Kriegeskorte N, et al. Circular analysis in systems neuroscience: the dangers of double dipping. Nature Neuroscience 12, 535–540 (2009). doi:10.1038/nn.2303
  16. Ioannidis JPA. Why most published research findings are false. PLoS Medicine 2, e124 (2005). doi:10.1371/journal.pmed.0020124
  17. Love MI, Huber W, Anders S. Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2. Genome Biology 15, 550 (2014). doi:10.1186/s13059-014-0550-8
  18. Brooks AN, et al. Conservation of an RNA regulatory map between Drosophila and mammals. Genome Research 21, 193–202 (2011). doi:10.1101/gr.108662.110
  19. Poldrack RA. Statistical Thinking for the 21st Century: a free online textbook. statsthinking21.github.io

Finished the topic?

Pass the check and the exercises, or mark the topic complete yourself. Progress is saved in this browser.