Test pathways with a defensible protein background
A pathway test depends on which proteins could have entered its foreground. The whole genome is not the sampling background for a filtered proteomics experiment. We use the eligible tested protein groups that also meet a declared annotation rule.
This lesson uses the accepted differential table and a preserved human membership file from Reactome release 98. The source contains memberships at all levels of the pathway hierarchy.
Resolve the group before counting it
Section titled “Resolve the group before counting it”A protein group contributes at most one observation to a pathway. Expanding a shared group into several gene names would count one measured signal several times and alter the test’s denominator.
The mapping retains every member accession. A group is eligible only when every member has a reviewed human UniProt accession and the same nonempty Reactome membership set. Groups with incompatible or missing member annotations remain in an exclusion table with their membership and reason. This conservative rule can discard useful measurements, but it prevents an arbitrary representative accession from deciding the pathway assignment.
We apply the same mapping rule to the foreground and background. Keeping an ambiguous group only when it appears significant would bias the test toward the desired conclusion.
The join reports the number of tested groups, mapped groups, excluded groups, and pathway memberships before enrichment. Those losses describe the part of the measured proteome that the interpretation can represent.
Define one hypothesis family
Section titled “Define one hypothesis family”The foreground uses the declared differential threshold among mapped tested groups. The background contains all mapped eligible tested groups, including the foreground. Both sets use protein-group identifiers rather than duplicated accessions.
For each pathway, a one-sided hypergeometric test asks whether the foreground contains more members than expected under sampling from that background. The family contains every pathway with 5 to 500 background groups, including pathways with no foreground hits. The analysis applies BH once across that complete family.
The R and Python examples use the same memberships, foreground, background, size limits, and alternative hypothesis. Their overlap counts, p-values, and adjusted p-values must agree within the recorded tolerances.
Interpret shared membership carefully
Section titled “Interpret shared membership carefully”Reactome pathways overlap and include parent-child relationships. Several small adjusted p-values can arise from the same group of proteins. They do not establish several independent mechanisms.
An enrichment result also lacks a direct activity measurement. Higher abundance of pathway members does not prove higher pathway flux or signaling activity. We inspect the contributing groups, their effect directions, and their culture-level measurements before attaching a biological interpretation.
The figure reports pathway size, foreground overlap, and the adjusted p-value. Its companion table retains the exact contributing groups. The source and license are available through Reactome’s download documentation and data license.
Count the measured groups once
Section titled “Count the measured groups once”The foreground contains mapped tested groups with a moderated differential BH value below 0.05, regardless of effect direction. The test therefore concerns an excess of differential groups, not increased pathway activity. The contributor table retains each group’s signed effect for interpretation.
R regenerates the declared primary limma model from the accepted fixtures. Python verifies the ordinary model and then reads that fresh moderated table to define exactly the same foreground. It independently calculates all pathway overlaps, hypergeometric probabilities, and pathway BH values.
Interpret this cohort
Section titled “Interpret this cohort”The measured background contains 406 mapped tested groups, and the foreground contains 150 differential groups. The complete family contains 448 pathways and produces 0 adjusted findings.
These tests support no pathway enrichment claim for this contrast under the declared mapping and background rules.
The display orders pathways by adjusted p-value, then foreground overlap. In this cohort, the displayed categories describe membership overlap without an adjusted enrichment finding.
library(ggplot2)library(jsonlite)source("/shared/ms_common.R")source("/shared/ms_models.R")data <- PrepareMsAnalysis(LoadMsData())primary <- FitMsLimma(data)WriteMsModelProvenance("outputs/model_provenance_r.json")primary$members <- data$groups$memberswrite.csv(primary, "outputs/primary_limma_r.csv", row.names = FALSE, na = "NA")write.csv(FitMsOrdinary(data), "outputs/ordinary_r.csv", row.names = FALSE, na = "NA")mapping <- read.delim("/fixtures/pathway_mapping.tsv", colClasses = "character", quote = "")membership <- read.delim("/fixtures/pathway_membership.tsv", colClasses = "character", quote = "")stopifnot(identical(mapping$group_id, primary$group_id))pathways <- TestMsPathways(primary, mapping, membership)result <- pathways$resultswrite.csv(result, "outputs/pathway_tests_r.csv", row.names = FALSE)write.csv(data.frame(group_id = pathways$background), "outputs/pathway_background_r.csv", row.names = FALSE)write.csv(data.frame(group_id = pathways$selected), "outputs/pathway_foreground_r.csv", row.names = FALSE)statuses <- sort(unique(mapping$mapping_status))mapping_summary <- data.frame( mapping_status = statuses, all_groups = integer(length(statuses)), tested_groups = integer(length(statuses)))for (index in seq_along(statuses)) { same_status <- mapping$mapping_status == statuses[index] mapping_summary$all_groups[index] <- sum(same_status) mapping_summary$tested_groups[index] <- sum(same_status & primary$tested)}write.csv(mapping_summary, "outputs/mapping_summary_r.csv", row.names = FALSE)contributors <- membership[membership$group_id %in% pathways$selected & membership$pathway_id %in% result$pathway_id, ]contributors <- merge(contributors, primary[c("group_id", "members", "log2_fold_change", "adjusted_p_value")], by = "group_id")contributors <- contributors[order(contributors$pathway_id, contributors$group_id), ]write.csv(contributors, "outputs/pathway_contributors_r.csv", row.names = FALSE)metrics <- list( tested_groups = sum(primary$tested), background_groups = length(pathways$background), foreground_groups = length(pathways$selected), tested_pathways = nrow(result), significant_pathways = sum(result$adjusted_p_value < 0.05))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE)cat("Tested protein groups:", metrics$tested_groups, "\n")cat("Mapped background groups:", metrics$background_groups, "\n")cat("Mapped differential groups:", metrics$foreground_groups, "\n")cat("Pathways in the BH family:", metrics$tested_pathways, "\n")cat("Pathways below BH 0.05:", metrics$significant_pathways, "\n")Tested protein groups: 463Mapped background groups: 406Mapped differential groups: 150Pathways in the BH family: 448Pathways below BH 0.05: 0display <- result[order(result$adjusted_p_value, -result$selected_hits, result$pathway_id), ]display <- head(display, 12L)if (nrow(display)) { display$label <- paste(display$pathway_id, substr(display$pathway_name, 1, 50)) display$label <- factor(display$label, levels = rev(display$label)) display$score <- -log10(pmax(display$adjusted_p_value, .Machine$double.xmin)) enrichment <- ggplot(display, aes(selected_hits, label, size = pathway_background_groups, color = score)) + geom_point() + scale_size_area(max_size = 8) + scale_color_gradient(low = "#b9d4dc", high = "#1c6377") + labs(x = "Differential protein groups", y = NULL, size = "Background groups", color = "-log10 BH") + theme_minimal(base_size = 9)} else { enrichment <- ggplot() + annotate("text", x = 0, y = 0, label = "No pathways meet the declared background size filter") + theme_void()}ggsave("outputs/pathway_enrichment_r.png", enrichment, width = 11, height = 6.5, dpi = 160, bg = "white")mapping_plot <- ggplot( mapping_summary, aes(tested_groups, reorder(mapping_status, tested_groups))) + geom_col(fill = "#287c8e") + labs(x = "Tested protein groups", y = "Annotation decision") + theme_minimal(base_size = 10)ggsave("outputs/pathway_mapping_r.png", mapping_plot, width = 10, height = 4.5, dpi = 160, bg = "white")

import importlib.utilimport jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
modules = {}for name in ["ms_common", "ms_models"]: spec = importlib.util.spec_from_file_location(name, f"/shared/{name}.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) modules[name] = modulems, models = modules["ms_common"], modules["ms_models"]data = ms.prepare_ms_analysis(ms.load_ms_data())ordinary = models.fit_ordinary(data)pd.testing.assert_frame_equal( ordinary, pd.read_csv("outputs/ordinary_r.csv"), check_dtype=False, rtol=1e-10, atol=1e-10)primary = pd.read_csv("outputs/primary_limma_r.csv")if not primary["group_id"].equals(ordinary["group_id"]): raise ValueError("The primary and ordinary group orders differ")np.testing.assert_array_equal(primary["tested"], ordinary["tested"])np.testing.assert_allclose(primary["log2_fold_change"], ordinary["log2_fold_change"], equal_nan=True, rtol=1e-10, atol=1e-10)mapping = pd.read_csv("/fixtures/pathway_mapping.tsv", sep="\t", dtype=str)membership = pd.read_csv("/fixtures/pathway_membership.tsv", sep="\t", dtype=str)if not mapping["group_id"].equals(primary["group_id"]): raise ValueError("The pathway mapping and model group orders differ")result, background, selected = models.pathway_tests(primary, mapping, membership)pd.testing.assert_frame_equal( result, pd.read_csv("outputs/pathway_tests_r.csv"), check_dtype=False, rtol=1e-10, atol=1e-10)result.to_csv("outputs/pathway_tests_python.csv", index=False)for name, identifiers in [("background", background), ("foreground", selected)]: table = pd.DataFrame({"group_id": identifiers}) pd.testing.assert_frame_equal( table, pd.read_csv(f"outputs/pathway_{name}_r.csv"), check_dtype=False) table.to_csv(f"outputs/pathway_{name}_python.csv", index=False)mapping_rows = []for status in sorted(mapping["mapping_status"].unique()): same_status = mapping["mapping_status"].eq(status) mapping_rows.append({ "mapping_status": status, "all_groups": int(same_status.sum()), "tested_groups": int((same_status & primary["tested"]).sum()), })mapping_summary = pd.DataFrame(mapping_rows)pd.testing.assert_frame_equal( mapping_summary, pd.read_csv("outputs/mapping_summary_r.csv"), check_dtype=False)mapping_summary.to_csv("outputs/mapping_summary_python.csv", index=False)contributor_mask = (membership["group_id"].isin(selected) & membership["pathway_id"].isin(result["pathway_id"]))contributors = membership.loc[contributor_mask]contributors = contributors.merge( primary[["group_id", "members", "log2_fold_change", "adjusted_p_value"]], on="group_id", validate="many_to_one")contributors = contributors.sort_values(["pathway_id", "group_id"])expected = pd.read_csv("outputs/pathway_contributors_r.csv")pd.testing.assert_frame_equal( contributors[expected.columns].reset_index(drop=True), expected, check_dtype=False, rtol=1e-10, atol=1e-10)contributors.to_csv("outputs/pathway_contributors_python.csv", index=False)metrics = { "tested_groups": int(primary["tested"].sum()), "background_groups": len(background), "foreground_groups": len(selected), "tested_pathways": len(result), "significant_pathways": int(result["adjusted_p_value"].lt(0.05).sum()),}Path("outputs/metrics_python.json").write_text(json.dumps(metrics, indent=2))print("Tested protein groups:", metrics["tested_groups"])print("Mapped background groups:", metrics["background_groups"])print("Mapped differential groups:", metrics["foreground_groups"])print("Pathways in the BH family:", metrics["tested_pathways"])print("Pathways below BH 0.05:", metrics["significant_pathways"])Tested protein groups: 463Mapped background groups: 406Mapped differential groups: 150Pathways in the BH family: 448Pathways below BH 0.05: 0display = result.sort_values( ["adjusted_p_value", "selected_hits", "pathway_id"], ascending=[True, False, True]).head(12)figure, axis = plt.subplots(figsize=(11, 6.5))if len(display): positions = np.arange(len(display)) score = -np.log10(np.maximum(display["adjusted_p_value"], np.finfo(float).tiny)) sizes = 20 + 180 * display["pathway_background_groups"] / 500 image = axis.scatter(display["selected_hits"], positions, s=sizes, c=score, cmap="Blues", edgecolor="#287c8e") labels = display["pathway_id"] + " " + display["pathway_name"].str[:50] axis.set_yticks(positions, labels, fontsize=8) axis.invert_yaxis() axis.set_xlabel("Differential protein groups") axis.set_title("Point area indicates background group count") figure.colorbar(image, ax=axis, label="-log10 BH")else: axis.text(0.5, 0.5, "No pathways meet the declared background size filter", ha="center", va="center", transform=axis.transAxes) axis.set_axis_off()figure.tight_layout()figure.savefig("outputs/pathway_enrichment_python.png", dpi=160, facecolor="white")plt.close(figure)display_mapping = mapping_summary.sort_values("tested_groups")figure, axis = plt.subplots(figsize=(10, 4.5))axis.barh(display_mapping["mapping_status"], display_mapping["tested_groups"], color="#287c8e")axis.set_xlabel("Tested protein groups")axis.set_ylabel("Annotation decision")figure.tight_layout()figure.savefig("outputs/pathway_mapping_python.png", dpi=160, facecolor="white")plt.close(figure)

The pathway table retains zero-hit tests and the mapping table retains excluded groups. When the differential foreground is empty, every tested pathway has a hypergeometric p-value of one. That result remains a valid output rather than a reason to change the foreground threshold.
Data reference
Section titled “Data reference”Reactome’s license agreement assigns CC0 to database data and CC BY 4.0 to its pathway illustrations. The membership file used here is data. These terms differ from the licenses for Reactome software.
Further reading
Section titled “Further reading”The Reactome data agreement distinguishes its database data from illustrations and software. It identifies the terms that apply to the pathway membership table used here.
The R p-value adjustment reference explains BH correction. Read it alongside the declared pathway family and the observed protein universe; the adjustment cannot repair a biased universe.