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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Bio import Phylo
import pandas as pd
import numpy as np
from itertools import combinations
import random
import math
from copy import deepcopy

from utils.utils import make_sub_folder


def safe_int16(mat):
    if mat.dtype == 'int16':
        return mat
    assert mat.min() >= -32768
    assert mat.max() <= 32767
    return mat.astype('int16')

def safe_int8(mat):
    if mat.dtype == 'int8':
        return mat
    assert mat.min() >= -128
    assert mat.max() <= 127
    return mat.astype('int8')

def safe_int32(mat):
    if mat.dtype == 'int32':
        return mat
    assert mat.min() >= -2147483648
    assert mat.max() <= 2147483647
    return mat.astype('int32')
  
def read_inputs(pfam, seed_folder, trees_folder):
    raw_msa = {}
    pfam_level_meta = {'pfam': pfam,
                       'clan': '',
                       'type': ''}
    
    num_seqs = 0
    with open(f'{seed_folder}/{pfam}.seed','r') as f:
        for line in f:
            if line.startswith('#=GF CL'):
                pfam_level_meta['clan'] = line.strip().split()[-1]
            
            elif line.startswith('#=GF TP'):
                pfam_level_meta['type'] = line.strip().split()[-1]
            
            if not line.startswith('#'):
                num_seqs += 1
                name, seq = line.strip().split()
                seq = seq.upper()
                raw_msa[name] = seq
    
    pfam_level_meta['pfam_Nseqs'] = num_seqs
    
    tree = Phylo.read(f'{trees_folder}/{pfam}.tree', 'newick')
    return raw_msa, tree, pfam_level_meta

def dedup(tuple_list):
    return list( set( tuple( sorted(t) ) for t in tuple_list ) )

def read_pairs_from_file(filename):
    df = pd.read_csv(filename, sep='\t')
    
    # added this bit to specifically handle my inputs
    df = df[['seq1','seq2']]
    
    pairs = df.itertuples(index=False, name=None)
    pairs = dedup(pairs)
    return pairs

def generate_random_pairs(seqnames, percent_of_pairs, filename_of_cherries):
    cherries = read_pairs_from_file(filename_of_cherries)
    reverse_cherries = []
    for (seq1, seq2) in cherries:
        reverse_cherries.append( (seq2, seq1) )
    
    banned_tuples = set( cherries + reverse_cherries )
    
    all_possible_pairs = [tup for tup in combinations(seqnames, 2) if 
                          tup not in banned_tuples]
    
    num_to_sample = math.ceil(percent_of_pairs * len(all_possible_pairs))
    pairs = random.sample(all_possible_pairs, num_to_sample)
    return pairs
    
def extract_alignment(ancestor, descendant, raw_msa):
    anc_gapped = raw_msa[ancestor]
    desc_gapped = raw_msa[descendant]
    alignment = []
    num_matches = 0
    num_subs = 0
    num_ins = 0
    num_dels = 0
    for tup in zip(anc_gapped, desc_gapped):
        if tup != ('.','.'):
            alignment.append(tup)
            
            # ins
            if tup[0] == '.' and tup[1] != '.':
                num_ins += 1
            
            # del
            elif tup[0] != '.' and tup[1] == '.':
                num_dels += 1
            
            # exact match
            elif tup[0] == tup[1]:
                num_matches += 1
            
            # subs
            else:
                num_subs += 1
    
    anc_seq_len = len( anc_gapped.replace('.','') )
    desc_seq_len = len( desc_gapped.replace('.','') )
    alignment_len = len( alignment )
    psi = num_matches/min(anc_seq_len, desc_seq_len)
    
    out_dict = {'perc_seq_id': psi,
                'anc_seq_len': anc_seq_len,
                'desc_seq_len': desc_seq_len,
                'alignment_len': alignment_len,
                'num_matches': num_matches,
                'num_subs': num_subs,
                'num_ins': num_ins,
                'num_dels': num_dels}
    return alignment, out_dict

def get_alphabet():
    special = ['<pad>', '<bos>', '<eos>']
    aas = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 
           'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
    mapping = {elem:i for i,elem in enumerate(special + aas)}
    mapping['.'] = 43
    return mapping

def reversible_featurizer(str_alignment, mapping, max_len):
    """
    unaligned_seqs_matrix = (B, L_seq, 2)
      - dim2=0: ancestor, unaligned
      - dim2=1: descendant, unaligned
      - L_seq INCLUDES <bos>, <eos>
    
    aligned_seqs_matrix = (B, L_align, 4)
      - dim2=0: ancestor GAPPED (aligned)
      - dim2=1: descendant GAPPED (aligned)
      - dim2=2: precomputed m indexes for neural models
      - dim2=3: precomputed n indexes for neural models
    
    """
    # dim0=0 is forward pair, dim0=1 is reverse pair
    unaligned_seqs_matrix = np.zeros( (2, max_len+2, 2) )
    aligned_seqs_matrix = np.zeros( (2, max_len+2, 4) )
    
    # padding token for aligned_seqs_matrix[:,:,[2,3]] should be -9
    aligned_seqs_matrix[:,:,[2,3]] = -9
    
    
    ################################
    ### initialize first positions #
    ################################
    # <bos> to start each unaligned sequence
    unaligned_seqs_matrix[:, 0, :] = 1
    
    # <bos> to start each aligned sequence
    aligned_seqs_matrix[:, 0, [0,1]] = 1
    
    # precomputed counts start with (m=1, n=0)
    aligned_seqs_matrix[:, 0, 2] = 1
    aligned_seqs_matrix[:, 0, 3] = 0
    
    
    ##########################################################
    ### step through alignment to fill from string_alignment #
    ##########################################################
    def update_buckets( which, 
                        align_idx, 
                        anc_char, 
                        desc_char, 
                        anc_pos, 
                        desc_pos):
        
        ##############
        ### deletion #
        ##############
        if (desc_char == '.') & (anc_char != '.'):
            ### add to unaligned seq features
            # ancestor
            unaligned_seqs_matrix[which, anc_pos, 0] = mapping[anc_char]
            
            # (no descendant sequence to add)
            
            
            ### add to aligned seq features
            # gapped ancestor
            aligned_seqs_matrix[which, align_idx, 0] = mapping[anc_char]
            
            # gapped descendant
            aligned_seqs_matrix[which, align_idx, 1] =mapping['.']
            
            # at delete site: (m+1, n)
            # precomputed m for NEXT ALIGN IDX
            prev_m = aligned_seqs_matrix[which, align_idx-1, 2]
            aligned_seqs_matrix[which, align_idx, 2] = prev_m + 1
            
            # precomputed n for NEXT ALIGN IDX
            prev_n = aligned_seqs_matrix[which, align_idx-1, 3]
            aligned_seqs_matrix[which, align_idx, 3] = prev_n
            
            
            ### update buckets for next iter
            anc_pos += 1
            
            
        ###############
        ### insertion #
        ###############
        elif (anc_char == '.') & (desc_char != '.'):
            ### add to unaligned seq features
            # (no ancestor sequence to add)
            
            # descendant
            unaligned_seqs_matrix[which, desc_pos, 1] = mapping[desc_char]
            
            
            ### add to aligned seq features
            # gapped ancestor
            aligned_seqs_matrix[which, align_idx, 0] = mapping['.']
            
            # gapped descendant
            aligned_seqs_matrix[which, align_idx, 1] =mapping[desc_char]
            
            # at insert site: (m, n+1)
            # precomputed m for NEXT ALIGN IDX
            prev_m = aligned_seqs_matrix[which, align_idx-1, 2]
            aligned_seqs_matrix[which, align_idx, 2] = prev_m 
            
            # precomputed n for NEXT ALIGN IDX
            prev_n = aligned_seqs_matrix[which, align_idx-1, 3]
            aligned_seqs_matrix[which, align_idx, 3] = prev_n + 1
            
            
            ### update buckets for next iter
            desc_pos += 1
            
            
        ###########
        ### match #
        ###########
        elif (anc_char != '.') & (desc_char != '.'):
            ### add to unaligned seq features
            # ancestor
            unaligned_seqs_matrix[which, anc_pos, 0] = mapping[anc_char]
            
            # descendant
            unaligned_seqs_matrix[which, desc_pos, 1] = mapping[desc_char]
            
            
            ### add to aligned seq features
            # gapped ancestor
            aligned_seqs_matrix[which, align_idx, 0] = mapping[anc_char]
            
            # gapped descendant
            aligned_seqs_matrix[which, align_idx, 1] =mapping[desc_char]
            
            # at match site: (m+1, n+1)
            # precomputed m for NEXT ALIGN IDX
            prev_m = aligned_seqs_matrix[which, align_idx-1, 2]
            aligned_seqs_matrix[which, align_idx, 2] = prev_m  + 1
            
            # precomputed n for NEXT ALIGN IDX
            prev_n = aligned_seqs_matrix[which, align_idx-1, 3]
            aligned_seqs_matrix[which, align_idx, 3] = prev_n + 1
            
            
            ### update buckets for next iter
            anc_pos += 1
            desc_pos += 1
            
        return anc_pos, desc_pos
    
    
    assert len(str_alignment) <= max_len

    fw_anc_pos = 1
    fw_desc_pos = 1
    rv_anc_pos = 1
    rv_desc_pos = 1
    for i, (seq1_char, seq2_char) in enumerate(str_alignment):
        # increment up by one, since you've already initialized first
        # positions
        align_idx = i+1
        
        # forward: (seq1, seq2)
        fw_out = update_buckets(which = 0,
                                align_idx = align_idx,
                                anc_char = seq1_char, 
                                desc_char = seq2_char, 
                                anc_pos = fw_anc_pos, 
                                desc_pos = fw_desc_pos)
        fw_anc_pos, fw_desc_pos = fw_out
        del fw_out
        
        # reverse: (seq2, seq1)
        rv_out = update_buckets(which = 1,
                                align_idx = align_idx,
                                anc_char = seq2_char, 
                                desc_char = seq1_char, 
                                anc_pos = rv_anc_pos, 
                                desc_pos = rv_desc_pos)
        rv_anc_pos, rv_desc_pos = rv_out
        del rv_out
    
    
    ###################################
    ### Add <eos> to end of sequences #
    ###################################
    ### updated unaligned_seqs_matrix 
    # forward: fw_anc_pos, fw_desc_pos
    unaligned_seqs_matrix[0, fw_anc_pos, 0] = 2
    unaligned_seqs_matrix[0, fw_desc_pos, 1] = 2
    
    # reverse: rv_anc_pos, rv_desc_pos
    unaligned_seqs_matrix[1, rv_anc_pos, 0] = 2
    unaligned_seqs_matrix[1, rv_desc_pos, 1] = 2
    
    
    ### update aligned_seqs_matrix at align_idx + 1
    aligned_seqs_matrix[:, align_idx+1, [0,1]] = 2


    ### try encoding
    unaligned_seqs_matrix = safe_int8(unaligned_seqs_matrix)
    aligned_seqs_matrix = safe_int16(aligned_seqs_matrix)
        
    return unaligned_seqs_matrix, aligned_seqs_matrix


def encode_one_pair(i, seq1, seq2, tree, raw_msa, pfam, max_len):
    dist = tree.distance(seq1,seq2)
    fw_pair_level_metadata = {'pairID': f'FW_{pfam}_p{i}',
                              'ancestor': seq1,
                              'descendant': seq2,
                              'TREEDIST_anc-to-desc': dist}
    
    rv_pair_level_metadata = {'pairID': f'RV_{pfam}_p{i}',
                              'ancestor': seq2,
                              'descendant': seq1,
                              'TREEDIST_anc-to-desc': dist}
    
    str_alignment, add_to_fw = extract_alignment(ancestor = seq1, 
                                                 descendant = seq2, 
                                                 raw_msa = raw_msa)
    fw_pair_level_metadata = {**fw_pair_level_metadata, **add_to_fw}
    
    # swap info between anc and desc for reverse pair
    add_to_rv = {'perc_seq_id': add_to_fw['perc_seq_id'],
                  'anc_seq_len': add_to_fw['desc_seq_len'],
                  'desc_seq_len': add_to_fw['anc_seq_len'],
                  'alignment_len': add_to_fw['alignment_len'],
                  'num_matches': add_to_fw['num_matches'],
                  'num_subs': add_to_fw['num_subs'],
                  'num_ins': add_to_fw['num_dels'],
                  'num_dels': add_to_fw['num_ins']
                  }
    rv_pair_level_metadata = {**rv_pair_level_metadata, **add_to_rv}
    del add_to_fw, add_to_rv
    
    
    # generate neural and hmm pair alignment inputs in one go
    mapping = get_alphabet()
    unaligned_seqs_matrix, aligned_seqs_matrix = reversible_featurizer(str_alignment = str_alignment, 
                                                                mapping = mapping, 
                                                                max_len = max_len)
    
    return (fw_pair_level_metadata, 
            rv_pair_level_metadata, 
            unaligned_seqs_matrix, 
            aligned_seqs_matrix)


def featurize_one_pfam(pfam, 
                       seed_folder, 
                       trees_folder, 
                       filename,
                       max_len,
                       pairs_from = 'file', 
                       percent_of_pairs = None):
    ### read inputs, get pairs
    raw_msa, tree, pfam_level_metadata = read_inputs(pfam = pfam, 
                                                      seed_folder = seed_folder, 
                                                      trees_folder = trees_folder)
    pairs = read_pairs_from_file(filename = filename)
    
    
    ### if you don't find any, exit function
    if len(pairs) == 0:
        return None
    
    
    ### iterate through pairs
    metadata = []
    unaligned_outputs = []
    aligned_outputs = []
    
    for pair_id, (seq1, seq2) in enumerate(pairs):
        out = encode_one_pair(i = pair_id, 
                              seq1 = seq1, 
                              seq2 = seq2, 
                              tree = tree,
                              raw_msa = raw_msa,
                              pfam = pfam,
                              max_len = max_len)
        metadata.append(out[0])
        metadata.append(out[1])
        unaligned_outputs.append(out[2])
        aligned_outputs.append(out[3])
    
    metadata = pd.DataFrame(metadata)
    unaligned_outputs = np.concatenate(unaligned_outputs, axis=0)
    aligned_outputs = np.concatenate(aligned_outputs, axis=0)
    
    
    ### add pfam level info to metadata
    for key, val in pfam_level_metadata.items():
        metadata[key] = val
        
    unaligned_outputs = safe_int8(unaligned_outputs)
    aligned_outputs = safe_int16(aligned_outputs)
    
    return unaligned_outputs, aligned_outputs, metadata


##################################
### gather random pairs; combine #
##################################
def make_rand_samp(pfam, 
                   seed_folder,
                   trees_folder,
                   percent_of_pairs,
                   file_of_cherries,
                   dset_prefix,
                   max_len):
    out = featurize_one_pfam(pfam = pfam, 
                             seed_folder = seed_folder,
                             trees_folder = trees_folder, 
                             pairs_from = 'rand_samp',
                             percent_of_pairs = percent_of_pairs,
                             filename = file_of_cherries,
                             max_len = max_len)
    
    if out != None:
        unaligned_outputs = out[0]
        aligned_outputs = out[1]
        metadata = out[2]
        
        with open(f'{dset_prefix}/{pfam}_seqs_unaligned.npy', 'wb') as g:
            np.save(g, unaligned_outputs)
        
        with open(f'{dset_prefix}/{pfam}_aligned_mats.npy', 'wb') as g:
            np.save(g, aligned_outputs)
        
        metadata.to_csv(f'{dset_prefix}/{pfam}_metadata.tsv', sep='\t')
        


##########################################################
### generate pairs from an input file (usually cherries) #
##########################################################
def samples_from_file(pfam, 
                      seed_folder,
                      trees_folder,
                      filename,
                      dset_prefix,
                      max_len):
    out = featurize_one_pfam(pfam = pfam, 
                              seed_folder = seed_folder,
                              trees_folder = trees_folder, 
                              pairs_from = 'file',
                              filename = filename,
                              max_len = max_len)
    
    if out != None:
        unaligned_outputs = out[0]
        aligned_outputs = out[1]
        metadata = out[2]
        
        with open(f'{dset_prefix}_full_length/{pfam}_seqs_unaligned.npy', 'wb') as g:
            np.save(g, unaligned_outputs)
        
        with open(f'{dset_prefix}_full_length/{pfam}_aligned_mats.npy', 'wb') as g:
            np.save(g, aligned_outputs)
        
        metadata.to_csv(f'{dset_prefix}_all_metadata/{pfam}_metadata.tsv', sep='\t')