-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_pathos.py
More file actions
2301 lines (1855 loc) · 85.9 KB
/
run_pathos.py
File metadata and controls
2301 lines (1855 loc) · 85.9 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
"""
PATHOS Prediction Runner
This script runs PATHOS predictions for variants not already in the database.
It validates input mutations, generates embeddings, runs inference, and combines
results from both database queries and de novo predictions.
Usage:
python run_pathos.py --input variants.txt --output results.csv
Input format:
P16501 M1A R56V
Q9Y6X3 M1C
"""
import argparse
import sqlite3
import sys
import os
import torch
import numpy as np
import pandas as pd
import requests
import time
from typing import Dict, List, Tuple, Optional, Set
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, as_completed
import multiprocessing
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from safetensors import safe_open
from safetensors.torch import save_file
from transformers import T5EncoderModel, AutoTokenizer, AutoModelForMaskedLM
from tqdm import tqdm
# import warnings
# warnings.filterwarnings('ignore')
from ete3 import Tree
from pastml.acr import pastml_pipeline
# Get the directory where this script is located (works for git repo)
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
# Fixed paths relative to script location
DB_PATH = os.path.join(SCRIPT_DIR, "database", "pathos.db")
AF_SQLITE_PATH = os.path.join(SCRIPT_DIR, "database", "af_index.sqlite")
FASTA_PATH = os.path.join(SCRIPT_DIR, "database", "uniprotsp_human_20032025_can_isoforms.fasta")
TREE_PATH = os.path.join(SCRIPT_DIR, "database", "clean_mammalia.tre")
MSA_FOLDER = os.path.join(SCRIPT_DIR, "database", "MSAs")
PASTML_CACHE = os.path.join(SCRIPT_DIR, "database", "pastml_cache")
FASTA_FOLDER = os.path.join(SCRIPT_DIR, "database", "fastas")
MAMMALS_DB = os.path.join(SCRIPT_DIR, "database", "mmseqs_db", "mammalsDB")
MODELS_FOLDER = os.path.join(SCRIPT_DIR, "models")
GFF_FOLDER = os.path.join(SCRIPT_DIR, "database", "uniprot")
STRING_PATH = os.path.join(SCRIPT_DIR, "database", "STRING_prot.tsv")
# Checks if all required paths exist
REQUIRED_PATHS = [DB_PATH, AF_SQLITE_PATH, FASTA_PATH,
TREE_PATH, MSA_FOLDER, MAMMALS_DB,
MODELS_FOLDER, STRING_PATH]
for path in REQUIRED_PATHS:
if not os.path.exists(path):
print(f"ERROR: Required path not found: {path}")
sys.exit(1)
# Trained model checkpoint files
TRAINED_MODELS = {
"ankh2_large": "PATHOS_ankh2.ckpt",
"esmc_600m": "PATHOS_ESMC.ckpt"
}
# Model configuration
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
PLM_MODELS = ["esmc_600m", "ankh2_large"]
PLM_EMBEDDING_DIMS = {"esmc_600m": 1152, "ankh2_large": 1536}
# Debug flag (set from --debug arg in __main__)
DEBUG = False
# Feature transformation parameters (from training data)
PARAM_PASTML = {'log_min': -9.400938817005075, 'log_max': 0.0002723707610688847}
PARAM_AF = {'log_min': -20.477300046830425, 'log_max': -1.4604105764703945e-06}
PARAM_STRING = {'log_min': -10.629354334852511, 'log_max': -0.8828422962808311}
# Amino acid alphabet
AA_ALPHABET = "ACDEFGHIKLMNPQRSTVWY"
class FC_model(nn.Module):
"""PATHOS prediction model"""
def __init__(self, input_size=6):
super(FC_model, self).__init__()
self.model = nn.Sequential(nn.Linear(input_size, 1))
self.sigmoid = nn.Sigmoid()
def forward(self, x):
return self.sigmoid(self.model(x))
# ============================================================================
# FEATURE GENERATION FUNCTIONS
# ============================================================================
def transform_log2_minmax(data, params):
"""Apply log2-minmax transformation to features"""
epsilon = 1e-9
data_log = np.log2(data + epsilon)
return (data_log - params['log_min']) / (params['log_max'] - params['log_min'])
# ============================================================================
# PASTML CONSERVATION SCORE COMPUTATION
# ============================================================================
def check_and_generate_msas(protein_ids: List[str], msa_folder: str, fasta_folder: str,
mammals_db: str, mem_limit: str = "8G", debug: bool = False) -> Tuple[List[str], List[str], List[str]]:
"""Check MSA availability for all proteins and generate missing ones
Args:
protein_ids: List of UniProt IDs to check
msa_folder: Path to MSA folder
fasta_folder: Path to individual FASTA files
mammals_db: Path to mammalsDB for mmseqs2
mem_limit: Memory limit for mmseqs2 (default: 8G)
debug: Print debug information (default: False)
Returns:
Tuple of (available_msas, generated_msas, failed_msas)
"""
import shutil
available = []
to_generate = []
# Check which MSAs exist
for protein_id in protein_ids:
msa_file = os.path.join(msa_folder, protein_id)
if os.path.exists(msa_file):
available.append(protein_id)
else:
to_generate.append(protein_id)
# Print summary before generation
print(f" MSA already available: {len(available)}/{len(protein_ids)}")
print(f" MSA to generate: {len(to_generate)}/{len(protein_ids)}")
generated = []
failed = []
if to_generate:
# Check if mmseqs is available
if shutil.which('mmseqs') is None:
print(f" WARNING: mmseqs not found, cannot generate MSAs")
failed = to_generate
elif not os.path.exists(mammals_db):
print(f" WARNING: mammalsDB not found at {mammals_db}, cannot generate MSAs")
failed = to_generate
else:
# Generate missing MSAs
print(f" Generating {len(to_generate)} MSAs with mmseqs2 (mem_limit={mem_limit})...")
for protein_id in tqdm(to_generate, desc=" Generating MSAs", dynamic_ncols=True):
result = generate_msa_with_mmseqs(protein_id, fasta_folder, msa_folder, mammals_db,
mem_limit=mem_limit, debug=debug)
if result:
generated.append(protein_id)
else:
failed.append(protein_id)
if debug:
print(f" Failed to generate MSA for {protein_id}")
return available, generated, failed
def generate_msa_with_mmseqs(protein_id: str, fasta_folder: str, msa_folder: str,
mammals_db: str, mem_limit: str = "8G", debug: bool = False) -> Optional[str]:
"""Generate MSA using mmseqs2 if not already available
Args:
protein_id: UniProt ID
fasta_folder: Path to folder containing individual FASTA files
msa_folder: Path to MSA output folder
mammals_db: Path to mammalsDB (without extension)
mem_limit: Memory limit for mmseqs2 (default: 8G)
debug: Print debug information (default: False)
Returns:
Path to generated MSA file, or None if generation failed
"""
import subprocess
import shutil
def debug_print(msg):
if debug:
print(f" [DEBUG mmseqs] {msg}")
# Check if mmseqs is available
if shutil.which('mmseqs') is None:
debug_print("mmseqs not found in PATH")
return None
fasta_file = os.path.join(fasta_folder, f"{protein_id}.fasta")
print(os.path.exists(fasta_file))
if not os.path.exists(fasta_file):
debug_print(f"FASTA file not found: {fasta_file}")
return None
if not os.path.exists(mammals_db):
debug_print(f"mammalsDB not found: {mammals_db}")
return None
# Output paths - use a temporary folder for intermediate files
temp_folder = os.path.join(msa_folder, f".tmp_{protein_id}")
os.makedirs(temp_folder, exist_ok=True)
path_queryDB = os.path.join(temp_folder, "queryDB")
result_prefix = os.path.join(temp_folder, f"result_{protein_id}")
tmp_folder = os.path.join(temp_folder, "tmp")
msa_result = os.path.join(temp_folder, f"result_{protein_id}_msa")
unpack_dir = os.path.join(temp_folder, "unpack")
# Final MSA path directly in msa_folder
final_msa = os.path.join(msa_folder, protein_id)
debug_print(f"Starting MSA generation for {protein_id}")
debug_print(f" FASTA: {fasta_file}")
debug_print(f" Temp folder: {temp_folder}")
debug_print(f" Final MSA: {final_msa}")
debug_print(f" Memory limit: {mem_limit}")
try:
# Step 1: Create query database
debug_print("Step 1/5: Creating query database...")
result = subprocess.run(
['mmseqs', 'createdb', fasta_file, path_queryDB],
check=True, capture_output=True, text=True
)
if debug and result.stderr:
debug_print(f" stderr: {result.stderr[:200]}")
# Step 2: Search against mammalsDB (with memory limit)
debug_print("Step 2/5: Searching against mammalsDB...")
result = subprocess.run(
['mmseqs', 'search', path_queryDB, mammals_db, result_prefix, tmp_folder,
'--max-seqs', '5000', '--min-seq-id', '0.5', '--split-memory-limit', mem_limit],
check=True, capture_output=True, text=True
)
if debug and result.stderr:
debug_print(f" stderr: {result.stderr[:200]}")
# Step 3: Convert alignments
debug_print("Step 3/5: Converting alignments...")
result = subprocess.run(
['mmseqs', 'convertalis', path_queryDB, mammals_db, result_prefix, f"{result_prefix}.m8"],
check=True, capture_output=True, text=True
)
if debug and result.stderr:
debug_print(f" stderr: {result.stderr[:200]}")
# Step 4: Generate MSA
debug_print("Step 4/5: Generating MSA...")
result = subprocess.run(
['mmseqs', 'result2msa', path_queryDB, mammals_db, result_prefix, msa_result],
check=True, capture_output=True, text=True
)
if debug and result.stderr:
debug_print(f" stderr: {result.stderr[:200]}")
# Step 5: Unpack MSA
debug_print("Step 5/5: Unpacking MSA...")
result = subprocess.run(
['mmseqs', 'unpackdb', msa_result, unpack_dir, '--unpack-name-mode', '0'],
check=True, capture_output=True, text=True
)
if debug and result.stderr:
debug_print(f" stderr: {result.stderr[:200]}")
# Step 6: Move final MSA to msa_folder and cleanup
msa_output = os.path.join(unpack_dir, "0")
if os.path.exists(msa_output):
shutil.move(msa_output, final_msa)
# Remove temporary folder
shutil.rmtree(temp_folder, ignore_errors=True)
debug_print(f"MSA generated successfully: {final_msa}")
return final_msa
debug_print(f"MSA output file not found: {msa_output}")
shutil.rmtree(temp_folder, ignore_errors=True)
return None
except subprocess.CalledProcessError as e:
debug_print(f"mmseqs command failed: {e.cmd}")
debug_print(f" Return code: {e.returncode}")
debug_print(f" stderr: {e.stderr[:500] if e.stderr else 'None'}")
shutil.rmtree(temp_folder, ignore_errors=True)
return None
except Exception as e:
debug_print(f"Exception: {type(e).__name__}: {e}")
shutil.rmtree(temp_folder, ignore_errors=True)
return None
def get_msa_fasta(msa_file: str) -> Dict[str, str]:
"""Load MSA sequences from FASTA file
Expects FASTA headers with organism names like:
>Homo_sapiens OS=...
"""
dict_seq = {}
get = False
if not os.path.exists(msa_file):
return {}
with open(msa_file) as fin:
for line in fin:
line = line.strip()
if line.startswith(">"):
if "OS" not in line:
get = False
continue
try:
org = "_".join(line.split("=")[1].split(" OX")[0].split())
if org in dict_seq:
get = False
continue
dict_seq[org] = ""
get = True
except:
get = False
continue
elif get:
dict_seq[org] += line
return dict_seq
def pos_to_msa_index(sequence: str, position: int) -> int:
"""Convert protein position to MSA index (accounting for gaps)"""
index = 0
for i, aa in enumerate(sequence):
if aa in AA_ALPHABET:
index += 1
if index == position:
return i
return -1
def create_pastml_annotation(dict_fasta: Dict[str, str], protein_id: str,
mutation: str, annotation_dir: str):
"""Create annotation CSV file for PASTML"""
wt_aa, position, mut_aa = parse_mutation(mutation)
if "Homo_sapiens" not in dict_fasta:
return False
msa_index = pos_to_msa_index(dict_fasta["Homo_sapiens"], position)
if msa_index == -1:
return False
os.makedirs(annotation_dir, exist_ok=True)
annot_file = os.path.join(annotation_dir, f"{protein_id}_{mutation}_annot.csv")
with open(annot_file, "w") as f:
f.write("organism,residue\n")
for org in dict_fasta:
if org == "Homo_sapiens":
# Use the mutant amino acid for human
f.write(f"{org},{mut_aa}\n")
else:
# Use the MSA amino acid for other organisms
aa = dict_fasta[org][msa_index] if msa_index < len(dict_fasta[org]) else '-'
f.write(f"{org},{aa}\n")
return True
def prune_phylo_tree(tree: 'Tree', msa_organisms: List[str], output_file: str) -> 'Tree':
"""Prune phylogenetic tree to match organisms in MSA"""
# Get tree node names from all nodes (not just leaves)
all_nodes = tree.get_descendants() + [tree]
tree_node_names = {node.name for node in all_nodes}
# Keep only organisms present in both tree and MSA
keep_org = [org for org in msa_organisms if org in tree_node_names]
if len(keep_org) < 2:
return None
pruned_tree = tree.copy()
pruned_tree.prune(keep_org) # Don't preserve branch length
# Write pruned tree
with open(output_file, "w") as f:
f.write(pruned_tree.write(format=1))
return pruned_tree
def run_pastml_inference(tree_file: str, annot_file: str, output_dir: str) -> bool:
"""Run PASTML ancestral sequence reconstruction"""
try:
pastml_pipeline(
data=annot_file,
data_sep=',',
columns=['residue'],
name_column='residue',
tree=tree_file,
work_dir=output_dir,
model="JC",
verbose=False
)
return True
except Exception as e:
return False
def compute_pastml_score(protein_id: str, mutation: str, msa_folder: str,
tree: 'Tree', tree_nodes: Set[str], cache_dir: str,
fasta_folder: str = None, mammals_db: str = None) -> float:
"""Compute PASTML conservation score for a single variant
Returns probability of mutation at ancestral node (0-1).
Higher values = mutation is common in evolution = less pathogenic.
Low values (close to 0) = mutation is rare = likely pathogenic.
If MSA is not available and fasta_folder/mammals_db are provided,
will attempt to generate MSA using mmseqs2.
"""
wt_aa, position, mut_aa = parse_mutation(mutation)
# Check cache first
cache_file = os.path.join(cache_dir, protein_id, f"{mutation}_pastml.txt")
if os.path.exists(cache_file):
try:
with open(cache_file) as f:
cached_value = float(f.read().strip())
return cached_value
except:
pass
# Setup directories
annotation_dir = os.path.join(cache_dir, protein_id, mutation)
os.makedirs(annotation_dir, exist_ok=True)
# Check if already computed
prob_file = os.path.join(annotation_dir, "marginal_probabilities.character_residue.model_JC.tab")
if not os.path.exists(prob_file):
# Load MSA
msa_file = os.path.join(msa_folder, protein_id)
if not os.path.exists(msa_file):
# Try to generate MSA with mmseqs2
if fasta_folder and mammals_db:
msa_file = generate_msa_with_mmseqs(protein_id, fasta_folder, msa_folder, mammals_db)
if not msa_file:
print(f" [PASTML] {protein_id}_{mutation}: NaN - MSA generation with mmseqs2 failed")
return np.nan
else:
print(f" [PASTML] {protein_id}_{mutation}: NaN - No MSA available and no fasta_folder/mammals_db provided")
return np.nan
dict_fasta = get_msa_fasta(msa_file)
if not dict_fasta:
print(f" [PASTML] {protein_id}_{mutation}: NaN - MSA file is empty or could not be parsed")
return np.nan
if "Homo_sapiens" not in dict_fasta:
print(f" [PASTML] {protein_id}_{mutation}: NaN - Homo_sapiens not found in MSA")
return np.nan
# Create annotation file
if not create_pastml_annotation(dict_fasta, protein_id, mutation, annotation_dir):
print(f" [PASTML] {protein_id}_{mutation}: NaN - Failed to create annotation file (position may be out of range)")
return np.nan
# Prune tree
pruned_tree_file = os.path.join(annotation_dir, f"{protein_id}_pruned.tre")
msa_organisms = list(dict_fasta.keys())
pruned_tree = prune_phylo_tree(tree, msa_organisms, pruned_tree_file)
if pruned_tree is None:
print(f" [PASTML] {protein_id}_{mutation}: NaN - Tree pruning failed (fewer than 2 organisms overlap with tree)")
return np.nan
# Run PASTML
annot_file = os.path.join(annotation_dir, f"{protein_id}_{mutation}_annot.csv")
if not run_pastml_inference(pruned_tree_file, annot_file, annotation_dir):
print(f" [PASTML] {protein_id}_{mutation}: NaN - PASTML inference failed")
return np.nan
# Read probability from output
try:
df_pastml = pd.read_csv(prob_file, sep="\t")
# Get ancestral node for Homo sapiens
tree_file = os.path.join(annotation_dir, f"named.tree_{protein_id}_pruned.nwk")
result_tree = Tree(tree_file, format=1)
human_node = result_tree.search_nodes(name="Homo_sapiens")[0]
parent_node_name = human_node.up.name
# Extract probability for the mutant amino acid
prob = df_pastml[df_pastml["node"] == parent_node_name][mut_aa].values[0]
# Cache result
os.makedirs(os.path.dirname(cache_file), exist_ok=True)
with open(cache_file, "w") as f:
f.write(str(prob))
return float(prob)
except Exception as e:
print(f" [PASTML] {protein_id}_{mutation}: NaN - Error reading probability: {e}")
return np.nan
# ============================================================================
# UNIPROT ANNOTATIONS (GFF-based implementation)
# ============================================================================
def download_gff_from_uniprot(protein_id: str, output_path: str) -> bool:
"""Download GFF annotation file from UniProt API
Args:
protein_id: UniProt accession ID
output_path: Where to save the GFF file
Returns:
True if successful, False otherwise
"""
try:
url = f"https://rest.uniprot.org/uniprotkb/{protein_id}.gff"
response = requests.get(url, timeout=30)
if response.status_code == 200:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, 'w') as f:
f.write(response.text)
return True
else:
return False
except Exception as e:
return False
def get_matrix_annot(protein_id: str, seq_length: int) -> Optional[np.ndarray]:
"""Create annotation matrix from GFF file for a protein"""
dict_index = {
'Beta strand': 0, 'Helix': 1, 'Natural variant': 2, 'Topological domain': 3,
'Mutagenesis': 4, 'Domain': 5, 'Region': 6, 'Alternative sequence': 7,
'Turn': 8, 'DNA binding': 9, 'Site': 10, 'Sequence conflict': 11,
'Disulfide bond': 12, 'Repeat': 13, 'Binding site': 14, 'Transmembrane': 15,
'Intramembrane': 16, 'Modified residue': 17
}
gff_file = os.path.join(GFF_FOLDER, f"{protein_id}.gff")
if not os.path.exists(gff_file):
os.makedirs(GFF_FOLDER, exist_ok=True)
if not download_gff_from_uniprot(protein_id, gff_file):
return np.zeros((seq_length, 18), dtype=int) # Return empty matrix of CORRECT size
try:
# Build matrix to exact sequence length. No trimming!
annot_matrix = np.zeros((seq_length, 18), dtype=int)
with open(gff_file) as f:
for line in f:
if line.startswith('#'): continue
items = line.strip().split("\t")
if len(items) < 5: continue
annot = items[2]
if annot not in dict_index:
continue
start_pos = min(int(items[3]), seq_length)
end_pos = min(int(items[4]), seq_length)
annot_index = dict_index[annot]
if annot != "Disulfide bond":
annot_matrix[start_pos - 1:end_pos, annot_index] = 1
else:
annot_matrix[start_pos - 1, annot_index] = 1
annot_matrix[end_pos - 1, annot_index] = 1
return annot_matrix
except Exception as e:
# Fallback to zeros of the correct size if parsing fails
return np.zeros((seq_length, 18), dtype=int)
def window_annot(mutation, matrix, window_size=5):
_, position, _ = parse_mutation(mutation)
position_idx = position - 1
total_length = matrix.shape[0]
left_part = window_size
right_part = window_size
if position_idx - left_part < 0:
excess = left_part - position_idx
left_part = position_idx
right_part += excess
if position_idx + right_part >= total_length:
excess = (position_idx + right_part + 1) - total_length
right_part -= excess
left_part += excess
final_matrix = matrix[position_idx - left_part: position_idx + right_part + 1].sum(axis=0)
return (final_matrix != 0).astype(int).tolist()
def load_uniprot_annotations(protein_id: str, mutation: str, sequence_length: int, window_size: int = 5) -> List[int]:
"""Load UniProt annotation features for a specific variant
This is the main function that combines get_matrix_annot and window_annot
to produce the final 18-dimensional binary annotation vector.
Args:
protein_id: UniProt accession ID
mutation: Mutation string (e.g., 'R50K')
sequence_length: Length of the protein sequence (used for window adjustment)
window_size: Window size for annotation extraction (default 5)
Returns:
List of 18 binary values representing annotations in the window
"""
# Get the full annotation matrix for this protein
matrix = get_matrix_annot(protein_id, sequence_length)
if matrix is None:
return [0] * 18
# Extract window-based features
annot_vector = window_annot(mutation, matrix, window_size=window_size)
return annot_vector
def get_gene_name_from_uniprot(uniprot_id: str) -> Optional[str]:
"""Query UniProt API to get gene name for a UniProt ID
Args:
uniprot_id: UniProt accession ID
Returns:
Gene name or None if not found
"""
try:
url = f"https://rest.uniprot.org/uniprotkb/{uniprot_id}.json"
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
# Try to get the primary gene name
if 'genes' in data and len(data['genes']) > 0:
if 'geneName' in data['genes'][0]:
gene_name = data['genes'][0]['geneName']['value']
return gene_name
except Exception as e:
pass
return None
def load_gene_names(protein_ids: List[str]) -> Dict[str, str]:
"""Load gene names for proteins from UniProt API
Args:
protein_ids: List of UniProt IDs
Returns:
Dictionary mapping UniProt ID to gene name
"""
gene_dict = {}
for pid in tqdm(protein_ids, desc="Fetching gene names", dynamic_ncols=True):
gene_name = get_gene_name_from_uniprot(pid)
if gene_name:
gene_dict[pid] = gene_name
time.sleep(0.1) # Rate limiting
return gene_dict
def load_allele_frequency(protein_id: str, mutation: str, gene_name: str, af_sqlite: str) -> float:
"""Load Allele Frequency for a specific variant from SQLite database
Args:
protein_id: UniProt ID
mutation: Mutation string (e.g., M1A)
gene_name: Gene name for the protein
af_sqlite: Path to AF SQLite database
Returns:
Allele frequency or 0 if not found (NaN values are treated as 0)
"""
if not af_sqlite or not os.path.exists(af_sqlite):
return np.nan
try:
conn = sqlite3.connect(af_sqlite)
cursor = conn.cursor()
query = "SELECT AF FROM af_table WHERE Gene=? AND Variation=?"
result = cursor.execute(query, (gene_name, mutation)).fetchone()
conn.close()
if result and result[0] is not None:
return float(result[0])
except Exception as e:
pass
return np.nan
def load_allele_frequencies_batch(variants: List[Tuple[str, str]], gene_names: Dict[str, str], af_sqlite: str) -> Dict[Tuple[str, str], float]:
"""Load Allele Frequencies for all variants in a single database query
Args:
variants: List of (protein_id, mutation) tuples
gene_names: Dictionary mapping protein IDs to gene names
af_sqlite: Path to AF SQLite database
Returns:
Dictionary mapping (protein_id, mutation) to allele frequency
"""
af_scores = {}
if not af_sqlite or not os.path.exists(af_sqlite):
return {v: np.nan for v in variants}
try:
conn = sqlite3.connect(af_sqlite)
cursor = conn.cursor()
# Build list of (gene, mutation) pairs to query
query_pairs = []
variant_to_gene = {}
for protein_id, mutation in variants:
gene_name = gene_names.get(protein_id)
if gene_name:
query_pairs.append((gene_name, mutation))
variant_to_gene[(protein_id, mutation)] = gene_name
# Query in batches to avoid SQLite limits
batch_size = 500
results_dict = {}
for i in range(0, len(query_pairs), batch_size):
batch = query_pairs[i:i + batch_size]
placeholders = ','.join(['(?, ?)'] * len(batch))
flat_params = [item for pair in batch for item in pair]
query = f"SELECT Gene, Variation, AF FROM af_table WHERE (Gene, Variation) IN (VALUES {placeholders})"
cursor.execute(query, flat_params)
for row in cursor.fetchall():
gene, variation, af = row
results_dict[(gene, variation)] = float(af) if af is not None else np.nan
conn.close()
# Map back to (protein_id, mutation) keys
for protein_id, mutation in variants:
gene_name = variant_to_gene.get((protein_id, mutation))
if gene_name and (gene_name, mutation) in results_dict:
af_scores[(protein_id, mutation)] = results_dict[(gene_name, mutation)]
else:
af_scores[(protein_id, mutation)] = np.nan
except Exception as e:
# Fallback: return NaN for all
return {v: np.nan for v in variants}
return af_scores
def load_string_scores_batch(protein_ids: List[str]) -> Dict[str, float]:
"""Load STRING interaction scores for all proteins at once
Args:
protein_ids: List of UniProt IDs
Returns:
Dictionary mapping protein ID to STRING score
"""
string_scores = {pid: np.nan for pid in protein_ids}
if not os.path.exists(STRING_PATH):
return string_scores
try:
df = pd.read_csv(STRING_PATH, sep='\t', names=["ID", "STRING"], header=None)
string_dict = dict(zip(df['ID'], df['STRING']))
for pid in protein_ids:
if pid in string_dict:
string_scores[pid] = float(string_dict[pid])
except Exception as e:
pass
return string_scores
def load_string_score(protein_id: str) -> float:
"""Load STRING interaction score for a protein
Args:
protein_id: UniProt ID
Returns:
STRING interaction score or default value if not found
"""
if not os.path.exists(STRING_PATH):
return np.nan
try:
df = pd.read_csv(STRING_PATH, sep='\t', names=["ID", "STRING"], header=None)
match = df[df['ID'] == protein_id]
if not match.empty:
return float(match.iloc[0]['STRING'])
except Exception as e:
pass
return np.nan
def _process_variant_worker(args):
"""Worker function for parallel variant processing (module-level for pickling)
Args:
args: Tuple of (protein_id, mutation, seq, af_score, string_score,
do_pastml, msa_dir, tree_path, cache, data_dir, fasta_folder, mammals_db)
Returns:
Dictionary with variant features or None if processing failed
"""
(protein_id, mutation, seq, af_score, string_score,
do_pastml, msa_dir, tree_path, cache, data_dir, fasta_folder, mammals_db) = args
try:
wt_aa, position, mut_aa = parse_mutation(mutation)
# Get annotation features
annot_features = load_uniprot_annotations(protein_id, mutation, len(seq), window_size=5)
# Compute PASTML score
if do_pastml and tree_path:
try:
local_tree = Tree(tree_path, format=1, quoted_node_names=False)
local_nodes = {n.name for n in local_tree.get_descendants() + [local_tree]}
pastml_score = compute_pastml_score(
protein_id, mutation, msa_dir, local_tree, local_nodes, cache,
fasta_folder=fasta_folder, mammals_db=mammals_db
)
except:
pastml_score = np.nan
else:
pastml_score = np.nan
return {
'ID': protein_id,
'Variation': mutation,
'PASTML': pastml_score,
'AF': af_score,
'STRING': string_score,
'ANNOTATIONS': annot_features
}
except Exception as e:
return None
def generate_features_for_variants(
variants: List[Tuple[str, str]],
sequences: Dict[str, str],
data_dir: str,
msa_folder: str = None,
tree_path: str = None,
pastml_cache: str = None,
compute_pastml: bool = False,
af_sqlite: str = None,
n_jobs: int = None,
fasta_folder: str = None,
mammals_db: str = None
) -> pd.DataFrame:
"""Generate all required features for PATHOS prediction
Args:
variants: List of (protein_id, mutation) tuples
sequences: Dictionary mapping protein IDs to sequences
data_dir: Base data directory
msa_folder: Path to MSA folder for PASTML
tree_path: Path to phylogenetic tree file
pastml_cache: Path to PASTML cache directory
compute_pastml: Whether to compute PASTML scores
af_sqlite: Path to allele frequency SQLite database
n_jobs: Number of parallel workers (default: CPU count - 1)
fasta_folder: Path to individual FASTA files (for MSA generation)
mammals_db: Path to mammalsDB for mmseqs2 (for MSA generation)
"""
# Load gene names for all proteins from UniProt API
unique_proteins = list(set([pid for pid, _ in variants]))
gene_names = load_gene_names(unique_proteins)
# Load phylogenetic tree if computing PASTML
tree = None
tree_nodes = set()
if compute_pastml:
if tree_path and os.path.exists(tree_path):
try:
tree = Tree(tree_path, format=1, quoted_node_names=False)
all_nodes = tree.get_descendants() + [tree]
tree_nodes = {node.name for node in all_nodes}
except Exception as e:
compute_pastml = False
else:
compute_pastml = False
# Pre-load STRING scores for all proteins in batch (single file read)
string_scores = load_string_scores_batch(unique_proteins)
# Pre-load all AF scores in batch (single database connection)
af_sqlite = af_sqlite or AF_SQLITE_PATH
af_scores = load_allele_frequencies_batch(variants, gene_names, af_sqlite)
# Determine number of workers
if n_jobs is None:
n_jobs = 5
# Prepare arguments for parallel processing
msa_folder = msa_folder or MSA_FOLDER
pastml_cache = pastml_cache or PASTML_CACHE
fasta_folder = fasta_folder or FASTA_FOLDER
mammals_db = mammals_db or MAMMALS_DB
rows = []
# Use parallel processing if n_jobs > 1 and we have enough variants
if n_jobs > 1 and len(variants) > 10:
# Prepare all arguments
all_args = []
for protein_id, mutation in variants:
seq = sequences.get(protein_id)
if not seq:
continue
string_score = string_scores.get(protein_id, np.nan)
af_score = af_scores.get((protein_id, mutation), np.nan)
all_args.append((
protein_id, mutation, seq, af_score, string_score,
compute_pastml, msa_folder, tree_path, pastml_cache, data_dir,
fasta_folder, mammals_db
))
# Process in parallel using module-level function
with ProcessPoolExecutor(max_workers=n_jobs) as executor:
futures = {executor.submit(_process_variant_worker, args): i for i, args in enumerate(all_args)}
for future in tqdm(as_completed(futures), total=len(futures), desc="Features", dynamic_ncols=True):
result = future.result()
if result is not None:
rows.append(result)
else:
# Sequential processing for small datasets or n_jobs=1
for protein_id, mutation in tqdm(variants, desc="Features", dynamic_ncols=True):
sequence = sequences.get(protein_id)
if not sequence:
continue
try:
wt_aa, position, mut_aa = parse_mutation(mutation)
# Get annotation features
annot_features = load_uniprot_annotations(protein_id, mutation, len(sequence), window_size=5)
# Compute PASTML score
if compute_pastml:
pastml_score = compute_pastml_score(
protein_id, mutation, msa_folder,
tree, tree_nodes, pastml_cache,
fasta_folder=fasta_folder, mammals_db=mammals_db
)
else:
pastml_score = np.nan
# Get pre-loaded scores
af_score = af_scores.get((protein_id, mutation), np.nan)
string_score = string_scores.get(protein_id, np.nan)
rows.append({
'ID': protein_id,