Take a protein intensity table and a metabolite feature table from raw numbers to a list of changes: log-transform, see why most gaps mean too low to see, filter, normalise with median centring and PQN, test with false discovery rate control, and judge how sure each identification is before testing enrichment.
From spectra to a table
In Pathways and enrichment analysis you started from a list of changed genes and asked what they had in common. This lesson is about where such a list comes from when the molecules measured are proteins or metabolites rather than RNA. Module 1's Proteomics and metabolomics explained how mass spectrometry and NMR take the measurements. Here the instruments have finished, the search software has run, and you are handed a table. What you do with that table decides which proteins or metabolites end up on your list.
Two kinds of table are common. A proteomics experiment gives a protein intensity table: one row per protein, one column per sample, and in each cell a number that grows with how much of that protein was in the sample. Software such as MaxQuant, DIA-NN or Spectronaut builds it from thousands of peptide signals. Because a peptide can be shared by related proteins, rows are often protein groups: proteins the peptides cannot tell apart. MaxQuant's proteinGroups.txt also has flag columns for decoy hits and lab contaminants such as skin keratin, which are removed first.
A metabolomics experiment run by liquid chromatography and mass spectrometry (LC-MS) gives a feature table. A feature is a signal defined by its mass-to-charge ratio (m/z) and its retention time, the moment it left the chromatography column. Tools such as XCMS, MZmine and MS-DIAL find features and line them up across samples. A feature is not yet a metabolite: one compound usually gives several features, and many features never get a name.
Unlike RNA-seq counts, both tables hold continuous intensities with many gaps, and the gaps are not random. A real public dataset runs to gigabytes of raw files, so this lesson uses simulated data: a protein table with the shape and quirks of a real label-free experiment, 2,000 proteins in 6 control and 6 treated samples, 200 of which truly change. Because we built it, we know the right answer and can see which choices find it. The code runs in Google Colab with NumPy, pandas and SciPy, already installed.
import numpy as np, pandas as pd
rng = np.random.default_rng(42)
n_prot, groups = 2000, ["ctrl"] * 6 + ["treat"] * 6
samples = [f"{g}_{i % 6 + 1}" for i, g in enumerate(groups)]
true = rng.normal(24, 2.5, n_prot) # log2 abundance of each protein
change = np.zeros(n_prot)
hit = rng.choice(n_prot, 200, replace=False) # 10% really change
change[hit] = rng.choice([-1, 1], 200) * rng.uniform(1, 2, 200)
log2 = np.empty((n_prot, 12))
for j, g in enumerate(groups):
load = rng.normal(0, 0.4) # how much was loaded in this run
log2[:, j] = true + (change if g == "treat" else 0) + load + rng.normal(0, 0.3, n_prot)
p_miss = 1 / (1 + np.exp((log2 - 21.5) / 0.5)) # faint proteins drop out (MNAR)
missing = (rng.random(log2.shape) < p_miss) | (rng.random(log2.shape) < 0.02) # + 2% at random (MCAR)
raw = np.where(missing, 0, 2 ** log2).astype("int64") # search software writes 0 for "not seen"
prot = pd.DataFrame(raw, columns=samples,
index=[f"P{i:05d}" for i in range(n_prot)])
print(prot.iloc[:4, [0, 1, 6, 7]].to_string())
print("zeros:", f"{(prot == 0).mean().mean():.1%}")What this does
changemoves 200 proteins up or down by a log2 fold change of 1 to 2 (two- to fourfold);loadshifts each whole sample a little, as when more or less material is injected.p_missmakes faint proteins likely to vanish, and 2% of values vanish at random. Gaps are written as 0, as many tools do.
Reading the output
About one value in five is 0. P00001 is missing from two of the four columns shown. That does not mean the cells had none of it, only that the instrument did not pick it up in that run.
Log scale and missing values
The first step is the one you met with expression data: take log2. Raw intensities are skewed and their noise grows with the signal; on the log scale a doubling is a step of 1 and the noise is similar across the range. First, the zeros must become NaN, Python's marker for "no value". A zero would give a logarithm of minus infinity, and would claim the protein was absent, which nobody measured.
lg = np.log2(prot.replace(0, np.nan)) # 0 means "not seen", not zero protein print(lg.iloc[:4, [0, 1, 6, 7]].round(2).to_string()) mean_seen = lg.mean(axis=1) # average over the runs where it was seen frac_missing = lg.isna().mean(axis=1) bins = pd.qcut(mean_seen, 4, labels=["faintest", "low", "high", "brightest"]) print(frac_missing.groupby(bins, observed=True).mean().round(3).to_string())
Reading the output
The proteins are sorted into four equal groups by their average intensity in the runs where they were seen. Half of all values are missing among the faintest quarter, but only about 2% among the brightest. That pattern is the signature of the two kinds of missing value you need to tell apart:
- Missing not at random (MNAR): the value is missing because it was low. The protein was there, but below what the instrument could detect in that run. Most gaps in proteomics and metabolomics are of this kind.
- Missing completely at random (MCAR): the value is missing for reasons unrelated to its size, for example a peptide that happened not to be selected for fragmentation in one run, or a peak the software failed to align.
A gap that means "low" carries information: a protein seen in all six treated samples and no controls is probably much lower in controls. Methods that treat every gap as random throw that away. Checking missingness against intensity, as above, shows which kind dominates.
Filtering and normalisation
A protein seen in only one or two of twelve runs cannot be compared fairly, so the next step is a valid-value filter. A common rule, used here, keeps a protein if it was measured in at least 4 of the 6 samples of at least one group. Requiring "at least one group" rather than "every group" keeps proteins that switch on or off between conditions, which are often the interesting ones.
Then comes normalisation: removing differences between whole samples that are not biology, such as how much material was loaded. The simplest method on the log scale is median centring: subtract each sample's median from every value in it, then add back the average median so the numbers stay on a familiar scale. It rests on one assumption, the same one behind the RNA-seq methods of Module 4: most proteins do not change between conditions, so any shift of the whole sample is technical.
ctrl, treat = lg.columns[:6], lg.columns[6:]
valid = (lg[ctrl].notna().sum(axis=1) >= 4) | (lg[treat].notna().sum(axis=1) >= 4)
lg = lg[valid]
print("proteins kept:", len(lg), "of", len(prot))
med = lg.median() # one median per sample
print("medians before:", med.round(2).tolist())
lg = lg - med + med.mean() # median centring
print("medians after: ", lg.median().round(2).tolist())Reading the output
The filter keeps 1,665 of the 2,000 proteins; the rest were too often unseen. Before normalisation, the sample medians differ by up to about 0.8 on the log2 scale, nearly a twofold difference that is purely technical. Afterwards they are identical. The medians use only values that were seen, so they sit a little high; as long as gaps are spread similarly across samples, that bias cancels out.
How to read this figure
Read left to right. The first two steps have one right answer. The highlighted three have several reasonable versions, each able to add or remove proteins, so a methods section should state all three.
To impute or not
Imputation means filling gaps with estimated values so that every protein has a full row. The right estimate depends on why a value is missing, which you rarely know for any single gap. The code compares three options:
- No imputation. Test on the values seen. Proteins absent from a whole group cannot be tested.
- Row mean. Fill each gap with the protein's average. This assumes the gap is random.
- Down-shifted normal. Draw random values from a narrow bell curve 1.8 standard deviations below each sample's mean and 0.3 standard deviations wide, the defaults in the Perseus software. This assumes the gap means "below detection".
Each is tested with Welch's t-test, which compares two means without assuming equal spread, and corrected with Benjamini–Hochberg, as in the previous lesson.
import warnings
from scipy.stats import ttest_ind, false_discovery_control
warnings.simplefilter("ignore") # SciPy warns about rows it cannot test; we handle them below
def downshift(df, shift=1.8, width=0.3, seed=1):
"""Fill gaps from a narrow normal curve below each sample's observed values."""
r = np.random.default_rng(seed)
out = df.copy()
for c in df:
m, s = df[c].mean(), df[c].std()
gaps = df[c].isna()
out.loc[gaps, c] = r.normal(m - shift * s, width * s, gaps.sum())
return out
def test(df):
t, p = ttest_ind(df[treat], df[ctrl], axis=1, equal_var=False, nan_policy="omit")
res = pd.DataFrame({"log2FC": df[treat].mean(axis=1) - df[ctrl].mean(axis=1),
"p": np.ma.filled(p, np.nan)}, index=df.index).dropna()
res["q"] = false_discovery_control(res["p"], method="bh")
return res.sort_values("p")
options = {"no imputation": lg,
"row mean": lg.T.fillna(lg.mean(axis=1)).T,
"down-shifted": downshift(lg)}
results = {name: test(df) for name, df in options.items()}
for pid in ["P01343", "P00791"]:
print(pid, "seen in ctrl", lg.loc[pid, ctrl].notna().sum(), "| treat", lg.loc[pid, treat].notna().sum())
for name, res in results.items():
if pid in res.index:
print(f" {name:14s} log2FC {res.loc[pid, 'log2FC']:5.2f} q {res.loc[pid, 'q']:.3f}")
else:
print(f" {name:14s} not testable")What this does
downshiftfills each sample separately; a differentseedgives slightly different results, itself a warning sign.testruns Welch's t-test on every row (axis=1), skipping gaps; rows that cannot be tested are dropped before the q-values.
Reading the output
P01343 really falls in treated samples: seen in all six controls and no treated samples, a textbook MNAR case. Without imputation it cannot be tested. The row mean copies the control level into the treated samples and reports a fold change of exactly 0, turning "too low to see" into "unchanged". Down-shifting points the right way, about twofold down, but its noisy values leave q at 0.11.
P00791 does not change. It is faint and was missed in all six treated runs by bad luck. Down-shifting filled those gaps with values above its measured control values, because the curve is placed relative to the whole sample, not this protein. The result is an increase with q = 0.028 that does not exist. A test cannot tell guesses from measurements.
truly = set(prot.index[hit]) & set(lg.index) # we only know this because we simulated
print("really changed and kept:", len(truly))
for name, res in results.items():
sig = res[(res.q < 0.05) & (res.log2FC.abs() >= 1)]
real = len(set(sig.index) & truly)
print(f"{name:14s} tested {len(res):4d} called {len(sig):3d} real {real:3d} false {len(sig) - real}")
top = results["no imputation"].head(5).copy()
top["n_ctrl"] = lg.loc[top.index, ctrl].notna().sum(axis=1)
top["n_treat"] = lg.loc[top.index, treat].notna().sum(axis=1)
print(top.to_string(float_format="{:.2g}".format))What this does
trulyholds the proteins we built to change that survived filtering; real data never give you this.- A protein is "called" if q < 0.05 and its absolute log2 fold change is at least 1, common cut-offs.
Reading the output
164 of the 200 changed proteins survived the filter. Here, no imputation calls the most real changes, 128, and no option makes a false call at these cut-offs. Row-mean filling loses some by shrinking differences; down-shifting loses more by adding noise to proteins that were mostly measured. With more on/off proteins the balance could tip the other way. Imputation is a modelling decision with costs, not a cleaning step.
A sensible default: test proteins with enough real values, and report proteins seen in one group only as a separate list. If you impute, match the method to the kind of gap and check your main findings survive another choice.
The last table is the shape of a typical results table: log2 fold change, p, q and valid values per group. Real tables add the gene name and the number of peptides behind each protein; one quantified from a single peptide deserves less trust than one with ten.
Go deeper: better tests for few replicates
With six samples per group, each protein's variance is estimated from very little data, so a t-test is easily fooled by a protein that happens to look unusually steady. Moderated tests, such as limma's empirical Bayes method, borrow strength across all proteins: each protein's variance is pulled towards the typical variance of proteins at a similar level. This gives more stable results and usually more power. limma is an R package, used for proteomics intensities as well as for the microarrays it was first written for. In Python, the Welch test used here is a fair, if conservative, baseline.
Metabolomics: dilution and PQN
Metabolomics tables need everything above, plus one extra problem. In urine, overall concentration varies a lot because people drink different amounts: a sample twice as dilute has every metabolite at half the level.
Dividing each sample by its total signal is thrown off when one big peak really changes: the total rises, and every other feature is scaled down wrongly. Probabilistic quotient normalisation (PQN) is more robust. It builds a reference sample, the median of each feature across samples, divides every feature by its reference value, and takes the median of those quotients as the sample's dilution factor. A few real changes barely move a median. The simulation below has 400 features in 10 urine samples with known dilutions, and one huge peak that rises tenfold in half of them.
rng = np.random.default_rng(7)
n_feat = 400
base = rng.lognormal(10, 1.5, n_feat) # typical level of each feature
dilution = rng.uniform(0.4, 2.5, 10) # how concentrated each urine sample was
conc = base[:, None] * rng.lognormal(0, 0.2, (n_feat, 10))
conc[0] = base.max() * 2 # feature F000 is the biggest peak
conc[0, 5:] *= 10 # ...and it rises tenfold in samples 6 to 10
met = pd.DataFrame(conc * dilution, index=[f"F{i:03d}" for i in range(n_feat)],
columns=[f"urine_{j + 1}" for j in range(10)])
def pqn(df):
ref = df.median(axis=1) # reference: the median sample
quotients = df.div(ref, axis=0) # every feature, divided by the reference
factor = quotients.median() # one dilution factor per sample
return df / factor, factor
total = met.sum() / met.sum().mean() # total-signal normalisation, for comparison
_, f_pqn = pqn(met)
check = pd.DataFrame({"true": dilution / dilution.mean(),
"total": total, "PQN": f_pqn / f_pqn.mean()})
print(check.round(2).T.to_string())Reading the output
Factors are scaled to average 1. PQN recovers the truth to within 0.04 in every sample. Total-signal normalisation overestimates the factor by about 0.15 to 0.25 in samples 6 to 10, where the big peak rose, and underestimates it in samples 1 to 5. Every other feature would then appear to fall in samples 6 to 10: a fake signal across hundreds of features.
PQN works on raw intensities and is followed by the log transform, filtering, gap handling and testing shown for proteins. Runs also include pooled quality-control samples, a mixture of all samples injected at intervals, to track instrument drift and drop unstable features.
How sure is the identification?
In proteomics, identification is controlled statistically. Spectra are matched to peptides, and the search is repeated against a decoy database of reversed or shuffled sequences that cannot be real. Decoy matches show how many false matches to expect at each score, so the software can set a cut-off for a chosen false discovery rate, typically 1% for peptide matches and again for proteins. The Reverse rows in proteinGroups.txt are those decoys.
In metabolomics, identification is often the hardest part, and confidence is reported as a level. The Metabolomics Standards Initiative defines four:
- Level 1, identified: matched to an authentic chemical standard run in the same lab, on at least two independent properties such as retention time and fragmentation spectrum.
- Level 2, putatively annotated: matched to a spectral library or the literature, without a standard.
- Level 3, putatively characterised class: the type of compound is clear, for example a lipid class, but not the exact molecule.
- Level 4, unknown: a reproducible feature with no assignment.
In untargeted studies most features stay at level 4. A results table should give the level of every named metabolite: a pathway story built on level 3 guesses is far weaker than one built on level 1.
The target-decoy approach was set out by Elias and Gygi (2007, Nature Methods); the identification levels come from Sumner et al. (2007, Metabolomics), the Metabolomics Standards Initiative's minimum reporting standards. PQN was introduced by Dieterle et al. (2006, Analytical Chemistry) for NMR urine data and is now used widely in LC-MS too. On imputation, Lazar et al. (2016, Journal of Proteome Research) compared many methods on label-free proteomics data and showed that the best choice depends on whether gaps are mostly MNAR or MCAR. When reading a paper, look for the filter rule, normalisation, imputation and identification confidence.
Where the data live, and the hand-off to enrichment
Many journals require proteomics data to be deposited in a ProteomeXchange repository, and the largest is PRIDE at EMBL-EBI. Accessions start with PXD and a dataset usually holds raw files, search results and often processed tables. Metabolomics data go to MetaboLights, also at EMBL-EBI (accessions starting MTBLS), or the Metabolomics Workbench in the United States. Reanalysing a deposited processed table with the steps above is good practice on real data.
The results table then feeds straight into the methods of Pathways and enrichment analysis. Map protein accessions to gene identifiers (Module 2), or metabolites to identifiers such as KEGG compound numbers. Then mind the background. The few thousand proteins detected are not a random sample of the genome: they are the abundant ones, rich in metabolism and translation. The fair background is the proteins quantified and kept, not all human genes; for metabolites, the ones you could identify.
from scipy.stats import hypergeom
n_list = 128 # proteins called significant
k = 12 # of them, members of "lipid metabolism"
for label, N, K in [("whole genome", 20000, 300), ("detected proteins", 1665, 110)]:
expected = n_list * K / N
p = hypergeom.sf(k - 1, N, K, n_list)
print(f"{label:18s} expected {expected:4.1f} observed {k} p = {p:.2g}")Worked example · the same 12 proteins, two backgrounds
detected proteins: 128 × 110 ÷ 1,665 = 8.5 expected, 12 observed, p = 0.13
Step by step. The set sizes are made up but realistic. Of 128 significant proteins, 12 are in a lipid metabolism set. Against the genome (300 of 20,000 genes) about 1.9 are expected, so 12 looks sixfold enriched. But lipid enzymes are abundant, so 110 of the 1,665 quantified proteins are in the set. Against that background 8.5 are expected, 12 is only 1.4 times that, and p = 0.13. The first test detected that the instrument sees abundant proteins, not that the treatment changed lipid metabolism.
Key point
In proteomics and metabolomics tables, most gaps mean "too low to see", not "random". Log-transform, filter on valid values, normalise with a method that suits the sample (median centring for proteins, PQN for dilute fluids), handle gaps deliberately rather than by default, correct for multiple testing, and report how confident each identification is. Then test enrichment against what you could detect, not the whole genome.
Further reading · Module 6PRIDE database: public proteomics datasets. · MetaboLights: public metabolomics studies. · ProteomeXchange: the consortium behind PXD accessions. · All reading for this course
Check your understanding
1. A protein is measured in all six control samples and in none of the six treated samples. What do the gaps most likely mean?
2. Why is probabilistic quotient normalisation (PQN) preferred to total-signal normalisation for urine metabolomics?
3. A proteomics study quantified 1,665 proteins and found 128 that changed. Which background should an over-representation test use?