/
data_processing.py
2663 lines (2363 loc) · 113 KB
/
data_processing.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
# LIBRARIES
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import os
from timeit import default_timer as timer # timer for performance
from copy import deepcopy
from multiprocessing import Pool
from scipy import linalg
import shutil
# GLOBAL VARIABLES
NUC = ['-', 'A', 'C', 'G', 'T']
PRO = ['-', 'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H',
'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V']
REF = NUC[0]
REF_TAG = 'EPI_ISL_402125'
ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+++++++++++++++++++++++++++'
NUMBERS = list('0123456789')
TIME_INDEX = 1
PROTEIN_LENGTHS = {'ORF3a' : 828, 'E' : 228, 'ORF6' : 186, 'ORF7a' : 365, 'ORF7b' : 132, 'S' : 3822,
'N' : 1260, 'M' : 669, 'ORF8' : 336, 'ORF10' : 117, 'NSP1' : 539, 'NSP2' : 1914,
'NSP3' : 5834, 'NSP4' : 1500, 'NSP5' : 917, 'NSP6' : 870, 'NSP7' : 249, 'NSP8' : 594,
'NSP9' : 339, 'NSP10' : 417, 'NSP12' :2795, 'NSP13' : 1803, 'NSP14' : 1582,
'NSP15' : 1038, 'NSP16' : 894}
START_IDX = 0
END_IDX = 29800
"""
ALPHABET_NEW = []
for i in ALPHABET:
ALPHABET_NEW.append(i)
for i in ALPHABET:
for j in ALPHABET:
ALPHABET_NEW.append(i + j)
"""
def load(file):
return np.load(file, allow_pickle=True)
# FUNCTIONS
def get_MSA(ref, noArrow=True):
"""Take an input FASTA file and return the multiple sequence alignment, along with corresponding tags. """
temp_msa = [i.split('\n') for i in open(ref).readlines()]
temp_msa = [i for i in temp_msa if len(i)>0]
msa = []
tag = []
for i in temp_msa:
if i[0][0]=='>':
msa.append('')
if noArrow: tag.append(i[0][1:])
else: tag.append(i[0])
else: msa[-1]+=i[0]
msa = np.array(msa)
return msa, tag
def get_label(i):
""" For a SARS-CoV-2 reference sequence index i, return the label in the form
'coding region - protein number-nucleotide in codon number'.
For example, 'ORF1b-204-1'.
Should check to make sure NSP12 labels are correct due to the frame shift."""
i = int(i)
frame_shift = str(i - get_codon_start_index(i))
if (25392<=i<26220):
return "ORF3a-" + str(int((i - 25392) / 3) + 1) + '-' + frame_shift
elif (26244<=i<26472):
return "E-" + str(int((i - 26244) / 3) + 1) + '-' + frame_shift
elif (27201<=i<27387):
return "ORF6-" + str(int((i - 27201) / 3) + 1) + '-' + frame_shift
# ORF7a and ORF7b overlap by 4 nucleotides
elif (27393<=i<27759):
return "ORF7a-" + str(int((i - 27393) / 3) + 1) + '-' + frame_shift
elif (27755<=i<27887):
return "ORF7b-" + str(int((i - 27755) / 3) + 1) + '-' + frame_shift
elif ( 265<=i<805):
return "NSP1-" + str(int((i - 265 ) / 3) + 1) + '-' + frame_shift
elif ( 805<=i<2719):
return "NSP2-" + str(int((i - 805 ) / 3) + 1) + '-' + frame_shift
elif ( 2719<=i<8554):
return "NSP3-" + str(int((i - 2719 ) / 3) + 1) + '-' + frame_shift
# Compound protein containing a proteinase, a phosphoesterase transmembrane domain 1, etc.
elif ( 8554<=i<10054):
return "NSP4-" + str(int((i - 8554 ) / 3) + 1) + '-' + frame_shift
# Transmembrane domain 2
elif (10054<=i<10972):
return "NSP5-" + str(int((i - 10054) / 3) + 1) + '-' + frame_shift
# Main proteinase
elif (10972<=i<11842):
return "NSP6-" + str(int((i - 10972) / 3) + 1) + '-' + frame_shift
# Putative transmembrane domain
elif (11842<=i<12091):
return "NSP7-" + str(int((i - 11842) / 3) + 1) + '-' + frame_shift
elif (12091<=i<12685):
return "NSP8-" + str(int((i - 12091) / 3) + 1) + '-' + frame_shift
elif (12685<=i<13024):
return "NSP9-" + str(int((i - 12685) / 3) + 1) + '-' + frame_shift
# ssRNA-binding protein
elif (13024<=i<13441):
return "NSP10-" + str(int((i - 13024) / 3) + 1) + '-' + frame_shift
# CysHis, formerly growth-factor-like protein
# Check that aa indexing is correct for NSP12, becuase there is a -1 ribosomal frameshift at 13468. It is not, because the amino acids in the first frame
# need to be added to the counter in the second frame.
elif (13441<=i<13467):
return "NSP12-" + str(int((i - 13441) / 3) + 1) + '-' + frame_shift
elif (13467<=i<16236):
return "NSP12-" + str(int((i - 13467) / 3) + 10) + '-' + frame_shift
# RNA-dependent RNA polymerase
elif (16236<=i<18039):
return "NSP13-" + str(int((i - 16236) / 3) + 1) + '-' + frame_shift
# Helicase
elif (18039<=i<19620):
return "NSP14-" + str(int((i - 18039) / 3) + 1) + '-' + frame_shift
# 3' - 5' exonuclease
elif (19620<=i<20658):
return "NSP15-" + str(int((i - 19620) / 3) + 1) + '-' + frame_shift
# endoRNAse
elif (20658<=i<21552):
return "NSP16-" + str(int((i - 20658) / 3) + 1) + '-' + frame_shift
# 2'-O-ribose methyltransferase
elif (21562<=i<25384):
return "S-" + str(int((i - 21562) / 3) + 1) + '-' + frame_shift
elif (28273<=i<29533):
return "N-" + str(int((i - 28273) / 3) + 1) + '-' + frame_shift
elif (29557<=i<29674):
return "ORF10-" + str(int((i - 29557) / 3) + 1) + '-' + frame_shift
elif (26522<=i<27191):
return "M-" + str(int((i - 26522) / 3) + 1) + '-' + frame_shift
elif (27893<=i<28259):
return "ORF8-" + str(int((i - 27893) / 3) + 1) + '-' + frame_shift
else:
return "NC-" + str(int(i))
def get_codon_start_index(i):
""" Given a sequence index i, determine the index of the first nucleotide in the codon. """
if (13467<=i<=21554):
return i - (i - 13467)%3
elif (25392<=i<=26219):
return i - (i - 25392)%3
elif (26244<=i<=26471):
return i - (i - 26244)%3
elif (27201<=i<=27386):
return i - (i - 27201)%3
# new to account for overlap of orf7a and orf7b (UNCOMMENT)
elif (27393<=i<=27754):
return i - (i - 27393)%3
elif (27755<=i<=27886):
return i - (i - 27755)%3
### considered orf7a and orf7b as one reading frame (INCORRECT)
### REMOVE BELOW
#elif (27393<=i<=27886):
# return i - (i - 27393)%3
### REMOVE ABOVE
elif ( 265<=i<=13467):
return i - (i - 265 )%3
elif (21562<=i<=25383):
return i - (i - 21562)%3
elif (28273<=i<=29532):
return i - (i - 28273)%3
elif (29557<=i<=29673):
return i - (i - 29557)%3
elif (26522<=i<=27190):
return i - (i - 26522)%3
elif (27893<=i<=28258):
return i - (i - 27893)%3
else:
return 0
def get_label_orf(i, split_orf1=False):
""" Converts the number in the sequence to the protein codon number, ORF1ab is not split up into non-structural proteins."""
i = int(i)
frame_shift = str(i - get_codon_start_index(i))
if (25392<=i<=26219):
return "ORF3a-" + str(int((i - 25392) / 3) + 1) + '-' + frame_shift
elif (26244<=i<=26471):
return "E-" + str(int((i - 26244) / 3) + 1) + '-' + frame_shift
elif (27201<=i<=27386):
return "ORF6-" + str(int((i - 27201) / 3) + 1) + '-' + frame_shift
elif (27393<=i<=27758):
return "ORF7a-" + str(int((i - 27393) / 3) + 1) + '-' + frame_shift
elif (27755<=i<=27886):
return "ORF7b-" + str(int((i - 27755) / 3) + 1) + '-' + frame_shift
elif ( 265<=i<=21551):
if split_orf1:
if ( 265<=i<13467):
return "ORF1a-" + str(int((i - 265 ) / 3) + 1) + '-' + frame_shift
else:
return "ORF1b-" + str(int((i - 13467) / 3) + 1) + '-' + frame_shift
else:
if ( 265<=i<13467):
return "ORF1ab-" + str(int((i - 265 ) / 3) + 1) + '-' + frame_shift
else:
return "ORF1ab-" + str(int((i - 13467) / 3) + 4402) + '-' + frame_shift
elif (21562<=i<=25383):
return "S-" + str(int((i - 21562) / 3) + 1) + '-' + frame_shift
elif (28273<=i<=29532):
return "N-" + str(int((i - 28273) / 3) + 1) + '-' + frame_shift
elif (29557<=i<=29673):
return "ORF10-" + str(int((i - 29557) / 3) + 1) + '-' + frame_shift
elif (26522<=i<=27190):
return "M-" + str(int((i - 26522) / 3) + 1) + '-' + frame_shift
elif (27893<=i<=28258):
return "ORF8-" + str(int((i - 27893) / 3) + 1) + '-' + frame_shift
else:
return "NC-" + str(int(i))
def get_label_orf_new(i, split_orf1=False):
nuc = i[-1]
index = i.split('-')[0]
if index[-1] in NUMBERS:
return get_label2(i)
else:
if index[-1] in list(ALPHABET) and index[-2] in list(ALPHABET):
temp = get_label_orf(index[:-2])
gap = index[-2:]
elif index[-1] in list(ALPHABET):
temp = get_label_orf(index[:-1])
gap = index[-1]
else:
temp = get_label_orf(index)
gap = None
temp = temp.split('-')
if gap is not None:
temp[1] += gap
#print(temp, gap)
temp.append(nuc)
label = '-'.join(temp)
return label
def orf_to_nsp(i, split_orf1=False):
"""Given a nucleotide label in the form orf1-#, return label in the form NSP#-#-#"""
n = 0
i_end = int(i[i.find('-')+1:])
if i[:i.find('-')]=='orf1a':
n += 264
elif i[:i.find('-')]=='orf1b':
n += 13466
else:
print('input invalid')
n += i_end * 3
return get_label(n)
def nsp_to_orf(i):
""" Given a nucleotide label in the form NSP#-#-# where the first number is the nonstructural protein number,
the second is codon number in the NSP and the third is the site number in the codon, returns a label in the
form ORF#-#-#.
CHECK THAT THIS WORKS"""
n = 0
if i[:3] != 'NSP':
return i
else:
# determine which NSP it came from and add the appropriate number of nucleotides
if i[4:6]=='1-':
n += 265
elif i[4:6]=='2-':
n += 805
elif i[4:6]=='3-':
n += 2719
elif i[4:6]=='4-':
n += 8554
elif i[4:6]=='5-':
n += 10054
elif i[4:6]=='6-':
n += 10972
elif i[4:6]=='7-':
n += 11842
elif i[4:6]=='8-':
n += 12091
elif i[4:6]=='9-':
n += 12687
elif i[4:6]=='10':
n += 13024
elif i[4:6]=='12':
n += 13441
elif i[4:6]=='13':
n += 16236
elif i[4:6]=='14':
n += 18039
elif i[4:6]=='15':
n += 19620
elif i[4:6]=='16':
n += 20658
# add 3 times the codon number
idx1 = i.find('-')+1
idx2 = i.find('-', idx1+1)
n += (int(i[idx1:idx2])-1) * 3
# add the nucleotide number within the codon
n += int(i[-1])
return(get_label_orf(n))
def get_label2(i):
return get_label(i[:-2]) + '-' + i[-1]
def get_label_new(i):
nuc = i[-1]
index = i.split('-')[0]
if index[-1] in NUMBERS:
return get_label(i[:-2]) + '-' + i[-1]
else:
if index[-1] in list(ALPHABET) and index[-2] in list(ALPHABET):
temp = get_label(index[:-2])
gap = index[-2:]
elif index[-1] in list(ALPHABET):
temp = get_label(index[:-1])
gap = index[-1]
else:
temp = get_label(index)
gap = None
temp = temp.split('-')
if gap is not None:
temp[1] += gap
#print(temp, gap)
temp.append(nuc)
label = '-'.join(temp)
return label
def separate_label_idx(i):
"""return the part of the site label that is an integer and the part that is letters for a nucleotide site such as 21000aE"""
index = str(i)
if index[-1] in NUMBERS:
return index, ''
else:
if index[-1] in list(ALPHABET) and index[-2] in list(ALPHABET):
return index[:-2], index[-2:]
elif index[-1] in list(ALPHABET):
return index[:-1], index[-1:]
else:
return index, ''
def index2frame(i):
""" Return the open reading frames corresponding to a given SARS-CoV-2 reference sequence index. """
frames = []
# ORF1b ORF3a E ORF6 ORF7a
if (13468<=i<=21555) or (25393<=i<=26220) or (26245<=i<=26472) or (27202<=i<=27387) or (27394<=i<=27759):
frames.append(1)
# ORF1a S N ORF10
if ( 266<=i<=13483) or (21563<=i<=25384) or (28274<=i<=29533) or (29558<=i<=29674):
frames.append(2)
# M ORF8
if (26523<=i<=27191) or (27894<=i<=28259):
frames.append(3)
return frames
def codon2aa(c, noq=False):
""" Return the amino acid character corresponding to the input codon. """
# If all nucleotides are missing, return gap
if c[0]=='-' and c[1]=='-' and c[2]=='-': return '-'
# Else if some nucleotides are missing, return '?'
elif c[0]=='-' or c[1]=='-' or c[2]=='-':
if noq: return '-'
else: return '?'
# If the first or second nucleotide is ambiguous, AA cannot be determined, return 'X'
elif c[0] in ['W', 'S', 'M', 'K', 'R', 'Y'] or c[1] in ['W', 'S', 'M', 'K', 'R', 'Y']: return 'X'
# Else go to tree
elif c[0]=='T':
if c[1]=='T':
if c[2] in ['T', 'C', 'Y']: return 'F'
elif c[2] in ['A', 'G', 'R']: return 'L'
else: return 'X'
elif c[1]=='C': return 'S'
elif c[1]=='A':
if c[2] in ['T', 'C', 'Y']: return 'Y'
elif c[2] in ['A', 'G', 'R']: return '*'
else: return 'X'
elif c[1]=='G':
if c[2] in ['T', 'C', 'Y']: return 'C'
elif c[2]=='A': return '*'
elif c[2]=='G': return 'W'
else: return 'X'
else: return 'X'
elif c[0]=='C':
if c[1]=='T': return 'L'
elif c[1]=='C': return 'P'
elif c[1]=='A':
if c[2] in ['T', 'C', 'Y']: return 'H'
elif c[2] in ['A', 'G', 'R']: return 'Q'
else: return 'X'
elif c[1]=='G': return 'R'
else: return 'X'
elif c[0]=='A':
if c[1]=='T':
if c[2] in ['T', 'C', 'Y']: return 'I'
elif c[2] in ['A', 'M', 'W']: return 'I'
elif c[2]=='G': return 'M'
else: return 'X'
elif c[1]=='C': return 'T'
elif c[1]=='A':
if c[2] in ['T', 'C', 'Y']: return 'N'
elif c[2] in ['A', 'G', 'R']: return 'K'
else: return 'X'
elif c[1]=='G':
if c[2] in ['T', 'C', 'Y']: return 'S'
elif c[2] in ['A', 'G', 'R']: return 'R'
else: return 'X'
else: return 'X'
elif c[0]=='G':
if c[1]=='T': return 'V'
elif c[1]=='C': return 'A'
elif c[1]=='A':
if c[2] in ['T', 'C', 'Y']: return 'D'
elif c[2] in ['A', 'G', 'R']: return 'E'
else: return 'X'
elif c[1]=='G': return 'G'
else: return 'X'
else: return 'X'
def freq_change_correlation(traj_file, group1, group2, region=False, df_var_label='variant_names'):
""" Takes two groups of mutations and the csv file that contains the changes in frequency for the mutations,
and calculates the correlation between them.
group1 and group2 can be names of variants.
FUTURE: let group1 and group2 also be lists of mutations"""
# load data
df = pd.read_csv(traj_file)
var_names = list(df[df_var_label])
#sites = list(df['sites'])
if isinstance(group1, str) and isinstance(group2, str):
# find rows with the appropriate groups
df1 = df[df[df_var_label]==group1]
df2 = df[df[df_var_label]==group2]
df1 = df1[[df_var_label, 'frequencies', 'location', 'times']].sort_values(by='location')
df2 = df2[[df_var_label, 'frequencies', 'location', 'times']].sort_values(by='location')
# find rows that have the same location for the two variants
locs1 = list(df1['location'])
locs2 = list(df2['location'])
locs_both = list(set(locs1).intersection(set(locs2))) # locations in which both variants appear
if region is not False:
if isinstance(region, str):
locs_both = list(np.array(locs_both)[np.array(locs_both)==region])
else:
locs_temp = []
for reg in region:
locs_temp.append(list(np.array(locs_both)[np.array(locs_both)==reg]))
locs_both = locs_temp
new_df1 = df1[np.isin(locs1, locs_both)]
new_df2 = df2[np.isin(locs2, locs_both)]
assert list(new_df1['location'])==list(new_df2['location'])
# find frequency changes
freqs1 = [np.array(i.split(' '), dtype=np.float32) for i in new_df1['frequencies'].to_numpy()]
freqs2 = [np.array(i.split(' '), dtype=np.float32) for i in new_df2['frequencies'].to_numpy()]
#print(freqs1[100])
delta_x1 = [np.diff(i) for i in freqs1]
delta_x2 = [np.diff(i) for i in freqs2]
# combine into a single list and find the correlation
total1 = [delta_x1[i][j] for i in range(len(delta_x1)) for j in range(len(delta_x1[i]))]
total2 = [delta_x2[i][j] for i in range(len(delta_x2)) for j in range(len(delta_x2[i]))]
return np.corrcoef(total1, total2)[0, 1]
def freq_change_correlation2(traj_file, group1, group2):
""" Takes two groups of mutations and the csv file that contains the changes in frequency for the mutations,
and calculates the correlation between them.
group1 and group2 can be names of variants.
FUTURE: let group1 and group2 also be lists of mutations"""
# load data
data = np.load(traj_file, allow_pickle=True)
muts = data['mutant_sites']
traj = data['traj']
freqs1 = []
freqs2 = []
for i in range(len(muts)):
muts_temp = [get_label2(j) for j in muts[i]]
if group1 in muts_temp and group2 in muts_temp:
temp1 = np.diff(traj[i][:, muts_temp.index(group1)])
temp2 = np.diff(traj[i][:, muts_temp.index(group2)])
for j in range(len(temp1)):
freqs1.append(temp1[j])
freqs2.append(temp2[j])
return np.corrcoef(freqs1, freqs2)[0,1]
def find_selection_all_time(inf_dir=None, link_file=None, sCutoff=None):
"""Find the selection coefficients for all sites and all groups of linked sites over all time"""
alleles = []
locs = []
paths = []
linked = np.load(link_file, allow_pickle=True)
for file in os.listdir(inf_dir):
if os.path.isdir(os.path.join(inf_dir, file)):
continue
data = np.load(os.path.join(inf_dir, file), allow_pickle=True)
alleles.append([get_label2(i) for i in data['allele_number']])
locs.append(file)
paths.append(os.path.join(inf_dir, file))
allele_number = np.unique([alleles[i][j] for i in range(len(alleles)) for j in range(len(alleles[i]))])
linked_all = np.unique([linked[i][j] for i in range(len(linked)) for j in range(len(linked[i]))])
labels = [i for i in allele_number if i not in linked_all]
labels_sorted = np.argsort(labels)
s_nolink = []
s_link = []
for file in paths:
data = np.load(file, allow_pickle=True)
s = data['selection']
muts = [get_label2(i) for i in data['allele_number']]
positions = np.searchsorted(np.array(labels)[labels_sorted], muts)
positions = labels_sorted[positions]
s_new = np.zeros((len(s), len(labels)))
s_link_new = np.zeros((len(s), len(linked)))
for i in range(len(muts)):
if muts[i] in linked_all:
for j in range(len(linked)):
if muts[i] in linked[j]:
s_link_new[:, j] += s[:, i]
elif muts[i] in labels:
s_new[:, positions[i]] += s[:, i]
else:
print(f'error: mutation {muts[i]} not found in overall list of mutations')
s_nolink.append(s_new)
s_link.append(s_link_new)
if sCutoff is None:
# returns the locations, and the linked and nonlinked coefficients over all time in each location
return locs, s_link, s_nolink
else:
largest_locs = []
largest_sites = []
largest_sel = []
for loc in range(len(locs)):
s_link_temp1 = np.amax(s_link[loc], axis=0)
s_link_temp2 = np.amin(s_link[loc], axis=0)
for i in range(len(s_link_temp1)):
if s_link_temp1[i] > sCutoff:
largest_locs.append(locs[loc])
largest_sites.append('/'.join(linked[i]))
largest_sel.append(s_link_temp1[i])
if s_link_temp2[i] < -sCutoff:
largest_locs.append(locs[loc])
largest_sites.append('/'.join(linked[i]))
largest_sel.append(s_link_temp2[i])
s_temp1 = np.amax(s_nolink[loc], axis=0)
s_temp2 = np.amin(s_nolink[loc], axis=0)
for i in range(len(s_temp1)):
if s_temp1[i] > sCutoff:
largest_locs.append(locs[loc])
largest_sites.append(allele_number[i])
largest_sel.append(s_temp1[i])
if s_temp2[i] < -sCutoff:
largest_locs.append(locs[loc])
largest_sites.append(allele_number[i])
largest_sel.append(s_temp2[i])
df_data = {
'locations' : largest_locs,
'sites' : largest_sites,
'selection' : largest_sel
}
df = pd.DataFrame(data=df_data)
return df
def find_null_distribution(file, link_file, neutral_tol=0.01):
""" Given the inferred coefficients over all time, find those that are ultimately inferred to be nearly neutral,
and then collect the inferred coefficients for these sites at every time."""
# loading and processing the data
data = np.load(file, allow_pickle=True)
linked_sites = np.load(link_file, allow_pickle=True) # sites that are fully linked in every region
traj_data = np.load(traj_file, allow_pickle=True)
traj = data['traj']
mutant_sites = data['mutant_sites']
times = data['times']
allele_number = data['allele_number']
labels = [get_label2(i) for i in allele_number]
linked_all = [linked_sites[i][j] for i in range(len(linked_sites)) for j in range(len(linked_sites[i]))]
inferred = data['selection']
digits = len(str(len(inferred)*len(inferred[0])))
# finding first time a mutation was observed
t_observed = np.zeros(len(allele_number))
alleles_sorted = np.sort(alelle_number)
pos_all = [np.searchsorted(alleles_sorted, mutant_sites[i]) for i in range(len(mutant_sites))]
for i in range(len(traj)):
positions = pos_all[i]
first_times = [times[i][np.nonzero(traj[i][:, j])[0][0]] for j in range(len(traj[i][0]))]
for j in range(len(mutant_sites[i])):
t_observed[positions[j]] = min(t_observed[positions[j]], first_times[j])
t_init_link = np.zeros(len(linked_sites))
for i in range(len(labels)):
if labels[i] in linked_all:
for j in range(len(linked_sites)):
if labels[i] in list(linked_sites[j]):
t_init_link[j] = min(t_init_link[j], t_observed[i])
# finding total coefficients for linked sites and adding them together.
inferred_link = np.zeros((len(inferred), len(linked_sites)))
inferred_nolink = []
labels_nolink = []
t_init_nolink = []
for i in range(len(linked_sites)):
for j in range(len(linked_sites[i])):
if np.any(linked_sites[i][j]==np.array(labels)):
inferred_link[:,i] += inferred[:, np.where(np.array(linked_sites[i][j])==np.array(labels))[0][0]]
counter = 0
for i in range(len(labels)):
if labels[i] not in linked_all:
inferred_nolink.append(inferred[:,i])
labels_nolink.append(labels[i])
t_init_nolink.append(t_observed[i])
counter+=1
nolink_new = np.zeros((len(inferred_nolink[0]), len(inferred_nolink)))
for i in range(len(inferred_nolink)):
nolink_new[:,i] = inferred_nolink[i]
inferred_nolink = nolink_new
# determing sites that are ultimately inferred to be nearly neutral
inf_new = np.concatenate((inferred_link, np.array(inferred_nolink)), axis=1)
t_init = np.concatenate((t_init_link, t_init_nolink))
neutral_mask = np.absolute(inf_new[-1])<neutral_tol
L = len([i for i in neutral_mask if i])
inferred_neut = np.zeros((len(inf_new), L))
t_init_new = np.array(t_init)[neutral_mask]
for i in range(len(inferred)):
inferred_neut[i] = inf_new[i][neutral_mask]
times_inf = data['times_inf']
assert(len(inferred_neut)==len(times_inf))
s_neutral = []
for i in range(len(inferred_neut[0])):
for j in range(len(inferred_neut)):
if t_init_new[i] <= times_inf[j]:
s_neutral.append(inferred_neut[j][i])
inferred_neut = s_neutral
inferred_neut = [inferred_neut[i][j] for i in range(len(inferred_neut)) for j in range(len(inferred_neut[i]))]
# If a site is inferred to have a selection coefficient of exactly zero, this is because it is the reference nucleotide.
inferred_neut = np.array(inferred_neut)[np.array(inferred_neut)!=0]
return inferred_neut
def infer_fast(numerator, covariance, alleles, g=40):
"""Infer selection coefficients given the numerator, the covariance and the alleles"""
alleles_unique = np.unique([int(i[:-2]) for i in alleles])
ref_seq, ref_tag = get_MSA(REF_TAG + '.fasta')
ref_seq = list(ref_seq[0])
ref_poly = np.array(ref_seq)[alleles_unique]
g1 = g1 * (N * k) / (1 + (k / R))
for i in range(len(covariance)):
covariance[i, i] += g1
# infer selection coefficients
s = linalg.solve(covariance, numerator, assume_a='sym')
s_ind = numerator / np.diag(covariance)
errors = 1 / np.sqrt(np.absolute(np.diag(covariance)))
# normalize reference nucleotide to zero
L = int(len(s) / 5)
selection = np.reshape(s, (L, q))
selection_nocovar = np.reshape(s_ind, (L, q))
# normalize reference mutation to have selection coefficient of zero
s_new = []
s_SL = []
for i in range(L):
idx = NUC.index(ref_poly[i])
temp_s = selection[i]
temp_s = temp_s - temp_s[idx]
temp_s_SL = selection_nocovar[i]
temp_s_SL = temp_s_SL - temp_s_SL[idx]
s_new.append(temp_s)
s_SL.append(temp_s_SL)
selection = s_new
selection_nocovar = s_SL
selection = np.array(selection).flatten()
selection_nocovar = np.array(selection_nocovar).flatten()
error_bars = errors
return selection, error_bars, selection_nocovar
def find_linked_coefficients(link_file, infer_file):
""" Finds the sum of the coefficients for linked sites given a .npz inference file"""
linked_sites = np.load(link_file, allow_pickle=True)
data = np.load(infer_file, allow_pickle=True)
inferred = data['selection']
error = data['error_bars']
alleles = data['allele_number']
labels = [get_label_new(i) for i in alleles]
inferred_link = np.zeros(len(linked_sites))
error_link = np.zeros(len(linked_sites))
for i in range(len(linked_sites)):
for j in range(len(linked_sites[i])):
if linked_sites[i][j] in list(labels):
loc = list(labels).index(linked_sites[i][j])
inferred_link[i] += inferred[loc]
error_link[i] += error[loc] ** 2
error_link = np.sqrt(error_link)
return inferred_link, error_link
def linked_coefficients(linked_sites, mutant_sites, selection, error):
""" Calculate the selection coefficients for the linked groups and the errors"""
inferred_link = np.zeros(len(linked_sites))
error_link = np.zeros(len(linked_sites))
for i in range(len(linked_sites)):
for j in range(len(linked_sites[i])):
if linked_sites[i][j] in list(mutant_sites):
loc = list(mutant_sites).index(linked_sites[i][j])
inferred_link[i] += selection[loc]
error_link[i] += error[loc] ** 2
error_link = np.sqrt(error_link)
return inferred_link, error_link
def bootstrap_variant_stats(directory, linked_sites, variant_names=None, out_file='bs-variant-stats'):
"""Finds the inferred coefficients for variants across a series of bootstrap inferences and then
calculates the mean/standard deviation"""
selection = []
errors = []
for file in os.listdir(directory):
data = np.load(os.path.join(directory, file), allow_pickle=True)
sel = data['selection']
muts = [get_label_new(i) for i in data['allele_number']]
err = data['error_bars']
inf, err = linked_coefficients(linked_sites, muts, sel, err)
selection.append(inf)
errors.append(err)
mean_s = np.mean(selection, axis=0)
std_dev = np.std(selection, axis=0)
avg_dev = np.sum([np.abs(i - mean_s) for i in selection], axis=0) / len(selection)
if variant_names==None:
variant_names = [f'Group {i}' for i in range(len(linked_sites))]
f = open(out_file + '.csv', 'w')
f.write('variant,mean_selection,standard_deviation,average_deviation,sites\n')
for i in range(len(linked_sites)):
sites = ' '.join(linked_sites[i])
f.write(f'{variant_names[i]},{mean_s[i]},{std_dev[i]},{avg_dev[i]},{sites}\n')
f.close()
def find_bootstrap_stats(directory, out_file, mutant_sites=None):
"""Find the mean and standard deviation of the inferred coefficients across a series of bootstrap inferences"""
selection = []
errors = []
alleles = []
mut_sites = np.load(os.path.join(directory, os.listdir(directory)[0]), allow_pickle=True)['allele_number']
num_bootstraps = len(os.listdir(directory))
for file in os.listdir(directory):
data = np.load(os.path.join(directory, file), allow_pickle=True)
selection.append(data['selection'])
errors.append(data['error_bars'])
alleles.append(data['allele_number'])
if mutant_sites is not None:
alleles_sorted = np.argsort(mutant_sites)
#positions = [np.searchsorted(np.array(mutant_sites)[alleles_sorted], i) for i in alleles]
#positions = [alleles_sorted[i] for i in positions]
#print(positions[0])
#print(mutant_sites)
#print(alleles[0][positions[0]])
new_s = np.zeros((num_bootstraps, len(mutant_sites)))
new_err = np.zeros((num_bootstraps, len(mutant_sites)))
for i in range(num_bootstraps):
mask = np.isin(alleles[i], mutant_sites)
temp_muts = alleles[i][mask]
positions = np.searchsorted(np.array(mutant_sites)[alleles_sorted], temp_muts)
positions = alleles_sorted[positions]
temp_s = selection[i][mask]
temp_err = errors[i][mask]
for j in range(len(temp_muts)):
new_s[i, positions[j]] = temp_s[j]
new_err[i, positions[j]] = temp_err[j]
#for j in range(len(positions[i])):
# new_s[i, positions[i][j]] = selection[i][j]
# new_err[i, positions[i][j]] = errors[i][j]
selection = new_s
errors = new_err
mut_sites = mutant_sites
mean_s = np.mean(selection, axis=0)
std_dev = np.std(selection, axis=0)
mean_error = np.mean(errors, axis=0)
f = open(out_file + '.csv', 'w')
f.write('mutant_site,mean_selection,standard_deviation,mean_error\n')
for i in range(len(mut_sites)):
f.write(f'{mut_sites[i]},{mean_s[i]},{std_dev[i]},{mean_error[i]}\n')
f.close()
# _ _ _ FUNCTIONS FOR CONVERTING BETWEEN BINARY SEQUENCE AND LABELED ONE _ _ _ #
def label_to_binary(seq, allele_number):
""" Transforms a labeled sequence into a binary one. """
new_seq = np.zeros(len(allele_number))
for i in range(len(seq)):
loc = np.where(allele_number==seq[i])
new_seq[loc] = 1
return new_seq
def binary_to_labeled(seq, mutant_sites):
""" Transforms a binary sequence into a labeled one. """
return np.array([mutant_sites[i] for i in range(len(seq)) if seq[i]==1])
def construct_sVec(sVec, allele_number):
""" Constructs a binary sVec from a labeled one. """
new_sVec = []
for i in range(len(sVec)):
sVec_temp = []
for j in range(len(sVec[i])):
sVec_temp.append(label_to_binary(sVec[i][j], allele_number))
new_sVec.append(sVec_temp)
return new_sVec
# ^ ^ ^ FUNCTIONS FOR CONVERTING BETWEEN BINARY SEQUENCE AND LABELED ONE ^ ^ ^ #
def clip_sequences(file, outfile, start=0, end=0):
""" Clip the sequences start and end times and resave the file"""
data = np.load(file, allow_pickle=True)
nVec = data['nVec']
sVec = data['sVec']
mutant_sites = data['mutant_sites']
times = data['times']
if end > 0:
nVec = nVec[:-end]
sVec = sVec[:-end]
times = times[:-end]
if start > 0:
nVec = nVec[start:]
sVec = sVec[start:]
times = times[start:]
f = open(outfile, mode='w+b')
np.savez_compressed(f, nVec=nVec, sVec=sVec, mutant_sites=mutant_sites, times=times)
f.close()
def combine_nonsyn_files(nonsyn_file, alternate_orf_file, out_file):
""" Combine the information in the regular nonsynonymous file with the information in the alternative
reading frames."""
data1 = np.load(nonsyn_file, allow_pickle=True)
types = data1['types']
locs = data1['locations']
data2 = np.load(alternate_orf_file, allow_pickle=True)
types_alt = data2['types']
types_new = []
for i in range(len(locs)):
if types[i] == 'S' and types_alt[i] == 'NS':
print('yes')
types_new.append('NNS')
else:
types_new.append(types[i])
f = open(out_file + '.npz', mode='w+b')
np.savez_compressed(f, locations=locs, types=types_new)
f.close()
def trajectory_calc_20e_eu1(nVec, sVec, mutant_sites_samp, d=5):
""" Calculates the frequency trajectories"""
variant_muts = ['NSP16-199-2-C', 'NSP1-60-2-C', 'NSP3-1189-2-T', 'M-93-2-G', 'N-220-1-T', 'ORF10-30-0-T', 'S-222-1-T']
variant_nucs = [i[-1] for i in variant_muts]
variant_sites = [list(mutant_sites_samp).index(i[:-2]) for i in variant_muts]
Q = np.ones(len(nVec))
for t in range(len(nVec)):
if len(nVec[t]) > 0:
Q[t] = np.sum(nVec[t])
single_freq_s = np.zeros(len(nVec))
for t in range(len(nVec)):
for j in range(len(sVec[t])):
seq_is_var = True
for i in range(len(variant_muts)):
if NUC[sVec[t][j][variant_sites[i]]] != variant_nucs[i]:
seq_is_var = False
break
if seq_is_var:
single_freq_s[t] += nVec[t][j] / Q[t]
return single_freq_s
def get_noncanonical_orfs(i):
# For a sequence index i, find the noncanonical reading frames, protein number, and nucleotide in codon number
i = int(i)
proteins = []
start_inds = [21744, 25814, 25457, 25524, 25596, 28284, 28734]
end_inds = [21860, 25879, 25579, 25694, 25694, 28574, 28952]
labels = ['ORF2b', 'ORF3b', 'ORF3c', 'ORF3d', 'ORF3d-2', 'ORF9b', 'ORF9c']
#start_codons = ['CUG', 'AUG', 'ACG', 'AUC', 'AUG', 'AUG', 'AUG', 'AUG', 'AUU', 'AUU', 'UUG', 'AUC', 'AUG', 'AUG', 'AUG']
for j in range(len(start_inds)):
if (start_inds[j]<=i<=end_inds[j]):
proteins.append(labels[j] + '-' + str(int((i - start_inds[j] + 1) / 3 ) + 1) + '-' + str((i - start_inds[j] + 1) % 3))
return proteins
def get_noncanonical_codon_start_index(i):
# Given a sequence index i, determine the index of the first nucleotide in the codon in each of the noncanonical reading frames.
i = int(i)
start_inds = [21744, 25814, 25457, 25524, 25596, 28284, 28734]
end_inds = [21860, 25879, 25579, 25694, 25694, 28574, 28952]
labels = ['ORF2b', 'ORF3b', 'ORF3c', 'ORF3d', 'ORF3d-2', 'ORF9b', 'ORF9c']
codon_inds = []
for j in range(len(start_inds)):
if (start_inds[j]<=i<=end_inds[j]):
codon_inds.append(i - (i - start_inds[j] + 1)%3)
return codon_inds
def classify_mutations_noncanonical(ref_seq, poly_sites, likely_alleles, likely_mutations):
""" Given the sites that are polymorphic in a specific region, determine if the mutations are synonymous or nonsynonymous. """
sites, states, ns_counter = [], [], []
for site in poly_sites:
start_inds = get_noncanonical_codon_start_index(site)
sites.append(get_noncanonical_orfs(site))
if len(start_inds)>0:
counter = 0
mut_type = "S"
for i in start_inds:
ref_codon = ref_seq[i:i+3]
mut_codon = [j for j in ref_codon]
indices = np.arange(i, i+3)
mut_codon[list(indices).index(site)] = likely_mutations[poly_sites.index(site)]
for j in range(len(indices)):
if indices[j] in np.array(poly_sites) and indices[j]!=site:
mut_codon[j] = likely_alleles[poly_sites.index(indices[j])]
if codon2aa(ref_codon)!=codon2aa(mut_codon):
mut_type = "NS"
counter += 1
ns_counter.append(counter)
states.append(mut_type)
else:
ns_counter.append(0)
states.append('None')
return sites, states, ns_counter
def separate_by_protein(inf_file, out_file=None):
""" Takes the inferred coefficients and separates them according to what protein they belong to"""
data = np.load(inf_file, allow_pickle=True)
alleles = data['allele_number']
labels = [get_label2(i) for i in alleles]
inferred = data['selection']
proteins = ['ORF3a', 'E', 'ORF6', 'ORF7a', 'ORF7b', 'S', 'N', 'M', 'ORF8', 'ORF10', 'NSP1-', 'NSP2',
'NSP3', 'NSP4', 'NSP5', 'NSP6', 'NSP7', 'NSP8', 'NSP9', 'NSP10', 'NSP12', 'NSP13', 'NSP14',
'NSP15', 'NSP16']
inf_new = []
label_new = []
for p in proteins:
temp_inf = []
temp_lab = []
for i in range(len(inferred)):
if labels[i][:len(p)]==p:
temp_inf.append(inferred[i])
temp_lab.append(labels[i])
inf_new.append(temp_inf)
label_new.append(temp_lab)
proteins_new = []
for p in proteins:
if p.find('-')!=-1:
proteins_new.append(p[:p.find('-')])
else:
proteins_new.append(p)
proteins = proteins_new
if out_file:
f = open(out_file + '.csv', mode='w')