precompute_alignments.py 8.94 KB
Newer Older
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1
import argparse
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
2
3
from functools import partial
import json
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
4
5
import logging
import os
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
6
7
8
import threading
from multiprocessing import cpu_count
from shutil import copyfile
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
9
10
import tempfile

sft-managed's avatar
sft-managed committed
11
12
import openfold.data.mmcif_parsing as mmcif_parsing
from openfold.data.data_pipeline import AlignmentRunner
13
from openfold.data.parsers import parse_fasta
14
from openfold.data.tools import hhsearch, hmmsearch
Gustaf's avatar
Gustaf committed
15
from openfold.np import protein, residue_constants
sft-managed's avatar
sft-managed committed
16
17
18
19

from utils import add_data_args


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
20
logging.basicConfig(level=logging.WARNING)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
21
22


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
23
24
25
26
27
28
def run_seq_group_alignments(seq_groups, alignment_runner, args):
    dirs = set(os.listdir(args.output_dir))
    for seq, names in seq_groups:
        first_name = names[0]
        alignment_dir = os.path.join(args.output_dir, first_name)
        
29
30
31
32
33
        try:
            os.makedirs(alignment_dir)
        except Exception as e:
            logging.warning(f"Failed to create directory for {first_name} with exception {e}...")
            continue
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
34
35
36
37
38
39
40
41
42

        fd, fasta_path = tempfile.mkstemp(suffix=".fasta")
        with os.fdopen(fd, 'w') as fp:
            fp.write(f'>query\n{seq}')

        try:
            alignment_runner.run(
                fasta_path, alignment_dir
            )
43
44
        except Exception as e:
            logging.warning(e)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
45
46
47
48
49
50
51
52
            logging.warning(f"Failed to run alignments for {first_name}. Skipping...")
            os.remove(fasta_path)
            os.rmdir(alignment_dir)
            continue

        os.remove(fasta_path)

        for name in names[1:]:
53
54
55
56
57
            if(name in dirs):
                logging.warning(
                    f'{name} has already been processed. Skipping...'
                )
                continue
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
58
59
            
            cp_dir = os.path.join(args.output_dir, name)
Gustaf Ahdritz's avatar
Fixes  
Gustaf Ahdritz committed
60
            os.makedirs(cp_dir, exist_ok=True)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
61
62
63
64
            
            for f in os.listdir(alignment_dir):
                copyfile(os.path.join(alignment_dir, f), os.path.join(cp_dir, f))

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
65

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
66
67
def parse_and_align(files, alignment_runner, args):
    for f in files:
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
68
69
        path = os.path.join(args.input_dir, f)
        file_id = os.path.splitext(f)[0]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
70
        seq_group_dict = {}  
Gustaf's avatar
Gustaf committed
71
        if(f.endswith('.cif')):
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
72
73
74
75
76
77
78
79
80
81
82
83
            with open(path, 'r') as fp:
                mmcif_str = fp.read()
            mmcif = mmcif_parsing.parse(
                file_id=file_id, mmcif_string=mmcif_str
            )
            if(mmcif.mmcif_object is None):
                logging.warning(f'Failed to parse {f}...')
                if(args.raise_errors):
                    raise list(mmcif.errors.values())[0]
                else:
                    continue
            mmcif = mmcif.mmcif_object
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
84
85
86
87
            for chain_letter, seq in mmcif.chain_to_seqres.items():
                chain_id = '_'.join([file_id, chain_letter])
                l = seq_group_dict.setdefault(seq, [])
                l.append(chain_id)
88
        elif(f.endswith('.fasta') or f.endswith('.fa')):
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
89
90
            with open(path, 'r') as fp:
                fasta_str = fp.read()
91
            input_seqs, _ = parse_fasta(fasta_str)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
92
93
94
95
96
97
98
            if len(input_seqs) != 1: 
                msg = f'More than one input_sequence found in {f}'
                if(args.raise_errors):
                    raise ValueError(msg)
                else:
                    logging.warning(msg)
            input_sequence = input_seqs[0]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
99
            seq_group_dict[input_sequence] = [file_id]
Gustaf's avatar
Gustaf committed
100
101
102
103
        elif(f.endswith('.core')):
            with open(path, 'r') as fp:
                core_str = fp.read()
            core_prot = protein.from_proteinnet_string(core_str)
Gustaf's avatar
Gustaf committed
104
            aatype = core_prot.aatype
Gustaf's avatar
Gustaf committed
105
106
107
108
            seq = ''.join([
                residue_constants.restypes_with_x[aatype[i]] 
                for i in range(len(aatype))
            ])
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
109
            seq_group_dict[seq] = [file_id]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
110
111
112
        else:
            continue

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
113
114
        seq_group_tuples = [(k,v) for k,v in seq_group_dict.items()]
        run_seq_group_alignments(seq_group_tuples, alignment_runner, args)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
115
116


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
117
118
def main(args):
    # Build the alignment tool runner
119
    if args.hmmsearch_binary_path is not None and args.pdb_seqres_database_path is not None:
120
121
122
123
124
        template_searcher = hmmsearch.Hmmsearch(
            binary_path=args.hmmsearch_binary_path,
            hmmbuild_binary_path=args.hmmbuild_binary_path,
            database_path=args.pdb_seqres_database_path,
        )
125
    elif args.hhsearch_binary_path is not None and args.pdb70_database_path is not None:
126
127
128
129
130
131
132
        template_searcher = hhsearch.HHSearch(
            binary_path=args.hhsearch_binary_path,
            databases=[args.pdb70_database_path],
        )
    else:
        template_searcher = None

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
133
134
135
136
137
138
    alignment_runner = AlignmentRunner(
        jackhmmer_binary_path=args.jackhmmer_binary_path,
        hhblits_binary_path=args.hhblits_binary_path,
        uniref90_database_path=args.uniref90_database_path,
        mgnify_database_path=args.mgnify_database_path,
        bfd_database_path=args.bfd_database_path,
139
        uniref30_database_path=args.uniref30_database_path,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
140
        uniclust30_database_path=args.uniclust30_database_path,
141
142
        uniprot_database_path=args.uniprot_database_path,
        template_searcher=template_searcher,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
143
144
145
        use_small_bfd=args.bfd_database_path is None,
        no_cpus=args.cpus_per_task,
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
146

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
147
148
149
150
151
152
153
154
155
    files = list(os.listdir(args.input_dir))

    # Do some filtering
    if(args.mmcif_cache is not None):
        with open(args.mmcif_cache, "r") as fp:
            cache = json.load(fp)
    else:
        cache = None

Gustaf Ahdritz's avatar
Fixes  
Gustaf Ahdritz committed
156
    dirs = []
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    if(cache is not None and args.filter):
        dirs = set(os.listdir(args.output_dir))
        def prot_is_done(f):
            prot_id = os.path.splitext(f)[0]
            if(prot_id in cache):
                chain_ids = cache[prot_id]["chain_ids"]
                for c in chain_ids:
                    full_name = prot_id + "_" + c
                    if(not full_name in dirs):
                        return False
            else:
                return False

            return True

        files = [f for f in files if not prot_is_done(f)]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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

    def split_up_arglist(arglist):
        # Split up the survivors
        if(os.environ.get("SLURM_JOB_NUM_NODES", 0)):
            num_nodes = int(os.environ["SLURM_JOB_NUM_NODES"])
            if(num_nodes > 1):
                node_id = int(os.environ["SLURM_NODEID"])
                logging.warning(f"Num nodes: {num_nodes}")
                logging.warning(f"Node ID: {node_id}")
                arglist = arglist[node_id::num_nodes]

        t_arglist = []
        for i in range(args.no_tasks):
            t_arglist.append(arglist[i::args.no_tasks])

        return t_arglist

    if(cache is not None and "seqs" in next(iter(cache.values()))):
        seq_group_dict = {}
        for f in files:
            prot_id = os.path.splitext(f)[0]
            if(prot_id in cache):
                prot_cache = cache[prot_id]
                chains_seqs = zip(
                    prot_cache["chain_ids"], prot_cache["seqs"]
                )
                for chain, seq in chains_seqs:
                    chain_name = prot_id + "_" + chain
                    if(chain_name not in dirs):
                        l = seq_group_dict.setdefault(seq, [])
                        l.append(chain_name)
       
        func = partial(run_seq_group_alignments, 
            alignment_runner=alignment_runner, 
            args=args
        )

        seq_groups = [(k,v) for k,v in seq_group_dict.items()]

        # Sort them by group length so the tasks are approximately balanced
        seq_groups = sorted(seq_groups, key=lambda x: len(x[1]))

        task_arglist = [[a] for a in split_up_arglist(seq_groups)]
    else:
        func = partial(parse_and_align,
            alignment_runner=alignment_runner,
            args=args,
        )
        task_arglist = [[a] for a in split_up_arglist(files)]

    threads = []
    for i, task_args in enumerate(task_arglist):
        print(f"Started thread {i}...")
        t = threading.Thread(target=func, args=task_args)
        threads.append(t)
        t.start()

    for t in threads:
        t.join()
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
232
233
234
235
236
237


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "input_dir", type=str,
238
239
        help="""Path to directory containing mmCIF, FASTA and/or ProteinNet
                .core files"""
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
240
241
242
243
244
245
246
    )
    parser.add_argument(
        "output_dir", type=str,
        help="Directory in which to output alignments"
    )
    add_data_args(parser)
    parser.add_argument(
247
        "--raise_errors", action="store_true", default=False,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
248
249
250
        help="Whether to crash on parsing errors"
    )
    parser.add_argument(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
251
        "--cpus_per_task", type=int, default=cpu_count(),
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
252
253
        help="Number of CPUs to use"
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
254
255
256
257
258
259
260
261
262
263
    parser.add_argument(
        "--mmcif_cache", type=str, default=None,
        help="Path to mmCIF cache. Used to filter files to be parsed"
    )
    parser.add_argument(
        "--no_tasks", type=int, default=1,
    )
    parser.add_argument(
        "--filter", type=bool, default=True,
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
264
265
266
267

    args = parser.parse_args()

    main(args)