Enrichment Analysis¶
Pathway enrichment analysis using PyDESeq2 and GSEA.
Overview¶
The enrichment module provides tools for:
- Differential Expression Analysis: Using PyDESeq2 to identify significantly changed genes
- Gene Set Enrichment Analysis (GSEA): Pathway-level analysis using GSEA CLI
- Pathway Visualization: Heatmap generation for pathway enrichment across trajectories
Main Classes¶
EnrichmentPipeline ¶
EnrichmentPipeline(
trajectory_dir: str,
output_dir: str,
cancer_type: str = "kirc",
data_dir: Optional[str] = None,
metadata_dir: Optional[str] = None,
control_data_dir: Optional[str] = None,
control_metadata_dir: Optional[str] = None,
gsea_path: str = "./GSEA_4.3.2/gsea-cli.sh",
pathways_file: str = "data/external/ReactomePathways.gmt",
n_threads: int = 4,
)
Main pipeline for dynamic enrichment analysis using PyDESeq2 and GSEA.
This class orchestrates the complete enrichment analysis workflow:
- PyDESeq2 Differential Expression Analysis
- Converts log2(RSEM+1) data back to integer RSEM counts
- Runs PyDESeq2 for each trajectory timepoint vs controls
-
Generates statistically valid log2FoldChange values
-
GSEA Pathway Enrichment
- Creates ranked gene lists (.rnk files) from DESeq2 results
- Executes GSEA in parallel with ReactomePathways gene sets
-
Collects pathway enrichment scores (NES, p-values, FDR)
-
Result Processing and Visualization
- Combines GSEA results across all trajectories and timepoints
- Generates pathway enrichment heatmaps
IMPORTANT: This pipeline uses PyDESeq2 for proper differential expression. DO NOT bypass this with simple fold-change calculations.
Initialize enrichment pipeline.
Args: trajectory_dir: Directory containing trajectory CSV files output_dir: Output directory for enrichment results cancer_type: Cancer type ('kirc', 'lobular', 'ductal') data_dir: Path to preprocessed RNA-seq data metadata_dir: Path to clinical metadata control_data_dir: Path to control RNA-seq data control_metadata_dir: Path to control metadata gsea_path: Path to GSEA CLI tool pathways_file: Path to pathways GMT file n_threads: Number of parallel threads
Source code in renalprog/enrichment.py
Functions¶
run ¶
Run the complete enrichment pipeline.
Args: skip_deseq: Skip DESeq processing (use if already completed) skip_gsea: Skip GSEA analysis (use if already completed) cleanup: Remove intermediate files after processing
Source code in renalprog/enrichment.py
_run_deseq_processing ¶
Process all trajectory files for DESeq analysis.
Source code in renalprog/enrichment.py
_combine_gsea_results ¶
Combine all GSEA results into a single dataset.
Source code in renalprog/enrichment.py
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 | |
Functions¶
Differential Expression¶
run_deseq2_analysis ¶
run_deseq2_analysis(
sample_data: DataFrame,
control_data: DataFrame,
control_metadata: DataFrame,
gene_list: ndarray,
sample_name: str,
stage_transition: str,
) -> pd.Series
Perform DESeq2 differential expression analysis between sample and controls.
This function properly: 1. Converts log2(RSEM+1) data back to RSEM integer counts 2. Runs PyDESeq2 analysis to get statistically valid log2FoldChange values 3. Returns ranked gene list for GSEA
Args: sample_data: Sample expression data (genes x 1) in log2(RSEM+1) format control_data: Control expression data (genes x samples) in log2(RSEM+1) format control_metadata: Control clinical metadata with stage information gene_list: List of genes sample_name: Name/ID of the sample stage_transition: Stage transition label (e.g., 'early_to_late', 'I_to_II')
Returns: Series of log2FoldChange values sorted for GSEA input
Source code in renalprog/enrichment.py
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 | |
GSEA Analysis¶
run_gsea_command ¶
Run a single GSEA command.
Args: cmd: GSEA command string
Returns: True if successful, False otherwise
Source code in renalprog/enrichment.py
Visualization¶
generate_pathway_heatmap ¶
generate_pathway_heatmap(
enrichment_df: DataFrame,
output_dir: str,
fdr_threshold: float = 0.05,
colorbar: bool = True,
legend: bool = False,
yticks_fontsize: int = 12,
show: bool = False,
) -> Tuple[pd.DataFrame, Dict[str, matplotlib.figure.Figure]]
Generate multiple pathway enrichment heatmaps from GSEA results.
This function creates several heatmaps showing the sum of NES (Normalized Enrichment Score) across all trajectories for each pathway at each timepoint:
- Top 50 most changing pathways (first vs last timepoint)
- Top 50 most upregulated pathways (average NES > 0)
- Top 50 most downregulated pathways (average NES < 0)
- Selected pathways (high-level Reactome + literature pathways)
The heatmaps have: - Rows: Pathway names - Columns: Timepoints (pseudo-time from early to late) - Values: Sum of NES across all trajectories at each timepoint
Args: enrichment_df: DataFrame with columns [Patient, Idx, Transition, NAME, ES, NES, FDR q-val] output_dir: Output directory for heatmap files fdr_threshold: FDR q-value threshold for significance (default: 0.05) colorbar: Whether to show colorbar (default: True) legend: Whether to show legend (default: False) yticks_fontsize: Font size for y-axis tick labels (default: 12) show: Whether to display the plot (default: False)
Returns: Tuple of (heatmap_data, figures_dict): - heatmap_data: DataFrame with summed NES values (pathways × timepoints) - figures_dict: Dictionary mapping figure names to Matplotlib Figure objects
Example: >>> enrichment_df = pd.read_csv('trajectory_enrichment.csv') >>> heatmap_data, figs = generate_pathway_heatmap( ... enrichment_df=enrichment_df, ... output_dir='results/', ... fdr_threshold=0.05 ... ) >>> print(f"Generated {len(figs)} heatmaps")
Source code in renalprog/enrichment.py
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 | |
Usage Examples¶
Running Complete Enrichment Pipeline¶
from renalprog.enrichment import EnrichmentPipeline
from pathlib import Path
# Initialize pipeline
pipeline = EnrichmentPipeline(
cancer_type="KIRC",
trajectory_dir=Path("data/processed/trajectories"),
output_dir=Path("data/processed/enrichment"),
gsea_path=Path("./GSEA_4.3.2/gsea-cli.sh"),
pathways_file=Path("data/external/ReactomePathways.gmt"),
n_threads=8,
n_threads_per_deseq=8
)
# Run full pipeline
results = pipeline.run()
Running DESeq2 Analysis¶
from renalprog.enrichment import run_deseq2_analysis
import pandas as pd
# Load trajectory data
trajectory_data = pd.read_csv("trajectory_001.csv", index_col=0)
control_data = pd.read_csv("control.csv", index_col=0)
# Run DESeq2
results_df = run_deseq2_analysis(
trajectory_samples=trajectory_data,
control_samples=control_data,
n_threads=8
)
# Results contain: log2FoldChange, pvalue, padj, etc.
print(results_df.head())
Creating RNK Files for GSEA¶
from renalprog.enrichment import create_rnk_file
# Create ranked gene list from DESeq2 results
rnk_file = create_rnk_file(
deseq_results=results_df,
output_path="analysis/genes.rnk"
)
Running GSEA¶
from renalprog.enrichment import run_gsea_command
# Run GSEA on ranked gene list
gsea_output = run_gsea_command(
rnk_file="analysis/genes.rnk",
gmt_file="data/external/ReactomePathways.gmt",
output_dir="analysis/gsea_results",
label="trajectory_001",
gsea_path="./GSEA_4.3.2/gsea-cli.sh"
)
Generating Pathway Heatmaps¶
from renalprog.enrichment import generate_pathway_heatmap
# Generate heatmaps from enrichment results
heatmap_data, figures = generate_pathway_heatmap(
enrichment_file="data/processed/enrichment/trajectory_enrichment.csv",
output_dir="data/processed/enrichment",
fdr_threshold=0.05,
n_timepoints=50
)
# figures contains:
# - "top_50_changing": Most variable pathways
# - "top_50_upregulated": Most upregulated pathways
# - "top_50_downregulated": Most downregulated pathways
# - "high_level": Reactome high-level pathways
# - "literature": Literature-curated pathways
Configuration¶
EnrichmentPipeline Parameters¶
cancer_type: Cancer type identifier (e.g., "KIRC", "BRCA")trajectory_dir: Directory containing trajectory CSV filesoutput_dir: Directory for output filesgsea_path: Path to GSEA CLI executablepathways_file: Path to GMT file with pathway definitionsn_threads: Number of parallel threads for processingn_threads_per_deseq: Number of threads per DESeq2 jobmemory_per_job_gb: Memory limit per DESeq2 job (default: 12 GB)total_memory_gb: Total available memory (default: 224 GB)
GSEA Parameters¶
nperm: Number of permutations (default: 1000)set_min: Minimum gene set size (default: 15)set_max: Maximum gene set size (default: 500)scoring_scheme: GSEA scoring method (default: "weighted")norm: Normalization method (default: "meandiv")
Pathway Collections¶
High-Level Reactome Pathways¶
29 top-level biological processes: - Autophagy - Cell Cycle - DNA Repair - Immune System - Metabolism - Signal Transduction - And more...
Literature-Curated Pathways¶
33 pathways from literature review: - VHL/HIF pathway - PI3K/AKT/MTOR pathway - Warburg effect - TCA cycle - And more...
Output Files¶
DESeq2 Results¶
{trajectory_id}_deseq_results.csv: Complete DESeq2 output{trajectory_id}.rnk: Ranked gene list for GSEA
GSEA Results¶
{trajectory_id}/gsea_report_for_na_pos_{timestamp}.tsv: Positive enrichment{trajectory_id}/gsea_report_for_na_neg_{timestamp}.tsv: Negative enrichment{trajectory_id}/ranked_gene_list_{timestamp}.tsv: Ranked genes with scores
Combined Results¶
trajectory_enrichment.csv: All GSEA results combinedpathway_heatmap_*.png/pdf/svg: Pathway heatmap visualizations
Performance Considerations¶
Memory Management¶
DESeq2 analysis is memory-intensive. The pipeline automatically: - Limits concurrent jobs based on available memory - Allocates memory per job (default: 12 GB) - Monitors memory usage
For large datasets:
pipeline = EnrichmentPipeline(
...,
n_threads=8, # Reduce parallelism
n_threads_per_deseq=4, # Reduce threads per job
memory_per_job_gb=16 # Increase memory per job
)
CPU Utilization¶
- DESeq2 jobs run in parallel (up to
n_threads) - Each job uses
n_threads_per_deseqthreads - Total CPU usage ≈
n_threads×n_threads_per_deseq
Recommended settings: - Small dataset (<100 trajectories): n_threads=8, n_threads_per_deseq=8 - Large dataset (>100 trajectories): n_threads=4, n_threads_per_deseq=12
Troubleshooting¶
Out of Memory Errors¶
# Reduce parallel jobs
pipeline = EnrichmentPipeline(..., n_threads=4)
# Increase memory per job
pipeline = EnrichmentPipeline(..., memory_per_job_gb=20)
GSEA Not Found¶
Ensure GSEA is installed and path is correct:
No Results Generated¶
Check logs for errors: