/
fanc_commands.py
5411 lines (4571 loc) · 194 KB
/
fanc_commands.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
import argparse
import logging
import os
import os.path
import textwrap
import shutil
import tempfile
import warnings
# configure logging
logger = logging.getLogger(__name__)
def fanc_parser():
usage = "fanc <command> [options]\n\n"
command_descriptions = dict()
for name, function in globals().items():
if name.endswith("_parser") and name != 'fanc_parser':
parser = function()
short_name = name[:-7].replace('_', '-')
command_descriptions[short_name] = parser.description.split(".")[0]
max_len = max([len(name) for name in command_descriptions.keys()]) + 4
usage += "-- Matrix generation --\n"
for name in ['auto', 'map', 'pairs', 'hic']:
padding = ' ' * (max_len - len(name))
usage += "{}{}{}\n".format(name, padding, command_descriptions.pop(name))
usage += "\n-- Matrix analysis --\n"
for name in ['cis-trans', 'expected', 'pca', 'compartments',
'insulation', 'directionality', 'boundaries',
'compare', 'loops', 'aggregate']:
padding = ' ' * (max_len - len(name))
usage += "{}{}{}\n".format(name, padding, command_descriptions.pop(name))
deprecated_descriptions = {name: command_descriptions.pop(name)
for name in ['from-juicer', 'from-cooler', 'stats', 'subset']}
usage += "\n-- Other helpers --\n"
for name in command_descriptions.keys():
padding = ' ' * (max_len - len(name))
usage += "{}{}{}\n".format(name, padding, command_descriptions.get(name))
usage += "\n-- Deprecated --\n"
for name in deprecated_descriptions.keys():
padding = ' ' * (max_len - len(name))
usage += "{}{}{}\n".format(name, padding, deprecated_descriptions.get(name))
parser = argparse.ArgumentParser(
description="fanc processing tool for Hi-C data",
usage=textwrap.dedent(usage)
)
parser.add_argument(
'-V', '--version', dest='print_version',
action='store_true',
help='Print version information'
)
parser.set_defaults(print_version=False)
parser.add_argument(
'--verbose', '-v', dest='verbosity',
action='count',
default=0,
help='Set verbosity level: Can be chained like '
'"-vvv" to increase verbosity. Default is to show '
'errors, warnings, and info messages (same as "-vv"). '
'"-v" shows only errors and warnings, "-vvv" shows '
'errors, warnings, info, and debug messages.'
)
parser.add_argument(
'-s', '--silent', dest='silent',
action='store_true',
help='Do not print log messages to command line.'
)
parser.set_defaults(silent=False)
parser.add_argument(
'-l', '--log-file', dest='log_file',
help='Path to file in which to save log.'
)
parser.add_argument(
'-m', '--email', dest='email_to_address',
help='Email address for fanc command summary.'
)
parser.add_argument(
'--smtp-server', dest='smtp_server',
help='SMTP server in the form smtp.server.com[:port].'
)
parser.add_argument(
'--smtp-username', dest='smtp_username',
help='SMTP username.'
)
parser.add_argument(
'--smtp-password', dest='smtp_password',
help='SMTP password.'
)
parser.add_argument(
'--smtp-sender-address', dest='email_from_address',
help='SMTP sender email address.'
)
parser.add_argument('command', nargs='?', help='Subcommand to run')
return parser
def auto_parser():
import fanc.commands.auto
return fanc.commands.auto.auto_parser()
def auto(argv, **kwargs):
import fanc.commands.auto
return fanc.commands.auto.auto(argv, **kwargs)
def map_parser():
parser = argparse.ArgumentParser(
prog="fanc map",
description='Map reads in a FASTQ file to a reference genome.'
)
parser.add_argument(
'input',
nargs='+',
help='File name of the input FASTQ file (or gzipped FASTQ)'
)
parser.add_argument(
'index',
help='Bowtie 2 or BWA genome index base. Index type will be '
'determined automatically.'
)
parser.add_argument(
'output',
help='Output file or folder. '
'When providing multiple input files, this must be the '
'path to an output folder.'
)
parser.add_argument(
'-m', '--min-size', dest='min_size',
type=int,
default=25,
help='Minimum length of read before extension. '
'Default %(default)d.'
)
parser.add_argument(
'-s', '--step-size', dest='step_size',
type=int,
default=10,
help='Number of base pairs to extend at each round of mapping. '
'Default is %(default)d.'
)
parser.add_argument(
'--trim-front', dest='trim_front',
action='store_true',
default=False,
help='Trim reads from front instead of back.'
)
parser.add_argument(
'-t', '--threads', dest='threads',
type=int,
default=1,
help='Number of threads used for mapping. Default: %(default)d'
)
parser.add_argument(
'-q', '--quality', dest='quality',
type=int,
help='Mapping quality cutoff. '
'Alignments with a quality score lower than this will be '
'sent to another mapping iteration. '
'Default: 3 (BWA), 30 (Bowtie2)'
)
parser.add_argument(
'-r', '--restriction-enzyme', dest='restriction_enzyme',
help='Name (case sensitive) of restriction enzyme used in Hi-C experiment. '
'Will be used to split reads by predicted ligation junction before mapping. '
'You can omit this if you do not want to split your reads by ligation junction. '
'Restriction names can be any supported by Biopython, which obtains data '
'from REBASE (http://rebase.neb.com/rebase/rebase.html). '
'For restriction enzyme cocktails, separate enzyme names with ","'
)
parser.add_argument(
'-k', '--max-alignments', dest='max_alignments',
type=int,
help='Maximum number of alignments per read to be reported.'
)
parser.add_argument(
'-a', '--all-alignments', dest='all_alignments',
action='store_true',
default=False,
help='Report all valid alignments of a read '
'Warning: very slow!.'
)
parser.add_argument(
'-b', '--batch-size', dest='batch_size',
type=int,
default=100000,
help='Number of reads processed (mapped and merged) in one go per worker. '
'The default %(default)d works well for large indexes (e.g. human, mouse). '
'Smaller indexes (e.g. yeast) will finish individual bowtie2 processes '
'very quickly - set this number higher to spawn new processes '
'less frequently. '
)
parser.add_argument(
'--fanc-parallel', dest='mapper_parallel',
action='store_false',
default=True,
help='Use FAN-C parallelisation, which launches multiple mapper jobs. '
'This may be faster in some cases than relying '
'on the internal paralellisation of the mapper, '
'but has potentially high disk I/O and memory usage.'
)
parser.add_argument(
'--split-fastq', dest='split_fastq',
action='store_true',
default=False,
help='Split FASTQ file into 10M chunks before mapping. '
'Easier on tmp partitions.'
)
parser.add_argument(
'--memory-map', dest='memory_map',
action='store_true',
default=False,
help='Map Bowtie2 index to memory. '
'Only enable if your system has enough memory '
'to hold the entire Bowtie2 index.'
)
parser.add_argument(
'--no-iterative', dest='iterative',
action='store_false',
default=True,
help='Do not use iterative mapping strategy. '
'(much faster, less sensitive).'
)
parser.add_argument(
'--mapper-type', dest='mapper_type',
help='Manually set mapper type. Currently supported: bowtie2, bwa, and bwa-mem2. '
'Not that this is generally auto-detected from the index path.'
)
parser.add_argument(
'-tmp', '--work-in-tmp', dest='tmp',
action='store_true',
default=False,
help='Copy original file to temporary directory.'
'Reduces network I/O.'
)
return parser
def map(argv, **kwargs):
parser = map_parser()
args = parser.parse_args(argv[2:])
# check arguments
input_files = args.input
index_path = os.path.expanduser(args.index)
output_folder = os.path.expanduser(args.output)
step_size = args.step_size
min_size = args.min_size
trim_front = args.trim_front
batch_size = args.batch_size
min_quality = args.quality
mapper_parallel = args.mapper_parallel
memory_map = args.memory_map
iterative = args.iterative
restriction_enzyme = args.restriction_enzyme
max_alignments = args.max_alignments
all_alignments = args.all_alignments
mapper_type = args.mapper_type
tmp = args.tmp
if mapper_parallel:
threads, mapper_threads = 1, args.threads
else:
threads, mapper_threads = args.threads, 1
if restriction_enzyme is not None:
restriction_enzyme = restriction_enzyme.split(",")
import fanc.map as map
from fanc.tools.general import mkdir
from genomic_regions.files import create_temporary_copy
from fanc.tools.files import random_name
from fanc.config import config
import subprocess
import tempfile
import shutil
import glob
additional_arguments = []
if memory_map:
additional_arguments += ['--mm']
if all_alignments:
additional_arguments += ['-a']
elif max_alignments is not None:
additional_arguments += ['-k', str(max_alignments)]
if index_path.endswith('.'):
index_path = index_path[:-1]
if mapper_type is None:
mapper_type = 'bwa'
for ending in ('amb', 'ann', 'bwt', 'pac', 'sa'):
file_name = index_path + '.{}'.format(ending)
if not os.path.isfile(file_name):
mapper_type = None
break
if mapper_type is None:
mapper_type = 'bwa-mem2'
for ending in ('amb', 'ann', 'bwt.2bit.64', 'pac', '0123'):
file_name = index_path + '.{}'.format(ending)
if not os.path.isfile(file_name):
mapper_type = None
break
if mapper_type is None:
mapper_type = 'bowtie2'
for i in range(1, 5):
if not os.path.exists(index_path + '.{}.bt2'.format(i)):
mapper_type = None
break
for i in range(1, 3):
if not os.path.exists(index_path + '.rev.{}.bt2'.format(i)):
mapper_type = None
break
if mapper_type is None:
raise RuntimeError("Cannot detect mapper type from index (supported are Bowtie2, BWA, and BWA-mem2)")
elif min_quality is None:
if mapper_type == 'bwa' or mapper_type == 'bwa-mem2':
min_quality = 3
elif mapper_type == 'bowtie2':
min_quality = 30
index_dir = None
try:
if tmp:
tmp = False
index_dir = tempfile.mkdtemp()
index_base = os.path.basename(index_path)
if mapper_type == 'bowtie2':
for file_name in glob.glob(index_path + '*.bt2'):
shutil.copy(file_name, index_dir)
elif mapper_type == 'bwa':
index_base = random_name()
for ending in ('amb', 'ann', 'bwt', 'pac', 'sa'):
file_name = index_path + '.{}'.format(ending)
shutil.copy(file_name, os.path.join(index_dir, '{}.{}'.format(index_base, ending)))
elif mapper_type == 'bwa-mem2':
index_base = random_name()
for ending in ('amb', 'ann', 'bwt.2bit.64', 'pac', '0123'):
file_name = index_path + '.{}'.format(ending)
shutil.copy(file_name, os.path.join(index_dir, '{}.{}'.format(index_base, ending)))
index_path = os.path.join(index_dir, index_base)
logger.debug('Index path: {}'.format(index_path))
tmp = True
mapper = None
if mapper_type == 'bowtie2':
if iterative:
mapper = map.Bowtie2Mapper(index_path, min_quality=min_quality,
additional_arguments=additional_arguments,
threads=mapper_threads)
else:
mapper = map.SimpleBowtie2Mapper(index_path, additional_arguments=additional_arguments,
threads=mapper_threads)
elif mapper_type == 'bwa' or mapper_type == 'bwa-mem2':
mapper_path = config.bwa_path if mapper_type == 'bwa' else config.bwa_mem2_path
logger.debug("Using bwa-mem2 at '{}'".format(mapper_path))
if iterative:
mapper = map.BwaMapper(index_path, min_quality=min_quality,
threads=mapper_threads, memory_map=memory_map,
_bwa_path=mapper_path)
else:
mapper = map.SimpleBwaMapper(index_path,
threads=mapper_threads, memory_map=memory_map,
_bwa_path=mapper_path)
for input_file in input_files:
input_file = os.path.expanduser(input_file)
if len(args.input) == 1 and not os.path.isdir(output_folder):
output_file = output_folder
else:
output_folder = mkdir(output_folder)
basename, extension = os.path.splitext(os.path.basename(input_file))
if basename.endswith('.fastq'):
basename = basename[:-6]
if basename.endswith('.fq'):
basename = basename[:-3]
output_file = os.path.join(output_folder, basename + '.bam')
if not args.split_fastq:
original_output_file = output_file
try:
if tmp:
tmp = False
input_file = create_temporary_copy(input_file, preserve_extension=True)
tmp_file = tempfile.NamedTemporaryFile(suffix=os.path.splitext(output_file)[1],
prefix='fanc_', delete=False)
tmp_file_name = tmp_file.name
output_file = tmp_file_name
tmp = True
logger.info("Starting mapping for {}".format(input_file))
map.iterative_mapping(input_file, output_file, mapper, threads=threads,
min_size=min_size, step_size=step_size, batch_size=batch_size,
trim_front=trim_front, restriction_enzyme=restriction_enzyme)
logger.debug("Mapping complete")
finally:
if tmp:
logger.debug("Removing tmp files")
os.remove(input_file)
shutil.copy(output_file, original_output_file)
os.remove(output_file)
logger.debug("Closing mapper")
mapper.close()
else:
from fanc.tools.files import split_fastq, merge_sam, gzip_splitext
logger.info("Splitting FASTQ files for mapping")
if os.path.isdir(output_folder):
split_tmpdir = tempfile.mkdtemp(dir=output_folder)
else:
split_tmpdir = tempfile.mkdtemp(dir=os.path.dirname(output_folder))
try:
split_fastq_tmpdir = mkdir(os.path.join(split_tmpdir, 'fastq'))
split_sam_tmpdir = mkdir(os.path.join(split_tmpdir, 'sam'))
split_bam_files = []
split_fastq_results = []
for split_file in split_fastq(input_file, split_fastq_tmpdir):
basename = os.path.basename(gzip_splitext(split_file)[0])
split_bam_file = split_sam_tmpdir + '/{}.bam'.format(basename)
split_bam_files.append(split_bam_file)
split_command = ['fanc', 'map', split_file, index_path, split_bam_file,
'-m', str(min_size), '-s', str(step_size), '-t', str(threads),
'-q', str(min_quality), '-b', str(batch_size)]
if not iterative:
split_command += ['--no-iterative']
if tmp:
split_command += ['-tmp']
if not mapper_parallel:
split_command += ['--fanc-parallel']
if memory_map:
split_command += ['--memory-map']
if trim_front:
split_command += ['--trim-front']
if restriction_enzyme is not None:
split_command += ['--restriction-enzyme', ",".join(restriction_enzyme)]
rt = subprocess.call(split_command)
split_fastq_results.append(rt)
for rt in split_fastq_results:
if rt != 0:
raise RuntimeError("Mapping had non-zero exit status")
logger.info("Merging BAM files into {}".format(output_file))
merge_sam(split_bam_files, output_file, tmp=tmp)
finally:
shutil.rmtree(split_tmpdir, ignore_errors=True)
finally:
if tmp:
logger.debug("Removing index dir")
shutil.rmtree(index_dir, ignore_errors=True)
def fragments_parser():
parser = argparse.ArgumentParser(
prog="fanc fragments",
description='In-silico genome digestion'
)
parser.add_argument(
'input',
help="Path to genome file (FASTA, folder with FASTA, hdf5 file), "
"which will be used in conjunction with the type of restriction enzyme to "
"calculate fragments directly."
)
parser.add_argument(
're_or_bin_size',
help="Restriction enzyme name or bin size to divide genome into fragments. "
"Restriction names can be any supported by Biopython, which obtains data "
"from REBASE (http://rebase.neb.com/rebase/rebase.html). "
"Use commas to separate multiple restriction enzymes, e.g. 'HindIII,MboI'"
)
parser.add_argument(
'output',
help='Output file with restriction fragments in BED format.'
)
parser.add_argument(
'-c', '--chromosomes', dest='chromosomes',
help='Comma-separated list of chromosomes to include in fragments BED file. '
'Other chromosomes will be excluded. The order of chromosomes will '
'be as stated in the list.'
)
return parser
def fragments(argv, **kwargs):
parser = fragments_parser()
args = parser.parse_args(argv[2:])
import os
genome_file = os.path.expanduser(args.input)
re_or_bin_size = args.re_or_bin_size.split(",")
output_file = os.path.expanduser(args.output)
chromosomes = args.chromosomes
from fanc.regions import genome_regions
regions = genome_regions(genome_file, re_or_bin_size)
from fanc.tools.files import write_bed
import warnings
from collections import defaultdict
if chromosomes is not None:
chromosomes = chromosomes.split(",")
chromosome_regions = defaultdict(list)
for region in regions:
chromosome_regions[region.chromosome].append(region)
regions = []
for chromosome in chromosomes:
if chromosome not in chromosome_regions:
raise ValueError("Chromosome {} is not found in genome. Please check your chromosome list!")
regions += chromosome_regions[chromosome]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
write_bed(output_file, regions)
def sort_sam_parser():
parser = argparse.ArgumentParser(
prog="fanc sort_sam",
description="Convenience function to sort a SAM file by name. "
"Exactly the same as 'samtools sort -n', but potentially"
"faster if sambamba is available."
)
parser.add_argument(
'sam',
help='Input SAM/BAM'
)
parser.add_argument(
'output',
nargs='?',
help='Output SAM/BAM. If not provided, will replace input '
'file with sorted version after sorting.'
)
parser.add_argument(
'-t', '--threads', dest='threads',
default=1,
type=int,
help='Number of sorting threads (only when sambamba is available). '
'Default: %(default)d'
)
parser.add_argument(
'-S', '--no-sambamba', dest='use_sambamba',
default=True,
action='store_false',
help='Do not use sambamba, even when it is available. '
'Use pysam instead.'
)
parser.add_argument(
'-tmp', '--work-in-tmp', dest='tmp',
action='store_true',
default=False,
help='Work in temporary directory'
)
return parser
def sort_sam(argv, **kwargs):
parser = sort_sam_parser()
args = parser.parse_args(argv[2:])
sam_file = os.path.expanduser(args.sam)
output_file = None if args.output is None else os.path.expanduser(args.output)
threads = args.threads
use_sambamba = args.use_sambamba
tmp = args.tmp
from genomic_regions.files import create_temporary_copy
from fanc.tools.files import sort_natural_sam
import tempfile
import shutil
success = False
original_input_file = sam_file
original_output_file = output_file
try:
if tmp:
tmp = False
sam_file = create_temporary_copy(sam_file)
if output_file is not None:
basename, extension = os.path.splitext(output_file)
with tempfile.NamedTemporaryFile(delete=False, prefix='fanc_', suffix=extension) as f:
output_file = f.name
tmp = True
logger.info("Working in tmp: {}, ".format(sam_file, output_file))
output_file = sort_natural_sam(sam_file, output_file, threads=threads, sambamba=use_sambamba)
success = True
finally:
if tmp:
if success:
if original_output_file is not None:
shutil.copy(output_file, original_output_file)
else:
shutil.copy(output_file, original_input_file)
os.remove(sam_file)
if os.path.normpath(sam_file) != os.path.normpath(output_file):
os.remove(output_file)
def pairs_parser():
parser = argparse.ArgumentParser(
prog="fanc pairs",
description='Process and filter read pairs'
)
parser.add_argument(
'input',
nargs='+',
help='IMPORTANT: The last positional argument will be '
'the output file, unless only a single Pairs object '
'is provided. In that case, filtering and correcting '
'will be done in place. '
'Possible inputs are: two SAM/BAM files (paired-end reads, '
'sorted by read name using "samtools sort -n" or equivalent) and an output file; '
'a HiC-Pro pairs file (format: '
'name<tab>chr1<tab>pos1<tab>strand1<tab>chr2<tab>pos2<tab>strand2) '
'and an output file; a pairs file in 4D Nucleome format '
'(https://github.com/4dn-dcic/pairix/blob/master/pairs_format_specification.md) '
'and an output file, '
'or an existing fanc Pairs object. '
'In case of SAM/BAM, HiC-Pro, or 4D Nucleome you must also provide the '
'--genome argument, and if --genome is not a file with '
'restriction fragments (or Hi-C bins), you must also provide the '
'--restriction-enzyme argument.'
)
parser.add_argument(
'-g', '--genome', dest='genome',
help='Path to region-based file (BED, GFF, ...) containing the non-overlapping '
'regions to be used for Hi-C binning. Typically restriction-enzyme fragments. '
'Alternatively: Path to genome file (FASTA, folder with FASTA, HDF5 file), '
'which will be used in conjunction with the type of restriction enzyme to '
'calculate fragments directly.'
)
parser.add_argument(
'-r', '--restriction_enzyme',
help='Name of the restriction enzyme used in the '
'experiment, e.g. HindIII, or MboI. Case-sensitive, '
'only necessary when --genome is provided as FASTA. '
'Restriction names can be any supported by Biopython, which obtains data '
'from REBASE (http://rebase.neb.com/rebase/rebase.html). '
'Separate multiple restriction enzymes with ","'
)
parser.add_argument(
'-m', '--filter-unmappable', dest='unmappable',
action='store_true',
default=False,
help='Filter read pairs where one or both halves are unmappable. '
'Only applies to SAM/BAM input!'
)
parser.add_argument(
'-u', '--filter-multimapping', dest='unique',
action='store_true',
default=False,
help='Filter reads that map multiple times. If the other '
'mapping locations have a lower score than the best one, '
'the best read is kept. '
'Only applies to SAM/BAM input!'
)
parser.add_argument(
'-us', '--filter-multimapping-strict', dest='unique_strict',
action='store_true',
default=False,
help='Strictly filter reads that map multiple times. '
'Only applies to SAM/BAM input!'
)
parser.add_argument(
'-q', '--filter-quality', dest='quality',
type=float,
help='Cutoff for the minimum mapping quality of a read. '
'For numbers larger than 1, will filter on MAPQ. '
'If a number between 0 and 1 is provided, will filter '
'on the AS tag instead of mapping quality (only BWA). '
'The quality cutoff is then interpreted as the '
'fraction of bases that have to be matched for any '
'given read. Only applies to SAM/BAM input! '
'Default: no mapping quality filter.'
)
parser.add_argument(
'-c', '--filter-contaminant', dest='contaminant',
help='Filter contaminating reads from other organism. '
'Path to mapped SAM/BAM file. '
'Will filter out reads with the same name. '
'Only applies to SAM/BAM input! '
'Default: no contaminant filter'
)
parser.add_argument(
'-i', '--filter-inward', dest='inward',
type=int,
help='Minimum distance for inward-facing read pairs. '
'Default: no inward ligation error filter'
)
parser.add_argument(
'-o', '--filter-outward', dest='outward',
type=int,
help='Minimum distance for outward-facing read pairs. '
'Default: no outward ligation error filter'
)
parser.add_argument(
'--filter-ligation-auto', dest='filter_le_auto',
action='store_true',
default=False,
help='Auto-guess settings for inward/outward read pair filters. '
'Overrides --filter-outward and --filter-inward if set. This '
'is highly experimental and known to overshoot in some cases. '
'It is generally recommended to specify cutoffs manually.'
)
parser.add_argument(
'-d', '--filter-re-distance', dest='redist',
type=int,
help='Maximum distance for a read to the nearest restriction site. '
'Default: no RE distance filter'
)
parser.add_argument(
'-l', '--filter-self-ligations', dest='self_ligated',
action='store_true',
default=False,
help='Remove read pairs representing self-ligated fragments.'
'Default: no self-ligation filter.'
)
parser.add_argument(
'-p', '--filter-pcr-duplicates', dest='dup_thresh',
type=int,
help='If specified, filter read pairs for PCR duplicates. Parameter determines '
'distance between alignment starts below which they are considered starting '
'at same position. Sensible values are between 1 and 5. Default: '
'no PCR duplicates filter'
)
parser.add_argument(
'-s', '--statistics', dest='stats',
help='Path for saving filter statistics'
)
parser.add_argument(
'--reset-filters', dest='reset_filters',
action='store_true',
default=False,
help='Remove all filters from the ReadPairs object.'
)
parser.add_argument(
'--statistics-plot', dest='stats_plot',
help='Path for saving filter statistics plot (PDF)'
)
parser.add_argument(
'--re-dist-plot', dest='re_dist_plot',
help='Plot the distribution of restriction site distances '
'of all read pairs (sum left and right read).'
)
parser.add_argument(
'--ligation-error-plot', dest='ligation_error_plot',
help='Plot the relative orientation of read pairs mapped '
'to the reference genome as a fraction of reads oriented '
'in the same direction. Allows the identification of '
'ligation errors as a function of genomic distance.'
)
parser.add_argument(
'-t', '--threads', dest='threads',
type=int,
default=1,
help='Number of threads to use for extracting fragment information. '
'Default: %(default)d'
)
parser.add_argument(
'-b', '--batch-size', dest='batch_size',
type=int,
default=1000000,
help='Batch size for read pairs to be submitted to individual processes. '
'Default: %(default)d'
)
parser.add_argument(
'-S', '--no-check-sorted', dest='check_sorted',
action='store_false',
default=True,
help='Assume SAM files are sorted and do not '
'check if that is actually the case'
)
parser.add_argument(
'-f', '--force-overwrite', dest='force_overwrite',
action='store_true',
default=False,
help='If the specified output file exists, it will be '
'overwritten without warning.'
)
parser.add_argument(
'--bwa', dest='bwa',
action='store_true',
default=False,
help='Use filters appropriate for BWA and not Bowtie2. '
'This will typically be identified automatically '
'from the SAM/BAM header. Set this flag if you are '
'having problems during filtering (typically 0 reads '
'pass the filtering threshold). '
)
parser.add_argument(
'-tmp', '--work-in-tmp', dest='tmp',
action='store_true',
default=False,
help='Work in temporary directory'
)
return parser
def pairs(argv, **kwargs):
parser = pairs_parser()
args = parser.parse_args(argv[2:])
import os
input_files = [os.path.expanduser(file_name) for file_name in args.input]
genome_file = os.path.expanduser(args.genome) if args.genome is not None else None
restriction_enzyme = args.restriction_enzyme
filter_unmappable = args.unmappable
filter_unique = args.unique
filter_unique_strict = args.unique_strict
filter_quality = args.quality
filter_contaminant = args.contaminant
filter_inward = args.inward
filter_outward = args.outward
filter_le_auto = args.filter_le_auto
filter_re_distance = args.redist
filter_self_ligations = args.self_ligated
filter_pcr_duplicates = args.dup_thresh
statistics_file = os.path.expanduser(args.stats) if args.stats is not None else None
statistics_plot_file = os.path.expanduser(args.stats_plot) if args.stats_plot is not None else None
re_dist_plot_file = os.path.expanduser(args.re_dist_plot) if args.re_dist_plot is not None else None
ligation_error_plot_file = os.path.expanduser(args.ligation_error_plot) \
if args.ligation_error_plot is not None else None
threads = args.threads
batch_size = args.batch_size
check_sam_sorted = args.check_sorted
force_overwrite = args.force_overwrite
reset_filters = args.reset_filters
tmp = args.tmp
from genomic_regions.files import create_temporary_copy, create_temporary_output
if restriction_enzyme is not None:
restriction_enzyme = restriction_enzyme.split(",")
tmp_input_files = []
original_pairs_file = None
pairs_file = None
pairs = None
try:
regions = None
if 2 <= len(input_files) <= 3:
if not force_overwrite and os.path.exists(input_files[-1]):
parser.error("Output file {} exists! Use -f to force "
"overwriting it!".format(input_files[-1]))
if genome_file is None:
parser.error("Must provide genome file (-g) when loading reads or pairs!")
logger.info("Getting genome regions (fragments or bins)")
from fanc.regions import genome_regions
try:
if tmp:
tmp = False
genome_file = create_temporary_copy(os.path.expanduser(genome_file))
tmp_input_files.append(genome_file)
tmp = True
regions = genome_regions(genome_file, restriction_enzyme=restriction_enzyme)
except ValueError:
if restriction_enzyme is None:
parser.error("Must provide --restriction-enzyme when --genome is "
"not a list of fragments or genomic bins!")
else:
raise
import fanc
if len(input_files) == 3:
logger.info("Three arguments detected, assuming SAM/BAM input.")
sam1_file = os.path.expanduser(input_files[0])
sam2_file = os.path.expanduser(input_files[1])
pairs_file = os.path.expanduser(input_files[2])
if tmp:
tmp = False
sam1_file = create_temporary_copy(sam1_file)
sam2_file = create_temporary_copy(sam2_file)
tmp_input_files += [sam1_file, sam2_file]
original_pairs_file = pairs_file
pairs_file = create_temporary_output(pairs_file)
tmp = True
from fanc.tools.general import get_sam_mapper
bwa = get_sam_mapper(sam1_file) in ['bwa', 'bwa-mem2'] or args.bwa
logger.info("Using filters appropriate for {}.".format('BWA' if bwa else 'Bowtie2'))
from fanc.pairs import BwaMemQualityFilter, BwaMemUniquenessFilter, \
UniquenessFilter, ContaminantFilter, QualityFilter, UnmappedFilter
from fanc.general import Mask
read_filters = []
if filter_unmappable:
f = UnmappedFilter(mask=Mask(ix=0, name='unmappable'))
read_filters.append(f)
if filter_unique or filter_unique_strict:
if bwa:
f = BwaMemUniquenessFilter(strict=filter_unique_strict,
mask=Mask(ix=1, name='multi-mapping'))
else:
f = UniquenessFilter(strict=filter_unique_strict,
mask=Mask(ix=1, name='multi-mapping'))
read_filters.append(f)
if filter_quality is not None:
if 0 < filter_quality < 1:
f = BwaMemQualityFilter(filter_quality, mask=Mask(ix=2, name='alignment score'))
else:
f = QualityFilter(int(filter_quality), mask=Mask(ix=2, name='MAPQ'))
read_filters.append(f)