Enrichment Analysis¶
Pathway enrichment analysis using PyDESeq2 and GSEA.
Overview¶
The renalprog.enrichment module provides functions for differential expression analysis and Gene Set Enrichment Analysis (GSEA) to identify biological pathways enriched in cancer progression trajectories.
Pipeline Usage¶
For running the complete enrichment pipeline, see the scripts in scripts/enrichment/:
py_deseq.py- Process trajectories of synthetic patient trajectories (or real ones, if you could ever get these).py_deseq_real.py- Process real patient data.trajectory_formatting.py- Combine GSEA results across multiple patients or trajectories.
Running the Pipeline¶
For synthetic trajectories:
python scripts/enrichment/py_deseq.py \
--cancer_type kirc \
--traj_dir data/interim/trajectories \
--source_target_file data/interim/source_target.csv \
--patient_stage_file data/interim/patient_stages.csv \
--stage_transition early_to_late \
--file data/interim/trajectories/early_to_late/patient_001.csv \
--nperm 1000 \
--pathway_file data/external/ReactomePathways.gmt
For real patients:
python scripts/enrichment/py_deseq_real.py \
--cancer_type kirc \
--data_dir data/interim/preprocessed/rnaseq.csv \
--metadata_dir data/interim/preprocessed/clinical.csv \
--nperm 1000 \
--pathway_file data/external/ReactomePathways.gmt
Tutorial¶
For a complete step-by-step guide, see the Step 6: Enrichment Analysis Tutorial.
API Reference¶
Core Functions¶
build_gsea_command¶
build_gsea_command ¶
build_gsea_command(
save_path_rnk_fun: str,
filename_rnk_fun: str,
pathway_file: str = "data/external/ReactomePathways.gmt",
mode: str = "Max_probe",
norm: str = "meandiv",
nperm: int = 1000,
rnd_seed: str = "timestamp",
scoring_scheme: str = "weighted",
set_max: int = 500,
set_min: int = 15,
)
Build a command string for running GSEA (Gene Set Enrichment Analysis) with pre-ranked gene lists.
Parameters: - save_path_rnk_fun (str): The directory where the pre-ranked gene list file is stored. - filename_rnk_fun (str): The name of the pre-ranked gene list file. - pathway_file (str, optional): Path to the gene set file in GMT format. Default is 'data/external/ReactomePathways.gmt'. - mode (str, optional): GSEA mode. Default is 'Max_probe'. - norm (str, optional): Normalization method. Default is 'meandiv'. - nperm (int, optional): Number of permutations. Default is 1000. - rnd_seed (str, optional): Random seed for reproducibility. Default is 'timestamp'. - scoring_scheme (str, optional): Scoring scheme for GSEA. Default is 'weighted'. - set_max (int, optional): Maximum size of gene sets to consider. Default is 500. - set_min (int, optional): Minimum size of gene sets to consider. Default is 15.
Returns: str: The GSEA command string.
Source code in renalprog/enrichment.py
Example:
from renalprog.enrichment import build_gsea_command
# Basic usage with defaults
cmd = build_gsea_command(
save_path_rnk_fun="data/interim/analysis/patient_001",
filename_rnk_fun="patient_001.rnk"
)
# Custom GSEA parameters
cmd = build_gsea_command(
save_path_rnk_fun="data/interim/analysis/patient_001",
filename_rnk_fun="patient_001.rnk",
pathway_file="data/external/c2.cp.kegg_legacy.v2025.1.Hs.symbols.gmt",
nperm=5000,
rnd_seed="42",
set_max=800,
set_min=10
)
print(cmd)
get_rnk_single_patient¶
get_rnk_single_patient ¶
get_rnk_single_patient(
path_above,
genes_here,
samples_real_l,
pat_i,
index_pat=None,
foldchange=True,
pathway_file="data/external/ReactomePathways.gmt",
mode="Max_probe",
norm="meandiv",
nperm=1000,
rnd_seed="timestamp",
scoring_scheme="weighted",
set_max=500,
set_min=15,
)
Generate GSEA command for a single patient based on gene expression data.
Parameters: - path_above (str): The parent directory for saving patient-specific data. - genes_here (list): List of gene names. - samples_real_l (pd.DataFrame): DataFrame containing gene expression data for single patient sample. - pat_i (str): Patient identifier. - index_pat (int, optional): Index of the patient. Default is None. - foldchange (bool, optional): If True, log2 fold change values are used; otherwise, raw gene expression values. - pathway_file (str, optional): Path to the GMT file containing gene sets. Default is 'data/external/ReactomePathways.gmt'. - mode (str, optional): GSEA collapse mode. Default is 'Max_probe'. - norm (str, optional): GSEA normalization mode. Default is 'meandiv'. - nperm (int, optional): Number of permutations. Default is 1000. - rnd_seed (str, optional): Random seed for GSEA. Default is 'timestamp'. - scoring_scheme (str, optional): GSEA scoring scheme. Default is 'weighted'. - set_max (int, optional): Maximum size of gene sets. Default is 500. - set_min (int, optional): Minimum size of gene sets. Default is 15.
Returns: str: The GSEA command string for the given patient and gene expression data.
Source code in renalprog/enrichment.py
Example:
from renalprog.enrichment import get_rnk_single_patient
import pandas as pd
# Prepare fold change data (from DESeq2 analysis)
fold_change_df = pd.DataFrame({
'log2FoldChange': [2.5, -1.8, 0.5, 3.2, -2.1]
}, index=['GENE1', 'GENE2', 'GENE3', 'GENE4', 'GENE5'])
# Generate GSEA command for single patient
gsea_cmd = get_rnk_single_patient(
path_above="data/interim/analysis",
genes_here=['GENE1', 'GENE2', 'GENE3', 'GENE4', 'GENE5'],
samples_real_l=fold_change_df,
pat_i="TCGA-A3-3306",
index_pat=None,
foldchange=True,
nperm=1000
)
fun_apply_deseq¶
fun_apply_deseq ¶
Perform DESeq2 analysis on RNA-seq data.
Parameters: - rnaseq_in (pd.DataFrame): RNA-seq count data. - clinical_in (pd.DataFrame): Clinical metadata, including the cancer stage.
Returns: pd.DataFrame: DataFrame containing DESeq2 analysis results.
Source code in renalprog/enrichment.py
Example:
from renalprog.enrichment import fun_apply_deseq
import pandas as pd
import numpy as np
# Prepare RNA-seq data (log2(RSEM+1) format)
rnaseq_data = pd.DataFrame(
np.random.uniform(0, 10, (100, 5)), # 100 genes, 5 samples
index=[f'GENE{i}' for i in range(100)],
columns=['Sample1', 'Sample2', 'Sample3', 'Sample4', 'Sample5']
)
# Prepare clinical metadata
clinical_data = pd.DataFrame({
'ajcc_pathologic_tumor_stage': ['Stage I', 'Stage I', 'Stage III', 'Stage III', 'Stage III']
}, index=['Sample1', 'Sample2', 'Sample3', 'Sample4', 'Sample5'])
# Run DESeq2 analysis
results_df = fun_apply_deseq(
rnaseq_in=rnaseq_data,
clinical_in=clinical_data
)
# Results contain: log2FoldChange, pvalue, padj, etc.
print(results_df[['log2FoldChange', 'pvalue', 'padj']].head())
fun_single_patient_and_gsea¶
fun_single_patient_and_gsea ¶
fun_single_patient_and_gsea(
patient_here,
patient_stage,
rnaseq_data,
path_above_in,
clinical_controls,
rnaseq_controls,
gene_list,
foldchange=True,
pathway_file="data/external/ReactomePathways.gmt",
mode="Max_probe",
norm="meandiv",
nperm=1000,
rnd_seed="timestamp",
scoring_scheme="weighted",
set_max=500,
set_min=15,
)
Perform analysis for a single patient and generate GSEA-related files.
Parameters: - patient_here: Current patient ID. - patient_stage: DataFrame containing patient stage information. - rnaseq_data: DataFrame containing RNAseq data. - path_above_in: Path to the directory containing patient data. - clinical_controls: DataFrame containing clinical control data. - rnaseq_controls: DataFrame containing RNAseq control data. - gene_list: List of genes. - foldchange: Boolean flag indicating whether to use fold change data in the analysis. Default is True. - pathway_file (str, optional): Path to the GMT file containing gene sets. Default is 'data/external/ReactomePathways.gmt'. - mode (str, optional): GSEA collapse mode. Default is 'Max_probe'. - norm (str, optional): GSEA normalization mode. Default is 'meandiv'. - nperm (int, optional): Number of permutations. Default is 1000. - rnd_seed (str, optional): Random seed for GSEA. Default is 'timestamp'. - scoring_scheme (str, optional): GSEA scoring scheme. Default is 'weighted'. - set_max (int, optional): Maximum size of gene sets. Default is 500. - set_min (int, optional): Minimum size of gene sets. Default is 15.
Returns: - bash_file_l: List of bash commands generated during the analysis.
Source code in renalprog/enrichment.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
Example:
from renalprog.enrichment import fun_single_patient_and_gsea
import pandas as pd
# Load your data
rnaseq_df = pd.read_csv('data/interim/rnaseq.csv', index_col=0)
clinical_controls_df = pd.read_csv('data/processed/controls/clinical_control.csv', index_col=0)
rnaseq_controls_df = pd.read_csv('data/processed/controls/rna_control.csv', index_col=0)
genes = rnaseq_df.columns.tolist()
# Analyze single patient with custom GSEA parameters
gsea_cmd = fun_single_patient_and_gsea(
patient_here='TCGA-A3-3306',
patient_stage='Stage II',
rnaseq_data=rnaseq_df,
path_above_in='data/interim/analysis',
clinical_controls=clinical_controls_df,
rnaseq_controls=rnaseq_controls_df,
gene_list=genes,
foldchange=True,
# GSEA parameters
pathway_file='data/external/ReactomePathways.gmt',
nperm=5000,
rnd_seed='42'
)
# The function generates .rnk files and returns the GSEA command to run
print(gsea_cmd)
fun_synth_single_patient_and_gsea¶
fun_synth_single_patient_and_gsea ¶
fun_synth_single_patient_and_gsea(
patient_here,
stage_trans_i,
rnaseq_data,
path_above_in,
clinical_controls,
rnaseq_controls,
gene_list,
index_pat=None,
foldchange=True,
pathway_file="data/external/ReactomePathways.gmt",
mode="Max_probe",
norm="meandiv",
nperm=1000,
rnd_seed="timestamp",
scoring_scheme="weighted",
set_max=500,
set_min=15,
)
Perform analysis for a single patient and generate GSEA-related files.
Parameters: - patient_here: str Current synth patient ID (like: pat_to_pat_interpolnum). - stage_trans_i: str containing synthetic patient stage transition information. 'I_to_II' or 'II_to_III'. - rnaseq_data: DataFrame containing RNAseq data only of synthetic patient to analyze. - path_above_in: Path to the directory containing patient data. - clinical_controls: DataFrame containing clinical control data. - rnaseq_controls: DataFrame containing RNAseq control data. - gene_list: List of genes. - index_pat: int, optional: Index of the synthetic patient. Default is None. - foldchange: Boolean flag indicating whether to use fold change data in the analysis. Default is True. - pathway_file (str, optional): Path to the GMT file containing gene sets. Default is 'data/external/ReactomePathways.gmt'. - mode (str, optional): GSEA collapse mode. Default is 'Max_probe'. - norm (str, optional): GSEA normalization mode. Default is 'meandiv'. - nperm (int, optional): Number of permutations. Default is 1000. - rnd_seed (str, optional): Random seed for GSEA. Default is 'timestamp'. - scoring_scheme (str, optional): GSEA scoring scheme. Default is 'weighted'. - set_max (int, optional): Maximum size of gene sets. Default is 500. - set_min (int, optional): Minimum size of gene sets. Default is 15.
Returns: - bash_file_l: List of bash commands generated during the analysis.
Source code in renalprog/enrichment.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 | |
Example:
from renalprog.enrichment import fun_synth_single_patient_and_gsea
import pandas as pd
# Load synthetic trajectory data
synth_traj = pd.read_csv('data/interim/trajectories/early_to_late/traj_001.csv', index_col=0)
clinical_controls_df = pd.read_csv('data/processed/controls/clinical_control.csv', index_col=0)
rnaseq_controls_df = pd.read_csv('data/processed/controls/rna_control.csv', index_col=0)
genes = synth_traj.index.tolist()
# Analyze synthetic patient at interpolation point 25
synth_patient_data = pd.DataFrame(synth_traj.iloc[:, 25]) # Column 25
gsea_cmd = fun_synth_single_patient_and_gsea(
patient_here='TCGA-A3-3306_to_TCGA-A3-3307_25',
stage_trans_i='early_to_late',
rnaseq_data=synth_patient_data,
path_above_in='data/interim/enrichment',
clinical_controls=clinical_controls_df,
rnaseq_controls=rnaseq_controls_df,
gene_list=genes,
index_pat=25,
foldchange=True,
# GSEA parameters
pathway_file='data/external/ReactomePathways.gmt',
nperm=1000,
rnd_seed='timestamp'
)
Pathway Visualization¶
generate_pathway_heatmap¶
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
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 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 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 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 | |
Example:
from renalprog.enrichment import generate_pathway_heatmap
import pandas as pd
# Load enrichment results (combined GSEA output)
enrichment_df = pd.read_csv(
'data/processed/enrichment/trajectory_enrichment.csv',
index_col=0
)
# Generate pathway heatmaps
heatmap_data, figures = generate_pathway_heatmap(
enrichment_df=enrichment_df,
output_dir='data/processed/enrichment/heatmaps',
fdr_threshold=0.05,
colorbar=True,
legend=False,
yticks_fontsize=10,
show=False
)
# Save figures
for name, fig in figures.items():
fig.savefig(f'data/processed/enrichment/heatmaps/{name}.png', dpi=300, bbox_inches='tight')
# Inspect top pathways
print(heatmap_data['top_50_changing'].head())
GSEA Parameters¶
All enrichment functions support customizable GSEA parameters. See the Tutorial Step 6: Enrichment Tutorial for detailed information.
Common Parameters¶
| Parameter | Default | Description |
|---|---|---|
pathway_file | 'data/external/ReactomePathways.gmt' | Path to gene set database |
mode | 'Max_probe' | Collapse mode for multiple probes |
norm | 'meandiv' | Normalization method |
nperm | 1000 | Number of permutations |
rnd_seed | 'timestamp' | Random seed |
scoring_scheme | 'weighted' | Scoring scheme |
set_max | 500 | Maximum gene set size |
set_min | 15 | Minimum gene set size |