-
Notifications
You must be signed in to change notification settings - Fork 522
/
Copy pathbatch.py
1790 lines (1619 loc) · 64.6 KB
/
batch.py
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
from __future__ import annotations
import os
os.environ["TF_FORCE_UNIFIED_MEMORY"] = "1"
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "2.0"
import json
import logging
import math
import random
import sys
import time
import zipfile
import shutil
from argparse import ArgumentParser
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, TYPE_CHECKING
from io import StringIO
import importlib_metadata
import numpy as np
import pandas
try:
import alphafold
except ModuleNotFoundError:
raise RuntimeError(
"\n\nalphafold is not installed. Please run `pip install colabfold[alphafold]`\n"
)
from alphafold.common import protein, residue_constants
# delay imports of tensorflow, jax and numpy
# loading these for type checking only can take around 10 seconds just to show a CLI usage message
if TYPE_CHECKING:
import haiku
from alphafold.model import model
from numpy import ndarray
from alphafold.common.protein import Protein
from alphafold.data import (
feature_processing,
msa_pairing,
pipeline,
pipeline_multimer,
templates,
)
from alphafold.data.tools import hhsearch
from colabfold.citations import write_bibtex
from colabfold.download import default_data_dir, download_alphafold_params
from colabfold.utils import (
ACCEPT_DEFAULT_TERMS,
DEFAULT_API_SERVER,
NO_GPU_FOUND,
CIF_REVISION_DATE,
get_commit,
safe_filename,
setup_logging,
CFMMCIFIO,
)
from Bio.PDB import MMCIFParser, PDBParser, MMCIF2Dict
logger = logging.getLogger(__name__)
def patch_openmm():
from simtk.openmm import app
from simtk.unit import nanometers, sqrt
# applied https://raw.githubusercontent.com/deepmind/alphafold/main/docker/openmm.patch
# to OpenMM 7.5.1 (see PR https://github.com/openmm/openmm/pull/3203)
# patch is licensed under CC-0
# OpenMM is licensed under MIT and LGPL
# fmt: off
def createDisulfideBonds(self, positions):
def isCyx(res):
names = [atom.name for atom in res._atoms]
return 'SG' in names and 'HG' not in names
# This function is used to prevent multiple di-sulfide bonds from being
# assigned to a given atom.
def isDisulfideBonded(atom):
for b in self._bonds:
if (atom in b and b[0].name == 'SG' and
b[1].name == 'SG'):
return True
return False
cyx = [res for res in self.residues() if res.name == 'CYS' and isCyx(res)]
atomNames = [[atom.name for atom in res._atoms] for res in cyx]
for i in range(len(cyx)):
sg1 = cyx[i]._atoms[atomNames[i].index('SG')]
pos1 = positions[sg1.index]
candidate_distance, candidate_atom = 0.3*nanometers, None
for j in range(i):
sg2 = cyx[j]._atoms[atomNames[j].index('SG')]
pos2 = positions[sg2.index]
delta = [x-y for (x,y) in zip(pos1, pos2)]
distance = sqrt(delta[0]*delta[0] + delta[1]*delta[1] + delta[2]*delta[2])
if distance < candidate_distance and not isDisulfideBonded(sg2):
candidate_distance = distance
candidate_atom = sg2
# Assign bond to closest pair.
if candidate_atom:
self.addBond(sg1, candidate_atom)
# fmt: on
app.Topology.createDisulfideBonds = createDisulfideBonds
def mk_mock_template(
query_sequence: Union[List[str], str], num_temp: int = 1
) -> Dict[str, Any]:
ln = (
len(query_sequence)
if isinstance(query_sequence, str)
else sum(len(s) for s in query_sequence)
)
output_templates_sequence = "A" * ln
output_confidence_scores = np.full(ln, 1.0)
templates_all_atom_positions = np.zeros(
(ln, templates.residue_constants.atom_type_num, 3)
)
templates_all_atom_masks = np.zeros((ln, templates.residue_constants.atom_type_num))
templates_aatype = templates.residue_constants.sequence_to_onehot(
output_templates_sequence, templates.residue_constants.HHBLITS_AA_TO_ID
)
template_features = {
"template_all_atom_positions": np.tile(
templates_all_atom_positions[None], [num_temp, 1, 1, 1]
),
"template_all_atom_masks": np.tile(
templates_all_atom_masks[None], [num_temp, 1, 1]
),
"template_sequence": [f"none".encode()] * num_temp,
"template_aatype": np.tile(np.array(templates_aatype)[None], [num_temp, 1, 1]),
"template_confidence_scores": np.tile(
output_confidence_scores[None], [num_temp, 1]
),
"template_domain_names": [f"none".encode()] * num_temp,
"template_release_date": [f"none".encode()] * num_temp,
"template_sum_probs": np.zeros([num_temp], dtype=np.float32),
}
return template_features
def mk_template(
a3m_lines: str, template_path: str, query_sequence: str
) -> Dict[str, Any]:
template_featurizer = templates.HhsearchHitFeaturizer(
mmcif_dir=template_path,
max_template_date="2100-01-01",
max_hits=20,
kalign_binary_path="kalign",
release_dates_path=None,
obsolete_pdbs_path=None,
)
hhsearch_pdb70_runner = hhsearch.HHSearch(
binary_path="hhsearch", databases=[f"{template_path}/pdb70"]
)
hhsearch_result = hhsearch_pdb70_runner.query(a3m_lines)
hhsearch_hits = pipeline.parsers.parse_hhr(hhsearch_result)
templates_result = template_featurizer.get_templates(
query_sequence=query_sequence, hits=hhsearch_hits
)
return dict(templates_result.features)
def validate_and_fix_mmcif(cif_file: Path):
"""validate presence of _entity_poly_seq in cif file and add revision_date if missing"""
# check that required poly_seq and revision_date fields are present
cif_dict = MMCIF2Dict.MMCIF2Dict(cif_file)
required = [
"_chem_comp.id",
"_chem_comp.type",
"_struct_asym.id",
"_struct_asym.entity_id",
"_entity_poly_seq.mon_id",
]
for r in required:
if r not in cif_dict:
raise ValueError(f"mmCIF file {cif_file} is missing required field {r}.")
if "_pdbx_audit_revision_history.revision_date" not in cif_dict:
logger.info(
f"Adding missing field revision_date to {cif_file}. Backing up original file to {cif_file}.bak."
)
shutil.copy2(cif_file, str(cif_file) + ".bak")
with open(cif_file, "a") as f:
f.write(CIF_REVISION_DATE)
def convert_pdb_to_mmcif(pdb_file: Path):
"""convert existing pdb files into mmcif with the required poly_seq and revision_date"""
id = pdb_file.stem
cif_file = pdb_file.parent.joinpath(f"{id}.cif")
if cif_file.is_file():
return
parser = PDBParser(QUIET=True)
structure = parser.get_structure(id, pdb_file)
cif_io = CFMMCIFIO()
cif_io.set_structure(structure)
cif_io.save(str(cif_file))
def mk_hhsearch_db(template_dir: str):
template_path = Path(template_dir)
cif_files = template_path.glob("*.cif")
for cif_file in cif_files:
validate_and_fix_mmcif(cif_file)
pdb_files = template_path.glob("*.pdb")
for pdb_file in pdb_files:
convert_pdb_to_mmcif(pdb_file)
pdb70_db_files = template_path.glob("pdb70*")
for f in pdb70_db_files:
os.remove(f)
with open(template_path.joinpath("pdb70_a3m.ffdata"), "w") as a3m, open(
template_path.joinpath("pdb70_cs219.ffindex"), "w"
) as cs219_index, open(
template_path.joinpath("pdb70_a3m.ffindex"), "w"
) as a3m_index, open(
template_path.joinpath("pdb70_cs219.ffdata"), "w"
) as cs219:
id = 1000000
index_offset = 0
cif_files = template_path.glob("*.cif")
for cif_file in cif_files:
with open(cif_file) as f:
cif_string = f.read()
cif_fh = StringIO(cif_string)
parser = MMCIFParser(QUIET=True)
structure = parser.get_structure("none", cif_fh)
models = list(structure.get_models())
if len(models) != 1:
raise ValueError(
f"Only single model PDBs are supported. Found {len(models)} models."
)
model = models[0]
for chain in model:
amino_acid_res = []
for res in chain:
if res.id[2] != " ":
raise ValueError(
f"PDB contains an insertion code at chain {chain.id} and residue "
f"index {res.id[1]}. These are not supported."
)
amino_acid_res.append(
residue_constants.restype_3to1.get(res.resname, "X")
)
protein_str = "".join(amino_acid_res)
a3m_str = f">{cif_file.stem}_{chain.id}\n{protein_str}\n\0"
a3m_str_len = len(a3m_str)
a3m_index.write(f"{id}\t{index_offset}\t{a3m_str_len}\n")
cs219_index.write(f"{id}\t{index_offset}\t{len(protein_str)}\n")
index_offset += a3m_str_len
a3m.write(a3m_str)
cs219.write("\n\0")
id += 1
def batch_input(
input_features: model.features.FeatureDict,
model_runner: model.RunModel,
model_name: str,
crop_len: int,
use_templates: bool,
) -> model.features.FeatureDict:
from colabfold.alphafold.msa import make_fixed_size
model_config = model_runner.config
eval_cfg = model_config.data.eval
crop_feats = {k: [None] + v for k, v in dict(eval_cfg.feat).items()}
max_msa_clusters = eval_cfg.max_msa_clusters
max_extra_msa = model_config.data.common.max_extra_msa
# templates models
if (model_name == "model_1" or model_name == "model_2") and use_templates:
pad_msa_clusters = max_msa_clusters - eval_cfg.max_templates
else:
pad_msa_clusters = max_msa_clusters
max_msa_clusters = pad_msa_clusters
# let's try pad (num_res + X)
input_fix = make_fixed_size(
input_features,
crop_feats,
msa_cluster_size=max_msa_clusters, # true_msa (4, 512, 68)
extra_msa_size=max_extra_msa, # extra_msa (4, 5120, 68)
num_res=crop_len, # aatype (4, 68)
num_templates=4,
) # template_mask (4, 4) second value
return input_fix
def predict_structure(
prefix: str,
result_dir: Path,
feature_dict: Dict[str, Any],
is_complex: bool,
use_templates: bool,
sequences_lengths: List[int],
crop_len: int,
model_type: str,
model_runner_and_params: List[Tuple[str, model.RunModel, haiku.Params]],
do_relax: bool = False,
rank_by: str = "auto",
random_seed: int = 0,
stop_at_score: float = 100,
stop_at_score_below: float = 0,
prediction_callback: Callable[[Any, Any, Any, Any, Any], Any] = None,
use_gpu_relax: bool = False,
):
"""Predicts structure using AlphaFold for the given sequence."""
plddts, paes, ptmscore, iptmscore = [], [], [], []
max_paes = []
unrelaxed_pdb_lines = []
relaxed_pdb_lines = []
prediction_times = []
relax_times = []
representations = []
seq_len = sum(sequences_lengths)
model_names = []
for (model_name, model_runner, params) in model_runner_and_params:
logger.info(f"Running {model_name}")
model_names.append(model_name)
# swap params to avoid recompiling
# note: models 1,2 have diff number of params compared to models 3,4,5 (this was handled on construction)
model_runner.params = params
processed_feature_dict = model_runner.process_features(
feature_dict, random_seed=random_seed
)
if not is_complex:
input_features = batch_input(
processed_feature_dict,
model_runner,
model_name,
crop_len,
use_templates,
)
else:
input_features = processed_feature_dict
start = time.time()
# The original alphafold only returns the prediction_result,
# but our patched alphafold also returns a tuple (recycles,tol)
prediction_result, recycles = model_runner.predict(
input_features, random_seed=random_seed
)
prediction_time = time.time() - start
prediction_times.append(prediction_time)
mean_plddt = np.mean(prediction_result["plddt"][:seq_len])
mean_ptm = prediction_result["ptm"]
if rank_by == "plddt":
mean_score = mean_plddt
else:
mean_score = mean_ptm
if is_complex or model_type == "AlphaFold2-ptm":
if model_type.startswith("AlphaFold2-multimer"):
mean_iptm = prediction_result["iptm"]
logger.info(
f"{model_name} took {prediction_time:.1f}s ({recycles} recycles) "
f"with pLDDT {mean_plddt:.3g}, ptmscore {mean_ptm:.3g} and iptm {mean_iptm:.3g}"
)
else:
logger.info(
f"{model_name} took {prediction_time:.1f}s ({recycles} recycles) "
f"with pLDDT {mean_plddt:.3g} and ptmscore {mean_ptm:.3g}"
)
else:
logger.info(
f"{model_name} took {prediction_time:.1f}s ({recycles} recycles) "
f"with pLDDT {mean_plddt:.3g}"
)
final_atom_mask = prediction_result["structure_module"]["final_atom_mask"]
b_factors = prediction_result["plddt"][:, None] * final_atom_mask
if is_complex and model_type == "AlphaFold2-ptm":
input_features["asym_id"] = feature_dict["asym_id"]
input_features["aatype"] = input_features["aatype"][0]
input_features["residue_index"] = input_features["residue_index"][0]
curr_residue_index = 1
res_index_array = input_features["residue_index"].copy()
res_index_array[0] = 0
for i in range(1, input_features["aatype"].shape[0]):
if (
input_features["residue_index"][i]
- input_features["residue_index"][i - 1]
) > 1:
curr_residue_index = 0
res_index_array[i] = curr_residue_index
curr_residue_index += 1
input_features["residue_index"] = res_index_array
unrelaxed_protein = protein.from_prediction(
features=input_features,
result=prediction_result,
b_factors=b_factors,
remove_leading_feature_dimension=not is_complex,
)
if prediction_callback is not None:
prediction_callback(
unrelaxed_protein,
sequences_lengths,
prediction_result,
input_features,
(model_name, False),
)
protein_lines = protein.to_pdb(unrelaxed_protein)
unrelaxed_pdb_path = result_dir.joinpath(f"{prefix}_unrelaxed_{model_name}.pdb")
unrelaxed_pdb_path.write_text(protein_lines)
representations.append(prediction_result.get("representations", None))
unrelaxed_pdb_lines.append(protein_lines)
plddts.append(prediction_result["plddt"][:seq_len])
ptmscore.append(prediction_result["ptm"])
if model_type.startswith("AlphaFold2-multimer"):
iptmscore.append(prediction_result["iptm"])
max_paes.append(prediction_result["max_predicted_aligned_error"].item())
paes_res = []
for i in range(seq_len):
paes_res.append(prediction_result["predicted_aligned_error"][i][:seq_len])
paes.append(paes_res)
if do_relax:
patch_openmm()
from alphafold.common import residue_constants
from alphafold.relax import relax
start = time.time()
###
# stereo_chemical_props.txt is from openstructure, see openstructure/README.md
# Hack so that we don't need to load the file into the alphafold package
stereo_chemical_props = (
Path(__file__)
.parent.absolute()
.joinpath("openstructure", "stereo_chemical_props.txt")
)
residue_constants.stereo_chemical_props_path = stereo_chemical_props
# Remove the padding because unlike to_pdb() amber doesn't handle that
remove_padding_mask = np.array(unrelaxed_protein.atom_mask.sum(axis=-1) > 0)
unrelaxed_protein = Protein(
atom_mask=unrelaxed_protein.atom_mask[remove_padding_mask],
atom_positions=unrelaxed_protein.atom_positions[remove_padding_mask],
aatype=unrelaxed_protein.aatype[remove_padding_mask],
residue_index=unrelaxed_protein.residue_index[remove_padding_mask],
b_factors=unrelaxed_protein.b_factors[remove_padding_mask],
chain_index=unrelaxed_protein.chain_index[remove_padding_mask],
)
# Relax the prediction.
amber_relaxer = relax.AmberRelaxation(
max_iterations=0,
tolerance=2.39,
stiffness=10.0,
exclude_residues=[],
max_outer_iterations=20,
use_gpu=use_gpu_relax,
)
relaxed_pdb_str, _, _ = amber_relaxer.process(prot=unrelaxed_protein)
relax_time = time.time() - start
relax_times.append(relax_time)
logger.info(f"Relaxation took {relax_time:.1f}s")
if prediction_callback is not None:
prediction_callback(
protein.from_pdb_string(relaxed_pdb_str),
sequences_lengths,
prediction_result,
input_features,
(model_name, True),
)
relaxed_pdb_path = result_dir.joinpath(f"{prefix}_relaxed_{model_name}.pdb")
relaxed_pdb_path.write_text(relaxed_pdb_str)
relaxed_pdb_lines.append(relaxed_pdb_str)
# early stop criteria fulfilled
if mean_score > stop_at_score or mean_score < stop_at_score_below:
break
# rerank models based on predicted lddt
if rank_by == "ptmscore":
model_rank = np.array(ptmscore).argsort()[::-1]
elif rank_by == "multimer":
rank_array = np.array(iptmscore) * 0.8 + np.array(ptmscore) * 0.2
model_rank = rank_array.argsort()[::-1]
else:
model_rank = np.mean(plddts, -1).argsort()[::-1]
out = {}
logger.info(f"reranking models by {rank_by}")
for n, key in enumerate(model_rank):
unrelaxed_pdb_path = result_dir.joinpath(
f"{prefix}_unrelaxed_rank_{n + 1}_{model_names[key]}.pdb"
)
unrelaxed_pdb_path.write_text(unrelaxed_pdb_lines[key])
unrelaxed_pdb_path_unranked = result_dir.joinpath(
f"{prefix}_unrelaxed_{model_names[key]}.pdb"
)
if unrelaxed_pdb_path_unranked.is_file():
unrelaxed_pdb_path_unranked.unlink()
if do_relax:
relaxed_pdb_path = result_dir.joinpath(
f"{prefix}_relaxed_rank_{n + 1}_{model_names[key]}.pdb"
)
relaxed_pdb_path.write_text(relaxed_pdb_lines[key])
relaxed_pdb_path_unranked = result_dir.joinpath(
f"{prefix}_relaxed_{model_names[key]}.pdb"
)
if relaxed_pdb_path_unranked.is_file():
relaxed_pdb_path_unranked.unlink()
# Write an easy-to-use format (PAE and plDDT)
scores_file = result_dir.joinpath(
f"{prefix}_unrelaxed_rank_{n + 1}_{model_names[key]}_scores.json"
)
with scores_file.open("w") as fp:
# We use astype(np.float64) to prevent very long stringified floats from float imprecision
scores = {
"max_pae": max_paes[key],
"pae": np.around(np.asarray(paes[key]).astype(np.float64), 2).tolist(),
"plddt": np.around(np.asarray(plddts[key]), 2).tolist(),
"ptm": np.around(ptmscore[key], 2).item(),
}
if model_type.startswith("AlphaFold2-multimer"):
scores["iptm"] = np.around(iptmscore[key], 2).item()
json.dump(scores, fp)
out[key] = {
"plddt": np.asarray(plddts[key]),
"pae": np.asarray(paes[key]),
"max_pae": max_paes[key],
"pTMscore": ptmscore[key],
"model_name": model_names[key],
"representations": representations[key],
}
return out, model_rank
def parse_fasta(fasta_string: str) -> Tuple[List[str], List[str]]:
"""Parses FASTA string and returns list of strings with amino-acid sequences.
Arguments:
fasta_string: The string contents of a FASTA file.
Returns:
A tuple of two lists:
* A list of sequences.
* A list of sequence descriptions taken from the comment lines. In the
same order as the sequences.
"""
sequences = []
descriptions = []
index = -1
for line in fasta_string.splitlines():
line = line.strip()
if line.startswith("#"):
continue
if line.startswith(">"):
index += 1
descriptions.append(line[1:]) # Remove the '>' at the beginning.
sequences.append("")
continue
elif not line:
continue # Skip blank lines.
sequences[index] += line
return sequences, descriptions
def get_queries(
input_path: Union[str, Path], sort_queries_by: str = "length"
) -> Tuple[List[Tuple[str, str, Optional[List[str]]]], bool]:
"""Reads a directory of fasta files, a single fasta file or a csv file and returns a tuple
of job name, sequence and the optional a3m lines"""
input_path = Path(input_path)
if not input_path.exists():
raise OSError(f"{input_path} could not be found")
if input_path.is_file():
if input_path.suffix == ".csv" or input_path.suffix == ".tsv":
sep = "\t" if input_path.suffix == ".tsv" else ","
df = pandas.read_csv(input_path, sep=sep)
assert "id" in df.columns and "sequence" in df.columns
queries = [
(seq_id, sequence.upper().split(":"), None)
for seq_id, sequence in df[["id", "sequence"]].itertuples(index=False)
]
for i in range(len(queries)):
if len(queries[i][1]) == 1:
queries[i] = (queries[i][0], queries[i][1][0], None)
elif input_path.suffix == ".a3m":
(seqs, header) = parse_fasta(input_path.read_text())
if len(seqs) == 0:
raise ValueError(f"{input_path} is empty")
query_sequence = seqs[0]
# Use a list so we can easily extend this to multiple msas later
a3m_lines = [input_path.read_text()]
queries = [(input_path.stem, query_sequence, a3m_lines)]
elif input_path.suffix in [".fasta", ".faa", ".fa"]:
(sequences, headers) = parse_fasta(input_path.read_text())
queries = []
for sequence, header in zip(sequences, headers):
sequence = sequence.upper()
if sequence.count(":") == 0:
# Single sequence
queries.append((header, sequence, None))
else:
# Complex mode
queries.append((header, sequence.upper().split(":"), None))
else:
raise ValueError(f"Unknown file format {input_path.suffix}")
else:
assert input_path.is_dir(), "Expected either an input file or a input directory"
queries = []
for file in sorted(input_path.iterdir()):
if not file.is_file():
continue
if file.suffix.lower() not in [".a3m", ".fasta", ".faa"]:
logger.warning(f"non-fasta/a3m file in input directory: {file}")
continue
(seqs, header) = parse_fasta(file.read_text())
if len(seqs) == 0:
logger.error(f"{file} is empty")
continue
query_sequence = seqs[0]
if len(seqs) > 1 and file.suffix in [".fasta", ".faa", ".fa"]:
logger.warning(
f"More than one sequence in {file}, ignoring all but the first sequence"
)
if file.suffix.lower() == ".a3m":
a3m_lines = [file.read_text()]
queries.append((file.stem, query_sequence.upper(), a3m_lines))
else:
if query_sequence.count(":") == 0:
# Single sequence
queries.append((file.stem, query_sequence, None))
else:
# Complex mode
queries.append((file.stem, query_sequence.upper().split(":"), None))
# sort by seq. len
if sort_queries_by == "length":
queries.sort(key=lambda t: len(t[1]))
elif sort_queries_by == "random":
random.shuffle(queries)
is_complex = False
for job_number, (raw_jobname, query_sequence, a3m_lines) in enumerate(queries):
if isinstance(query_sequence, list):
is_complex = True
break
if a3m_lines is not None and a3m_lines[0].startswith("#"):
a3m_line = a3m_lines[0].splitlines()[0]
tab_sep_entries = a3m_line[1:].split("\t")
if len(tab_sep_entries) == 2:
query_seq_len = tab_sep_entries[0].split(",")
query_seq_len = list(map(int, query_seq_len))
query_seqs_cardinality = tab_sep_entries[1].split(",")
query_seqs_cardinality = list(map(int, query_seqs_cardinality))
is_single_protein = (
True
if len(query_seq_len) == 1 and query_seqs_cardinality[0] == 1
else False
)
if not is_single_protein:
is_complex = True
break
return queries, is_complex
def pair_sequences(
a3m_lines: List[str], query_sequences: List[str], query_cardinality: List[int]
) -> str:
a3m_line_paired = [""] * len(a3m_lines[0].splitlines())
for n, seq in enumerate(query_sequences):
lines = a3m_lines[n].splitlines()
for i, line in enumerate(lines):
if line.startswith(">"):
if n != 0:
line = line.replace(">", "\t", 1)
a3m_line_paired[i] = a3m_line_paired[i] + line
else:
a3m_line_paired[i] = a3m_line_paired[i] + line * query_cardinality[n]
return "\n".join(a3m_line_paired)
def pad_sequences(
a3m_lines: List[str], query_sequences: List[str], query_cardinality: List[int]
) -> str:
_blank_seq = [
("-" * len(seq))
for n, seq in enumerate(query_sequences)
for _ in range(query_cardinality[n])
]
a3m_lines_combined = []
pos = 0
for n, seq in enumerate(query_sequences):
for j in range(0, query_cardinality[n]):
lines = a3m_lines[n].split("\n")
for a3m_line in lines:
if len(a3m_line) == 0:
continue
if a3m_line.startswith(">"):
a3m_lines_combined.append(a3m_line)
else:
a3m_lines_combined.append(
"".join(_blank_seq[:pos] + [a3m_line] + _blank_seq[pos + 1 :])
)
pos += 1
return "\n".join(a3m_lines_combined)
def get_msa_and_templates(
jobname: str,
query_sequences: Union[str, List[str]],
result_dir: Path,
msa_mode: str,
use_templates: bool,
custom_template_path: str,
pair_mode: str,
host_url: str = DEFAULT_API_SERVER,
) -> Tuple[
Optional[List[str]], Optional[List[str]], List[str], List[int], List[Dict[str, Any]]
]:
from colabfold.colabfold import run_mmseqs2
use_env = msa_mode == "MMseqs2 (UniRef+Environmental)"
# remove duplicates before searching
query_sequences = (
[query_sequences] if isinstance(query_sequences, str) else query_sequences
)
query_seqs_unique = []
for x in query_sequences:
if x not in query_seqs_unique:
query_seqs_unique.append(x)
query_seqs_cardinality = [0] * len(query_seqs_unique)
for seq in query_sequences:
seq_idx = query_seqs_unique.index(seq)
query_seqs_cardinality[seq_idx] += 1
template_features = []
if use_templates:
a3m_lines_mmseqs2, template_paths = run_mmseqs2(
query_seqs_unique,
str(result_dir.joinpath(jobname)),
use_env,
use_templates=True,
host_url=host_url,
)
if custom_template_path is not None:
template_paths = {}
for index in range(0, len(query_seqs_unique)):
template_paths[index] = custom_template_path
if template_paths is None:
logger.info("No template detected")
for index in range(0, len(query_seqs_unique)):
template_feature = mk_mock_template(query_seqs_unique[index])
template_features.append(template_feature)
else:
for index in range(0, len(query_seqs_unique)):
if template_paths[index] is not None:
template_feature = mk_template(
a3m_lines_mmseqs2[index],
template_paths[index],
query_seqs_unique[index],
)
if len(template_feature["template_domain_names"]) == 0:
template_feature = mk_mock_template(query_seqs_unique[index])
logger.info(f"Sequence {index} found no templates")
else:
logger.info(
f"Sequence {index} found templates: {template_feature['template_domain_names'].astype(str).tolist()}"
)
else:
template_feature = mk_mock_template(query_seqs_unique[index])
logger.info(f"Sequence {index} found no templates")
template_features.append(template_feature)
else:
for index in range(0, len(query_seqs_unique)):
template_feature = mk_mock_template(query_seqs_unique[index])
template_features.append(template_feature)
if len(query_sequences) == 1:
pair_mode = "none"
if pair_mode == "none" or pair_mode == "unpaired" or pair_mode == "unpaired+paired":
if msa_mode == "single_sequence":
a3m_lines = []
num = 101
for i, seq in enumerate(query_seqs_unique):
a3m_lines.append(">" + str(num + i) + "\n" + seq)
else:
# find normal a3ms
a3m_lines = run_mmseqs2(
query_seqs_unique,
str(result_dir.joinpath(jobname)),
use_env,
use_pairing=False,
host_url=host_url,
)
else:
a3m_lines = None
if msa_mode != "single_sequence" and (
pair_mode == "paired" or pair_mode == "unpaired+paired"
):
# find paired a3m if not a homooligomers
if len(query_seqs_unique) > 1:
paired_a3m_lines = run_mmseqs2(
query_seqs_unique,
str(result_dir.joinpath(jobname)),
use_env,
use_pairing=True,
host_url=host_url,
)
else:
# homooligomers
num = 101
paired_a3m_lines = []
for i in range(0, query_seqs_cardinality[0]):
paired_a3m_lines.append(
">" + str(num + i) + "\n" + query_seqs_unique[0] + "\n"
)
else:
paired_a3m_lines = None
return (
a3m_lines,
paired_a3m_lines,
query_seqs_unique,
query_seqs_cardinality,
template_features,
)
def build_monomer_feature(
sequence: str, unpaired_msa: str, template_features: Dict[str, Any]
):
msa = pipeline.parsers.parse_a3m(unpaired_msa)
# gather features
return {
**pipeline.make_sequence_features(
sequence=sequence, description="none", num_res=len(sequence)
),
**pipeline.make_msa_features([msa]),
**template_features,
}
def build_multimer_feature(paired_msa: str) -> Dict[str, ndarray]:
parsed_paired_msa = pipeline.parsers.parse_a3m(paired_msa)
return {
f"{k}_all_seq": v
for k, v in pipeline.make_msa_features([parsed_paired_msa]).items()
}
def process_multimer_features(
features_for_chain: Dict[str, Dict[str, ndarray]]
) -> Dict[str, ndarray]:
all_chain_features = {}
for chain_id, chain_features in features_for_chain.items():
all_chain_features[chain_id] = pipeline_multimer.convert_monomer_features(
chain_features, chain_id
)
all_chain_features = pipeline_multimer.add_assembly_features(all_chain_features)
# np_example = feature_processing.pair_and_merge(
# all_chain_features=all_chain_features, is_prokaryote=is_prokaryote)
feature_processing.process_unmerged_features(all_chain_features)
np_chains_list = list(all_chain_features.values())
# noinspection PyProtectedMember
pair_msa_sequences = not feature_processing._is_homomer_or_monomer(np_chains_list)
chains = list(np_chains_list)
chain_keys = chains[0].keys()
updated_chains = []
for chain_num, chain in enumerate(chains):
new_chain = {k: v for k, v in chain.items() if "_all_seq" not in k}
for feature_name in chain_keys:
if feature_name.endswith("_all_seq"):
feats_padded = msa_pairing.pad_features(
chain[feature_name], feature_name
)
new_chain[feature_name] = feats_padded
new_chain["num_alignments_all_seq"] = np.asarray(
len(np_chains_list[chain_num]["msa_all_seq"])
)
updated_chains.append(new_chain)
np_chains_list = updated_chains
np_chains_list = feature_processing.crop_chains(
np_chains_list,
msa_crop_size=feature_processing.MSA_CROP_SIZE,
pair_msa_sequences=pair_msa_sequences,
max_templates=feature_processing.MAX_TEMPLATES,
)
# merge_chain_features crashes if there are additional features only present in one chain
# remove all features that are not present in all chains
common_features = set([*np_chains_list[0]]).intersection(*np_chains_list)
np_chains_list = [
{key: value for (key, value) in chain.items() if key in common_features}
for chain in np_chains_list
]
np_example = feature_processing.msa_pairing.merge_chain_features(
np_chains_list=np_chains_list,
pair_msa_sequences=pair_msa_sequences,
max_templates=feature_processing.MAX_TEMPLATES,
)
np_example = feature_processing.process_final(np_example)
# Pad MSA to avoid zero-sized extra_msa.
np_example = pipeline_multimer.pad_msa(np_example, min_num_seq=512)
return np_example
def pair_msa(
query_seqs_unique: List[str],
query_seqs_cardinality: List[int],
paired_msa: Optional[List[str]],
unpaired_msa: Optional[List[str]],
) -> str:
if paired_msa is None and unpaired_msa is not None:
a3m_lines = pad_sequences(
unpaired_msa, query_seqs_unique, query_seqs_cardinality
)
elif paired_msa is not None and unpaired_msa is not None:
a3m_lines = (
pair_sequences(paired_msa, query_seqs_unique, query_seqs_cardinality)
+ "\n"
+ pad_sequences(unpaired_msa, query_seqs_unique, query_seqs_cardinality)
)
elif paired_msa is not None and unpaired_msa is None:
a3m_lines = pair_sequences(
paired_msa, query_seqs_unique, query_seqs_cardinality
)
else:
raise ValueError(f"Invalid pairing")
return a3m_lines
def generate_input_feature(
query_seqs_unique: List[str],
query_seqs_cardinality: List[int],
unpaired_msa: List[str],
paired_msa: List[str],
template_features: List[Dict[str, Any]],
is_complex: bool,
model_type: str,
) -> Tuple[Dict[str, Any], Dict[str, str]]:
from colabfold.colabfold import chain_break
input_feature = {}
domain_names = {}
if is_complex and model_type == "AlphaFold2-ptm":
a3m_lines = pair_msa(
query_seqs_unique, query_seqs_cardinality, paired_msa, unpaired_msa
)
total_sequence = ""
Ls = []
for sequence_index, sequence in enumerate(query_seqs_unique):
for cardinality in range(0, query_seqs_cardinality[sequence_index]):
total_sequence += sequence
Ls.append(len(sequence))
input_feature = build_monomer_feature(
total_sequence, a3m_lines, mk_mock_template(total_sequence)
)
input_feature["residue_index"] = chain_break(input_feature["residue_index"], Ls)
input_feature["asym_id"] = np.array(
[int(n) for n, l in enumerate(Ls) for _ in range(0, l)]
)
if any(
[