-
Notifications
You must be signed in to change notification settings - Fork 0
/
illumina.py
executable file
·1469 lines (1303 loc) · 65.2 KB
/
illumina.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
"""
Utilities for demultiplexing Illumina data.
"""
__author__ = "[email protected]"
__commands__ = []
import argparse
import logging
import os
import os.path
import re
import gc
import csv
import json
import sqlite3, itertools
import shutil
import subprocess
import tempfile
import xml.etree.ElementTree
from collections import defaultdict
import concurrent.futures
import arrow
import util.cmd
import util.file
import util.misc
import tools.picard
from util.illumina_indices import IlluminaIndexReference, IlluminaBarcodeHelper
log = logging.getLogger(__name__)
# =========================
# *** illumina_demux ***
# =========================
def parser_illumina_demux(parser=argparse.ArgumentParser()):
parser.add_argument('inDir', help='Illumina BCL directory (or tar.gz of BCL directory). This is the top-level run directory.')
parser.add_argument('lane', help='Lane number.', type=int)
parser.add_argument('outDir', help='Output directory for BAM files.')
parser.add_argument('--outMetrics',
help='Output ExtractIlluminaBarcodes metrics file. Default is to dump to a temp file.',
default=None)
parser.add_argument('--commonBarcodes',
help='''Write a TSV report of all barcode counts, in descending order.
Only applicable for read structures containing "B"''',
default=None)
parser.add_argument('--max_barcodes',
help='''Cap the commonBarcodes report length to this size (default: %(default)s)''',
default=10000, type=int)
parser.add_argument('--sampleSheet',
default=None,
help='''Override SampleSheet. Input tab or CSV file w/header and four named columns:
barcode_name, library_name, barcode_sequence_1, barcode_sequence_2.
Default is to look for a SampleSheet.csv in the inDir.''')
parser.add_argument('--runInfo',
default=None,
dest="runinfo",
help='''Override RunInfo. Input xml file.
Default is to look for a RunInfo.xml file in the inDir.''')
parser.add_argument('--flowcell', help='Override flowcell ID (default: read from RunInfo.xml).', default=None)
parser.add_argument('--read_structure',
help='Override read structure (default: read from RunInfo.xml).',
default=None)
parser.add_argument('--append_run_id',
help='If specified, output filenames will include the flowcell ID and lane number.',
action='store_true')
parser.add_argument('--out_meta_by_sample',
help='Output json metadata by sample',
default=None)
parser.add_argument('--out_meta_by_filename',
help='Output json metadata by bam file basename',
default=None)
parser.add_argument('--out_runinfo',
help='Output json metadata about the run',
default=None)
for opt in tools.picard.ExtractIlluminaBarcodesTool.option_list:
if opt not in ('read_structure', 'num_processors'):
parser.add_argument('--' + opt,
help='Picard ExtractIlluminaBarcodes ' + opt.upper() + ' (default: %(default)s)',
default=tools.picard.ExtractIlluminaBarcodesTool.defaults.get(opt))
for opt in tools.picard.IlluminaBasecallsToSamTool.option_list:
if opt == 'adapters_to_check':
parser.add_argument('--' + opt,
nargs='*',
help='Picard IlluminaBasecallsToSam ' + opt.upper() + ' (default: %(default)s)',
default=tools.picard.IlluminaBasecallsToSamTool.defaults.get(opt))
elif opt in ('read_structure', 'num_processors'):
pass
else:
parser.add_argument('--' + opt,
help='Picard IlluminaBasecallsToSam ' + opt.upper() + ' (default: %(default)s)',
default=tools.picard.IlluminaBasecallsToSamTool.defaults.get(opt))
parser.add_argument('--JVMmemory',
help='JVM virtual memory size (default: %(default)s)',
default=tools.picard.IlluminaBasecallsToSamTool.jvmMemDefault)
util.cmd.common_args(parser, (('threads', tools.picard.IlluminaBasecallsToSamTool.defaults['num_processors']), ('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_illumina_demux)
return parser
def main_illumina_demux(args):
''' Read Illumina runs & produce BAM files, demultiplexing to one bam per sample, or
for simplex runs, a single bam will be produced bearing the flowcell ID.
Wraps together Picard's ExtractBarcodes (for multiplexed samples) and IlluminaBasecallsToSam
while handling the various required input formats. Also can
read Illumina BCL directories, tar.gz BCL directories.
'''
# prepare
illumina = IlluminaDirectory(args.inDir)
illumina.load()
if args.runinfo:
runinfo = RunInfo(args.runinfo)
else:
runinfo = illumina.get_RunInfo()
if args.flowcell:
flowcell = args.flowcell
else:
flowcell = runinfo.get_flowcell()
if args.run_start_date:
run_date = args.run_start_date
else:
run_date = runinfo.get_rundate_american()
if args.read_structure:
read_structure = args.read_structure
else:
read_structure = runinfo.get_read_structure()
if args.append_run_id:
run_id = "{}.{}".format(flowcell, args.lane)
else:
run_id = None
if args.sampleSheet:
samples = SampleSheet(args.sampleSheet, only_lane=args.lane, append_run_id=run_id)
else:
samples = illumina.get_SampleSheet(only_lane=args.lane, append_run_id=run_id)
link_locs=False
# For HiSeq-4000/X runs, If Picard's CheckIlluminaDirectory is
# called with LINK_LOCS=true, symlinks with absolute paths
# may be created, pointing from tile-specific *.locs to the
# single s.locs file in the Intensities directory.
# These links may break if the run directory is moved.
# We should begin by removing broken links, if present,
# and call CheckIlluminaDirectory ourselves if a 's.locs'
# file is present, but only if the directory check fails
# since link_locs=true tries to create symlinks even if they
# (or the files) already exist
try:
tools.picard.CheckIlluminaDirectoryTool().execute(
illumina.get_BCLdir(),
args.lane,
read_structure,
link_locs=link_locs
)
except subprocess.CalledProcessError as e:
log.warning("CheckIlluminaDirectory failed for %s", illumina.get_BCLdir())
if os.path.exists(os.path.join(illumina.get_intensities_dir(), "s.locs")):
# recurse to remove broken links in directory
log.info("This run has an 's.locs' file; checking for and removing broken per-tile symlinks...")
broken_links = util.file.find_broken_symlinks(illumina.get_intensities_dir())
if len(broken_links):
for lpath in broken_links:
log.info("Removing broken symlink: %s", lpath)
os.unlink(lpath)
# call CheckIlluminaDirectory with LINK_LOCS=true
link_locs=True
log.info("Checking run directory with Picard...")
tools.picard.CheckIlluminaDirectoryTool().execute(
illumina.get_BCLdir(),
args.lane,
read_structure,
link_locs=link_locs
)
else:
log.error("CheckIlluminaDirectory failed for %s", illumina.get_BCLdir())
multiplexed_samples = True if 'B' in read_structure else False
if multiplexed_samples:
assert samples is not None, "This looks like a multiplexed run since 'B' is in the read_structure: a SampleSheet must be given."
else:
assert samples==None, "A SampleSheet may not be provided unless 'B' is present in the read_structure"
if args.commonBarcodes:
log.warning("--commonBarcodes was set but 'B' is not present in the read_structure; emitting an empty file.")
util.file.touch(args.commonBarcodes)
# B in read structure indicates barcoded multiplexed samples
if multiplexed_samples:
# Picard ExtractIlluminaBarcodes
extract_input = util.file.mkstempfname('.txt', prefix='.'.join(['barcodeData', flowcell, str(args.lane)]))
barcodes_tmpdir = tempfile.mkdtemp(prefix='extracted_barcodes-')
samples.make_barcodes_file(extract_input)
out_metrics = (args.outMetrics is None) and util.file.mkstempfname('.metrics.txt') or args.outMetrics
picardOpts = dict((opt, getattr(args, opt)) for opt in tools.picard.ExtractIlluminaBarcodesTool.option_list
if hasattr(args, opt) and getattr(args, opt) != None)
picardOpts['read_structure'] = read_structure
tools.picard.ExtractIlluminaBarcodesTool().execute(
illumina.get_BCLdir(),
args.lane,
extract_input,
barcodes_tmpdir,
out_metrics,
picardOptions=picardOpts,
JVMmemory=args.JVMmemory)
if args.commonBarcodes:
barcode_lengths = re.findall(r'(\d+)B',read_structure)
try:
barcode1_len=int(barcode_lengths[0])
except IndexError:
barcode1_len = 0
try:
barcode2_len=int(barcode_lengths[1])
except IndexError:
barcode2_len = 0
# this step can take > 2 hours on a large high-output flowcell
# so kick it to the background while we demux
#count_and_sort_barcodes(barcodes_tmpdir, args.commonBarcodes)
executor = concurrent.futures.ProcessPoolExecutor()
executor.submit(count_and_sort_barcodes, barcodes_tmpdir, args.commonBarcodes, barcode1_len, barcode2_len, truncateToLength=args.max_barcodes, threads=util.misc.sanitize_thread_count(args.threads))
# Picard IlluminaBasecallsToSam
basecalls_input = util.file.mkstempfname('.txt', prefix='.'.join(['library_params', flowcell, str(args.lane)]))
samples.make_params_file(args.outDir, basecalls_input)
picardOpts = dict((opt, getattr(args, opt)) for opt in tools.picard.IlluminaBasecallsToSamTool.option_list
if hasattr(args, opt) and getattr(args, opt) != None)
picardOpts['run_start_date'] = run_date
picardOpts['read_structure'] = read_structure
if args.threads:
picardOpts['num_processors'] = args.threads
if not picardOpts.get('sequencing_center') and runinfo:
picardOpts['sequencing_center'] = runinfo.get_machine()
if picardOpts.get('sequencing_center'):
picardOpts["sequencing_center"] = util.file.string_to_file_name(picardOpts["sequencing_center"])
if args.out_runinfo:
with open(args.out_runinfo, 'wt') as outf:
json.dump({
'sequencing_center':picardOpts['sequencing_center'],
'run_start_date':runinfo.get_rundate_iso(),
'read_structure':picardOpts['read_structure'],
'indexes':str(samples.indexes),
'run_id':runinfo.get_run_id(),
'lane':str(args.lane),
'flowcell':str(runinfo.get_flowcell()),
'lane_count':str(runinfo.get_lane_count()),
'surface_count':str(runinfo.get_surface_count()),
'swath_count':str(runinfo.get_swath_count()),
'tile_count':str(runinfo.get_tile_count()),
'total_tile_count':str(runinfo.tile_count()),
'sequencer_model':runinfo.get_machine_model(),
}, outf, indent=2)
# manually garbage collect to make sure we have as much RAM free as possible
gc.collect()
if multiplexed_samples:
tools.picard.IlluminaBasecallsToSamTool().execute(
illumina.get_BCLdir(),
barcodes_tmpdir,
flowcell,
args.lane,
basecalls_input,
picardOptions=picardOpts,
JVMmemory=args.JVMmemory)
# organize samplesheet metadata as json
sample_meta = list(samples.get_rows())
for row in sample_meta:
row['lane'] = str(args.lane)
if args.out_meta_by_sample:
with open(args.out_meta_by_sample, 'wt') as outf:
json.dump(dict((r['sample'],r) for r in sample_meta), outf, indent=2)
if args.out_meta_by_filename:
with open(args.out_meta_by_filename, 'wt') as outf:
json.dump(dict((r['run'],r) for r in sample_meta), outf, indent=2)
else:
tools.picard.IlluminaBasecallsToSamTool().execute_single_sample(
illumina.get_BCLdir(),
os.path.join(args.outDir,flowcell+".bam"),
flowcell,
args.lane,
flowcell,
picardOptions=picardOpts,
JVMmemory=args.JVMmemory)
# clean up
if multiplexed_samples:
if args.commonBarcodes:
log.info("waiting for commonBarcodes output to finish...")
executor.shutdown(wait=True)
os.unlink(extract_input)
os.unlink(basecalls_input)
shutil.rmtree(barcodes_tmpdir)
illumina.close()
log.info("illumina_demux complete")
return 0
__commands__.append(('illumina_demux', parser_illumina_demux))
# ==========================
# *** flowcell_metadata ***
# ==========================
def parser_flowcell_metadata(parser=argparse.ArgumentParser()):
parser.add_argument('outMetadataFile', help='path of file to which metadata will be written.')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--inDir', dest="in_dir", help='Illumina BCL directory (or tar.gz of BCL directory). This is the top-level run directory.', default=None)
group.add_argument('--runInfo',
default=None,
dest="run_info",
help='''RunInfo.xml file.''')
group.add_argument('--flowcellID', dest="flowcell_id", help='flowcell ID (default: read from RunInfo.xml).', default=None)
util.cmd.common_args(parser, (('threads', tools.picard.IlluminaBasecallsToSamTool.defaults['num_processors']), ('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_flowcell_metadata)
return parser
def main_flowcell_metadata(args):
''' Writes run metadata to a file
'''
if args.flowcell_id:
machine_matches = RunInfo.get_machines_for_flowcell_id(args.flowcell_id)
machine_match = None
if len(machine_matches)>1:
raise LookupError("Multiple sequencers found for flowcell ID: %s" % " ".join([m["machine"] for m in machine_matches]))
if len(machine_matches)==0:
raise LookupError("No sequencers found for flowcell ID '%s' " % args.flowcell_id)
machine_match = machine_matches[0]
if args.run_info:
runinfo = RunInfo(args.run_info)
machine_match = runinfo.infer_sequencer_model()
if args.in_dir:
illumina = IlluminaDirectory(args.in_dir)
illumina.load()
runinfo = illumina.get_RunInfo()
machine_match = runinfo.infer_sequencer_model()
with open(args.outMetadataFile,"w") as outf:
for k,v in machine_match.items():
if type(v)==str and len(v)>0 or type(v)!=str:
outline = "{k}\t{v}\n".format(k=k,v=v)
print(outline,end="")
outf.writelines([outline])
__commands__.append(('flowcell_metadata', parser_flowcell_metadata))
# ==========================
# *** lane_metrics ***
# ==========================
def parser_lane_metrics(parser=argparse.ArgumentParser()):
parser.add_argument('inDir', help='Illumina BCL directory (or tar.gz of BCL directory). This is the top-level run directory.')
parser.add_argument('outPrefix', help='''Prefix path to the *.illumina_lane_metrics and *.illumina_phasing_metrics files.''')
parser.add_argument('--read_structure',
help='Override read structure (default: read from RunInfo.xml).',
default=None)
parser.add_argument('--JVMmemory',
help='JVM virtual memory size (default: %(default)s)',
default=tools.picard.ExtractIlluminaBarcodesTool.jvmMemDefault)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_lane_metrics)
return parser
def main_lane_metrics(args):
'''
Write out lane metrics to a tsv file.
'''
# prepare
illumina = IlluminaDirectory(args.inDir)
illumina.load()
if args.read_structure:
read_structure = args.read_structure
else:
read_structure = illumina.get_RunInfo().get_read_structure()
# Picard CollectIlluminaLaneMetrics
output_dir = os.path.dirname(os.path.realpath(args.outPrefix))
output_prefix = os.path.basename(os.path.realpath(args.outPrefix))
picardOpts = dict((opt, getattr(args, opt)) for opt in tools.picard.CollectIlluminaLaneMetricsTool.option_list
if hasattr(args, opt) and getattr(args, opt) != None)
picardOpts['read_structure'] = read_structure
tools.picard.CollectIlluminaLaneMetricsTool().execute(
illumina.path,
output_dir,
output_prefix,
picardOptions=picardOpts,
JVMmemory=args.JVMmemory)
illumina.close()
return 0
__commands__.append(('lane_metrics', parser_lane_metrics))
# ==========================
# *** common_barcodes ***
# ==========================
def parser_common_barcodes(parser=argparse.ArgumentParser()):
parser.add_argument('inDir', help='Illumina BCL directory (or tar.gz of BCL directory). This is the top-level run directory.')
parser.add_argument('lane', help='Lane number.', type=int)
parser.add_argument('outSummary', help='''Path to the summary file (.tsv format). It includes several columns:
(barcode1, likely_index_name1, barcode2, likely_index_name2, count),
where likely index names are either the exact match index name for the barcode
sequence, or those Hamming distance of 1 away.''')
parser.add_argument('--truncateToLength',
help='If specified, only this number of barcodes will be returned. Useful if you only want the top N barcodes.',
type=int,
default=None)
parser.add_argument('--omitHeader',
help='If specified, a header will not be added to the outSummary tsv file.',
action='store_true')
parser.add_argument('--includeNoise',
help='If specified, barcodes with periods (".") will be included.',
action='store_true')
parser.add_argument('--outMetrics',
help='Output ExtractIlluminaBarcodes metrics file. Default is to dump to a temp file.',
default=None)
parser.add_argument('--sampleSheet',
default=None,
help='''Override SampleSheet. Input tab or CSV file w/header and four named columns:
barcode_name, library_name, barcode_sequence_1, barcode_sequence_2.
Default is to look for a SampleSheet.csv in the inDir.''')
parser.add_argument('--flowcell', help='Override flowcell ID (default: read from RunInfo.xml).', default=None)
parser.add_argument('--read_structure',
help='Override read structure (default: read from RunInfo.xml).',
default=None)
for opt in tools.picard.ExtractIlluminaBarcodesTool.option_list:
if opt not in ('read_structure', 'num_processors'):
parser.add_argument('--' + opt,
help='Picard ExtractIlluminaBarcodes ' + opt.upper() + ' (default: %(default)s)',
default=tools.picard.ExtractIlluminaBarcodesTool.defaults.get(opt))
parser.add_argument('--JVMmemory',
help='JVM virtual memory size (default: %(default)s)',
default=tools.picard.ExtractIlluminaBarcodesTool.jvmMemDefault)
util.cmd.common_args(parser, (('threads',None), ('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_common_barcodes)
return parser
def main_common_barcodes(args):
'''
Extract Illumina barcodes for a run and write a TSV report
of the barcode counts in descending order
'''
# prepare
illumina = IlluminaDirectory(args.inDir)
illumina.load()
if args.flowcell:
flowcell = args.flowcell
else:
flowcell = illumina.get_RunInfo().get_flowcell()
if args.read_structure:
read_structure = args.read_structure
else:
read_structure = illumina.get_RunInfo().get_read_structure()
if args.sampleSheet:
samples = SampleSheet(args.sampleSheet, only_lane=args.lane)
else:
samples = illumina.get_SampleSheet(only_lane=args.lane)
# Picard ExtractIlluminaBarcodes
barcode_file = util.file.mkstempfname('.txt', prefix='.'.join(['barcodeData', flowcell, str(args.lane)]))
barcodes_tmpdir = tempfile.mkdtemp(prefix='extracted_barcodes-')
samples.make_barcodes_file(barcode_file)
out_metrics = (args.outMetrics is None) and util.file.mkstempfname('.metrics.txt') or args.outMetrics
picardOpts = dict((opt, getattr(args, opt)) for opt in tools.picard.ExtractIlluminaBarcodesTool.option_list
if hasattr(args, opt) and getattr(args, opt) != None)
picardOpts['read_structure'] = read_structure
tools.picard.ExtractIlluminaBarcodesTool().execute(
illumina.get_BCLdir(),
args.lane,
barcode_file,
barcodes_tmpdir,
out_metrics,
picardOptions=picardOpts,
JVMmemory=args.JVMmemory)
barcode_lengths = re.findall(r'(\d+)B',read_structure)
try:
barcode1_len=int(barcode_lengths[0])
except IndexError:
barcode1_len = 0
try:
barcode2_len=int(barcode_lengths[1])
except IndexError:
barcode2_len = 0
count_and_sort_barcodes(barcodes_tmpdir, args.outSummary, barcode1_len, barcode2_len, args.truncateToLength, args.includeNoise, args.omitHeader, args.threads)
# clean up
os.unlink(barcode_file)
shutil.rmtree(barcodes_tmpdir)
illumina.close()
return 0
__commands__.append(('common_barcodes', parser_common_barcodes))
def count_and_sort_barcodes(barcodes_dir, outSummary, barcode1_len=8, barcode2_len=8, truncateToLength=None, includeNoise=False, omitHeader=False, threads=None):
# collect the barcode file paths for all tiles
tile_barcode_files = [os.path.join(barcodes_dir, filename) for filename in os.listdir(barcodes_dir)]
# count all of the barcodes present in the tile files
log.info("reading barcodes in all tile files")
with util.file.CountDB() as reduce_db:
barcodefile_tempfile_tuples = [(tile_barcode_file,util.file.mkstempfname('sqlite_.db')) for tile_barcode_file in tile_barcode_files]
# scatter tile-specific barcode files among workers to store barcode counts in SQLite
workers = util.misc.sanitize_thread_count(threads)
with concurrent.futures.ProcessPoolExecutor(max_workers=workers) as executor:
futures = [executor.submit(util.file.count_occurrences_in_tsv_sqlite_backed, tf, bf, include_noise=includeNoise) for bf,tf in barcodefile_tempfile_tuples]
for future in concurrent.futures.as_completed(futures):
tmp_db, barcode_file = future.result()
log.debug("done reading barcodes from %s; adding to total...",barcode_file)
# gather and reduce counts from separate SQLite databases into one
reduce_db.add_counts_from_other_db(tmp_db)
os.unlink(tmp_db)
illumina_reference = IlluminaIndexReference()
log.info("Number of barcodes seen %s",reduce_db.get_num_IDS())
# write the barcodes and their corresponding counts
with open(outSummary, 'w') as tsvfile:
log.info("sorting counts...")
log.info("writing output...")
writer = csv.writer(tsvfile, delimiter='\t')
# write the header unless the user has specified not to do so
if not omitHeader:
writer.writerow(("Barcode1", "Likely_Index_Names1", "Barcode2", "Likely_Index_Names2", "Count"))
for num_processed,row in enumerate(reduce_db.get_counts_descending()):
if truncateToLength and num_processed>truncateToLength:
break
barcode,count = row
writer.writerow((barcode[:barcode1_len], ",".join([x for x in illumina_reference.guess_index(barcode[:barcode1_len], distance=1)] or ["Unknown"]),
barcode[barcode1_len:len(barcode)], ",".join([x for x in illumina_reference.guess_index(barcode[barcode1_len:len(barcode)], distance=1)] or ["Unknown"]),
count))
if num_processed%50000==0:
log.debug("written %s barcode summaries to output file",num_processed)
log.info("done")
# ======================================
# *** guess_low-abundance_barcodes ***
# ======================================
def parser_guess_barcodes(parser=argparse.ArgumentParser()):
parser.add_argument('in_barcodes', help='The barcode counts file produced by common_barcodes.')
parser.add_argument('in_picard_metrics', help='The demultiplexing read metrics produced by Picard.')
parser.add_argument('out_summary_tsv', help='''Path to the summary file (.tsv format). It includes several columns:
(sample_name, expected_barcode_1, expected_barcode_2,
expected_barcode_1_name, expected_barcode_2_name,
expected_barcodes_read_count, guessed_barcode_1,
guessed_barcode_2, guessed_barcode_1_name,
guessed_barcode_2_name, guessed_barcodes_read_count,
match_type),
where the expected values are those used by Picard during demultiplexing
and the guessed values are based on the barcodes seen among the data.''')
group = parser.add_mutually_exclusive_group()
group.add_argument('--readcount_threshold',
default=None,
type=int,
help='''If specified, guess barcodes for samples with fewer than this many reads.''')
group.add_argument('--sample_names',
nargs='*',
help='If specified, only guess barcodes for these sample names.',
type=str,
default=None)
parser.add_argument('--outlier_threshold',
help='threshold of how far from unbalanced a sample must be to be considered an outlier.',
type=float,
default=0.775)
parser.add_argument('--expected_assigned_fraction',
help='The fraction of reads expected to be assigned. An exception is raised if fewer than this fraction are assigned.',
type=float,
default=0.7)
group2 = parser.add_mutually_exclusive_group()
group2.add_argument('--number_of_negative_controls',
help='If specified, the number of negative controls in the pool, for calculating expected number of reads in the rest of the pool.',
type=int)
group2.add_argument('--neg_control_prefixes',
nargs='+',
help='If specified, the sample name prefixes assumed for counting negative controls. Case-insensitive.',
type=str,
default=["neg", "water", "NTC", "H2O"])
parser.add_argument('--rows_limit',
default=1000,
type=int,
help='''The number of rows to use from the in_barcodes.''')
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_guess_barcodes, split_args=True)
return parser
def main_guess_barcodes(in_barcodes,
in_picard_metrics,
out_summary_tsv,
sample_names,
outlier_threshold,
expected_assigned_fraction,
number_of_negative_controls,
readcount_threshold,
rows_limit,
neg_control_prefixes):
"""
Guess the barcode value for a sample name,
based on the following:
- a list is made of novel barcode pairs seen in the data, but not in the picard metrics
- for the sample in question, get the most abundant novel barcode pair where one of the
barcodes seen in the data matches one of the barcodes in the picard metrics (partial match)
- if there are no partial matches, get the most abundant novel barcode pair
Limitations:
- If multiple samples share a barcode with multiple novel barcodes, disentangling them
is difficult or impossible
The names of samples to guess are selected:
- explicitly by name, passed via argument, OR
- explicitly by read count threshold, OR
- automatically (if names or count threshold are omitted)
based on basic outlier detection of deviation from an assumed-balanced pool with
some number of negative controls
"""
bh = util.illumina_indices.IlluminaBarcodeHelper(in_barcodes, in_picard_metrics, rows_limit)
guessed_barcodes = bh.find_uncertain_barcodes(sample_names=sample_names,
outlier_threshold=outlier_threshold,
expected_assigned_fraction=expected_assigned_fraction,
number_of_negative_controls=number_of_negative_controls,
readcount_threshold=readcount_threshold,
neg_control_prefixes=neg_control_prefixes)
bh.write_guessed_barcodes(out_summary_tsv, guessed_barcodes)
__commands__.append(('guess_barcodes', parser_guess_barcodes))
# ============================
# *** IlluminaDirectory ***
# ============================
class IlluminaDirectory(object):
''' A class that handles Illumina data directories
'''
def __init__(self, uri):
self.uri = uri
self.path = None
self.tempDir = None
self.runinfo = None
self.samplesheet = None
def __enter__(self):
self.load()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return 0
def load(self):
if self.path is None:
if '://' in self.uri:
raise NotImplementedError('boto s3 download here uri -> tarball')
# tarball = util.file.mkstempfname('.tar.gz')
# # TODO: download here, uri -> tarball
# self._extract_tarball(tarball)
# os.unlink(tarball)
else:
if os.path.isdir(self.uri):
self.path = self.uri
else:
self._extract_tarball(self.uri)
self._fix_path()
def _fix_path(self):
assert self.path is not None
# this is not the correct root-level directory
# sometimes this points to one level up
while True:
if os.path.isdir(os.path.join(self.path, 'Data', 'Intensities', 'BaseCalls')):
# found it! self.path is correct
break
else:
subdirs = list(os.path.join(self.path, x) for x in os.listdir(self.path)
if os.path.isdir(os.path.join(self.path, x)))
if len(subdirs) == 1:
# follow the rabbit hole
self.path = subdirs[0]
else:
# don't know where to go now!
raise Exception('cannot find Data/Intensities/BaseCalls/ inside %s (%s)' % (self.uri, self.path))
def _extract_tarball(self, tarfile):
self.tempDir = tempfile.mkdtemp(prefix='IlluminaDirectory-')
self.path = self.tempDir
util.file.extract_tarball(tarfile, self.tempDir)
def close(self):
if self.tempDir:
shutil.rmtree(self.tempDir)
self.tempDir = None
def get_RunInfo(self):
if self.runinfo is None:
runinfo_file = os.path.join(self.path, 'RunInfo.xml')
util.file.check_paths(runinfo_file)
self.runinfo = RunInfo(runinfo_file)
return self.runinfo
def get_SampleSheet(self, only_lane=None, append_run_id=None):
if self.samplesheet is None:
samplesheet_file = os.path.join(self.path, 'SampleSheet.csv')
util.file.check_paths(samplesheet_file)
self.samplesheet = SampleSheet(samplesheet_file, only_lane=only_lane, append_run_id=append_run_id)
return self.samplesheet
def get_intensities_dir(self):
return os.path.join(self.path, 'Data', 'Intensities')
def get_BCLdir(self):
return os.path.join(self.get_intensities_dir(), 'BaseCalls')
# ==================
# *** RunInfo ***
# ==================
class RunInfo(object):
''' A class that reads the RunInfo.xml file emitted by Illumina
MiSeq and HiSeq machines.
'''
def __init__(self, xml_fname):
self.fname = xml_fname
self.root = xml.etree.ElementTree.parse(xml_fname).getroot()
def get_fname(self):
return self.fname
def get_run_id(self):
return self.root[0].attrib['Id']
def get_flowcell_raw(self):
return self.root[0].find('Flowcell').text
def get_flowcell(self):
fc = self.get_flowcell_raw()
# slice in the case where the ID has a prefix of zeros
if re.match(r"^0+-", fc):
if '-' in fc:
# miseq often adds a bunch of leading zeros and a dash in front
fc = "-".join(fc.split('-')[1:])
# >=5 to avoid an exception here: https://github.com/broadinstitute/picard/blob/2.17.6/src/main/java/picard/illumina/IlluminaBasecallsToSam.java#L510
# <= 15 to limit the bytes added to each bam record
assert len(fc) >= 5,"The flowcell ID must be five or more characters in length"
if len(fc) > 15:
log.warning("The provided flowcell ID is longer than 15 characters. Is that correct?")
return fc
def _get_rundate_obj(self):
"""
Access the text of the <Date> node in the RunInfo.xml file
and returns an arrow date object.
"""
rundate = self.root[0].find('Date').text
# possible formats found in RunInfo.xml:
# "170712" (YYMMDD)
# "20170712" (YYYYMMDD)
# "6/27/2018 4:59:20 PM" (M/D/YYYY h:mm:ss A)
# "2021-04-21T20:48:39Z" (YYYY-MM-DDTHH:mm:ssZ) [seen on NextSeq 2000]
datestring_formats = [
"YYMMDD",
"YYYYMMDD",
"M/D/YYYY h:mm:ss A",
"YYYY-MM-DDTHH:mm:ssZ"
]
for datestring_format in datestring_formats:
try:
date_parsed = arrow.get(rundate, datestring_format)
return date_parsed
except arrow.parser.ParserError:
pass
raise arrow.parser.ParserError("The date string seen in RunInfo.xml ('%s') did not match known Illumina formats: %s" % (rundate,datestring_formats) )
def get_rundate_american(self):
return str(self._get_rundate_obj().format("MM/DD/YYYY"))
def get_rundate_iso(self):
return str(self._get_rundate_obj().format("YYYY-MM-DD"))
def get_machine(self):
return self.root[0].find('Instrument').text
def get_read_structure(self):
reads = []
for x in self.root[0].find('Reads').findall('Read'):
order = int(x.attrib['Number'])
read = x.attrib['NumCycles'] + (x.attrib['IsIndexedRead'] == 'Y' and 'B' or 'T')
reads.append((order, read))
return ''.join([r for _, r in sorted(reads)])
def num_reads(self):
return sum(1 for x in self.root[0].find('Reads').findall('Read') if x.attrib['IsIndexedRead'] == 'N')
def get_lane_count(self):
layout = self.root[0].find('FlowcellLayout')
return int(layout.attrib['LaneCount'])
def get_surface_count(self):
layout = self.root[0].find('FlowcellLayout')
return int(layout.attrib['SurfaceCount'])
def get_swath_count(self):
layout = self.root[0].find('FlowcellLayout')
return int(layout.attrib['SwathCount'])
def get_tile_count(self):
layout = self.root[0].find('FlowcellLayout')
return int(layout.attrib['TileCount'])
def get_section_count(self):
layout = self.root[0].find('FlowcellLayout')
# not ever flowcell type has sections but some do (ex. NextSeq 550 does)
# return 1 in the event it's not listed in the RunInfo.xml file
return int(layout.attrib.get('SectionPerLane',1))
def tile_count(self):
lane_count = self.get_lane_count()
surface_count = self.get_surface_count()
swath_count = self.get_swath_count()
tile_count = self.get_tile_count()
section_count = self.get_section_count()
total_tile_count = lane_count*surface_count*swath_count*tile_count*section_count
return total_tile_count
def machine_model_from_tile_count(self):
"""
Return machine name and lane count based on tile count
Machine names aim to conform to the NCBI SRA controlled
vocabulary for Illumina sequencers available here:
https://www.ncbi.nlm.nih.gov/viewvc/v1/trunk/sra/doc/SRA_1-5/SRA.common.xsd?view=co&content-type=text%2Fplain
"""
tc = self.tile_count()
machine=None
if tc == 2:
log.info("Detected %s tiles, interpreting as MiSeq nano run.",tc)
machine = {"machine":"Illumina MiSeq","lane_count":1}
elif tc == 8:
log.info("Detected %s tiles, interpreting as MiSeq micro run.",tc)
machine = {"machine":"Illumina MiSeq","lane_count":1}
elif tc == 16:
log.info("Detected %s tiles, interpreting as iSeq run.",tc)
machine = {"machine":"Illumina iSeq 100","lane_count":1}
elif tc == 28:
log.info("Detected %s tiles, interpreting as MiSeq run.",tc)
machine = {"machine":"Illumina MiSeq","lane_count":1}
elif tc == 38:
log.info("Detected %s tiles, interpreting as MiSeq run.",tc)
machine = {"machine":"Illumina MiSeq","lane_count":1}
elif tc == 128:
log.info("Detected %s tiles, interpreting as HiSeq2k run.",tc)
machine = {"machine":"Illumina HiSeq 2500","lane_count":2}
elif tc == 132:
# NextSeq P2 kit can be used on either NextSeq 1000 or 2000
# so we cannot know which from the tile count alone
log.info("Detected %s tiles, interpreting as NextSeq 1000/2000 P2 run.",tc)
machine = {"machine":"NextSeq 1000/2000","lane_count":1}
elif tc == 264:
log.info("Detected %s tiles, interpreting as NextSeq 2000 P3 run.",tc)
machine = {"machine":"NextSeq 2000","lane_count":2}
elif tc == 288:
# NextSeq 550 is a NextSeq 500 that can also read arrays.
# Since we cannot tell them apart based on tile count, we call it the 550
log.info("Detected %s tiles, interpreting as NextSeq 550 (mid-output) run.",tc)
machine = {"machine":"NextSeq 550","lane_count":4}
elif tc == 624:
log.info("Detected %s tiles, interpreting as Illumina NovaSeq 6000 run.",tc)
machine = {"machine":"Illumina NovaSeq 6000","lane_count":2}
elif tc == 768:
# HiSeq 2000 and 2500 have the same number of tiles
# Defaulting to the newer HiSeq 2500
log.info("Detected %s tiles, interpreting as HiSeq2500 run.",tc)
machine = {"machine":"Illumina HiSeq 2500","lane_count":8}
elif tc == 864:
# NextSeq 550 is a NextSeq 500 that can also read arrays.
# Since we cannot tell them apart based on tile count, we call it the 550
log.info("Detected %s tiles, interpreting as NextSeq 550 (high-output) run.",tc)
machine = {"machine":"NextSeq 550","lane_count":4}
elif tc == 896:
log.info("Detected %s tiles, interpreting as HiSeq4k run.",tc)
machine = {"machine":"Illumina HiSeq 4000","lane_count":8}
elif tc == 1408:
log.info("Detected %s tiles, interpreting as Illumina NovaSeq 6000 run.",tc)
machine = {"machine":"Illumina NovaSeq 6000","lane_count":2}
elif tc == 3744:
log.info("Detected %s tiles, interpreting as Illumina NovaSeq 6000 run.",tc)
machine = {"machine":"Illumina NovaSeq 6000","lane_count":4}
elif tc > 3744:
log.info("Tile count: %s tiles (unknown instrument type).",tc)
return machine
def get_flowcell_chemistry(self):
guessed_sequencer = self.infer_sequencer_model()
return guessed_sequencer["chemistry"]
def get_flowcell_lane_count(self):
guessed_sequencer = self.infer_sequencer_model()
try:
return self.get_lane_count()
except Exception as e:
return guessed_sequencer.get("lane_count",None)
def get_machine_model(self):
guessed_sequencer = self.infer_sequencer_model()
return guessed_sequencer["machine"]
@classmethod
def get_machines_for_flowcell_id(cls, fcid):
sequencer_by_fcid = []
for key in cls.flowcell_to_machine_model_and_chemistry:
if re.search(key,fcid):
sequencer_by_fcid.append(cls.flowcell_to_machine_model_and_chemistry[key])
return sequencer_by_fcid
def infer_sequencer_model(self):
fcid = self.get_flowcell_raw()
sequencer_by_tile_count = self.machine_model_from_tile_count()
sequencers_by_fcid = self.get_machines_for_flowcell_id(fcid)
if len(sequencers_by_fcid)>1:
raise LookupError("Multiple sequencers possible: %s",fcid)
print("self.tile_count()",self.tile_count())
# always return sequencer model based on flowcell ID, if we can
if len(sequencers_by_fcid)>0:
if sequencer_by_tile_count is not None and sequencers_by_fcid[0]["machine"]!=sequencer_by_tile_count["machine"]:
log.warning("Sequencer type inferred from flowcell ID: %s does not match sequencer inferred from tile count: %s; is this a new machine type?" % (sequencers_by_fcid[0]["machine"], sequencer_by_tile_count["machine"]))
return sequencers_by_fcid[0]
# otherwise return based on tile count if we can
elif sequencer_by_tile_count is not None:
log.warning("Sequencer type unknown flowcell ID: %s, yet sequencer type was inferred for tile count: %s; is this a new flowcell ID pattern?" % (fcid, self.tile_count()))
return sequencer_by_tile_count
# otherwise we do not know
else:
log.warning("Tile count: %s and flowcell ID: %s are both novel; is this a new machine type?" % (self.tile_count(), fcid))
return {"machine":"UNKNOWN","lane_count":self.get_lane_count()}
# Machine names aim to conform to the NCBI SRA controlled
# vocabulary for Illumina sequencers available here:
# https://www.ncbi.nlm.nih.gov/viewvc/v1/trunk/sra/doc/SRA_1-5/SRA.common.xsd?view=co&content-type=text%2Fplain
flowcell_to_machine_model_and_chemistry = {
r'[A-Z,0-9]{5}AAXX':{
"machine": "Illumina Genome Analyzer IIx",
"chemistry": "All",
"lane_count": 8,
"note": ""
},
r'[A-Z,0-9]{5}ABXX':{
"machine": "Illumina HiSeq 2000",
"chemistry": "V2 Chemistry",
"lane_count": 8,
"note": ""
},
r'[A-Z,0-9]{5}ACXX':{
"machine": "Illumina HiSeq 2000",
"chemistry": "V3 Chemistry",
"lane_count": 8,