-
Notifications
You must be signed in to change notification settings - Fork 1
/
ngs.py
1737 lines (1498 loc) · 60.1 KB
/
ngs.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 29 2019
@author: [email protected]
"""
# Replace the following two variables with paths to bbmerge and flash.
BBMerge_path = '~/bbmap/bbmerge.sh'
FLASH_path = '~/FLASH-1.2.11/flash'
import os
import re
import sys
import glob
import tqdm
import itertools
import numpy as np
import pandas as pd
from functools import partial
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
from Bio.Seq import translate, Seq
from CDR_identifier import cdr_finder
from multiprocessing import get_context
#NGS_sample classes are used to analyze the raw .fastq files from the core to generate seq:freq data.
#R1.fastq + R2.fastq --> merged.fastq --> merged.fasta --> seq: freq
class NGS_sample(object):
#NGS_sample class analyzes the .fastq.gz output files from a MiSeq NextGen Sequencing Run. The output files will be used with NGS_round_data.
def __init__(self, sequence_length, starting_sequence, output_path, qtrim, cdr_regions = None, mutation_locations = None, use_cdr_finder = False, cdr_finder_kwargs = None, sub_string = None):
'''
Input:
sequence_length: <class 'int'> the length of the DNA sequence
starting_sequence: <class 'str'> a string of the starting amino acids in the sequence.
output_path: <class 'str'> the directory where the output will be saved.
qtrim: <class 'int'> qtrim parameter for bbmerge
cdr_regions: <class 'list'> List containing tuples of <class 'int'> representing start and end positions of cdrs.
mutation_locations: <class 'list'> containing <class 'int'> representing positions of mutations within cdrs.
use_cdr_finder: <class 'bool'> Specifies whether cdr_regions will be used to get cdr locations or CDR_identifier.cdr_finder
cdr_finder_kwargs: <class 'dict'> keyword dictionary containing arguments to CDR_identifier.cdr_finder:
{'vh_loc':[x,x+n], # or None specifies location of variable domain
'vl_loc':None, # or [y, y+m]
'definition':'kabat',
'which_CDRHs':[True, True, True],
'which_CDRLs':[False, False, False]}
sub_string: <class 'list'> representing the start and end of the sequence to consider for analysis.
'''
if cdr_finder_kwargs is not None:
from CDR_identifier import cdr_finder, split_sequences
if cdr_regions == None and mutation_locations == None and use_cdr_finder == False:
print('You must supply either cdr_regions and mutation_regions or set use_cdr_finder to True')
quit()
if use_cdr_finder:
if not cdr_finder_kwargs:
print('must provide cdr finder arguments.')
quit()
self.sequence_length = sequence_length
if output_path.endswith('/'):
self.output_path = output_path
else:
self.output_path = output_path + '/'
self.starting_sequence = starting_sequence.upper()
self.qtrim = qtrim
self.cdr_regions = cdr_regions
self.mutation_locations = mutation_locations
self.cdr_finder_kwargs = cdr_finder_kwargs
self.use_cdr_finder = use_cdr_finder
self.sub_string = sub_string
def run_flash(self):
'''
runs flash on unzipped .fastq files to form a single merged .fastq file.
creates the following files containing merged sequences, unmerged sequences, and histogram data of merged read length
'merged_6436-MS-1_barcode-barcode_SX.extendedFrags.fastq'
'merged_6436-MS-1_barcode-barcode_SX.notCombined_1.fastq'
'merged_6436-MS-1_barcode-barcode_SX.notCombined_2.fastq'
'merged_6436-MS-1_barcode-barcode_SX.hist'
'merged_6436-MS-1_barcode-barcode_SX.histogram'
Finds and uses two read files in directory
'6436-MS-1_barcode-barcode_SX_R1_001.fastq'
'6436-MS-1_barcode-barcode_SX_R2_001.fastq'
'''
m = glob.glob('*merged*.fastq')
if len(m) == 0:
f = glob.glob('*.fastq')
os.system(f"{FLASH_path} {f[0]} {f[1]} -M 301 -o merged_{f[0].split('_R')[0]}")
def run_bbmerge(self):
'''
runs bbmerge on unzipped .fastq files to form one .fastq file for the sample
default value for qtrim is currently 10. Should be altered based on FastQC results.
qtrim sets the quality trimming metric for bbmerge
creates two files containing merged sequences and unmerged sequences
'Sample_x_merged.fastq'
'Sample_x_unmerged.fastq'
Finds and uses two read files in directory
'Sample_x_R1_001.fastq'
'Sample_x_R2_001.fastq'
'''
m = glob.glob('*merged.fastq')
if len(m) == 0:
f = glob.glob('*.fastq')
os.system(f"{BBMerge_path} in1={f[0]} in2={f[1]} out={re.sub('_R[1,2]_001.fastq', '_merged.fastq', f[0])} -qtrim=15") #outu={re.sub('_R[1,2]_001.fastq', '_unmerged.fastq', f[0])}
print('{} and {} successfully merged.'.format(f[0], f[1]))
else:
for fqm in m:
os.system('rm {}'.format(fqm))
f = glob.glob('*.fastq')
os.system(f"{BBMerge_path} in1={f[0]} in2={f[1]} out={re.sub('_R[1,2]_001.fastq', '_merged.fastq', f[0])} -qtrim=15") #outu={re.sub('_R[1,2]_001.fastq', '_unmerged.fastq', f[0])}
print('{} and {} successfully merged.'.format(f[0], f[1]))
def process_fasta_line(self, line):
line = line.split('\n')[0]
seq_num = 0
dna_lines = 0
seq_dict = {}
cdr_dict = {}
if self.mutation_locations is not None:
mutation_dict = {}
if not line.startswith('>'):
if self.sub_string is not None:
seq = line[self.sub_string[0]:self.sub_string[1]]
else:
seq = line
dna_lines += 1
if len(seq) >= self.sequence_length and 'N' not in seq and len(seq) % 3 == 0:
aa_seq = translate(seq)
if not aa_seq.startswith(self.starting_sequence):
seq_class = Seq(seq)
aa_seq = str(translate(str(seq_class.reverse_complement())))
if '*' not in aa_seq:
seq_num += 1
try:
seq_dict[aa_seq] += 1
except:
seq_dict[aa_seq] = 1
cdr_str = ''
if self.cdr_regions is None:
if self.cdr_finder_kwargs['vh_loc'] is not None:
VH = aa_seq[self.cdr_finder_kwargs['vh_loc'][0]:self.cdr_finder_kwargs['vh_loc'][1]]
else:
VH = None
if self.cdr_finder_kwargs['vl_loc'] is not None:
VL = aa_seq[self.cdr_finder_kwargs['vl_loc'][0]:self.cdr_finder_kwargs['vl_loc'][1]]
else:
VL = None
try:
cdr_finder_dict = cdr_finder(VH_seq = VH, VL_seq = VL, **self.cdr_finder_kwargs)
except:
return [seq_dict, {}, seq_num, dna_lines]
cdr_str = ''
for cdr, cdr_set in cdr_finder_dict.items():
cdr_str += cdr_set[0] + '_'
else:
for cdr in self.cdr_regions:
cdr_str += f'{aa_seq[cdr[0]:cdr[1]]}_'
cdr_str = cdr_str[0:len(cdr_str) - 1]
if self.mutation_locations is not None:
mutation_str = ''
for mutation in self.mutation_locations:
mutation_str += cdr_str[mutation]
try:
mutation_dict[mutation_str] += 1
except:
mutation_dict[mutation_str] = 1
try:
cdr_dict[cdr_str] += 1
except:
cdr_dict[cdr_str] = 1
if self.mutation_locations is not None:
return [seq_dict, cdr_dict, mutation_dict, seq_num, dna_lines]
else:
return [seq_dict, cdr_dict, seq_num, dna_lines]
def condense_dictionaries(self, dict_list):
condensed_dict = {}
for d in dict_list:
for key, value in d.items():
try:
condensed_dict[key] += value
except:
condensed_dict[key] = value
return condensed_dict
def get_freq_fasta_mp(self):
try:
print('Analyzing fasta file now.')
for fa in glob.glob('*.fasta'):
lines = open(fa)
if os.cpu_count() > 1:
p2 = get_context('fork').Pool(os.cpu_count()-1)
else:
p2 = get_context('fork').Pool()
results = p2.map(self.process_fasta_line, lines)
p2.close()
p2.join()
s_dicts = [results[i][0] for i in range(len(results))]
c_dicts = [results[i][1] for i in range(len(results))]
if self.mutation_locations is not None:
m_dicts = [results[i][2] for i in range(len(results))]
if os.cpu_count() > 1:
p = get_context('fork').Pool(os.cpu_count()-1)
else:
p = get_context('fork').Pool()
if self.mutation_locations is not None:
seq_dict, cdr_dict, mutation_dict = p.map(self.condense_dictionaries, [s_dicts, c_dicts, m_dicts])
else:
seq_dict, cdr_dict = p.map(self.condense_dictionaries, [s_dicts, c_dicts])
p.close()
p.join()
seq_num = 0
dna_lines = 0
if self.mutation_locations is not None:
for result in results:
seq_num += result[3]
dna_lines += result[4]
else:
for result in results:
seq_num += result[2]
dna_lines += result[3]
print(f'Creating csv file now. {seq_num} correct reads found from {dna_lines} total sequences')
count_outfile = open(f"{self.output_path}Count_{''.join(str(int(fa.split('_merged')[0].split('_')[2].split('S')[1]) + 1000))}.csv", 'w')
count_outfile.write(f'{seq_num}')
count_outfile.close()
seq_outfile = open('{}Sequences_{}.csv'.format(self.output_path, ''.join(str(int(fa.split('_merged')[0].split('_')[2].split('S')[1]) + 1000))), 'w')
for sequence in sorted(seq_dict, key=seq_dict.get, reverse=True):
seq_outfile.write('{}, {}\n'.format(sequence, seq_dict[sequence]/float(seq_num)))
seq_dict.pop(sequence)
seq_outfile.close()
cdr_outfile = open('{}CDR_{}.csv'.format(self.output_path, ''.join(str(int(fa.split('_merged')[0].split('_')[2].split('S')[1]) + 1000))), 'w')
for cdr in sorted(cdr_dict, key=cdr_dict.get, reverse=True):
cdr_outfile.write('{}, {}\n'.format(cdr, cdr_dict[cdr]/float(seq_num)))
cdr_dict.pop(cdr)
cdr_outfile.close()
if self.mutation_locations is not None:
mutation_outfile = open('{}Mutation_{}.csv'.format(self.output_path, ''.join(str(int(fa.split('_merged')[0].split('_')[2].split('S')[1]) + 1000))), 'w')
for mutation in sorted(mutation_dict, key=mutation_dict.get, reverse=True):
mutation_outfile.write('{}, {}\n'.format(mutation, mutation_dict[mutation]/float(seq_num)))
mutation_dict.pop(mutation)
mutation_outfile.close()
print('CSV File successfully created.')
except:
try:
p2.close()
p2.join()
return
except:
p.close()
p.join()
return
def analyze_sample_mp(self, sample_input):
'''
input:
sample_input: <class 'int'> sample number ids.
sample_input: <class 'tuple'> sample id and y/n for fasta recreation.
'''
if type(sample_input) == tuple:
sample = sample_input[0]
y_n = sample_input[1]
else:
sample = sample_input
y_n = 'y'
print('Analyzing Sample {}'.format(sample))
os.chdir('Sample_{}'.format(sample))
print('unzipping .fastq.gz files')
unzip()
#self.run_flash()
self.run_bbmerge()
print('converting to fasta')
convert(y_n)
os.chdir('../')
def analyze_all_samples_mp(self, samples):
'''
input:
samples: <class 'list'> list containg sample number ids.
'''
if os.cpu_count() > 1:
p1 = get_context('fork').Pool(os.cpu_count()-1)
else:
p1 = get_context('fork').Pool()
p1.map(self.analyze_sample_mp, samples)
p1.close()
p1.join()
for sample in samples:
print(f'Calculating frequencies of Sample {sample}')
os.chdir('Sample_{}'.format(sample))
self.get_freq_fasta_mp()
os.chdir('../')
class NGS_phased_sample(NGS_sample):
#To be used with samples prepared with amplicon phasing. Output will be used with NGS_round_data.
def __init__(self, sequence_length, starting_sequence, output_path, qtrim, cdr_regions = None, mutation_locations = None, use_cdr_finder = False, cdr_finder_kwargs = None, sub_string = None):
'''
Input:
sequence_length: <class 'int'> the length of the DNA sequence
starting_sequence: <class 'str'> a string of the starting amino acids in the sequence.
output_path: <class 'str'> the directory where the output will be saved.
qtrim: <class 'int'> qtrim parameter for bbmerge
cdr_regions: <class 'list'> List containing tuples of <class 'int'> representing start and end positions of cdrs.
mutation_locations: <class 'list'> containing <class 'int'> representing positions of mutations within cdrs.
use_cdr_finder: <class 'bool'> Specifies whether cdr_regions will be used to get cdr locations or CDR_identifier.cdr_finder
cdr_finder_kwargs: <class 'dict'> keyword dictionary containing arguments to CDR_identifier.cdr_finder:
{'vh_loc':[x,x+n], # or None specifies location of variable domain
'vl_loc':None, # or [y, y+m]
'definition':'kabat',
'which_CDRHs':[True, True, True],
'which_CDRLs':[False, False, False]}
sub_string: <class 'dict'> {sample_1: [a, b], sample_2: [c, d], ...}
'''
if cdr_finder_kwargs is not None:
from CDR_identifier import cdr_finder, split_sequences
if cdr_regions == None and mutation_locations == None and use_cdr_finder == False:
print('You must supply either cdr_regions and mutation_regions or set use_cdr_finder to True')
quit()
if use_cdr_finder:
if not cdr_finder_kwargs:
print('must provide cdr finder arguments.')
quit()
self.sequence_length = sequence_length
if output_path.endswith('/'):
self.output_path = output_path
else:
self.output_path = output_path + '/'
self.starting_sequence = starting_sequence.upper()
self.qtrim = qtrim
self.cdr_regions = cdr_regions
self.mutation_locations = mutation_locations
self.cdr_finder_kwargs = cdr_finder_kwargs
self.use_cdr_finder = use_cdr_finder
self.sub_string = sub_string
def process_phased_fasta_line(self, sample, line):
seq_num = 0
dna_lines = 0
seq_dict = {}
cdr_dict = {}
if self.mutation_locations is not None:
mutation_dict = {}
#only look at sequence lines
if not line.startswith('>'):
seq = line.split('\n')[0]
dna_lines += 1
#Check if sequence is ~correct length
if len(seq) >= self.sequence_length and len(seq) % 3 == 0:
#check if first few amino acids are correct or have ~one mutation causes incorrect start
if hamming_distance(translate(seq[self.sub_string[sample][0]:self.sub_string[sample][1]])[0:len(self.starting_sequence)], self.starting_sequence) <= 1:
seq_num += 1
aa_seq = translate(seq[self.sub_string[sample][0]:self.sub_string[sample][1]])
try:
seq_dict[aa_seq] += 1
except:
seq_dict[aa_seq] = 1
#check is seq is shifted upstream 1 bp
elif hamming_distance(translate(seq[self.sub_string[sample][0] - 1:self.sub_string[sample][1]])[0:len(self.starting_sequence)], self.starting_sequence) <= 1:
seq_num += 1
aa_seq = translate(seq[self.sub_string[sample][0] - 1:self.sub_string[sample][1]])
try:
seq_dict[aa_seq] += 1
except:
seq_dict[aa_seq] = 1
#check if seq is shifted downstream 1 bp
elif hamming_distance(translate(seq[self.sub_string[sample][0] + 1:self.sub_string[sample][1]])[0:len(self.starting_sequence)], self.starting_sequence) <= 1:
seq_num += 1
aa_seq = translate(seq[self.sub_string[sample][0] + 1:self.sub_string[sample][1]])
try:
seq_dict[aa_seq] += 1
except:
seq_dict[aa_seq] = 1
#Use reverse complement if every above check failed.
else:
seq = Seq(seq).reverse_complement()
#check if first few amino acids are correct or have ~one mutation causes incorrect start
if hamming_distance(translate(seq[self.sub_string[sample][0]:self.sub_string[sample][1]])[0:len(self.starting_sequence)], self.starting_sequence) <= 1:
seq_num += 1
aa_seq = translate(seq[self.sub_string[sample][0]:self.sub_string[sample][1]])
try:
seq_dict[aa_seq] += 1
except:
seq_dict[aa_seq] = 1
#check is seq is shifted upstream 1 bp
elif hamming_distance(translate(seq[self.sub_string[sample][0] - 1:self.sub_string[sample][1]])[0:len(self.starting_sequence)], self.starting_sequence) <= 1:
seq_num += 1
aa_seq = translate(seq[self.sub_string[sample][0] - 1:self.sub_string[sample][1]])
try:
seq_dict[aa_seq] += 1
except:
seq_dict[aa_seq] = 1
#check if seq is shifted downstream 1 bp
elif hamming_distance(translate(seq[self.sub_string[sample][0] + 1:self.sub_string[sample][1]])[0:len(self.starting_sequence)], self.starting_sequence) <= 1:
seq_num += 1
aa_seq = translate(seq[self.sub_string[sample][0] + 1:self.sub_string[sample][1]])
try:
seq_dict[aa_seq] += 1
except:
seq_dict[aa_seq] = 1
#Convert aa_seq to cdr_str and mut_str
if 'aa_seq' in locals():
try:
cdr_str = ''
if self.cdr_regions is None:
if self.cdr_finder_kwargs['vh_loc'] is not None:
VH = aa_seq[self.cdr_finder_kwargs['vh_loc'][0]:self.cdr_finder_kwargs['vh_loc'][1]]
else:
VH = None
if self.cdr_finder_kwargs['vl_loc'] is not None:
VL = aa_seq[self.cdr_finder_kwargs['vl_loc'][0]:self.cdr_finder_kwargs['vl_loc'][1]]
else:
VL = None
try:
cdr_finder_dict = cdr_finder(VH_seq = VH, VL_seq = VL, **self.cdr_finder_kwargs)
except:
return [seq_dict, {}, seq_num, dna_lines]
cdr_str = ''
for cdr, cdr_set in cdr_finder_dict.items():
cdr_str += cdr_set[0] + '_'
else:
for cdr in self.cdr_regions:
cdr_str += f'{aa_seq[cdr[0]:cdr[1]]}_'
cdr_str = cdr_str[0:len(cdr_str) - 1]
try:
cdr_dict[cdr_str] += 1
except:
cdr_dict[cdr_str] = 1
except Exception as e:
#print('Errored out in CDR_STR')
#print(f'Errored out due to {e}\n \t')
exc_type, exc_obj, exc_tb = sys.exc_info()
#print(exc_type, exc_obj, exc_tb)
if self.mutation_locations is not None:
try:
mutation_str = ''
for mutation in self.mutation_locations:
mutation_str += cdr_str[mutation]
try:
mutation_dict[mutation_str] += 1
except:
mutation_dict[mutation_str] = 1
except Exception as e:
#print(f'Errored out on MUT_STR, {aa_seq}, {cdr_str}, {mutation}')
#print(f'Errored out due to {e}\n \t')
exc_type, exc_obj, exc_tb = sys.exc_info()
#print(exc_type, exc_obj, exc_tb)
if self.mutation_locations is not None:
return [seq_dict, cdr_dict, mutation_dict, seq_num, dna_lines]
else:
return [seq_dict, cdr_dict, seq_num, dna_lines]
def get_freq_fasta_phased_mp(self, sample):
try:
print('Analyzing fasta file now.')
for fa in glob.glob('*.fasta'):
lines = open(fa)
if os.cpu_count() > 1:
p2 = get_context('fork').Pool(os.cpu_count()-1)
else:
p2 = get_context('fork').Pool()
func = partial(self.process_phased_fasta_line, sample)
results = p2.map(func, lines)
p2.close()
p2.join()
print('FASTA processing done.')
s_dicts = [results[i][0] for i in range(len(results))]
c_dicts = [results[i][1] for i in range(len(results))]
if self.mutation_locations is not None:
m_dicts = [results[i][2] for i in range(len(results))]
print('Condensing output now.')
if os.cpu_count() > 1:
p = get_context('fork').Pool(os.cpu_count()-1)
else:
p = get_context('fork').Pool()
if self.mutation_locations is not None:
seq_dict, cdr_dict, mutation_dict = p.map(self.condense_dictionaries, [s_dicts, c_dicts, m_dicts])
print('Dictionaries concatenated.')
else:
seq_dict, cdr_dict = p.map(self.condense_dictionaries, [s_dicts, c_dicts])
p.close()
p.join()
seq_num = 0
dna_lines = 0
if self.mutation_locations is not None:
for result in results:
seq_num += result[3]
dna_lines += result[4]
else:
for result in results:
seq_num += result[2]
dna_lines += result[3]
print(f'Creating csv file now. {seq_num} correct reads found from {dna_lines} total sequences')
count_outfile = open(f"{self.output_path}Count_{sample + 1000}.csv", 'w')
count_outfile.write(f'{seq_num}')
count_outfile.close()
seq_outfile = open(f"{self.output_path}Sequences_{sample + 1000}.csv", 'w')
for sequence in sorted(seq_dict, key=seq_dict.get, reverse=True):
seq_outfile.write('{}, {}\n'.format(sequence, seq_dict[sequence]/float(seq_num)))
seq_dict.pop(sequence)
seq_outfile.close()
cdr_outfile = open(f"{self.output_path}CDR_{sample + 1000}.csv", 'w')
for cdr in sorted(cdr_dict, key=cdr_dict.get, reverse=True):
cdr_outfile.write('{}, {}\n'.format(cdr, cdr_dict[cdr]/float(seq_num)))
cdr_dict.pop(cdr)
cdr_outfile.close()
if self.mutation_locations is not None:
mutation_outfile = open(f"{self.output_path}Mutation_{sample + 1000}.csv", 'w')
for mutation in sorted(mutation_dict, key=mutation_dict.get, reverse=True):
mutation_outfile.write('{}, {}\n'.format(mutation, mutation_dict[mutation]/float(seq_num)))
mutation_dict.pop(mutation)
mutation_outfile.close()
print('CSV File successfully created.')
except Exception as e:
#print(f'Errored out due to {e}\n \t')
exc_type, exc_obj, exc_tb = sys.exc_info()
#print(exc_type, exc_obj, exc_tb)
try:
p2.close()
p2.join()
return
except:
p.close()
p.join()
return
def analyze_all_samples_phased_mp(self, samples):
'''
input:
samples: <class 'list'> list containg sample number ids or tuple of sample id and y/n for fasta.
'''
if os.cpu_count() > 1:
p1 = get_context('fork').Pool(os.cpu_count()-1)
else:
p1 = get_context('fork').Pool()
p1.map(self.analyze_sample_mp, samples)
p1.close()
p1.join()
for sample in samples:
if type(sample) == tuple:
sample = sample[0]
print(f'Calculating frequencies of Sample {sample}')
os.chdir('Sample_{}'.format(sample))
self.get_freq_fasta_phased_mp(sample)
os.chdir('../')
#NGS_round_data Classes. used to contain sequence:frequency data for each sample.
class NGS_round_data(object):
#to be used for analysis of anlyzed ngs data.
def __init__(self, Round, sequence_type, samples, sample_of_interest, path, wild_type = None, mutations_dict = None):
'''
A class containing all frequency data from NGS sequencing experiments and to analyze the results.
NGS data should be stored in same directory as this file. It should be stored in a sub directory Rx/ where x is the round.
Inside of Rx/ there should be several files.
Sequences_XXX.csv
Mutation_XXX.csv
CDR_XXX.csv
RX_sort_counts.csv
these files will be created upon analyzing the NGS data.
NGS_round initializes with
Round: <class 'int'> representing the round the samples come from.
sequence_type: <class 'str'> representing what type of sequence the data was analyzed as.
Full sequence: sequences
CDR sequence: CDRs
only mutated residues: mutations
samples: <class 'list'> list of the corresponding samples of each sequencing file. The order should be the same as the sequencing files
sample_of_interest: <class 'str'> contains the primary antigen of interest (e.g. 'ABF')
path: <class 'str'> path to the frequency and count data
wild_type: <class 'str'> wild type sequence/CDR_str/mutation of wild type clone if applicable
mutations_dict: <class 'dict'> dictionary of non-wildtype amino acids muated to. len(mutations_dict.keys()) = len(mutation_str)
NGS_round will have the following attributes
self.round: <class 'int'> corresponding round
self.sample_counts: <class 'dict'> {sample: num_seq_in_sample}
self.data: <class 'dict'> contains all frequency data for each sample
{
sample1: {seq1: freq_sample1_seq1, ..., seqN: freq_sample1_seqN}
sample2: {seq1: freq_sample2_seq1, ..., seqM: freq_sample2_seqM}
...
sampleK: {seq1: freq_sampleK_seq1, ..., seqJ: freq_sampleK_seqJ}
}
self.sample_differences: <class 'dict'> contains number of sequences in a sample that aren't observed in sample_of_interest
{
sample_of_interest: 0,
sample2: 5000,
...
sampleN: 20942
}
self.count_data: <class 'dict'> unused, but contains the distribution of counts for each sample
'''
self.round = Round
if path.endswith('/'):
self.path = path
else:
self.path = path+'/'
self.samples = samples
self.sample_counts = {line.split('\n')[0].split(',')[0]: float(line.split('\n')[0].split(',')[1]) for line in open(f'{self.path}R{self.round}/R{self.round}_sort_counts.csv')}
self.sample_of_interest = sample_of_interest
self.sequence_type = sequence_type
self.current_path = os.getcwd()
if self.sequence_type == 'sequences':
self.data = self.get_round_dicts('{}R{}/'.format(self.path, self.round), 'Seq*.csv')
elif self.sequence_type == 'mutations':
self.data = self.get_round_dicts('{}R{}/'.format(self.path, self.round), 'Mu*.csv')
elif self.sequence_type == 'CDRs':
self.data = self.get_round_dicts('{}R{}/'.format(self.path, self.round), 'CD*.csv')
self.sample_differences = {}
for sample in self.samples:
self.sample_differences[sample] = len(self.data[self.sample_of_interest].keys()) - len(set(self.data[self.sample_of_interest].keys()).intersection(set(self.data[sample].keys())))
self.count_data = {}
for sample in self.samples:
self.count_data[sample] = []
for freq in self.data[sample].values():
self.count_data[sample].append(float(freq*float(self.sample_counts[sample])))
if wild_type is not None:
self.wt = wild_type
if mutations_dict is not None:
self.mutations_dict = mutations_dict
def get_seq_dict(self, path):
'''
get_seq_dict creates a dictionary of seq: freq from analyzed NGS files.
input:
path: path to NGS analyzed csvs.
output:
sequence dictionary
{seq: freq}
'''
seq_dict = {}
for line in open(path, 'r'):
seq_dict[line.split(',')[0]] = float(line.split(',')[1].split('\n')[0])
return seq_dict
def get_round_dicts(self, path, file_type):
'''
calls get_seq_dict on all samples within a round and creates a dictionary of all of the individual dictionaries.
'''
os.chdir(path)
muts = glob.glob(file_type)
muts = sorted(muts, key = lambda f: int(f.split('_')[1].split('.')[0]))
print(muts)
if len(muts) != len(self.samples):
print('The number of samples does not match the number of sample files. Please update samples list.\n')
if os.cpu_count() > 1:
p = get_context('fork').Pool(os.cpu_count() - 1)
else:
p = get_context('fork').Pool()
results = p.map(self.get_seq_dict, muts)
p.close()
p.join()
r = {}
for i in range(len(muts)):
r[self.samples[i]] = results[i]
os.chdir(self.current_path)
return r
def alter_data_dict(self):
'''
alter_data_dict adds sequences to sample dictionaries if that sequence is observed in sample_of_interest
data_added contains dictionaries with increased number of sequences and the frequencies are scalled to sum to unity.
output:
self.data_added = {
Sample1: {seq1: freq, ...}
}
'''
if self.sample_of_interest in self.samples:
self.data_added = {}
for sample in self.samples:
self.data_added[sample] = {}
# iterates through sequences in sample of interest and another sample
for seq in set(self.data[self.sample_of_interest].keys()).union(set(self.data[sample].keys())):
# if seq is only in sample of interest add to data_added[sample]
if seq not in self.data[sample]:
self.data_added[sample][seq] = 1/(float(self.sample_counts[sample]) + float(self.sample_differences[sample]))
else:
self.data_added[sample][seq] = (self.data[sample][seq] * float(self.sample_counts[sample]))/(float(self.sample_counts[sample]) + float(self.sample_differences[sample]))
else:
print('Please check sample_of_interest parameter. {} was not found in sample list'.format(self.sample_of_interest))
print('Acceptable values are {}'.format(self.samples))
def condense_data(self, sample_requirements, threshold = 0):
'''
condense_data creates another dictionary that only contains sequences that are observed in all of the sample_requirements.
for non required sorts data is pulled from data_added dictionary even if it is observed in that sort.
input:
sample_requirements: <class 'list'> sets which samples sequences need to be observed in.
threshold: <class 'int'> number of observations of each sequence in each sample. default = 0
output:
self.condensed_data = {
seq: [freq1, freq2, ..., freqN]
...
}
self.condensed_data_order contains the order of how the data was entered.
'''
self.alter_data_dict()
self.condensed_data = {}
self.condensed_data_order = []
# checks to ensure sample_requirements is a list and if not populates it correctly.
if type(sample_requirements) != list:
print('Enter sample_requirements as list not {}'.format(type(sample_requirements)))
list_not_done = True
sample_requirements = []
while list_not_done:
required_sample = input('Enter required sample now. Type XXX to stop entry.\n')
if required_sample != 'XXX':
if required_sample != '':
sample_requirements.append(required_sample)
else:
list_not_done = False
seqs = common_clones({self: sample_requirements}, threshold)
for seq in seqs:
for sample in self.samples:
if sample not in self.condensed_data_order:
self.condensed_data_order.append(sample)
if sample in sample_requirements:
if seq in self.data[sample].keys():
try:
self.condensed_data[seq].append(self.data[sample][seq])
except:
self.condensed_data[seq] = [self.data[sample][seq]]
else:
break
else:
if seq in self.data_added[sample].keys():
try:
self.condensed_data[seq].append(self.data_added[sample][seq])
except:
self.condensed_data[seq] = [self.data_added[sample][seq]]
else:
break
def get_enrichment_ratios(self, sample_requirements, threshold = 0):
'''
calculates enrichment ratios. log2(freq_sort/freq_input)
input:
sample_requirements: <class 'list'> used to create self.condensed_data for calculations
output:
self.er = {
seq: [log2(freq_i/freq_input) ...]
...
}
'''
self.condense_data(sample_requirements, threshold)
try:
input_index = self.condensed_data_order.index('Input')
except:
print('Input frequency not found.')
self.er = {}
self.er_order = []
for seq, freq_list in self.condensed_data.items():
self.er[seq] = []
for i in range(len(freq_list)):
if i != input_index:
if self.condensed_data_order[i] not in self.er_order:
self.er_order.append(self.condensed_data_order[i])
self.er[seq].append(np.log2(freq_list[i] / freq_list[input_index]))
def mutational_analysis(self, num_mutations, sample_requirements = None, er_indecies = None, clone_set = None, threshold = 0, recalculate = False):
'''
Performs mutational analysis on a NGS_round_data class.
Code should be optimized. Specifically creating mut_seqs_dict and wt_seqs_dict. Could probably alter code to find which positions are different from wt
and only search mutation sets with the same differences. multiprocessing might also be added.
'''
#get locations of possible mutations
try:
eval(f'self.mutations_dictionary_{num_mutations}')
if recalculate:
raise ValueError
except:
mutation_str_length = len(self.wt)
mut_loc_dict = {i: loc for i, loc in enumerate(list(itertools.combinations(list(range(mutation_str_length)), num_mutations)))}
#create possible mutations dictionary -- Fast
mutation_number = 0
exec(f'self.mutations_dictionary_{num_mutations} = dict()')
for loc in tqdm.tqdm(mut_loc_dict.values()):
mutations_dictionary_subkey = ''
for i in loc:
mutations_dictionary_subkey += str(i) + ','
key_list = [i for i in mutations_dictionary_subkey.split(',') if i != '']
product_list = [self.mutations_dict[int(j)] for j in key_list]
possible_mutations = list(itertools.product(*product_list))
for m in possible_mutations:
exec(f'self.mutations_dictionary_{num_mutations}[{mutation_number}] = dict()')
exec(f'self.mutations_dictionary_{num_mutations}[{mutation_number}][{mutations_dictionary_subkey}] = {m}')
mutation_number += 1
if sample_requirements is not None:
try:
eval(f'self.mut_seqs_{num_mutations}')
eval(f'self.wt_seqs_{num_mutations}')
if recalculate:
raise ValueError
except:
#calculate enrichment ratios
try:
self.er
except:
self.get_enrichment_ratios(sample_requirements, threshold)
#calculate mut_seq_dict and wt_seq_dict slowest part currently
mut_seqs = {m: [] for m in eval(f'self.mutations_dictionary_{num_mutations}.keys()')}
wt_seqs = {m: [] for m in eval(f'self.mutations_dictionary_{num_mutations}.keys()')}
exec(f'self.mut_seqs_{num_mutations} = {mut_seqs}')
exec(f'self.wt_seqs_{num_mutations} = {wt_seqs}')
if clone_set is not None:
seqs = clone_set
else:
seqs = common_clones({self: sample_requirements}, threshold)
seqs_dict = {i: [aa for aa in s] for i, s in enumerate(seqs)}
clone_df = pd.DataFrame.from_dict(seqs_dict, orient = 'index')
for m, mut_dict in tqdm.tqdm(eval(f'self.mutations_dictionary_{num_mutations}.items()')):
for loc, muts in mut_dict.items():
mut_sub = clone_df[clone_df.loc[:, loc] == muts].loc[:, loc].dropna()
wts = [self.wt[i] for i in loc]
wt_sub = clone_df[clone_df.loc[:, loc] == wts].loc[:, loc].dropna()
for c in mut_sub.index:
seq = ''.join(clone_df.loc[c, :])
eval(f'self.mut_seqs_{num_mutations}[m].append(seq)')
for c in wt_sub.index:
seq = ''.join(clone_df.loc[c, :])
eval(f'self.wt_seqs_{num_mutations}[m].append(seq)')
if er_indecies is not None:
try:
eval(f'self.spearman_coefficients_{num_mutations}')
if recalculate:
raise ValueError
except:
#calculate spearman info
exec(f'self.spearman_coefficients_{num_mutations} = dict()')
for index in tqdm.tqdm(er_indecies):
exec(f'self.spearman_coefficients_{num_mutations}[self.er_order[index]] = dict()')
for m in tqdm.tqdm(eval(f'self.mutations_dictionary_{num_mutations}.keys()')):
data = {}
for seq in eval(f'self.mut_seqs_{num_mutations}[m]'):
try:
data[self.er[seq][index]][0] += 1
except:
data[self.er[seq][index]] = [1, 0]
for seq in eval(f'self.wt_seqs_{num_mutations}[m]'):
try:
data[self.er[seq][index]][1] += 1
except:
data[self.er[seq][index]] = [0, 1]
er_data = []
freq_data = []
for e, nums in data.items():
er_data.append(e)
freq_data.append(nums[0] / (sum(nums)))
exec(f'self.spearman_coefficients_{num_mutations}[self.er_order[index]][m] = list(spearmanr(er_data, freq_data))')
def process_seq_mut_analysis(self, product_entry):
seq = product_entry[0]
m = product_entry[1][0]
mut_dict = product_entry[1][1]
num_mutations = product_entry[2]
pbar = product_entry[3]
if hamming_distance(seq, self.wt) < num_mutations:
return
for loc, muts in mut_dict.items():
mut_count = 0
wt_count = 0
for i, l in enumerate(list(loc)):
if seq[int(l)] == muts[i]:
mut_count += 1
elif seq[int(l)] == self.wt[int(l)]:
wt_count += 1
if mut_count == num_mutations:
eval(f'self.mut_seqs_{num_mutations}[{m}].append(seq)')
elif wt_count == num_mutations:
eval(f'self.wt_seqs_{num_mutations}[{m}].append(seq)')
pbar.update(1)
def mutational_analysis_mp(self, num_mutations, sample_requirements = None, er_indecies = None, clone_set = None, threshold = 0, recalculate = False):
'''
Performs mutational analysis on a NGS_round_data class.
Code should be optimized. Specifically creating mut_seqs_dict and wt_seqs_dict. Could probably alter code to find which positions are different from wt
and only search mutation sets with the same differences. multiprocessing might also be added.
'''
#get locations of possible mutations
try:
eval(f'self.mutations_dictionary_{num_mutations}')
if recalculate:
raise ValueError
except:
mutation_str_length = len(self.wt)
mut_loc_dict = {i: loc for i, loc in enumerate(list(itertools.combinations(list(range(mutation_str_length)), num_mutations)))}
#create possible mutations dictionary -- Fast
mutation_number = 0
exec(f'self.mutations_dictionary_{num_mutations} = dict()')
for loc in tqdm.tqdm(mut_loc_dict.values()):
mutations_dictionary_subkey = ''
for i in loc:
mutations_dictionary_subkey += str(i) + ','
key_list = [i for i in mutations_dictionary_subkey.split(',') if i != '']
product_list = [self.mutations_dict[int(j)] for j in key_list]
possible_mutations = list(itertools.product(*product_list))
for m in possible_mutations:
exec(f'self.mutations_dictionary_{num_mutations}[{mutation_number}] = dict()')
exec(f'self.mutations_dictionary_{num_mutations}[{mutation_number}][{mutations_dictionary_subkey}] = {m}')
mutation_number += 1