"runtime/rust/vscode:/vscode.git/clone" did not exist on "e1bd07fead371307d2458ed13330dc898df1f4f9"
precompute_alignments.py 8.18 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
Gustaf's avatar
Gustaf committed
14
from openfold.np import protein, residue_constants
sft-managed's avatar
sft-managed committed
15
16
17
18

from utils import add_data_args


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


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
22
23
24
25
26
27
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)
        
28
29
30
31
32
        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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

        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
            )
        except:
            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:]:
51
52
53
54
55
            if(name in dirs):
                logging.warning(
                    f'{name} has already been processed. Skipping...'
                )
                continue
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
56
57
            
            cp_dir = os.path.join(args.output_dir, name)
Gustaf Ahdritz's avatar
Fixes  
Gustaf Ahdritz committed
58
            os.makedirs(cp_dir, exist_ok=True)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
59
60
61
62
            
            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
63

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
64
65
def parse_and_align(files, alignment_runner, args):
    for f in files:
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
66
67
        path = os.path.join(args.input_dir, f)
        file_id = os.path.splitext(f)[0]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
68
        seq_group_dict = {}  
Gustaf's avatar
Gustaf committed
69
        if(f.endswith('.cif')):
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
70
71
72
73
74
75
76
77
78
79
80
81
            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
82
83
84
85
            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)
86
        elif(f.endswith('.fasta') or f.endswith('.fa')):
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
87
88
            with open(path, 'r') as fp:
                fasta_str = fp.read()
89
            input_seqs, _ = parse_fasta(fasta_str)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
90
91
92
93
94
95
96
            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
97
            seq_group_dict[input_sequence] = [file_id]
Gustaf's avatar
Gustaf committed
98
99
100
101
        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
102
            aatype = core_prot.aatype
Gustaf's avatar
Gustaf committed
103
104
105
106
            seq = ''.join([
                residue_constants.restypes_with_x[aatype[i]] 
                for i in range(len(aatype))
            ])
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
107
            seq_group_dict[seq] = [file_id]
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
108
109
110
        else:
            continue

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
111
112
        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
113
114


Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def main(args):
    # Build the alignment tool runner
    alignment_runner = AlignmentRunner(
        jackhmmer_binary_path=args.jackhmmer_binary_path,
        hhblits_binary_path=args.hhblits_binary_path,
        hhsearch_binary_path=args.hhsearch_binary_path,
        uniref90_database_path=args.uniref90_database_path,
        mgnify_database_path=args.mgnify_database_path,
        bfd_database_path=args.bfd_database_path,
        uniclust30_database_path=args.uniclust30_database_path,
        pdb70_database_path=args.pdb70_database_path,
        use_small_bfd=args.bfd_database_path is None,
        no_cpus=args.cpus_per_task,
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
129

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
130
131
132
133
134
135
136
137
138
    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
139
    dirs = []
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    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
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

    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
215
216
217
218
219
220


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "input_dir", type=str,
221
222
        help="""Path to directory containing mmCIF, FASTA and/or ProteinNet
                .core files"""
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
223
224
225
226
227
228
229
230
231
232
233
    )
    parser.add_argument(
        "output_dir", type=str,
        help="Directory in which to output alignments"
    )
    add_data_args(parser)
    parser.add_argument(
        "--raise_errors", type=bool, default=False,
        help="Whether to crash on parsing errors"
    )
    parser.add_argument(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
234
        "--cpus_per_task", type=int, default=cpu_count(),
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
235
236
        help="Number of CPUs to use"
    )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
237
238
239
240
241
242
243
244
245
246
    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
247
248
249
250

    args = parser.parse_args()

    main(args)