-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1793 lines (1429 loc) · 71.3 KB
/
main.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
# -*- coding: utf-8 -*-
import numpy as np
import logging
import tempfile
import os
import shutil
import subprocess
import time
import xlsxwriter
import pandas as pd
from pathlib import Path
from datetime import datetime
from argparse import ArgumentParser, ArgumentTypeError
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise ArgumentTypeError('Boolean value expected.')
# project column name on sample sheet
# i have the bbmap directory symbolic path saved to /usr/local/bin
def parse_process_arrays_args(parser: ArgumentParser):
"""Parses the python script arguments from bash and makes sure files/inputs are valid"""
parser.add_argument('-r', '--run_id',
type=str,
help='Required: id for your run',
required=True)
parser.add_argument('-i', '--input_dir',
type=str,
help='Required: directory where your R1, R2 fastq (paired-end read) fastq files exist. This does not search Subdirectories',
required=True)
parser.add_argument('-g', '--genotyper_root_dir',
type=str,
help='Required: Directory full path of this repository',
required=True)
parser.add_argument('--output_dir',
type=str,
help='Optional: directory where your output_dir',
default=None,
required=False)
parser.add_argument('--experiment',
type=str,
help='Optional: Experiment Number if different from run_id, or will set as same',
default=None,
required=False)
parser.add_argument('--BBDUK_PATH',
type=str,
help='Optional: path where bbduk.sh is if not symbolically linked to bbduk.sh',
default='bbduk.sh',
required=False)
parser.add_argument('--STATS_PATH',
type=str,
help='Optional: path where bbduk.sh is if not symbolically linked to default stats.sh',
default='stats.sh',
required=False)
parser.add_argument('--BBMAP_PATH',
type=str,
help='Optional: path where bbduk.sh is if not symbolically linked to bbmap.sh',
default='bbmap.sh',
required=False)
parser.add_argument('--BBMERGE_PATH',
type=str,
help='Optional: path where bbduk.sh is if not symbolically linked to bbmerge.sh',
default='bbmerge.sh',
required=False)
parser.add_argument('--sample_sheet_path',
type=str,
help='Use full path if there is multiple .csv in your input_dir or if you have you samplesheet not in your input_dir',
default=None,
required=False)
parser.add_argument('--VSEARCH_PATH',
type=str,
help='Optional: path used to trigger vsearch',
default='vsearch',
required=False)
parser.add_argument('--project_column',
type=str,
help='Optional: if on your Sample_Project the column is not Sample_Project',
default='Sample_Project',
required=False)
parser.add_argument('--species_column',
type=str,
help='Optional: if on your sample sheet the Species column is not Species',
default='Species',
required=False)
def get_process_arrays_args():
""" Inputs arguments from bash
Gets the arguments, checks requirements, returns a dictionary of arguments
Return: args - Arguments as a dictionary
"""
parser = ArgumentParser()
parse_process_arrays_args(parser)
args = parser.parse_args()
return args
args = get_process_arrays_args()
EXPERIMENT = args.experiment
RUN_ID = args.run_id
if EXPERIMENT is None:
EXPERIMENT = RUN_ID
input_dir = args.input_dir
output_dir = args.output_dir
if output_dir is None:
output_dir = os.path.join(input_dir, 'out')
genotyper_root_dir=args.genotyper_root_dir
BBDUK_PATH = args.BBDUK_PATH
STATS_PATH = args.STATS_PATH
BBMAP_PATH = args.BBMAP_PATH
BBMERGE_PATH = args.BBMERGE_PATH
sample_path = args.sample_sheet_path
vsearch_path = args.VSEARCH_PATH
USEARCH_PATH = vsearch_path
species_column = args.species_column
project_column = args.project_column
project_list = [] # optional must be perfectly spelled and is case sensitve as on your sample sheet
if os.path.exists(input_dir):
print("Make sure fastq.gz and samplesheet (.csv) have been successfully copied: ")
print(input_dir)
else:
print("creat a input folder and copy fastq.gz and samplesheet (.csv) to it in the directory:")
print(input_dir)
raise ('INPUT FOLDER DOES NOT EXIST!')
file_list = os.listdir(input_dir)
fastq_list = [x for x in file_list if (x.endswith('.fastq.gz') or x.endswith('.fq.gz')) and not x.startswith('._')]
if sample_path is None:
sample_list = [x for x in file_list if x.endswith('.csv') and not x.startswith('._')]
if len(sample_list) > 1:
raise ('Too many .csv files in input older cannot determine samplesheet!')
elif len(sample_list) == 1:
sample_path = os.path.join(input_dir, sample_list[0])
print('Sample sheet path: {0}'.format(sample_path))
else:
print('NO SAMPLE SHEET FOUND')
raise ('INPUT FOLDER DOES NOT EXIST!')
else:
if not os.path.exists(sample_path):
raise ('Sample path declared does not exist, this needs to be a full path!')
"""# PIPELINE BEGINS: DO EDIT BELOW THIS SECTION!
## Output files:
### Dependencies
+ Jupyter Notebook/Jupyter Lab
+ Python 3 (tested on anaconda distribution of Python 3.6.4)
+ Access to dholk.primate.wisc.edu
+ pigz (in PATH)
+ bbmap (in PATH)
+ bbmerge (in PATH)
+ bbduk (in PATH)
+ DO NOT USE: USEARCH v10 (discontinued)
+ vsearch
+ ! wget https://github.com/torognes/vsearch/releases/download/v2.21.1/vsearch-2.21.1-linux-x86_64.tar.gz
+ Pandas (tested from anaconda distribution)
## Configure file paths"""
ref_dict = {
'REF': {
'MCM': os.path.join(genotyper_root_dir, 'ref/MCM_MHC-all_mRNA-MiSeq_singles-RENAME_20Jun16.fasta'),
'MAMU_04_21': os.path.join(genotyper_root_dir, 'ref/25533_ipd_miSeq_deduplicated_6Apr21.fasta'),
'MANE': os.path.join(genotyper_root_dir, 'ref/Mane_MiSeq-IPD_17.06.01_2.2.0.0_plus_SP_RW.fasta'),
'MAMU': os.path.join(genotyper_root_dir, 'ref/26128_ipd-mhc-mamu-2021-07-09.miseq.RWv4.fasta')
},
'PCR_PRIMERS': os.path.join(genotyper_root_dir, 'ref/SBT195_MHCII_primers_2Sep13.fasta')
}
"""# Results and cohort sorting intermediate input files structure
- The input files will be automatically moved by cohort. This is because the pivot tables are contructed by cohort and this will be one less step.
- they will go to <input_dir>/input_fq_by_cohort/*miseqnumber*/*cohort_name*
# split up main dir into different cohorts
- open the sample sheet
- look split by same cohorts
- mkdir for each cohort
- mv files to each by cohort
- use cyber duck's webdav to download the files from illumina
"""
# create nested dictionaries of dictionaries to support haplotyping against multiple haplotype definitions
### Indian rhesus ###
indian_rhesus = {'PREFIX': 'Mamu'}
# Indian rhesus MHC updated by Roger 24 August 2021
indian_rhesus['MHC_A_HAPLOTYPES'] = {
'A001.01': ['A1_001'],
'A002.01': ['A1_002_01'],
'A003.01': ['A1_003'],
'A004.01': ['A1_004'],
'A006.01': ['A1_006'],
'A007.01': ['A1_007'],
'A008.01': ['A1_008'],
'A011.01': ['A1_011'],
'A012.01': ['A1_012'],
'A016.01': ['A1_016'],
'A018.01': ['A1_018'],
'A018.02': ['A1_018', 'A2_01'],
'A019.01': ['A1_019'],
'A019.02': ['A1_019_11', 'A1_003'],
'A022.01': ['A1_022'],
'A023.01': ['A1_023'],
'A025.01': ['A1_025'],
'A026.01': ['A1_026'],
'A028.01': ['A1_028g'],
'A055.01': ['A1_055'],
'A074.01': ['A1_074'],
'A110-A111.01': ['A1_110_A1_111'],
'A224.01': ['A2_24', 'A1_003'],
}
indian_rhesus['MHC_B_HAPLOTYPES'] = {
'B001.01': ['B_001', 'B_007', 'B_030'],
'B001.03': ['B_001_02', 'B_094', 'B_095'],
'B002.01': ['B_002'],
'B008.01': ['B_008', 'B_006'],
'B012.01': ['B_012', 'B_030', 'B_082'],
'B012.02': ['B_012', 'B_022', 'B_030'],
'B012.03': ['B_012', 'B_022', 'B_030', 'B_031g'],
'B015.01': ['B_015g2', 'B_005g'],
'B015.02': ['B_015g2', 'B_068g1'],
'B015.03': ['B_015g2', 'B_031g', 'B_068g1'],
'B017.01': ['B_017', 'B_029'],
'B017.02': ['B_017', 'B_065', 'B_083'],
'B017.04': ['B_017', 'B_065', 'B_068', 'B_083'],
'B024.01': ['B_024', 'B_019'],
'B028.01': ['B_028', 'B_021'],
'B043.01': ['B_043', 'B_030'],
'B043.02': ['B_043', 'B_030', 'B_031_03', 'B_073'],
'B043.03': ['B_043', 'B_030', 'B_073'],
'B045.01': ['B_045', 'B_037'],
'B047.01': ['B_047'],
'B048.01': ['B_048', 'B_041'],
'B055.01': ['B_055', 'B_052', 'B_058'],
'B056.01': ['B_056', 'B_067'],
'B056.02': ['B_056', 'B_066', 'B_068'],
'B069.01': ['B_069', 'B_065'],
'B069.02': ['B_069', 'B_068', 'B_075'],
'B071.01': ['B_047_B_071', 'B_006'],
'B080.01': ['B_080', 'B_081'],
'B091.01': ['B_091', 'B_068'],
'B093.01': ['B_093'],
'B106.01': ['B_106', 'B_033'],
}
indian_rhesus['MHC_DRB_HAPLOTYPES'] = {
'DR01.01': ['DRB1_04_06_01', 'DRB5_03_01'],
'DR01.03': ['DRB1_04_11', 'DRB5_03_09'],
'DR01.04': ['DRB1_04_06_01', 'DRB5_03_09'],
'DR02.01': ['DRB3_04_03', 'DRB_W003_05'],
'DR03.01': ['DRB1_03_03_01', 'DRB1_10_07'],
'DR03.02': ['DRB1_03_12', 'DRB1_10_07'],
'DR03.03': ['DRB1_03_17', 'DRB1_10_08'],
'DR03.04': ['DRB1_03_18', 'DRB1_10_03'],
'DR03.05': ['DRB1_03_06', 'DRB1_10_07'],
'DR03.06': ['DRB1_03_06', 'DRB1_10_03'],
'DR03.07': ['DRB1_03_19', 'DRB1_10_03'],
'DR03.08': ['DRB1_03_03_01', 'DRB1_10_03'],
'DR03.09': ['DRB1_03_20', 'DRB1_10_02_02'],
'DR04.01': ['DRB1_03_09', 'DRB_W002_01'],
'DR04.02': ['DRB1_03_18', 'DRB_W002_01'],
'DR04.03': ['DRB1_03_09', 'DRB_W002_03'],
'DR05.01': ['DRB1_04_03', 'DRB_W005_01'],
'DR05.02': ['DRB1_04_03', 'DRB_W005_02'],
'DR06.01': ['DRB_W003_03', 'DRB_W004_01'],
'DR08.01': ['DRB_W028_01', 'DRB3_04_09', 'DRB5_03_07'],
'DR09.01': ['DRB1_04_04', 'DRB_W007_02_01', 'DRB_W003_07'],
'DR09.02': ['DRB1_04_08', 'DRB_W007_01'],
'DR10.01': ['DRB1_07_01', 'DRB3_04_05', 'DRB5_03_03'],
'DR10.02': ['DRB1_07_01', 'DRB3_04_05', 'DRB5_03_01'],
'DR11.01': ['DRB_W025_01'],
'DR11.02': ['DRB_W205_w_01'],
'DR11.03': ['DRB_W025_05', 'DRB1_07_04'],
'DR13.01': ['DRB1_03_18', 'DRB_W006_03', 'DRB_W006_04'],
'DR13.02': ['DRB1_03_18', 'DRB_W006_11', 'DRB_W006_04'],
'DR14.01': ['DRB3_04_10', 'DRB_W004_02', 'DRB_W027_01'],
'DR14.02': ['DRB3_04_10', 'DRB_W004_02', 'DRB_W027_02'],
'DR15.01/02': ['DRB_W006_06', 'DRB_W021_04', 'DRB_W026g'],
'DR15.03': ['DRB_W006_06', 'DRB_W021_04', 'DRB_W002_01'],
'DR16.01': ['DRB1_03_10', 'DRB_W001_01', 'DRB_W006_02', 'DRB_W006_09_01'],
'DR18.01': ['DRB4_01_02', 'DRB5_03_06'],
'DR28.01': ['DRB1_07g', 'DRB4_01_04', 'DRB_W102_01'],
'DR29.01': ['DRB1_10_11', 'DRB_W001_05'],
'DR30.01': ['DRB1_07_05', 'DRB_W002_03']
}
indian_rhesus['MHC_DQA_HAPLOTYPES'] = {
'01_02': ['DQA1_01_02'],
'01_07': ['DQA1_01_07'],
'01_09': ['DQA1_01_09'],
'01g1': ['DQA1_01g1'],
'01g2': ['DQA1_01g2'],
'01g3': ['DQA1_01g3'],
'01g4': ['DQA1_01g4'],
'05_01': ['DQA1_05_01'],
'05_02': ['DQA1_05_02'],
'05_03': ['DQA1_05_03'],
'05_04': ['DQA1_05_04'],
'05_05': ['DQA1_05_05'],
'05_06': ['DQA1_05_06'],
'05_07': ['DQA1_05_07'],
'23_01': ['DQA1_23_01'],
'23_02': ['DQA1_23_02'],
'23_03': ['DQA1_23_03'],
'24_02': ['DQA1_24_02'],
'24_04': ['DQA1_24_04'],
'24_08': ['DQA1_24_08'],
'24g1': ['DQA1_24g1'],
'24g2': ['DQA1_24g2'],
'26_01': ['DQA1_26_01'],
'26g1': ['DQA1_26g1'],
'26g2': ['DQA1_26g2']
}
indian_rhesus['MHC_DQB_HAPLOTYPES'] = {
'06_01': ['DQB1_06_01'],
'06_07': ['DQB1_06_07'],
'06_08': ['DQB1_06_08'],
'06_09': ['DQB1_06_09'],
'06_10': ['DQB1_06_10'],
'06_13_01': ['DQB1_06_13_01'],
'06g1': ['DQB1_06g1'],
'06g2': ['DQB1_06g2'],
'06g3': ['DQB1_06g3'],
'06g4': ['DQB1_06g4'],
'15_02': ['DQB1_15_02'],
'15g1': ['DQB1_15g1'],
'15g2': ['DQB1_15g2'],
'16_01': ['DQB1_16_01'],
'16_03': ['DQB1_16_03'],
'17_03': ['DQB1_17_03'],
'17g1': ['DQB1_17g1'],
'17g2': ['DQB1_17g2'],
'17g3': ['DQB1_17g3'],
'18_08': ['DQB1_18_08'],
'18_10': ['DQB1_18_10'],
'18_12': ['DQB1_18_12'],
'18_17': ['DQB1_18_17'],
'18_20': ['DQB1_18_20'],
'18_24': ['DQB1_18_24'],
'18g3': ['DQB1_18g3'],
'18g4': ['DQB1_18g4'],
'18g5': ['DQB1_18g5'],
'24_01': ['DQB1_24_01'],
'27g': ['DQB1_27g']
}
indian_rhesus['MHC_DPA_HAPLOTYPES'] = {
'02_03': ['DPA1_02_03'],
'02_08': ['DPA1_02_08'],
'02_13': ['DPA1_02_13'],
'02_14': ['DPA1_02_14'],
'02_15': ['DPA1_02_15'],
'02_16': ['DPA1_02_16'],
'02_20': ['DPA1_02_20'],
'02g1': ['DPA1_02g1'],
'02g2': ['DPA1_02g2'],
'02g3': ['DPA1_02g3'],
'02g4': ['DPA1_02g4'],
'04_01': ['DPA1_04_01'],
'04_04': ['DPA1_04_04'],
'04g': ['DPA1_04g'],
'06g': ['DPA1_06g'],
'07_01': ['DPA1_07_01'],
'07_04': ['DPA1_07_04'],
'07_09': ['DPA1_07_09'],
'07g1': ['DPA1_07g1'],
'07g2': ['DPA1_07g2'],
'07g3': ['DPA1_07g3'],
'08g': ['DPA1_08g'],
'09_01': ['DPA1_09_01'],
'10_01': ['DPA1_10_01'],
'11_01': ['DPA1_11_01']
}
indian_rhesus['MHC_DPB_HAPLOTYPES'] = {
'01g1': ['DPB1_01g1'],
'01g2': ['DPB1_01g2'],
'01g3': ['DPB1_01g3'],
'01g4': ['DPB1_01g4'],
'01g5': ['DPB1_01g5'],
'02_02': ['DPB1_02_02'],
'02g': ['DPB1_02g'],
'03g': ['DPB1_03g'],
'04_01': ['DPB1_04_01'],
'05_01': ['DPB1_05_01'],
'05_02': ['DPB1_05_02'],
'06_04': ['DPB1_06_04'],
'06g': ['DPB1_06g'],
'07g1': ['DPB1_07g1'],
'07g2': ['DPB1_07g2'],
'08_01': ['DPB1_08_01'],
'08_02': ['DPB1_08_02'],
'15_03': ['DPB1_15_03'],
'15g': ['DPB1_15g'],
'16_01': ['DPB1_16_01'],
'17_01': ['DPB1_17_01'],
'18_01': ['DPB1_18_01'],
'19_02': ['DPB1_19_02'],
'19_06': ['DPB1_19_06'],
'19g1': ['DPB1_19g1'],
'19g2': ['DPB1_19g2'],
'21_01': ['DPB1_21_01'],
'21_02': ['DPB1_21_02'],
'21_03': ['DPB1_21_03'],
'23_01': ['DPB1_23_01'],
'23_02': ['DPB1_23_02'],
'24_01': ['DPB1_24_01']
}
### Mauritian cynomolgus macaques ###
mcm = {'PREFIX': 'Mafa'}
# MCM MHC updated by Roger 29 May 2018
mcm['MHC_A_HAPLOTYPES'] = {
'M1A': ['05_M1M2M3_A1_063g', '07_M1M2_70_156bp', '11_M1_E_02g3|E_02_nov_09,_E_02_nov_10', '04_M1_AG_05_3mis_156bp'],
'M2A': ['05_M1M2M3_A1_063g', '07_M1M2_70_156bp', '02_M2_G_02_06_156bp'],
'M3A': ['05_M1M2M3_A1_063g', '07_M3_70_156bp'],
'M4A': ['05_M4_A1_031_01'],
'M5A': ['05_M5_A1_033_01'],
'M6A': ['05_M6_A1_032_01', '05_M6_A1_047_01'],
'M7A': ['05_M7_A1_060_05']
}
mcm['MHC_B_HAPLOTYPES'] = {
'M1B': ['12_M1_B_134_02', '12_M1_B_152_01N'],
'M2B': ['12_M2_B_019_03', '12_M2_B_150_01_01'],
'M3B': ['12_M3_B_165_01', '12_M3_B_075_01'],
'M4B': ['12_M4_B_088_01', '12_M4_B_127_nov_01'],
'M5B': ['12_M5_B_167_01N', '12_M5_B_051_04'],
'M6B': ['12_M6_B17_01_g103c', '12_M6_B_095_01'],
'M7B': ['12_M7_B_072_02', '12_M7_B_166_01']
}
mcm['MHC_DRB_HAPLOTYPES'] = {
'M1DR': ['13_M1_DRB_W21_01', '13_M1_DRB_W5_01'],
'M2DR': ['13_M2_DRB1_10_01', '13_M2_DRB_W4_02'],
'M3DR': ['13_M3_DRB1_10_02', '13_M3_DRB_W49_01_01'],
'M4DR': ['13_M4_DRB4_01_01'],
'M5DR': ['13_M5_DRB4_01_02'],
'M6DR': ['13_M6_DRB1_04_02_01', '13_M6_DRB_W4_01'],
'M7DR': ['13_M7_DRB_W1_03', '13_M7_DRB_W36_05']
}
mcm['MHC_DQA_HAPLOTYPES'] = {
'M1DQ': ['14_M1_DQB1_18_01_01'],
'M2DQ': ['14_M2_DQA1_01_04'],
'M3DQ': ['14_M3_DQB1_16_01', '14_M3_DQA1_05_03_01'],
'M4DQ': ['14_M4_DQB1_06_08', '14_M4_DQA1_01_07_01'],
'M5DQ': ['14_M5_DQA1_01_06', '14_M5_DQB1_06_11'],
'M6DQ': ['14_M6_DQA1_01_08_01'],
'M7DQ': ['14_M7_DQA1_23_01', '14_M7_DQB1_18_14']
}
mcm['MHC_DQB_HAPLOTYPES'] = {
'M1DQ': ['14_M1_DQB1_18_01_01'],
'M2DQ': ['14_M2_DQA1_01_04'],
'M3DQ': ['14_M3_DQB1_16_01', '14_M3_DQA1_05_03_01'],
'M4DQ': ['14_M4_DQB1_06_08', '14_M4_DQA1_01_07_01'],
'M5DQ': ['14_M5_DQA1_01_06', '14_M5_DQB1_06_11'],
'M6DQ': ['14_M6_DQA1_01_08_01'],
'M7DQ': ['14_M7_DQA1_23_01', '14_M7_DQB1_18_14']
}
mcm['MHC_DPA_HAPLOTYPES'] = {
'M1DP': ['15_M1_DPA1_07_02', '15_M1_DPB1_19_03'],
'M2DP': ['15_M2_DPA1_07_01', '15_M2_DPB1_20_01'],
'M3DP': ['15_M3_DPB1_09_02'],
'M4M7DP': ['15_M4M7_DPB1_03_03'],
'M5M6DP': ['15_M5M6_DPB1_04_01']
}
mcm['MHC_DPB_HAPLOTYPES'] = {
'M1DP': ['15_M1_DPA1_07_02', '15_M1_DPB1_19_03'],
'M2DP': ['15_M2_DPA1_07_01', '15_M2_DPB1_20_01'],
'M3DP': ['15_M3_DPB1_09_02'],
'M4M7DP': ['15_M4M7_DPB1_03_03'],
'M5M6DP': ['15_M5M6_DPB1_04_01']
}
haplotype_dict = {'MAMU': indian_rhesus, 'MCM': mcm, 'MANE': indian_rhesus}
"""## Genotype miSeq data against reference FASTA
This is a new implementation of the MHC genotyping pipeline. Considerations:
Current throughput is about 360 samples per hour (10 seconds per sample).
- Export to Excel similar to current format
- Jupyter Notebook for portability and reproducible data analysis. This is really important so we can distribute users' data and the full analysis of their results.
One possibly controversial decision in this algorithm is that I selectively include identical sequences that are found as a fraction of total reads. This runs the risk of losing some sequences that could potentially be informative. When making this decision, I thought a lot about lossless compression of music. There is a lot of discussion about whether lossy compression of music files (e.g., 320kb MP3 is distinguishable from lossless FLAC/ALAC (https://www.npr.org/sections/therecord/2015/06/02/411473508/how-well-can-you-hear-audio-quality). I think there is a parallel in MHC genotyping -- do we really need to know all MHC if they are present in very low abundance of cDNA? Could we improve genotyping by simply reporting those sequences that comprise a significant fraction of reads (set to 0.1% of total reads by default)? I would need to be convinced that this really helps.
## Dependencies
+ Jupyter Notebook/Jupyter Lab
+ Python 3 (tested on anaconda distribution of Python 3.6.4)
+ Access to dholk.primate.wisc.edu
+ pigz (in PATH)
+ bbmap (in PATH)
+ bbmerge (in PATH)
+ bbduk (in PATH)
+ USEARCH v10 (attempts automatic installation if not available)
+ Pandas (tested from anaconda distribution)
"""
# generic functions
log = logging.getLogger(__name__)
def print_status(status):
'''print timestamped status update'''
print('--[' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '] ' + status + '--')
log.info(status)
def create_temp_folder():
'''make temporary folder at specified location'''
TMP_DIR = tempfile.mkdtemp(dir=os.path.join(output_dir, 'TMP'))
return TMP_DIR
def close_temp_folder(tmp_dir):
'''destroy temporary folder after it is no longer used'''
os.removedirs(tmp_dir)
def create_output_folder(cwd):
'''create timestamped output folder at specified location'''
# fetch current time
CURRENT_TIME = datetime.now().strftime("%Y%m%d%H%M%S")
# path to output folder
OUTPUT_FOLDER = cwd + '/' + CURRENT_TIME
# create folder if it doesn't already exist
if not os.path.exists(OUTPUT_FOLDER):
os.makedirs(OUTPUT_FOLDER)
# print output folder name
print_status('Output folder: ' + OUTPUT_FOLDER)
return OUTPUT_FOLDER
def run_command(cmd_list, stdout_file=None, stderr_file=None):
'''run command with subprocess.call
if stdout or stderr arguments are passed, save to specified file
'''
import subprocess
print_status(' '.join(cmd_list)) # print status
# if neither stdout or stderr specified
if stdout_file is None and stderr_file is None:
print(cmd_list)
subprocess.call(cmd_list)
# if only stdout is specified
elif stdout_file is not None and stderr_file is None:
with open(stdout_file, 'w') as so:
subprocess.call(cmd_list, stdout=so)
# if only stderr is specified
elif stdout_file is None and stderr_file is not None:
with open(stderr_file, 'w') as se:
subprocess.call(cmd_list, stderr=se)
# if both stdout and stderr are specified
elif stdout_file is not None and stderr_file is not None:
with open(stdout_file, 'w') as so:
with open(stderr_file, 'w') as se:
subprocess.call(cmd_list, stdout=so, stderr=se)
else:
pass
def test_executable(cmd):
'''check that a particular command can be run as an executable'''
import shutil
assert shutil.which(cmd) is not None, 'Executable ' + cmd + ' cannot be run'
def get_notebook_path(out_dir):
'''get name of 20835-genotyping.ipynb file in current working directory
copy to output folder
'''
import os
import shutil
cwd = os.getcwd() # get working directory
notebook_path = cwd + '/26887-miseq-genotyping.ipynb'
# copy to output folder
shutil.copy2(notebook_path, out_dir + '/' + EXPERIMENT + '.ipynb')
def file_size(f):
'''return file size'''
import os
return os.stat(f).st_size
"""## Create data structure for paired-end reads
Make dictionary containing R1/R2 miSeq read pairs, alternative sample identifiers, and miSeq run IDs and uses sample names as the dictionary key. This should only cause problems if multiple samples with the same name are run in the same workflow invokation, which seems unlikely. The system requires gzip-FASTQ files and will abort if FASTQ files are not gzip-compressed. This is to protect users from themselves - having uncompressed FASTQ files in the filesystem is a quick way to fill hard drives. There _is_ an uncompressed, merged FASTQ file that gets generated in the temporary intermediate files; such files are necessary for USEARCH functionality.
As a convenience, animal identifiers and run information is downloaded directly from the dholk LabKey server. Data from every genotyping run should be in this system so I have built this workflow to deliberately break if the data isn't in LabKey. Just today (2018-05-25 --dho) I had to spend time scouring BaseSpace for miSeq files that weren't properly archived in our LabKey system. So it does not seem unreasonable to me to enforce correct usage of the miSeq LabKey system.
"""
def is_gz_file(filepath):
'''test if file is gzip-compressed
return True if gzip-compressed
source: https://stackoverflow.com/questions/3703276/how-to-tell-if-a-file-is-gzip-compressed
'''
import binascii
with open(filepath, 'rb') as test_f:
return binascii.hexlify(test_f.read(2)) == b'1f8b'
def get_read_dict(df_samples_i):
READS = {}
sample_list = list(df_samples_i['Sample_ID'].unique())
for sample_i in sample_list:
df_samples_j = df_samples_i[df_samples_i['Sample_ID'] == sample_i]
CLIENT_ID = list(df_samples_j['Sample_Name'])[0]
RUN_ID = list(df_samples_j['Run'])[0]
read_list = list(df_samples_j['FILEPATH'])
for filepath_i in read_list:
if 'R1' == filepath_i.split('_')[-2]:
R1 = filepath_i
break
for filepath_i in read_list:
if 'R2' == filepath_i.split('_')[-2]:
R2 = filepath_i
break
comments = ""
if "Comments" in df_samples_j.columns:
df_samples_j['Comments'] = df_samples_j['Comments'].astype(str)
comments = ';'.join(df_samples_j['Comments'].unique())
if comments == 'nan':
comments = ''
READS[sample_i] = [R1, R2, CLIENT_ID, RUN_ID, comments]
return READS
def decompress_fastq(reads):
'''decompress FASTQ file with pigz and return path to decompressed file'''
# ensure bbduk can be run from path
test_executable('pigz')
# command
decompress_fastq_cmd = ['pigz',
'-d',
'-k',
reads]
# run command
run_command(decompress_fastq_cmd)
# return path to decompressed file
return os.path.splitext(reads)[0]
def vsearch_unique(reads, out_dir):
# vsearch_path
# test_executable(vsearch_path)
READS_BN = [x for x in map(str.strip, (os.path.basename(reads)).split('.')) if x][0]
vsearch_unique_cmd = [vsearch_path,
'--fastx_uniques',
reads,
'--sizeout',
'--relabel',
'Uniq',
'--fastaout',
out_dir + '/' + READS_BN + '.unique.fasta', ]
# run command
run_command(vsearch_unique_cmd)
# test that output file exists before exiting function
assert os.path.exists(
out_dir + '/' + READS_BN + '.unique.fasta') == 1, out_dir + '/' + READS_BN + '.unique.fasta' + ' does not exist'
# return unique sequence FASTQ and total number of merged reads
return out_dir + '/' + READS_BN + '.unique.fasta'
def usearch_unique(reads, out_dir):
'''expect merged gzip-compressed FASTQ files
run clumpify'''
import os
# ensure bbduk can be run from path
test_executable(USEARCH_PATH)
# make sure FASTQ files exists
assert os.path.exists(reads) == 1, 'FASTQ file ' + reads + ' does not exist'
# get basename for reads
READS_BN = [x for x in map(str.strip, (os.path.basename(reads)).split('.')) if x][0]
# decompress FASTQ for use with USEARCH
READS_DECOMPRESSED = decompress_fastq(reads)
assert os.path.exists(READS_DECOMPRESSED) == 1, READS_DECOMPRESSED + ' does not exist'
# USEARCH unique command
usearch_unique_cmd = [USEARCH_PATH,
'-fastx_uniques',
READS_DECOMPRESSED,
'-sizeout',
'-relabel',
'Uniq',
'-fastaout',
out_dir + '/' + READS_BN + '.unique.fasta', ]
# run command
run_command(usearch_unique_cmd)
# test that output file exists before exiting function
assert os.path.exists(
out_dir + '/' + READS_BN + '.unique.fasta') == 1, out_dir + '/' + READS_BN + '.unique.fasta' + ' does not exist'
# return unique sequence FASTQ and total number of merged reads
return (out_dir + '/' + READS_BN + '.unique.fasta')
def vsearch_denoise(reads, read_ct, out_dir):
'''remove sequencing artifacts and chimeras by running UNOISE from the USEARCH package
Expects decompressed FASTA unique sequences created from fastx_uniques command
Preserves output sequences over a calculated minimum abundance
'''
import os
# ensure bbduk can be run from path
# test_executable(vsearch_path)
# make sure FASTA file exists
assert os.path.exists(reads) == 1, 'Unique FASTA file ' + reads + ' does not exist'
# get basename for reads
READS_BN = [x for x in map(str.strip, (os.path.basename(reads)).split('.')) if x][0]
# calculate UNOISE minuniquesize threshold
MIN_READS = str(calculate_threshold(min_freq=0.0002, reads=reads, read_ct=read_ct))
print("MINREADS: {0}".format(MIN_READS))
# if MIN_READS < 2 (as can happen for samples with low coverage, set MIN_READS = 2)
if int(MIN_READS) < 2:
MIN_READS = '2'
# USEARCH unoise command
# include only sequences greater than min_reads threshold
vsearch_unoise_cmd = [vsearch_path,
'--cluster_unoise',
reads,
'--minsize',
MIN_READS,
'--unoise_alpha',
'2',
'--centroids',
os.path.join(out_dir, READS_BN + '.unoise.fasta')]
# run command
run_command(vsearch_unoise_cmd)
# extract ZOTU sequences from unique FASTA
vsearch_chimera_cmd = [vsearch_path,
'--uchime_denovo',
os.path.join(out_dir, READS_BN + '.unoise.fasta'),
'--abskew',
'16',
'--nonchimeras',
os.path.join(out_dir, READS_BN + '.zotu_descriptive.fasta')]
# run command
run_command(vsearch_chimera_cmd, stdout_file=os.path.join(out_dir, 'stdout.txt'),
stderr_file=os.path.join(out_dir, 'stderr.txt'))
# test that output file exists before exiting function
assert os.path.exists(os.path.join(out_dir,
READS_BN + '.zotu_descriptive.fasta')) == 1, out_dir + '/' + READS_BN + '.zotu_descriptive.fasta' + ' does not exist'
# return unique sequence FASTQ and total number of merged reads
return os.path.join(out_dir, READS_BN + '.zotu_descriptive.fasta')
def parse_unoise_output(denoise_stats, zotu_tmp_fasta, reads_bn, out_dir):
'''UNOISE3 creates a new FASTA file without size annotations
Parse zotu stats file to add size annotations to zotus so read count is preserved
'''
import re
# make list of Zotu identifiers
descriptive_names = []
# read unoise_tabbed_output
with open(denoise_stats) as fp:
for line in fp:
if 'zotu' in line: # save only lines that correspond to zotus
descriptive_names.append(line.split("\t")[0]) # save descriptive name, such as Uniq413;size=9;
# read zotu_tmp_fasta
# replace non-informative Zotu name with descriptive name
ct = 0 # initialize counter
with open(out_dir + '/' + reads_bn + '.zotu_descriptive.fasta', 'w') as w: # save zotus to new file
with open(zotu_tmp_fasta) as fp:
for line in fp:
if '>' in line: # save only lines that correspond to zotus
w.write(re.sub('>Zotu[0-9]*', '>' + descriptive_names[ct], line)) # write descriptive fasta header
ct = ct + 1
else:
w.write(line) # write sequence lines as-is
return out_dir + '/' + reads_bn + '.zotu_descriptive.fasta'
def count_reads(reads):
'''count number of reads in a FASTQ/FASTA file
use bbmap stats.sh
return count as integer
'''
import subprocess
# path to stats.sh
# ensure stats.sh can be run from path
test_executable(STATS_PATH)
# make sure FASTQ input file exists
assert os.path.exists(reads) == 1, 'Read file ' + reads + ' does not exist'
# stats command
stats_cmd = [STATS_PATH,
'in=' + reads,
'format=4']
# run command
output = subprocess.check_output(stats_cmd).decode("utf-8")
# filter output
# get first entry on second line, which will always be sequence length
read_ct = (output.split('\n')[1]).split('\t')[0]
return int(read_ct)
def calculate_threshold(min_freq, reads, read_ct):
'''determine the -minuniquesize parameter for usearch unique
count number of reads in FASTQ file and then return threshold
0.001 would save unique sequences greater than 0.1% of all sequences in dataset'''
# multiply read threshold by read count
minuniquesize = int(min_freq * read_ct)
# return threshold and number of total reads)
return (minuniquesize)
"""## Remove primers with bbduk
Need to remove primer sequences from left and right ends of individual reads before merging. It is essential to do this in multiple steps (left-end trimming first; right end trimming second) to prevent removal of primers from incorrect locations within the sequences. The default k-mer size for bbduk is 50 so if this is not set to a number as small or smaller than the smallest PCR primer trimming will not work correctly.
"""
def remove_primers(R1, R2, primers, out_dir):
'''expect gzip-compressed R1 and R2 FASTQ files
run bbduk to remove primers
first remove from left end of sequence
then remove from right end of sequence
save results to temporary directory'''
import os
# path to bbduk
# ensure bbduk can be run from path
test_executable(BBDUK_PATH)
# make sure primer file exists
assert os.path.exists(primers) == 1, 'Specified primer file ' + primers + ' does not exist'
# get basename for R1 and R2
R1_BN = os.path.splitext(os.path.basename(R1))[0]
R2_BN = os.path.splitext(os.path.basename(R2))[0]
# trim from left
left_primer_cmd = [BBDUK_PATH,
'in=' + R1,
'in2=' + R2,
'ref=' + "'" + primers + "'",
'ktrim=l',
'k=15',
'restrictleft=30',
'out=' + out_dir + '/' + R1_BN + '_l.fastq.gz',
'out2=' + out_dir + '/' + R2_BN + '_l.fastq.gz']
# next trim from right
right_primer_cmd = [BBDUK_PATH,
'in=' + out_dir + '/' + R1_BN + '_l.fastq.gz',
'in2=' + out_dir + '/' + R2_BN + '_l.fastq.gz',
'ref=' + "'" + primers + "'",
'ktrim=r',
'restrictright=30',
'k=15',
'out=' + out_dir + '/' + R1_BN + '_lr.fastq.gz',
'out2=' + out_dir + '/' + R2_BN + '_lr.fastq.gz']
# run commands
run_command(left_primer_cmd)
# make sure output files from left primer trim exit
assert os.path.exists(
out_dir + '/' + R1_BN + '_l.fastq.gz') == 1, out_dir + '/' + R1_BN + '_l.fastq.gz' + ' does not exist'
assert os.path.exists(
out_dir + '/' + R2_BN + '_l.fastq.gz') == 1, out_dir + '/' + R2_BN + '_l.fastq.gz' + ' does not exist'
run_command(right_primer_cmd)
assert os.path.exists(
out_dir + '/' + R1_BN + '_lr.fastq.gz') == 1, out_dir + '/' + R1_BN + '_lr.fastq.gz' + ' does not exist'
assert os.path.exists(
out_dir + '/' + R2_BN + '_lr.fastq.gz') == 1, out_dir + '/' + R2_BN + '_lr.fastq.gz' + ' does not exist'
# return output files as tuple
return (out_dir + '/' + R1_BN + '_lr.fastq.gz', out_dir + '/' + R2_BN + '_lr.fastq.gz')
"""## Merge reads
After trimming, merge overlapping reads and use these merged reads for miSeq genotyping. bbmerge defaults are inconsistent when merging reads from longer amplicons (such as the 280bp MHC class II amplicons) that do not have a long overlap. Performance can be improved by first merging with the default parameters but then repeating merging after applying 3' trims of increasing stringency. Roger and I empirically tested different trim qualities up to 40 and discovered that performance does not improve beyond a trip of 30.
"""
def merge_reads(R1, R2, out_dir):
'''expect gzip-compressed R1 and R2 FASTQ files
run bbmerge'''
import os
# path to bbduk
# ensure bbduk can be run from path
test_executable(BBMERGE_PATH)
# make sure R1 and R2 files exists
assert os.path.exists(R1) == 1, 'R1 file ' + R1 + ' does not exist'
assert os.path.exists(R2) == 1, 'R1 file ' + R2 + ' does not exist'
# get basename for R1
R1_BN = [x for x in map(str.strip, (os.path.basename(R1)).split('.')) if x][0]