π§ Pathway Analysis Fundamentals
π― What is Pathway Analysis?
Pathway analysis is the process of interpreting high-throughput molecular data (genes, proteins, metabolites) in the context of biological pathways. It identifies which pathways are significantly affected in a condition, revealing the functional meaning behind gene lists. KEGG (Kyoto Encyclopedia of Genes and Genomes) is one of the most widely used pathway databases, providing maps for metabolic, signaling, and disease pathways across thousands of organisms.
Why Pathway Analysis Matters
Interpretation: Biological meaning. Enrichment: Over-represented pathways. Mechanism: How genes work together. Comparison: Across conditions. Drug discovery: Targets. Systems: Holistic view.
# KEGG & Pathway Analysis β the big picture
# Interpreting omics data in pathway context.
print("""
=== KEGG & Pathway Analysis ===
What it is:
- Interpret omics data
- Biological pathways
- Over-representation
- Functional meaning
Why it matters:
- Biological interpretation
- Pathway enrichment
- Mechanism of action
- Cross-condition comparison
- Drug discovery
- Systems biology
KEGG:
- Kyoto Encyclopedia of Genes and Genomes
- Pathways, genes, compounds, diseases
- Cross-species
- KO numbers
Other databases:
- Reactome
- WikiPathways
- BioCyc
- PANTHER
- Pathway Commons
Applications:
- Transcriptomics
- Proteomics
- Metabolomics
- Multi-omics
- Disease analysis
- Drug discovery
""")
print("=== Historical Context ===")
print("""
1995: KEGG founded (Kanehisa)
2000: KEGG PATHWAY database
2005: KEGG BRITE, KO
2010: Pathway enrichment tools
2015: GSEA, clusterProfiler
2020: Multi-omics, single-cell
2025: AI, knowledge graphs, integration
""")
print("=== Why It's Hard ===")
print("""
1. COVERAGE
- Not all genes in pathways
- Incomplete annotation
2. CROSS-SPECIES
- Different gene IDs
- Orthology mapping
3. REDUNDANCY
- Overlapping pathways
- Hierarchical
4. STATISTICS
- Multiple testing
- Background choice
5. VISUALIZATION
- Complex maps
- Many genes
""")π― Why KEGG Matters
π― The Value of KEGG
KEGG provides a comprehensive, cross-species, manually curated resource for pathway analysis. It's the most widely used pathway database in bioinformatics.
Key Benefits
Comprehensive: Many pathways. Cross-species: Orthology. Curated: Manual. Visual: Maps. Integrated: Genes, compounds, diseases. Free: Academic.
# Why KEGG Matters
print("=== 1. Comprehensive ===")
print("""
Comprehensive:
- > 500 pathways
- Metabolic, signaling, disease
- > 8,000 organisms
- > 30 million genes
Example:
Glycolysis: hsa00010
MAPK signaling: hsa04010
p53 signaling: hsa04115
Cancer: hsa05200
""")
print("\n=== 2. Cross-Species ===")
print("""
Cross-species:
- KO numbers
- Orthology
- Compare species
Example:
Human gene TP53
β KO K04451
β Mouse gene Trp53
β Same KO
β Same pathway
""")
print("\n=== 3. Curated ===")
print("""
Curated:
- Manual annotation
- Expert review
- Quality
Example:
KEGG pathway maps
β Manually drawn
β Updated regularly
""")
print("\n=== 4. Visual ===")
print("""
Visual:
- Pathway maps
- Diagrams
- Clear
Example:
Glycolysis map
β Enzymes
β Metabolites
β Reactions
""")
print("\n=== 5. Integrated ===")
print("""
Integrated:
- Genes
- Compounds
- Reactions
- Diseases
- Drugs
Example:
Pathway β Genes β Diseases
β Drug targets
""")
print("\n=== 6. Free ===")
print("""
Free:
- Academic use
- Web access
- API
- FTP
Example:
https://www.kegg.jp/
https://rest.kegg.jp/
""")
print("\n=== 7. Enrichment ===")
print("""
Enrichment:
- Gene list β pathways
- Over-representation
- Statistical
Example:
DE genes
β Enriched pathways
β Biological meaning
""")
print("\n=== 8. Drug Discovery ===")
print("""
Drug:
- Target identification
- Pathway analysis
- Drug repurposing
Example:
Cancer pathways
β Drug targets
β Therapeutics
""")
print("\n=== 9. Disease Analysis ===")
print("""
Disease:
- Disease pathways
- Mechanisms
- Biomarkers
Example:
Alzheimer's
β Pathways
β Mechanisms
""")
print("\n=== 10. Systems Biology ===")
print("""
Systems:
- Networks
- Pathways
- Integration
Example:
Multi-omics
β Pathway analysis
β Systems view
""")πΊοΈ KEGG Database
π― KEGG Resources
KEGG is a collection of databases: PATHWAY, GENES, KO, BRITE, COMPOUND, DRUG, DISEASE, and more. Each serves a different purpose.
KEGG Databases
PATHWAY: Maps. GENES: Genomes. KO: Orthology. BRITE: Hierarchy. COMPOUND: Chemicals. DISEASE: Diseases.
# KEGG Database
print("=== KEGG PATHWAY ===")
print("""
PATHWAY:
- Pathway maps
- Metabolic, signaling, disease
- > 500 pathways
- Manually drawn
Example:
hsa00010 β Glycolysis
hsa04010 β MAPK signaling
hsa04115 β p53 signaling
hsa05200 β Cancer
Format:
- KGML (XML)
- PNG (image)
- HTML (web)
""")
print("\n=== KEGG GENES ===")
print("""
GENES:
- Complete genomes
- > 8,000 organisms
- Gene catalogs
Example:
hsa:7157 β Human TP53
mmu:22059 β Mouse Trp53
dme:TP53 β Fly p53
Format:
- FASTA
- Flat file
""")
print("\n=== KEGG KO ===")
print("""
KO (KEGG Orthology):
- Orthologous genes
- Functional groups
- Cross-species
Example:
K04451 β TP53
K00001 β Alcohol dehydrogenase
Format:
- K number
- Functional annotation
""")
print("\n=== KEGG BRITE ===")
print("""
BRITE:
- Hierarchical classifications
- Functional hierarchies
- Protein families
Example:
ko00001 β KEGG Orthology
ko03000 β Transcription factors
ko04131 β Membrane trafficking
Format:
- Hierarchical
- Text
""")
print("\n=== KEGG COMPOUND ===")
print("""
COMPOUND:
- Chemical compounds
- Metabolites
- Drugs
Example:
C00031 β D-Glucose
C00002 β ATP
Format:
- C number
- Chemical structure
""")
print("\n=== KEGG DRUG ===")
print("""
DRUG:
- Approved drugs
- Drug targets
- Drug metabolism
Example:
D00001 β Water
D00123 β Aspirin
Format:
- D number
- Drug information
""")
print("\n=== KEGG DISEASE ===")
print("""
DISEASE:
- Disease entries
- Disease genes
- Pathways
Example:
H00001 β Acute myeloid leukemia
H00002 β Bladder cancer
Format:
- H number
- Disease information
""")
print("\n=== KEGG Modules ===")
print("""
MODULE:
- Functional units
- Sub-pathways
- Building blocks
Example:
M00001 β Glycolysis
M00002 β Gluconeogenesis
Format:
- M number
- Functional module
""")
print("\n=== Database Statistics ===")
print(f"{'Database':<20} {'Entries':<15} {'Description':<30}")
print("-" * 65)
print(f"{'PATHWAY':<20} {'~500':<15} {'Pathway maps':<30}")
print(f"{'GENES':<20} {'~30M':<15} {'Genes':<30}")
print(f"{'KO':<20} {'~25,000':<15} {'Orthologs':<30}")
print(f"{'BRITE':<20} {'~1,000':<15} {'Hierarchies':<30}")
print(f"{'COMPOUND':<20} {'~20,000':<15} {'Compounds':<30}")
print(f"{'DRUG':<20} {'~12,000':<15} {'Drugs':<30}")
print(f"{'DISEASE':<20} {'~2,500':<15} {'Diseases':<30}")
print("\n=== Access ===")
print("""
Web:
- https://www.kegg.jp/
API:
- https://rest.kegg.jp/
FTP:
- ftp://ftp.genome.jp/pub/kegg/
""")π’ KO & BRITE
π― KEGG Orthology
KO (KEGG Orthology) is a classification system that groups orthologous genes from different species into functional units. Each KO has a unique identifier (K number) and links genes to pathways.
KO & BRITE
KO: Ortholog group. K number: ID. BRITE: Hierarchy. Mapping: Gene β KO. Cross-species: Compare. Pathways: Link.
# KO & BRITE
print("=== KO (KEGG Orthology) ===")
print("""
KO:
- Orthologous genes
- Functional group
- Cross-species
Example:
K04451 β TP53
K00001 β Alcohol dehydrogenase
Format:
- K number
- Functional annotation
- Gene links
""")
print("\n=== KO Mapping ===")
print("""
Mapping:
- Gene β KO
- Species-specific
- Orthology
Example:
Human TP53 (hsa:7157)
β KO K04451
Mouse Trp53 (mmu:22059)
β KO K04451
Fly p53 (dme:TP53)
β KO K04451
""")
print("\n=== BRITE ===")
print("""
BRITE:
- Hierarchical classifications
- Functional hierarchies
- Protein families
Example:
ko00001 β KEGG Orthology
ko03000 β Transcription factors
ko04131 β Membrane trafficking
ko02000 β Transporters
Format:
- Hierarchical
- Text
- Gene lists
""")
print("\n=== KO Hierarchy ===")
print("""
Hierarchy:
- ko00001 (KEGG Orthology)
βββ Metabolism
β βββ Carbohydrate metabolism
β βββ Energy metabolism
β βββ ...
βββ Genetic Information Processing
βββ Environmental Information Processing
βββ Cellular Processes
βββ Organismal Systems
βββ Human Diseases
""")
print("\n=== KO Statistics ===")
print("""
Statistics:
- KO entries: ~25,000
- Genes: ~30 million
- Species: ~8,000
- Pathways: ~500
""")
print("\n=== KO Retrieval ===")
print("""
Retrieval:
- KEGG API
- KEGG website
- KEGGREST (R)
- Requests (Python)
Example:
https://rest.kegg.jp/get/K04451
https://rest.kegg.jp/link/hsa/K04451
""")
print("\n=== Python KO Retrieval ===")
print("""
import requests
def get_ko(ko_id):
url = f"https://rest.kegg.jp/get/{ko_id}"
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
def get_ko_genes(ko_id, organism="hsa"):
url = f"https://rest.kegg.jp/link/{organism}/{ko_id}"
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
# Example
ko = get_ko("K04451")
print(ko)
genes = get_ko_genes("K04451", "hsa")
print(genes)
""")
print("\n=== KO to Pathway ===")
print("""
KO β Pathway:
- Link KO to pathways
- Cross-reference
Example:
K04451 (TP53)
β hsa04115 (p53 signaling)
β hsa05200 (Cancer)
β hsa04210 (Apoptosis)
""")
print("\n=== Use Cases ===")
print("""
Use cases:
- Cross-species comparison
- Functional annotation
- Pathway mapping
- Orthology assignment
- Metagenomics
- Comparative genomics
""")π€οΈ Pathway Types
π― Types of KEGG Pathways
KEGG pathways are organized into several categories: metabolism, genetic information processing, environmental information processing, cellular processes, organismal systems, and human diseases.
Pathway Categories
Metabolism: Biochemical. Genetic: DNA/RNA. Environmental: Signaling. Cellular: Processes. Organismal: Systems. Disease: Human.
# Pathway Types
print("=== 1. Metabolism ===")
print("""
Metabolism:
- Carbohydrate
- Energy
- Lipid
- Nucleotide
- Amino acid
- Glycan
- Cofactor
- Secondary metabolites
Examples:
hsa00010 β Glycolysis
hsa00020 β TCA cycle
hsa00190 β Oxidative phosphorylation
hsa00980 β Metabolism of xenobiotics
""")
print("\n=== 2. Genetic Information Processing ===")
print("""
Genetic:
- Transcription
- Translation
- Replication
- Repair
- Folding
- Degradation
Examples:
hsa03010 β Ribosome
hsa03040 β Spliceosome
hsa03410 β Base excision repair
hsa04141 β Protein processing
""")
print("\n=== 3. Environmental Information Processing ===")
print("""
Environmental:
- Signal transduction
- Membrane transport
- Signaling molecules
Examples:
hsa04010 β MAPK signaling
hsa04151 β PI3K-Akt signaling
hsa04310 β Wnt signaling
hsa02010 β ABC transporters
""")
print("\n=== 4. Cellular Processes ===")
print("""
Cellular:
- Cell cycle
- Cell death
- Cell motility
- Transport
- Catabolism
Examples:
hsa04110 β Cell cycle
hsa04210 β Apoptosis
hsa04144 β Endocytosis
hsa04140 β Autophagy
""")
print("\n=== 5. Organismal Systems ===")
print("""
Organismal:
- Immune
- Endocrine
- Circulatory
- Digestive
- Nervous
- Sensory
- Development
- Aging
Examples:
hsa04610 β Complement cascade
hsa04910 β Insulin signaling
hsa04080 β Neuroactive ligand
hsa04211 β Longevity
""")
print("\n=== 6. Human Diseases ===")
print("""
Disease:
- Cancer
- Infectious
- Immune
- Neurodegenerative
- Cardiovascular
- Metabolic
Examples:
hsa05200 β Cancer
hsa05130 β Pathogenic E. coli
hsa05010 β Alzheimer's
hsa04930 β Type II diabetes
""")
print("\n=== 7. Drug Development ===")
print("""
Drug:
- Drug targets
- Drug metabolism
- Drug action
Examples:
hsa00982 β Drug metabolism
hsa07010 β Drug targets
""")
print("\n=== 8. Pathway IDs ===")
print("""
Format:
- Organism prefix (hsa, mmu, etc.)
- 5-digit number
- Category
Examples:
hsa00010 β Human glycolysis
mmu00010 β Mouse glycolysis
eco00010 β E. coli glycolysis
""")
print("\n=== 9. Pathway Size ===")
print(f"{'Category':<30} {'Pathways':<15}")
print("-" * 45)
print(f"{'Metabolism':<30} {'~150':<15}")
print(f"{'Genetic Information':<30} {'~30':<15}")
print(f"{'Environmental Information':<30} {'~50':<15}")
print(f"{'Cellular Processes':<30} {'~50':<15}")
print(f"{'Organismal Systems':<30} {'~100':<15}")
print(f"{'Human Diseases':<30} {'~100':<15}")
print(f"{'Drug Development':<30} {'~10':<15}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Metabolic analysis
- Signaling analysis
- Disease analysis
- Drug discovery
- Systems biology
- Comparative genomics
""")π Pathway Enrichment
π― Finding Over-Represented Pathways
Pathway enrichment analysis identifies KEGG pathways that are over-represented in a set of genes compared to a background. It's the most common pathway analysis method.
Enrichment
Input: Gene list. Background: All genes. Test: Hypergeometric. Correction: FDR. Output: Enriched pathways. Interpret: Biology.
# Pathway Enrichment
print("=== What is Enrichment? ===")
print("""
Enrichment:
- Gene list (e.g., DE genes)
- Background (all genes)
- Over-representation
Example:
100 DE genes
β 20 in "Cell cycle"
β Expected: 5
β Enriched (p < 0.001)
""")
print("\n=== Statistical Test ===")
print("""
Hypergeometric test:
- Probability of observing k or more
- Given N, K, n
Parameters:
- N: total genes
- K: genes in pathway
- n: gene list size
- k: overlap
Example:
N = 20,000
K = 200 (cell cycle)
n = 100 (DE genes)
k = 20 (overlap)
β p-value
""")
print("\n=== Multiple Testing ===")
print("""
Multiple testing:
- Many pathways tested
- False positives
- Correction needed
Corrections:
- Bonferroni: strict
- Benjamini-Hochberg (FDR): common
- Storey: less strict
Example:
500 pathways
β 25 false positives at p < 0.05
β FDR correction
""")
print("\n=== Background ===")
print("""
Background:
- All genes tested
- Or all genes in genome
- Affects results
Example:
RNA-seq: all expressed genes
Microarray: all probes
Genome: all genes
Choice matters!
""")
print("\n=== Tools ===")
print("""
1. clusterProfiler (R)
2. KEGGREST (R)
3. Pathview (R)
4. DAVID (Web)
5. g:Profiler (Web)
6. Enrichr (Web)
7. WebGestalt (Web)
8. KEGG API (Python)
9. GSEA (Web/Desktop)
""")
print("\n=== R clusterProfiler ===")
print("""
library(clusterProfiler)
library(org.Hs.eg.db)
# Enrichment
ekegg <- enrichKEGG(
gene = gene_list,
organism = "hsa",
pvalueCutoff = 0.05,
qvalueCutoff = 0.05
)
# View
head(ekegg)
# Plot
dotplot(ekegg)
barplot(ekegg)
""")
print("\n=== Python KEGGREST ===")
print("""
import requests
from scipy.stats import hypergeom
def kegg_enrichment(gene_list, background, organism="hsa"):
\"\"\"Simple KEGG enrichment.\"\"\"
# Get pathways for genes
# ...
pass
""")
print("\n=== Interpretation ===")
print("""
Interpretation:
- Enriched pathways
- Biological meaning
- Hypotheses
Example:
Cancer dataset
β "Cell cycle" enriched
β Proliferation
β Hypothesis
""")
print("\n=== Common Pitfalls ===")
print("""
Pitfalls:
- Wrong background
- Multiple testing
- Redundant pathways
- Small gene lists
- Annotation bias
Best practices:
- Correct background
- FDR correction
- Filter redundant
- Min gene list (10-20)
- Consider bias
""")
print("\n=== Visualization ===")
print("""
Visualization:
- Bar plot
- Dot plot
- Pathway map
- Network
Tools:
- clusterProfiler
- pathview
- KEGG mapper
""")π GSEA
π― Gene Set Enrichment Analysis
GSEA (Gene Set Enrichment Analysis) determines whether a defined set of genes (e.g., a KEGG pathway) shows statistically significant, concordant differences between two biological states. Unlike enrichment, GSEA uses all genes ranked by expression.
GSEA
Input: Ranked gene list. Sets: Pathways. Method: Running sum. Output: Enrichment score. Correction: FDR. Interpret: Coordinated changes.
# GSEA
print("=== What is GSEA? ===")
print("""
GSEA:
- Gene Set Enrichment Analysis
- Ranked gene list
- Gene sets (pathways)
- Coordinated changes
Difference from enrichment:
- Enrichment: cutoff list
- GSEA: all genes ranked
- GSEA: more sensitive
""")
print("\n=== Algorithm ===")
print("""
Steps:
1. Rank genes by expression
2. For each gene set:
- Calculate running sum
- Enrichment score (ES)
3. Permutation test
4. Normalize (NES)
5. FDR correction
Output:
- ES: enrichment score
- NES: normalized ES
- p-value
- FDR
- Leading edge
""")
print("\n=== Enrichment Score ===")
print("""
ES:
- Maximum deviation from zero
- Running sum
- Positive: enriched at top
- Negative: enriched at bottom
Example:
ES = 0.8
β Enriched at top
β Upregulated
""")
print("\n=== Leading Edge ===")
print("""
Leading edge:
- Genes contributing to ES
- Core enrichment
- Most important
Example:
Pathway with 100 genes
β 20 in leading edge
β Key genes
""")
print("\n=== Tools ===")
print("""
1. GSEA (Broad)
- Desktop
- Web
- Standard
2. clusterProfiler (R)
- gseKEGG
- gseGO
3. fgsea (R)
- Fast
- Flexible
4. GSEApy (Python)
- Python
- Flexible
5. WebGestalt
- Web
- Comprehensive
""")
print("\n=== R clusterProfiler GSEA ===")
print("""
library(clusterProfiler)
# GSEA
gsea <- gseKEGG(
geneList = ranked_genes,
organism = "hsa",
pvalueCutoff = 0.05
)
# View
head(gsea)
# Plot
gseaplot(gsea, geneSetID = "hsa04110")
""")
print("\n=== Python GSEApy ===")
print("""
import gseapy
# GSEA
gsea = gseapy.gsea(
data=expression_data,
gene_sets='KEGG_2021_Human',
cls='phenotype.cls',
permutation_num=1000,
outdir='gsea_output'
)
# View
print(gsea.res2d)
""")
print("\n=== Interpretation ===")
print("""
Interpretation:
- Positive NES: upregulated
- Negative NES: downregulated
- Leading edge: key genes
Example:
Cell cycle: NES = 2.1
β Upregulated
β Proliferation
""")
print("\n=== Advantages ===")
print("""
Advantages:
- No cutoff
- More sensitive
- Detects coordinated changes
- Robust
Disadvantages:
- Slower
- Complex
- Requires ranking
""")
print("\n=== Use Cases ===")
print("""
Use cases:
- Transcriptomics
- Proteomics
- Drug response
- Disease
- Time course
- Single-cell
""")π¨ Pathway Visualization
π― Seeing Pathways
Pathway visualization is crucial for interpreting results. Tools like pathview, KEGG Mapper, and clusterProfiler provide rich visualizations.
Visualization
Pathview: Map data. KEGG Mapper: Web. clusterProfiler: Plots. Cytoscape: Networks. iPath: Multi-omics. Python: Custom.
# Pathway Visualization
print("=== 1. Pathview ===")
print("""
Pathview:
- R package
- Maps data to KEGG pathway
- Color by expression
- Publication quality
Example:
library(pathview)
pv.out <- pathview(
gene.data = gene_data,
pathway.id = "hsa04110",
species = "hsa"
)
""")
print("\n=== 2. KEGG Mapper ===")
print("""
KEGG Mapper:
- Web tool
- Maps genes to pathways
- Color by data
- Interactive
URL:
https://www.kegg.jp/kegg/mapper/
Use:
- Upload gene list
- Select pathway
- Visualize
""")
print("\n=== 3. clusterProfiler ===")
print("""
clusterProfiler:
- R package
- Dot plot
- Bar plot
- Enrichment map
- Network
Example:
dotplot(ekegg)
barplot(ekegg)
cnetplot(ekegg)
emapplot(ekegg)
""")
print("\n=== 4. Cytoscape ===")
print("""
Cytoscape:
- Network visualization
- Pathway analysis
- Enrichment map
Example:
- Import enrichment
- EnrichmentMap
- Clustering
- Layout
""")
print("\n=== 5. iPath ===")
print("""
iPath:
- Web tool
- Multi-omics
- Pathway mapping
- Interactive
URL:
https://pathways.embl.de/
""")
print("\n=== 6. Python Visualization ===")
print("""
import matplotlib.pyplot as plt
import pandas as pd
def plot_pathway_enrichment(results):
\"\"\"Plot pathway enrichment.\"\"\"
df = pd.DataFrame([{
"pathway": r["Description"],
"pvalue": r["pvalue"],
"count": r["Count"]
} for r in results])
df = df.sort_values("pvalue").head(20)
plt.figure(figsize=(10, 8))
plt.barh(df["pathway"], -np.log10(df["pvalue"]), color='purple')
plt.xlabel("-log10(p-value)")
plt.title("Pathway Enrichment")
plt.tight_layout()
plt.savefig("pathway_enrichment.png")
plt.show()
# Use
# plot_pathway_enrichment(results)
""")
print("\n=== 7. Network Visualization ===")
print("""
Network:
- Nodes: Pathways
- Edges: Overlap
- Clusters: Modules
Tools:
- Cytoscape
- NetworkX
- igraph
- clusterProfiler
""")
print("\n=== 8. Best Practices ===")
print("""
1. Sort by p-value
2. Show top 20
3. Color by p-value
4. Size by count
5. Remove redundancy
6. Label clearly
7. Export high-quality
8. Include legend
""")π οΈ Tools (clusterProfiler, pathview, KEGGREST)
π― Pathway Analysis Tools
Many tools exist for KEGG pathway analysis. Each has strengths and is suited to different use cases.
Tools
clusterProfiler: R. pathview: R. KEGGREST: R. GSEApy: Python. DAVID: Web. KEGG Mapper: Web.
# Tools
print("=== clusterProfiler ===")
print("""
clusterProfiler:
- R package
- Enrichment
- GSEA
- Visualization
Features:
- enrichKEGG
- gseKEGG
- dotplot
- barplot
- cnetplot
- emapplot
Install:
BiocManager::install("clusterProfiler")
""")
print("\n=== pathview ===")
print("""
pathview:
- R package
- Map data to pathway
- Color by expression
- Publication quality
Features:
- pathview()
- KEGG pathway
- Gene data
- Compound data
Install:
BiocManager::install("pathview")
""")
print("\n=== KEGGREST ===")
print("""
KEGGREST:
- R package
- KEGG API
- Retrieve data
- Programmatic
Features:
- keggGet
- keggList
- keggLink
- keggFind
Install:
BiocManager::install("KEGGREST")
""")
print("\n=== GSEApy ===")
print("""
GSEApy:
- Python
- GSEA
- Enrichment
- Flexible
Features:
- gsea
- enrichr
- prerank
- Visualization
Install:
pip install gseapy
""")
print("\n=== DAVID ===")
print("""
DAVID:
- Web: david.ncifcrf.gov
- Popular
- Enrichment
- Functional annotation
Features:
- KEGG enrichment
- GO enrichment
- Clustering
- Visualization
""")
print("\n=== KEGG Mapper ===")
print("""
KEGG Mapper:
- Web: kegg.jp/kegg/mapper
- Map genes
- Color pathways
- Interactive
Features:
- Search
- Color
- Export
- Link
""")
print("\n=== Other Tools ===")
print("""
1. WebGestalt
- Web
- Comprehensive
2. g:Profiler
- Web
- Fast
3. Enrichr
- Web
- Simple
4. Reactome
- Web
- Pathways
5. WikiPathways
- Web
- Community
6. PANTHER
- Web
- Classification
7. iPathwayGuide
- Web
- Advanced
""")
print("\n=== Tool Comparison ===")
print(f"{'Tool':<20} {'Type':<15} {'Enrichment':<15} {'GSEA':<15} {'Free':<10}")
print("-" * 75)
print(f"{'clusterProfiler':<20} {'R':<15} {'Yes':<15} {'Yes':<15} {'Yes':<10}")
print(f"{'pathview':<20} {'R':<15} {'No':<15} {'No':<15} {'Yes':<10}")
print(f"{'KEGGREST':<20} {'R':<15} {'No':<15} {'No':<15} {'Yes':<10}")
print(f"{'GSEApy':<20} {'Python':<15} {'Yes':<15} {'Yes':<15} {'Yes':<10}")
print(f"{'DAVID':<20} {'Web':<15} {'Yes':<15} {'No':<15} {'Yes':<10}")
print(f"{'GSEA':<20} {'Desktop':<15} {'No':<15} {'Yes':<15} {'Yes':<10}")
print("\n=== When to Use Which ===")
print("""
USE clusterProfiler:
β R
β Enrichment
β GSEA
β Visualization
USE pathview:
β Map data
β Publication
β KEGG pathway
USE KEGGREST:
β Retrieve data
β Programmatic
β R
USE GSEApy:
β Python
β GSEA
β Flexible
USE DAVID:
β Quick
β No coding
β Popular
USE KEGG Mapper:
β Web
β Interactive
β Visualization
""")π Python Integration
π― Pathway Analysis with Python
Python is a powerful language for KEGG pathway analysis. Here's how to use it with KEGG API, GSEApy, and other libraries.
Python
Requests: KEGG API. GSEApy: GSEA. Pandas: Data. Matplotlib: Plot. NetworkX: Graphs. Automate: Pipeline.
# Python Integration
print("=== 1. KEGG API with Requests ===")
print("""
import requests
def get_kegg_pathway(pathway_id):
url = f"https://rest.kegg.jp/get/{pathway_id}"
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
# Example
pathway = get_kegg_pathway("hsa04110")
print(pathway[:500])
""")
print("\n=== 2. Get Genes in Pathway ===")
print("""
def get_pathway_genes(pathway_id, organism="hsa"):
url = f"https://rest.kegg.jp/link/{organism}/{pathway_id}"
response = requests.get(url)
if response.status_code == 200:
genes = []
for line in response.text.strip().split("\\n"):
parts = line.split("\\t")
if len(parts) == 2:
genes.append(parts[1].replace(f"{organism}:", ""))
return genes
return []
# Example
genes = get_pathway_genes("hsa04110")
print(f"Genes: {len(genes)}")
print(genes[:10])
""")
print("\n=== 3. Map Genes to Pathways ===")
print("""
def map_gene_to_pathways(gene_id, organism="hsa"):
url = f"https://rest.kegg.jp/link/pathway/{organism}:{gene_id}"
response = requests.get(url)
if response.status_code == 200:
pathways = []
for line in response.text.strip().split("\\n"):
parts = line.split("\\t")
if len(parts) == 2:
pathways.append(parts[1])
return pathways
return []
# Example
pathways = map_gene_to_pathways("7157") # TP53
print(pathways)
""")
print("\n=== 4. Simple Enrichment ===")
print("""
import requests
from scipy.stats import hypergeom
import numpy as np
def kegg_enrichment(gene_list, background, organism="hsa"):
\"\"\"Simple KEGG enrichment.\"\"\"
# Get all pathways
url = f"https://rest.kegg.jp/list/pathway/{organism}"
response = requests.get(url)
pathways = {}
for line in response.text.strip().split("\\n"):
parts = line.split("\\t")
if len(parts) == 2:
pathways[parts[0]] = parts[1]
# For each pathway
results = []
N = len(background)
n = len(gene_list)
for pathway_id, name in pathways.items():
# Get genes in pathway
genes = get_pathway_genes(pathway_id, organism)
K = len(genes)
k = len(set(gene_list) & set(genes))
if k > 0:
p = hypergeom.sf(k-1, N, K, n)
results.append({
"pathway": pathway_id,
"name": name,
"count": k,
"pvalue": p
})
# Sort
results.sort(key=lambda x: x["pvalue"])
return results
# Example
# results = kegg_enrichment(gene_list, background)
""")
print("\n=== 5. GSEA with GSEApy ===")
print("""
import gseapy
# GSEA
gsea = gseapy.gsea(
data="expression_data.txt",
gene_sets="KEGG_2021_Human",
cls="phenotype.cls",
permutation_num=1000,
outdir="gsea_output"
)
# View
print(gsea.res2d)
""")
print("\n=== 6. Enrichr with GSEApy ===")
print("""
import gseapy
# Enrichr
enr = gseapy.enrichr(
gene_list=gene_list,
gene_sets="KEGG_2021_Human",
organism="human",
outdir="enrichr_output"
)
# View
print(enr.results)
""")
print("\n=== 7. Visualization ===")
print("""
import matplotlib.pyplot as plt
import numpy as np
def plot_enrichment(results, output="enrichment.png"):
\"\"\"Plot enrichment results.\"\"\"
results = results[:20]
names = [r["name"] for r in results]
pvals = [-np.log10(r["pvalue"]) for r in results]
plt.figure(figsize=(10, 8))
plt.barh(names, pvals, color='purple')
plt.xlabel("-log10(p-value)")
plt.title("KEGG Pathway Enrichment")
plt.tight_layout()
plt.savefig(output)
plt.show()
# Use
# plot_enrichment(results)
""")
print("\n=== 8. Complete Pipeline ===")
print("""
import requests
from scipy.stats import hypergeom
import pandas as pd
def kegg_pipeline(gene_list, background, organism="hsa"):
\"\"\"Complete KEGG enrichment pipeline.\"\"\"
# Get all pathways
url = f"https://rest.kegg.jp/list/pathway/{organism}"
response = requests.get(url)
pathways = {}
for line in response.text.strip().split("\\n"):
parts = line.split("\\t")
if len(parts) == 2:
pathways[parts[0]] = parts[1]
# Enrichment
results = []
N = len(background)
n = len(gene_list)
for pathway_id, name in pathways.items():
genes = get_pathway_genes(pathway_id, organism)
K = len(genes)
k = len(set(gene_list) & set(genes))
if k > 0:
p = hypergeom.sf(k-1, N, K, n)
results.append({
"pathway": pathway_id,
"name": name,
"count": k,
"pvalue": p
})
# Sort and FDR
results.sort(key=lambda x: x["pvalue"])
df = pd.DataFrame(results)
df["fdr"] = df["pvalue"] * len(df) / (df.index + 1)
df = df[df["fdr"] < 0.05]
return df
# Use
# df = kegg_pipeline(gene_list, background)
# print(df.head())
""")βοΈ Database Comparison
π― Which Pathway Database?
KEGG is not the only pathway database. Reactome, WikiPathways, and BioCyc offer different strengths.
Comparison
KEGG: Comprehensive. Reactome: Curated. WikiPathways: Community. BioCyc: Many organisms. PANTHER: Classification. Pathway Commons: Integration.
| Database | Coverage | Curation | Species | Best For |
|---|---|---|---|---|
| KEGG | Comprehensive | Manual | 8,000+ | General, metabolic |
| Reactome | Detailed | Expert | ~20 | Human, signaling |
| WikiPathways | Community | Community | ~30 | Emerging topics |
| BioCyc | Many | Curated | ~20,000 | Microbes, metabolic |
| PANTHER | Classification | Curated | ~100 | Protein families |
| Pathway Commons | Integrated | Integrated | ~20 | Integration |
| MetaCyc | Metabolic | Curated | ~3,000 | Metabolism |
| Ingenuity (IPA) | Commercial | Curated | Human, mouse, rat | Commercial |
# Decision Guide
print("=== Choose Database by Need ===")
print("""
General pathway analysis:
β KEGG
Human signaling:
β Reactome
Emerging topics:
β WikiPathways
Microbes:
β BioCyc
Metabolism:
β MetaCyc
Integration:
β Pathway Commons
Commercial:
β IPA
""")
print("\n=== Speed Comparison ===")
print(f"{'Database':<20} {'Pathways':<15} {'Species':<15} {'API':<10}")
print("-" * 60)
print(f"{'KEGG':<20} {'~500':<15} {'8,000+':<15} {'Yes':<10}")
print(f"{'Reactome':<20} {'~2,500':<15} {'~20':<15} {'Yes':<10}")
print(f"{'WikiPathways':<20} {'~3,000':<15} {'~30':<15} {'Yes':<10}")
print(f"{'BioCyc':<20} {'~3,000':<15} {'~20,000':<15} {'Yes':<10}")
print("\n=== When to Use Which ===")
print("""
USE KEGG:
β General
β Metabolic
β Cross-species
β Enrichment
USE Reactome:
β Human
β Signaling
β Detailed
β Curated
USE WikiPathways:
β Community
β Emerging
β Open
USE BioCyc:
β Microbes
β Metabolic
β Many organisms
USE PANTHER:
β Classification
β Protein families
""")πΌ Use Cases
π― Where KEGG Is Used
KEGG pathway analysis is used across biology: transcriptomics, proteomics, metabolomics, disease research, and drug discovery.
Use Cases
Transcriptomics: DE genes. Proteomics: Proteins. Metabolomics: Metabolites. Disease: Mechanisms. Drug: Targets. Microbiome: Functions.
# Use Cases
print("=== 1. Transcriptomics ===")
print("""
Use case:
- RNA-seq
- DE genes
- Pathway enrichment
Workflow:
1. RNA-seq
2. DE analysis
3. KEGG enrichment
4. Interpretation
Example:
Cancer vs normal
β DE genes
β Cell cycle enriched
β Proliferation
""")
print("\n=== 2. Proteomics ===")
print("""
Use case:
- Mass spectrometry
- Protein list
- Pathway enrichment
Workflow:
1. Proteomics
2. Protein list
3. KEGG enrichment
4. Interpretation
Example:
Drug treatment
β Proteins
β Apoptosis enriched
β Mechanism
""")
print("\n=== 3. Metabolomics ===")
print("""
Use case:
- Metabolites
- Metabolic pathways
- KEGG enrichment
Workflow:
1. Metabolomics
2. Metabolite list
3. KEGG enrichment
4. Interpretation
Example:
Disease
β Metabolites
β TCA cycle enriched
β Mechanism
""")
print("\n=== 4. Multi-Omics ===")
print("""
Use case:
- RNA + protein + metabolite
- Integrated analysis
- Pathways
Workflow:
1. Multi-omics
2. Integration
3. KEGG enrichment
4. Systems view
Example:
Cancer
β Multi-omics
β Pathways
β Mechanism
""")
print("\n=== 5. Disease Analysis ===")
print("""
Use case:
- Disease genes
- Pathways
- Mechanisms
Workflow:
1. Disease genes
2. KEGG enrichment
3. Pathways
4. Mechanism
Example:
Alzheimer's
β Disease genes
β Pathways
β Amyloid
""")
print("\n=== 6. Drug Discovery ===")
print("""
Use case:
- Drug targets
- Pathways
- Repurposing
Workflow:
1. Drug targets
2. KEGG enrichment
3. Pathways
4. Repurposing
Example:
Drug
β Targets
β Pathways
β New uses
""")
print("\n=== 7. Microbiome ===")
print("""
Use case:
- Metagenomics
- KEGG modules
- Functions
Workflow:
1. Metagenomics
2. KO annotation
3. KEGG modules
4. Functions
Example:
Gut microbiome
β KO
β Pathways
β Functions
""")
print("\n=== 8. Single-Cell ===")
print("""
Use case:
- scRNA-seq
- Cell types
- Pathways
Workflow:
1. scRNA-seq
2. Clustering
3. KEGG enrichment
4. Cell-type specific
Example:
Tumor
β Cell types
β Pathways
β Heterogeneity
""")
print("\n=== 9. Plant Biology ===")
print("""
Use case:
- Plant genomics
- Pathways
- Traits
Workflow:
1. Plant genomics
2. DE genes
3. KEGG enrichment
4. Traits
Example:
Drought
β DE genes
β Pathways
β Tolerance
""")
print("\n=== 10. Microbiology ===")
print("""
Use case:
- Bacterial genomes
- Metabolic pathways
- Functions
Workflow:
1. Bacterial genome
2. KO annotation
3. KEGG pathways
4. Functions
Example:
Pathogen
β Genome
β Pathways
β Targets
""")β FAQ
π― Frequently Asked Questions
Answers to common questions about KEGG and pathway analysis.
What is KEGG?
KEGG (Kyoto Encyclopedia of Genes and Genomes) is a comprehensive database resource for understanding high-level functions and utilities of biological systems from molecular-level information. It includes pathway maps, gene catalogs, chemical compounds, and disease information.
What is a KEGG pathway?
A KEGG pathway is a diagrammatic representation of molecular interactions, reactions, and networks in a biological process. Examples include metabolic pathways (e.g., glycolysis, TCA cycle), signaling pathways (e.g., MAPK, p53), and disease pathways. Each pathway has a unique ID (e.g., hsa00010 for glycolysis).
What is a KO number?
A KO (KEGG Orthology) number is a unique identifier (e.g., K00001) assigned to a group of orthologous genes that share the same function. KO numbers link genes across species to KEGG pathways, enabling cross-species pathway analysis.
What is pathway enrichment analysis?
Pathway enrichment analysis identifies KEGG pathways that are over-represented (enriched) in a set of genes (e.g., differentially expressed genes) compared to a background. It uses statistical tests (hypergeometric, Fisher's exact) and corrects for multiple testing (FDR). Tools include clusterProfiler, KEGGREST, and DAVID.
What is GSEA?
GSEA (Gene Set Enrichment Analysis) is a method that determines whether a defined set of genes (e.g., a KEGG pathway) shows statistically significant, concordant differences between two biological states. Unlike enrichment, GSEA uses all genes ranked by expression, not just a cutoff list.
What is the difference between KEGG and Reactome?
KEGG is a comprehensive database covering metabolism, signaling, and disease across thousands of species. Reactome is a curated, expert-written database of human and model organism pathways, with detailed molecular reactions. KEGG is broader; Reactome is deeper for human.
How do I map my genes to KEGG pathways?
Use KEGG Mapper (web), clusterProfiler (R), KEGGREST (R), or the KEGG API (Python). You can map gene IDs to KO numbers, then to pathways. For cross-species, use KO numbers.
What is the best background for KEGG enrichment?
The best background is the set of all genes that could have been detected in your experiment. For RNA-seq, use all expressed genes. For microarrays, use all probes. For genome-wide, use all genes. The choice of background significantly affects results.
What is a pathway map?
A pathway map is a diagram showing the relationships between genes, proteins, and metabolites in a biological process. KEGG pathway maps are manually drawn and use standard symbols (e.g., rectangles for genes, circles for metabolites).
Can I use KEGG for metagenomics?
Yes. KEGG is widely used in metagenomics. You can annotate genes with KO numbers using tools like GhostKOALA or KofamKOALA, then map to KEGG modules and pathways to infer community functions.
# Quick Reference
print("=== Quick Answers ===")
print("""
Q: What is KEGG?
A: Pathway database.
Q: KO number?
A: Ortholog group ID (K00001).
Q: Pathway ID?
A: Organism + number (hsa00010).
Q: Enrichment?
A: Over-represented pathways.
Q: GSEA?
A: Ranked gene list analysis.
Q: Tools?
A: clusterProfiler, pathview, KEGGREST, GSEApy.
Q: R?
A: clusterProfiler, pathview, KEGGREST.
Q: Python?
A: GSEApy, requests.
Q: Web?
A: DAVID, KEGG Mapper, g:Profiler.
Q: Cross-species?
A: Use KO numbers.
Q: Free?
A: Yes β all major tools are free.
""")π Future
π― Where Pathway Analysis Is Going
The future is AI-integrated, single-cell, spatial, multi-omics, and knowledge graphs.
Future Directions
AI: Integration. Single-cell: Resolution. Spatial: Location. Multi-omics: Integrated. Graphs: Knowledge. Real-time: Updates.
# Future of Pathway Analysis
print("=== 1. AI Integration ===")
print("""
Trend: AI + pathways
Ideas:
- AI-powered annotation
- Predictive pathways
- NLP for literature
- Knowledge graphs
Examples:
- AlphaFold
- GPT for biology
- AI curation
Future:
- Automated
- Predictive
- Integrated
""")
print("\n=== 2. Single-Cell ===")
print("""
Trend: Single-cell pathways
Current:
- Bulk pathways
- Average
Future:
- Single-cell pathways
- Cell-type specific
- Trajectory
Examples:
- scRNA-seq + KEGG
- Cell atlas
- Developmental
Future:
- Cell-type resolution
- Trajectories
- Dynamics
""")
print("\n=== 3. Spatial ===")
print("""
Trend: Spatial pathways
Current:
- Tissue-level
Future:
- Spatial pathways
- Location-specific
- Microenvironment
Examples:
- Spatial transcriptomics
- Imaging
- Tumor
Future:
- Spatial resolution
- Microenvironment
- Context
""")
print("\n=== 4. Multi-Omics ===")
print("""
Trend: Multi-omics pathways
Current:
- Single omics
Future:
- Multi-omics pathways
- Integration
- Systems
Examples:
- RNA + protein + metabolite
- Pathway analysis
- Integrated view
Future:
- Unified
- Integrated
- Systems-level
""")
print("\n=== 5. Knowledge Graphs ===")
print("""
Trend: Knowledge graphs
Current:
- Separate databases
- Flat files
Future:
- Knowledge graphs
- Linked data
- Reasoning
Examples:
- KEGG + Reactome
- Wikidata
- SPOKE
Future:
- Unified
- Reasoning
- Discovery
""")
print("\n=== 6. Real-Time ===")
print("""
Trend: Real-time pathways
Current:
- Periodic updates
- Static
Future:
- Real-time
- Streaming
- Live
Examples:
- COVID-19
- Outbreak
- Surveillance
Future:
- Real-time
- Continuous
- Dynamic
""")
# TIMELINE
print("\n=== Timeline ===")
print("""
Past:
1995: KEGG founded
2000: KEGG PATHWAY
2005: KO, BRITE
2010: Enrichment tools
2015: GSEA, clusterProfiler
2020: Multi-omics
Present:
2025: AI integration
2026: Single-cell
Future:
2030: Spatial
2035: Knowledge graphs
2040: Real-time?
""")
print("\n=== Final Thoughts ===")
print("""
KEGG & pathway analysis is:
- Essential for omics
- Comprehensive
- Cross-species
- Evolving
The future is:
- AI-integrated
- Single-cell
- Spatial
- Multi-omics
- Knowledge graphs
- Real-time
"Pathways are the language of biology."
Keep exploring. Keep building.
""")