forked from hhx465453939/OpenClaw-Medical-Skills
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_gene_enrichment.py
More file actions
1478 lines (1207 loc) · 50 KB
/
test_gene_enrichment.py
File metadata and controls
1478 lines (1207 loc) · 50 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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
316
317
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
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
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Comprehensive Test Suite for tooluniverse-gene-enrichment Skill
Tests all enrichment capabilities: ORA, GSEA, multiple databases,
ID conversion, cross-validation, and multiple testing correction.
"""
import sys
import time
import traceback
import re
# ============================================================
# Test Infrastructure
# ============================================================
RESULTS = []
def run_test(test_func):
"""Run a test function and record results."""
name = test_func.__name__
doc = test_func.__doc__ or name
start = time.time()
try:
test_func()
elapsed = time.time() - start
RESULTS.append({"name": name, "doc": doc.strip(), "status": "PASS", "time": elapsed, "error": None})
print(f" PASS {name} ({elapsed:.1f}s)")
except Exception as e:
elapsed = time.time() - start
error_msg = f"{type(e).__name__}: {e}"
RESULTS.append({"name": name, "doc": doc.strip(), "status": "FAIL", "time": elapsed, "error": error_msg})
print(f" FAIL {name} ({elapsed:.1f}s): {error_msg}")
traceback.print_exc()
# ============================================================
# Test Data
# ============================================================
CANCER_GENES = ["TP53", "BRCA1", "EGFR", "MYC", "AKT1", "PTEN", "RB1", "MDM2", "CDK4", "CCND1"]
IMMUNE_GENES = ["IL6", "TNF", "IL10", "IFNG", "IL1B", "CCL2", "CXCL8", "IL2", "IL4", "TGFB1",
"CD4", "CD8A", "FOXP3", "STAT3", "JAK1", "JAK2", "NFKB1", "IRF1", "TLR4", "MYD88"]
SIGNALING_GENES = ["EGFR", "KRAS", "BRAF", "MAP2K1", "MAPK1", "PIK3CA", "AKT1", "MTOR",
"RAF1", "SOS1", "GRB2", "SHC1", "HRAS", "NRAS", "ERBB2"]
ENSEMBL_IDS = ["ENSG00000141510", "ENSG00000012048", "ENSG00000146648",
"ENSG00000136997", "ENSG00000142208"]
# ============================================================
# Phase 1: gseapy ORA Tests
# ============================================================
def test_01_gseapy_go_bp_enrichment():
"""gseapy ORA: GO Biological Process enrichment with cancer gene list"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
assert len(df) > 0, "No results returned"
assert 'Term' in df.columns, "Missing Term column"
assert 'P-value' in df.columns, "Missing P-value column"
assert 'Adjusted P-value' in df.columns, "Missing Adjusted P-value column"
assert 'Overlap' in df.columns, "Missing Overlap column"
assert 'Genes' in df.columns, "Missing Genes column"
sig = df[df['Adjusted P-value'] < 0.05]
assert len(sig) > 0, "No significant GO BP terms found"
# Verify top term contains GO ID
top_term = sig.iloc[0]['Term']
assert re.search(r'GO:\d+', top_term), f"Top term missing GO ID: {top_term}"
# Verify p-values are valid
assert all(df['P-value'] >= 0), "Negative p-values found"
assert all(df['P-value'] <= 1), "P-values > 1 found"
assert all(df['Adjusted P-value'] >= 0), "Negative adjusted p-values found"
print(f" {len(sig)} significant GO BP terms (p_adj < 0.05)")
print(f" Top term: {sig.iloc[0]['Term'][:80]}")
def test_02_gseapy_go_mf_enrichment():
"""gseapy ORA: GO Molecular Function enrichment"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Molecular_Function_2021',
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
assert len(df) > 0, "No results returned"
sig = df[df['Adjusted P-value'] < 0.05]
assert len(sig) > 0, "No significant GO MF terms"
print(f" {len(sig)} significant GO MF terms")
def test_03_gseapy_go_cc_enrichment():
"""gseapy ORA: GO Cellular Component enrichment"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Cellular_Component_2021',
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
assert len(df) > 0, "No results returned"
sig = df[df['Adjusted P-value'] < 0.05]
assert len(sig) > 0, "No significant GO CC terms"
print(f" {len(sig)} significant GO CC terms")
def test_04_gseapy_kegg_enrichment():
"""gseapy ORA: KEGG pathway enrichment"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='KEGG_2021_Human',
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
assert len(df) > 0, "No KEGG results returned"
sig = df[df['Adjusted P-value'] < 0.05]
assert len(sig) > 0, "No significant KEGG pathways"
# Cancer genes should have cancer pathways
cancer_pathways = sig[sig['Term'].str.contains('cancer|carcinoma|melanoma|glioma', case=False)]
assert len(cancer_pathways) > 0, "No cancer-related KEGG pathways found for cancer genes"
print(f" {len(sig)} significant KEGG pathways")
print(f" Most enriched: {sig.iloc[0]['Term']}")
def test_05_gseapy_reactome_enrichment():
"""gseapy ORA: Reactome pathway enrichment"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='Reactome_Pathways_2024',
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
assert len(df) > 0, "No Reactome results returned"
sig = df[df['Adjusted P-value'] < 0.05]
assert len(sig) > 0, "No significant Reactome pathways"
print(f" {len(sig)} significant Reactome pathways")
def test_06_gseapy_msigdb_hallmark():
"""gseapy ORA: MSigDB Hallmark enrichment"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='MSigDB_Hallmark_2020',
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
assert len(df) > 0, "No Hallmark results returned"
sig = df[df['Adjusted P-value'] < 0.05]
print(f" {len(sig)} significant Hallmark terms")
if len(sig) > 0:
print(f" Top: {sig.iloc[0]['Term']}")
def test_07_gseapy_wikipathways():
"""gseapy ORA: WikiPathways enrichment"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='WikiPathways_2024_Human',
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
assert len(df) > 0, "No WikiPathways results returned"
sig = df[df['Adjusted P-value'] < 0.05]
print(f" {len(sig)} significant WikiPathways terms")
def test_08_gseapy_multi_library():
"""gseapy ORA: Multiple libraries in one call"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets=['GO_Biological_Process_2021', 'KEGG_2021_Human', 'Reactome_Pathways_2024'],
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
assert len(df) > 0, "No results returned"
# Verify Gene_set column distinguishes libraries
libraries = df['Gene_set'].unique()
assert len(libraries) == 3, f"Expected 3 libraries, got {len(libraries)}: {list(libraries)}"
print(f" Libraries: {list(libraries)}")
for lib in libraries:
lib_sig = df[(df['Gene_set'] == lib) & (df['Adjusted P-value'] < 0.05)]
print(f" {lib}: {len(lib_sig)} significant terms")
def test_09_gseapy_results_structure():
"""gseapy ORA: Verify DataFrame column structure and types"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None,
no_plot=True,
)
df = result.results
expected_cols = ['Gene_set', 'Term', 'Overlap', 'P-value', 'Adjusted P-value',
'Old P-value', 'Old Adjusted P-value', 'Odds Ratio', 'Combined Score', 'Genes']
for col in expected_cols:
assert col in df.columns, f"Missing column: {col}"
# Verify types
assert df['P-value'].dtype in ['float64', 'float32'], f"P-value dtype: {df['P-value'].dtype}"
assert df['Adjusted P-value'].dtype in ['float64', 'float32'], f"Adj P-value dtype: {df['Adjusted P-value'].dtype}"
assert df['Odds Ratio'].dtype in ['float64', 'float32'], f"Odds Ratio dtype: {df['Odds Ratio'].dtype}"
print(f" All {len(expected_cols)} expected columns present with correct types")
# ============================================================
# Phase 2: GSEA Tests
# ============================================================
def test_10_gsea_preranked_go_bp():
"""gseapy GSEA: Preranked GO Biological Process"""
import gseapy
import pandas as pd
import numpy as np
np.random.seed(42)
genes = CANCER_GENES + ["GAPDH", "ACTB", "TUBB", "ALB", "INS", "TNF",
"IL6", "IL10", "VEGFA", "KRAS", "RAF1", "MAP2K1",
"MAPK1", "PIK3CA", "MTOR", "JAK1", "STAT3",
"NOTCH1", "WNT1", "SHH"]
ranks = pd.Series(np.random.randn(len(genes)), index=genes).sort_values(ascending=False)
result = gseapy.prerank(
rnk=ranks,
gene_sets='GO_Biological_Process_2021',
outdir=None,
no_plot=True,
seed=42,
min_size=3,
max_size=500,
permutation_num=100,
)
df = result.res2d
assert len(df) > 0, "No GSEA results returned"
expected_cols = ['Name', 'Term', 'ES', 'NES', 'NOM p-val', 'FDR q-val', 'FWER p-val', 'Lead_genes']
for col in expected_cols:
assert col in df.columns, f"Missing GSEA column: {col}"
print(f" {len(df)} terms analyzed")
sig = df[df['FDR q-val'].astype(float) < 0.25]
print(f" {len(sig)} significant (FDR < 0.25)")
def test_11_gsea_preranked_kegg():
"""gseapy GSEA: Preranked KEGG pathways"""
import gseapy
import pandas as pd
import numpy as np
np.random.seed(42)
genes = list(set(SIGNALING_GENES + CANCER_GENES[:5]))
ranks = pd.Series(np.random.randn(len(genes)), index=genes).sort_values(ascending=False)
result = gseapy.prerank(
rnk=ranks,
gene_sets='KEGG_2021_Human',
outdir=None,
no_plot=True,
seed=42,
min_size=3,
max_size=500,
permutation_num=100,
)
df = result.res2d
assert len(df) > 0, "No GSEA KEGG results"
print(f" {len(df)} KEGG terms analyzed by GSEA")
def test_12_gsea_nes_sign():
"""gseapy GSEA: NES sign reflects enrichment direction"""
import gseapy
import pandas as pd
# Create ranked list with cancer genes at top (positive)
gene_scores = {g: 5.0 - i * 0.3 for i, g in enumerate(CANCER_GENES)}
# Add non-cancer genes at bottom (negative)
filler = ["GAPDH", "ACTB", "ALB", "INS", "TUBB", "HBB", "HBA1",
"TTN", "MUC16", "OBSCN", "AHNAK", "SYNE1", "FLNB", "PLEC",
"DSP", "MACF1", "BCLAF1", "SRRM2"]
for i, g in enumerate(filler):
gene_scores[g] = -0.5 - i * 0.3
ranks = pd.Series(gene_scores).sort_values(ascending=False)
result = gseapy.prerank(
rnk=ranks,
gene_sets='GO_Biological_Process_2021',
outdir=None,
no_plot=True,
seed=42,
min_size=3,
max_size=500,
permutation_num=100,
)
df = result.res2d
# There should be both positive and negative NES values
nes_values = df['NES'].astype(float)
has_positive = any(nes_values > 0)
has_negative = any(nes_values < 0)
print(f" Positive NES: {sum(nes_values > 0)}, Negative NES: {sum(nes_values < 0)}")
assert has_positive or has_negative, "NES values should include positive or negative"
# ============================================================
# Phase 3: PANTHER Enrichment Tests
# ============================================================
def test_13_panther_go_bp():
"""PANTHER: GO Biological Process enrichment"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.PANTHER_enrichment(
gene_list=','.join(CANCER_GENES),
organism=9606,
annotation_dataset='GO:0008150'
)
assert isinstance(result, dict), f"Expected dict, got {type(result)}"
data = result.get('data', {})
terms = data.get('enriched_terms', [])
assert len(terms) > 0, "No PANTHER enriched terms"
# Verify term structure
first = terms[0]
assert 'term_id' in first, "Missing term_id"
assert 'term_label' in first, "Missing term_label"
assert 'pvalue' in first, "Missing pvalue"
assert 'fdr' in first, "Missing fdr"
assert 'fold_enrichment' in first, "Missing fold_enrichment"
sig = [t for t in terms if t.get('fdr', 1) < 0.05]
print(f" {len(sig)} significant PANTHER GO BP terms")
if sig:
print(f" Top: {sig[0]['term_label']} (fdr={sig[0]['fdr']:.2e})")
def test_14_panther_go_mf():
"""PANTHER: GO Molecular Function enrichment"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.PANTHER_enrichment(
gene_list=','.join(CANCER_GENES),
organism=9606,
annotation_dataset='GO:0003674'
)
terms = result.get('data', {}).get('enriched_terms', [])
assert len(terms) > 0, "No PANTHER GO MF terms"
sig = [t for t in terms if t.get('fdr', 1) < 0.05]
print(f" {len(sig)} significant PANTHER GO MF terms")
def test_15_panther_go_cc():
"""PANTHER: GO Cellular Component enrichment"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.PANTHER_enrichment(
gene_list=','.join(CANCER_GENES),
organism=9606,
annotation_dataset='GO:0005575'
)
terms = result.get('data', {}).get('enriched_terms', [])
assert len(terms) > 0, "No PANTHER GO CC terms"
sig = [t for t in terms if t.get('fdr', 1) < 0.05]
print(f" {len(sig)} significant PANTHER GO CC terms")
def test_16_panther_pathway():
"""PANTHER: PANTHER Pathway enrichment"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.PANTHER_enrichment(
gene_list=','.join(CANCER_GENES),
organism=9606,
annotation_dataset='ANNOT_TYPE_ID_PANTHER_PATHWAY'
)
terms = result.get('data', {}).get('enriched_terms', [])
assert len(terms) > 0, "No PANTHER pathway terms"
sig = [t for t in terms if t.get('fdr', 1) < 0.05]
print(f" {len(sig)} significant PANTHER pathways")
if sig:
print(f" Top: {sig[0]['term_label']}")
# ============================================================
# Phase 4: STRING Enrichment Tests
# ============================================================
def test_17_string_functional_enrichment():
"""STRING: Functional enrichment (all categories)"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.STRING_functional_enrichment(
protein_ids=CANCER_GENES,
species=9606
)
assert isinstance(result, dict), f"Expected dict, got {type(result)}"
data = result.get('data', [])
assert isinstance(data, list), f"Data should be list, got {type(data)}"
assert len(data) > 0, "No STRING enrichment results"
# Verify categories are present
categories = set(d.get('category', '') for d in data)
assert 'Process' in categories or 'KEGG' in categories, f"Expected Process or KEGG in categories: {categories}"
print(f" Categories found: {sorted(categories)}")
# Filter GO BP
go_bp = [d for d in data if d.get('category') == 'Process']
print(f" GO BP terms: {len(go_bp)}")
# Filter KEGG
kegg = [d for d in data if d.get('category') == 'KEGG']
print(f" KEGG terms: {len(kegg)}")
def test_18_string_kegg_enrichment():
"""STRING: KEGG pathway enrichment filtered from functional enrichment"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.STRING_functional_enrichment(
protein_ids=CANCER_GENES,
species=9606,
category='KEGG'
)
data = result.get('data', [])
kegg = [d for d in data if d.get('category') == 'KEGG']
assert len(kegg) > 0, "No KEGG terms from STRING"
# Verify KEGG structure
first = kegg[0]
assert 'term' in first, "Missing term"
assert 'p_value' in first, "Missing p_value"
assert 'fdr' in first, "Missing fdr"
assert 'description' in first, "Missing description"
assert 'number_of_genes' in first, "Missing number_of_genes"
sig = [d for d in kegg if d.get('fdr', 1) < 0.05]
print(f" {len(sig)} significant KEGG terms from STRING")
if sig:
print(f" Top: {sig[0]['description']} (fdr={sig[0]['fdr']:.2e})")
def test_19_string_ppi_enrichment():
"""STRING: PPI enrichment test (network connectivity)"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.STRING_ppi_enrichment(
protein_ids=CANCER_GENES,
species=9606
)
# PPI enrichment returns connectivity statistics
assert result is not None, "No PPI enrichment result"
print(f" PPI enrichment result type: {type(result)}")
if isinstance(result, dict):
print(f" Keys: {list(result.keys())[:10]}")
# ============================================================
# Phase 5: Reactome Enrichment Tests
# ============================================================
def test_20_reactome_pathway_enrichment():
"""Reactome: Pathway overrepresentation analysis"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.ReactomeAnalysis_pathway_enrichment(
identifiers=' '.join(CANCER_GENES),
page_size=30
)
assert isinstance(result, dict), f"Expected dict, got {type(result)}"
data = result.get('data', {})
pathways = data.get('pathways', [])
assert len(pathways) > 0, "No Reactome pathways returned"
# Verify pathway structure
first = pathways[0]
assert 'pathway_id' in first, "Missing pathway_id"
assert 'name' in first, "Missing name"
assert 'p_value' in first, "Missing p_value"
assert 'fdr' in first, "Missing fdr"
assert 'entities_found' in first, "Missing entities_found"
sig = [p for p in pathways if p.get('fdr', 1) < 0.05]
print(f" {len(sig)} significant Reactome pathways (fdr < 0.05)")
if sig:
print(f" Top: {sig[0]['name']} (fdr={sig[0]['fdr']:.2e})")
# Verify identifiers_not_found
not_found = data.get('identifiers_not_found', -1)
print(f" Identifiers not found: {not_found}")
def test_21_reactome_cross_validation():
"""Reactome: Cross-validate gseapy vs Reactome API results"""
import gseapy
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
# gseapy Reactome
gseapy_result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='Reactome_Pathways_2024',
organism='human',
outdir=None, no_plot=True,
)
gseapy_sig = set(gseapy_result.results[gseapy_result.results['Adjusted P-value'] < 0.05]['Term'].str.lower())
# Reactome API
api_result = tu.tools.ReactomeAnalysis_pathway_enrichment(
identifiers=' '.join(CANCER_GENES),
page_size=30
)
api_pathways = api_result.get('data', {}).get('pathways', [])
api_sig = set(p['name'].lower() for p in api_pathways if p.get('fdr', 1) < 0.05)
# Check for overlap (terms may not match exactly due to naming differences)
print(f" gseapy significant terms: {len(gseapy_sig)}")
print(f" Reactome API significant terms: {len(api_sig)}")
# At least some overlap expected
if gseapy_sig and api_sig:
overlap = 0
for g_term in gseapy_sig:
for a_term in api_sig:
if g_term in a_term or a_term in g_term:
overlap += 1
break
print(f" Approximate overlap: {overlap} terms")
# ============================================================
# Phase 6: ID Conversion Tests
# ============================================================
def test_22_mygene_batch_conversion():
"""ID Conversion: Ensembl to Symbol via MyGene batch query"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.MyGene_batch_query(
gene_ids=ENSEMBL_IDS,
fields="symbol,entrezgene,ensembl.gene"
)
# Handle different response structures
results = result.get('results', result.get('data', {}).get('results', []))
assert len(results) > 0, "No MyGene results"
symbols = []
for hit in results:
symbol = hit.get('symbol')
if symbol:
symbols.append(symbol)
print(f" {hit['query']} -> {symbol}")
assert len(symbols) >= 3, f"Expected at least 3 symbols, got {len(symbols)}"
assert 'TP53' in symbols, "TP53 not found in conversion"
def test_23_string_map_identifiers():
"""ID Conversion: Gene symbols to STRING IDs"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
result = tu.tools.STRING_map_identifiers(
protein_ids=CANCER_GENES[:5],
species=9606
)
# Can return list or dict with data
if isinstance(result, dict):
data = result.get('data', result)
else:
data = result
if isinstance(data, list):
assert len(data) > 0, "No STRING mappings"
for item in data[:3]:
print(f" {item.get('queryItem', '?')} -> {item.get('preferredName', '?')} ({item.get('stringId', '?')})")
def test_24_enrichment_after_id_conversion():
"""ID Conversion: Convert Ensembl IDs then run enrichment"""
import gseapy
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
# Convert Ensembl to symbols
result = tu.tools.MyGene_batch_query(
gene_ids=ENSEMBL_IDS,
fields="symbol"
)
results = result.get('results', result.get('data', {}).get('results', []))
symbols = [hit.get('symbol', hit['query']) for hit in results if 'symbol' in hit]
assert len(symbols) >= 3, f"Not enough symbols converted: {symbols}"
# Run enrichment with converted symbols
go_result = gseapy.enrichr(
gene_list=symbols,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
assert len(go_result.results) > 0, "No enrichment after ID conversion"
print(f" Converted {len(ENSEMBL_IDS)} Ensembl IDs to {len(symbols)} symbols")
print(f" Enrichment returned {len(go_result.results)} terms")
# ============================================================
# Phase 7: Multiple Testing Correction Tests
# ============================================================
def test_25_bh_correction():
"""Multiple Testing: Benjamini-Hochberg correction"""
import gseapy
import numpy as np
from statsmodels.stats.multitest import multipletests
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
raw_pvals = result.results['P-value'].values
assert len(raw_pvals) > 0, "No p-values to correct"
reject, corrected, _, _ = multipletests(raw_pvals, alpha=0.05, method='fdr_bh')
n_sig = sum(reject)
print(f" BH: {n_sig}/{len(raw_pvals)} significant")
assert all(corrected >= raw_pvals), "BH-corrected p-values should be >= raw p-values"
def test_26_bonferroni_correction():
"""Multiple Testing: Bonferroni correction"""
import gseapy
import numpy as np
from statsmodels.stats.multitest import multipletests
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
raw_pvals = result.results['P-value'].values
reject_bh, bh_pvals, _, _ = multipletests(raw_pvals, alpha=0.05, method='fdr_bh')
reject_bonf, bonf_pvals, _, _ = multipletests(raw_pvals, alpha=0.05, method='bonferroni')
n_bh = sum(reject_bh)
n_bonf = sum(reject_bonf)
print(f" BH: {n_bh} significant, Bonferroni: {n_bonf} significant")
assert n_bonf <= n_bh, "Bonferroni should be more conservative than BH"
def test_27_correction_comparison():
"""Multiple Testing: Compare BH, Bonferroni, BY methods"""
import gseapy
from statsmodels.stats.multitest import multipletests
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
raw_pvals = result.results['P-value'].values
methods = ['fdr_bh', 'bonferroni', 'fdr_by', 'holm-sidak', 'holm']
counts = {}
for method in methods:
reject, _, _, _ = multipletests(raw_pvals, alpha=0.05, method=method)
counts[method] = sum(reject)
print(f" Correction comparison:")
for method, count in counts.items():
print(f" {method}: {count} significant")
# BH should be less conservative than Bonferroni
assert counts['fdr_bh'] >= counts['bonferroni'], "BH should find >= Bonferroni significant terms"
# ============================================================
# Phase 8: Cross-Validation Tests
# ============================================================
def test_28_cross_validate_go_bp():
"""Cross-Validation: Compare gseapy vs PANTHER vs STRING GO BP"""
import gseapy
import re
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
# gseapy
gseapy_result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
gseapy_go = set()
for term in gseapy_result.results[gseapy_result.results['Adjusted P-value'] < 0.05]['Term']:
m = re.search(r'(GO:\d+)', term)
if m:
gseapy_go.add(m.group(1))
# PANTHER
panther_result = tu.tools.PANTHER_enrichment(
gene_list=','.join(CANCER_GENES),
organism=9606,
annotation_dataset='GO:0008150'
)
panther_go = set(t['term_id'] for t in panther_result.get('data', {}).get('enriched_terms', [])
if t.get('fdr', 1) < 0.05)
# STRING
string_result = tu.tools.STRING_functional_enrichment(
protein_ids=CANCER_GENES,
species=9606
)
string_data = string_result.get('data', [])
string_go = set()
if isinstance(string_data, list):
for d in string_data:
if d.get('category') == 'Process' and d.get('fdr', 1) < 0.05:
term_id = d.get('term', '')
# STRING uses GOBP:XXXXXXX format sometimes
term_id = term_id.replace('GOBP:', 'GO:')
string_go.add(term_id)
# Count consensus
all_terms = gseapy_go | panther_go | string_go
consensus = 0
for term in all_terms:
sources = sum([term in gseapy_go, term in panther_go, term in string_go])
if sources >= 2:
consensus += 1
print(f" gseapy: {len(gseapy_go)} GO BP terms")
print(f" PANTHER: {len(panther_go)} GO BP terms")
print(f" STRING: {len(string_go)} GO BP terms")
print(f" Consensus (2+ sources): {consensus} terms")
# At least some consensus expected for well-known cancer genes
assert consensus > 0, "No consensus GO BP terms found across tools"
def test_29_cross_validate_kegg():
"""Cross-Validation: Compare gseapy KEGG vs STRING KEGG"""
import gseapy
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
# gseapy KEGG
gseapy_kegg = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='KEGG_2021_Human',
organism='human',
outdir=None, no_plot=True,
)
gseapy_terms = set(gseapy_kegg.results[gseapy_kegg.results['Adjusted P-value'] < 0.05]['Term'].str.lower())
# STRING KEGG
string_result = tu.tools.STRING_functional_enrichment(
protein_ids=CANCER_GENES,
species=9606
)
string_data = string_result.get('data', [])
string_kegg_terms = set()
if isinstance(string_data, list):
for d in string_data:
if d.get('category') == 'KEGG' and d.get('fdr', 1) < 0.05:
string_kegg_terms.add(d.get('description', '').lower())
# Check overlap
overlap = 0
for g_term in gseapy_terms:
for s_term in string_kegg_terms:
if g_term in s_term or s_term in g_term:
overlap += 1
break
print(f" gseapy KEGG significant: {len(gseapy_terms)}")
print(f" STRING KEGG significant: {len(string_kegg_terms)}")
print(f" Approximate overlap: {overlap}")
# ============================================================
# Phase 9: Different Gene Lists Tests
# ============================================================
def test_30_immune_gene_enrichment():
"""Different Gene List: Immune gene enrichment"""
import gseapy
result = gseapy.enrichr(
gene_list=IMMUNE_GENES,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
sig = result.results[result.results['Adjusted P-value'] < 0.05]
assert len(sig) > 0, "No significant terms for immune genes"
# Should find immune-related terms
immune_terms = sig[sig['Term'].str.contains('immune|cytokine|inflammatory|interleukin', case=False)]
assert len(immune_terms) > 0, "No immune-related GO terms found for immune gene list"
print(f" {len(sig)} significant terms, {len(immune_terms)} immune-related")
print(f" Top immune term: {immune_terms.iloc[0]['Term'][:80]}")
def test_31_signaling_gene_enrichment():
"""Different Gene List: Signaling pathway gene enrichment"""
import gseapy
result = gseapy.enrichr(
gene_list=SIGNALING_GENES,
gene_sets='KEGG_2021_Human',
organism='human',
outdir=None, no_plot=True,
)
sig = result.results[result.results['Adjusted P-value'] < 0.05]
assert len(sig) > 0, "No significant KEGG pathways for signaling genes"
# Should find MAPK/PI3K/RAS pathways
signal_paths = sig[sig['Term'].str.contains('MAPK|PI3K|Ras|EGFR|ErbB|signaling', case=False)]
assert len(signal_paths) > 0, "No signaling pathways found for signaling gene list"
print(f" {len(sig)} significant KEGG pathways")
print(f" {len(signal_paths)} signaling-related pathways")
def test_32_small_gene_list():
"""Edge Case: Small gene list (3 genes)"""
import gseapy
small_list = ["TP53", "BRCA1", "EGFR"]
result = gseapy.enrichr(
gene_list=small_list,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
df = result.results
assert len(df) > 0, "No results for small gene list"
sig = df[df['Adjusted P-value'] < 0.05]
print(f" Small list (3 genes): {len(sig)} significant terms")
def test_33_large_gene_list():
"""Edge Case: Large gene list (>40 genes)"""
import gseapy
large_list = CANCER_GENES + IMMUNE_GENES + SIGNALING_GENES
# Remove duplicates
large_list = list(set(large_list))
result = gseapy.enrichr(
gene_list=large_list,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
df = result.results
assert len(df) > 0, "No results for large gene list"
sig = df[df['Adjusted P-value'] < 0.05]
print(f" Large list ({len(large_list)} genes): {len(sig)} significant terms")
# ============================================================
# Phase 10: Specific Term Lookup Tests
# ============================================================
def test_34_find_specific_go_term():
"""Specific Term: Find a specific GO term in enrichment results"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='GO_Biological_Process_2021',
organism='human',
outdir=None, no_plot=True,
)
# Search for "cell cycle" related terms
df = result.results
cell_cycle = df[df['Term'].str.contains('cell cycle', case=False)]
assert len(cell_cycle) > 0, "No cell cycle terms found for cancer genes"
for _, row in cell_cycle.head(3).iterrows():
print(f" {row['Term'][:60]}")
print(f" P-value: {row['P-value']:.6e}")
print(f" Adjusted P-value: {row['Adjusted P-value']:.6e}")
print(f" Overlap: {row['Overlap']}")
def test_35_find_specific_kegg_pathway():
"""Specific Term: Find a specific KEGG pathway and its p-value"""
import gseapy
result = gseapy.enrichr(
gene_list=CANCER_GENES,
gene_sets='KEGG_2021_Human',
organism='human',
outdir=None, no_plot=True,
)
df = result.results
# Look for p53 signaling pathway
p53_pathway = df[df['Term'].str.contains('p53', case=False)]
if len(p53_pathway) > 0:
row = p53_pathway.iloc[0]
print(f" p53 signaling pathway found:")
print(f" Term: {row['Term']}")
print(f" P-value: {row['P-value']:.6e}")
print(f" Adjusted P-value: {row['Adjusted P-value']:.6e}")
print(f" Genes: {row['Genes']}")
else:
# Try broader search
signal_paths = df[df['Term'].str.contains('signaling|pathway', case=False)]
assert len(signal_paths) > 0, "No signaling pathways found"
print(f" p53 pathway not found, but {len(signal_paths)} other signaling pathways present")
# ============================================================
# Phase 11: GO Term Detail Tests
# ============================================================
def test_36_go_term_details():
"""GO Term: Get details for a specific GO term"""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
# GO:0051726 = regulation of cell cycle
result = tu.tools.GO_get_term_by_id(go_id='GO:0051726')
assert result is not None, "No result for GO:0051726"
print(f" GO:0051726 result type: {type(result)}")