-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtilities.py
More file actions
1495 lines (1147 loc) · 53.6 KB
/
Utilities.py
File metadata and controls
1495 lines (1147 loc) · 53.6 KB
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
'''Utilities.py - Tools for writing reproducible scripts
=========================================================
The :mod:`Utilities` modules contains utility functions for argument
parsing, logging and record keeping within scripts.
This module is imported by most UMI-tools tools. It provides convenient
and consistent methods for
* `Record keeping`_
* `Argument parsing`_
* `Input/Output redirection`_
* `Logging`_
* `Running external commands`_
* `Benchmarking`_
The basic usage of this module within a script is::
"""script_name.py - my script
Mode Documentation
"""
import sys
import optparse
import Utilities as U
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv: argv = sys.argv
# setup command line parser
parser = U.OptionParser(version="%prog version: $Id$",
usage=globals()["__doc__"] )
parser.add_option("-t", "--test", dest="test", type="string",
help="supply help")
# add common options (-h/--help, ...) and parse
# command line
(options, args) = U.Start(parser)
# do something
# ...
U.info("an information message")
U.warn("a warning message)
## write footer and output benchmark information.
U.Stop()
if __name__ == "__main__":
sys.exit(main(sys.argv))
Record keeping
--------------
The central functions in this module are the :py:func:`Start` and
:py:func:`Stop` methods which are called before or after any work is
done within a script.
The :py:func:`Start` is called with an U.OptionParser object.
:py:func:`Start` will add additional command line arguments, such as
``--help`` for command line help or ``--verbose`` to control the
:term:`loglevel`. It can also add optional arguments for scripts
needing database access, writing to multiple output files, etc.
:py:func:`Start` will write record keeping information to a
logfile. Typically, logging information is output on stdout, prefixed
by a `#`, but it can be re-directed to a separate file. Below is a
typical output::
# output generated by /ifs/devel/andreas/cgat/beds2beds.py --force-output --exclusive-overlap --method=unmerged-combinations --output-filename-pattern=030m.intersection.tsv.dir/030m.intersection.tsv-%s.bed.gz --log=030m.intersection.tsv.log Irf5-030m-R1.bed.gz Rela-030m-R1.bed.gz
# job started at Thu Mar 29 13:06:33 2012 on cgat150.anat.ox.ac.uk -- e1c16e80-03a1-4023-9417-f3e44e33bdcd
# pid: 16649, system: Linux 2.6.32-220.7.1.el6.x86_64 #1 SMP Fri Feb 10 15:22:22 EST 2012 x86_64
# exclusive : True
# filename_update : None
# ignore_strand : False
# loglevel : 1
# method : unmerged-combinations
# output_filename_pattern : 030m.intersection.tsv.dir/030m.intersection.tsv-%s.bed.gz
# output_force : True
# pattern_id : (.*).bed.gz
# stderr : <open file \'<stderr>\', mode \'w\' at 0x2ba70e0c2270>
# stdin : <open file \'<stdin>\', mode \'r\' at 0x2ba70e0c2150>
# stdlog : <open file \'030m.intersection.tsv.log\', mode \'a\' at 0x1f1a810>
# stdout : <open file \'<stdout>\', mode \'w\' at 0x2ba70e0c21e0>
# timeit_file : None
# timeit_header : None
# timeit_name : all
# tracks : None
The header contains information about:
* the script name (``beds2beds.py``)
* the command line options (``--force-output --exclusive-overlap
--method=unmerged-combinations
--output-filename-pattern=030m.intersection.tsv.dir/030m.intersection.tsv-%s.bed.gz
--log=030m.intersection.tsv.log Irf5-030m-R1.bed.gz
Rela-030m-R1.bed.gz``)
* the time when the job was started (``Thu Mar 29 13:06:33 2012``)
* the location it was executed (``cgat150.anat.ox.ac.uk``)
* a unique job id (``e1c16e80-03a1-4023-9417-f3e44e33bdcd``)
* the pid of the job (``16649``)
* the system specification (``Linux 2.6.32-220.7.1.el6.x86_64 #1
SMP Fri Feb 10 15:22:22 EST 2012 x86_64``)
It is followed by a list of all options that have been set in the script.
Once completed, a script will call the :py:func:`Stop` function to
signify the end of the experiment.
:py:func:`Stop` will output to the log file that the script has
concluded successfully. Below is typical output::
# job finished in 11 seconds at Thu Mar 29 13:06:44 2012 -- 11.36 0.45 0.00 0.01 -- e1c16e80-03a1-4023-9417-f3e44e33bdcd
The footer contains information about:
* the job has finished (``job finished``)
* the time it took to execute (``11 seconds``)
* when it completed (``Thu Mar 29 13:06:44 2012``)
* some benchmarking information (``11.36 0.45 0.00 0.01``)
which is ``user time``, ``system time``,
``child user time``, ``child system time``.
* the unique job id (``e1c16e80-03a1-4023-9417-f3e44e33bdcd``)
The unique job id can be used to easily retrieve matching information
from a concatenation of log files.
Argument parsing
----------------
The module provides :class:`OptionParser` to facilitate option
parsing. :class:`OptionParser` is derived from the
:py:class:`optparse.OptionParser` class, but has improvements to
provide better formatted output on the command line. It also allows to
provide a comma-separated list to options that accept multiple
arguments. Thus, ``--method=sort --method=crop`` and
``--method=sort,crop`` are equivalent.
Input/Output redirection
------------------------
:func:`Start` adds the options ``--stdin``, ``--stderr` and
``--stdout`` which allow using files as input/output streams.
To make this work, scripts should not read from sys.stdin or write to
sys.stdout directly, but instead use ``options.stdin`` and
``options.stdout``. For example to simply read all lines from stdin
and write to stdout, use::
(options, args) = U.Start(parser)
input_data = options.stdin.readlines()
options.stdout.write("".join(input_data))
The script can then be used in many different contexts::
cat in.data | python script.py > out.data
python script.py --stdin=in.data > out.data
python script.py --stdin=in.data --stdout=out.data
The method handles gzip compressed files transparently. The following
are equivalent::
zcat in.data.gz | python script.py | gzip > out.data.gz
python script.py --stdin=in.data.gz --stdout=out.data.gz
For scripts producing multiple output files, use the argument
``add_output_options=True`` to :func:`Start`. This provides the option
``--output-filename-pattern`` on the command line. The user can then
supply a pattern for output files. Any ``%s`` appearing in the pattern
will be substituted by a ``section``. Inside the script, When opening
an output file, use the method :func:`openOutputFile` to provide a
file object::
output_histogram = U.openOutputFile(section="histogram")
output_stats = U.openOutputFile(section="stats")
If the user calls the script with::
python script.py --output-filename-pattern=sample1_%s.tsv.gz
the script will create the files ``sample1_histogram.tsv.gz`` and
``sample1_stats.tsv.gz``.
This method will also add the option ``--force-output`` to permit
overwriting existing files.
Logging
-------
:py:mod:`Utilities` provides the well known logging methods from
the :py:mod:`logging` module such as :py:func:`info`,
:py:func:`warn`, etc. These are provided so that no additional import
of the :py:mod:`logging` module is required, but either functions
can be used.
Running external commands
-------------------------
The :func:`run` method is a shortcut :py:func:`subprocess.call` and
similar methods with some additional sanity checking.
Benchmarking
------------
The :func:`Start` method records basic benchmarking information when a
script starts and :func:`Stop` outputs it as part of its final log
message::
# job finished in 11 seconds at Thu Mar 29 13:06:44 2012 -- 11.36 0.45 0.00 0.01 -- e1c16e80-03a1-4023-9417-f3e44e33bdcd
See `Record keeping`_ for an explanations of the fields.
To facilitate collecting benchmark information from running multiple
scripts, these data can be tagged and saved in a separate file. See the
command line options ``--timeit``, ``--timeit-name``, ``--timeit-header``
in :func:`Start`.
The module contains some decorator functions for benchmarking
(:func:`benchmark`) and caching function (:func:`cachedfunction`) or
class method (:func:`cachedmethod`) calls.
Complete reference
------------------
'''
########################################################################################
# The code for Utilities.py has been taken with permission from CGAT.Experiment.py
# https://github.com/CGATOxford/cgat/blob/master/CGAT/Experiment.py
# and CGATPipelines.CGATPipelines.Pipeline.Files.py
# https://github.com/CGATOxford/CGATPipelines/blob/master/CGATPipelines/Pipeline/Files.py
#########################################################################################
import re
import sys
import time
import inspect
import copy
import os
import logging
import collections
import gzip
import optparse
import textwrap
import random
import uuid
import tempfile
from builtins import bytes, chr
class DefaultOptions:
stdlog = sys.stdout
stdout = sys.stdout
stderr = sys.stderr
stdin = sys.stdin
loglevel = 2
timeit_file = None
compresslevel = 6
global_starting_time = time.time()
global_options = DefaultOptions()
global_args = None
global_id = uuid.uuid4()
global_benchmark = collections.defaultdict(int)
##########################################################################
# The code for BetterFormatter has been taken from
# http://code.google.com/p/yjl/source/browse/Python/snippet/BetterFormatter.py
__copyright__ = """
Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
Copyright (c) 2011 Yu-Jie Lin. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
class BetterFormatter(optparse.IndentedHelpFormatter):
"""A formatter for :class:`OptionParser` outputting indented
help text.
"""
def __init__(self, *args, **kwargs):
optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs)
self.wrapper = textwrap.TextWrapper(width=self.width)
def _formatter(self, text):
return '\n'.join(['\n'.join(p) for p in
map(self.wrapper.wrap,
self.parser.expand_prog_name(text).split('\n'))])
def format_description(self, description):
if description:
return self._formatter(description) + '\n'
else:
return ''
def format_epilog(self, epilog):
if epilog:
return '\n' + self._formatter(epilog) + '\n'
else:
return ''
def format_usage(self, usage):
return self._formatter(optparse._("Usage: %s\n") % usage)
def format_option(self, option):
# Ripped and modified from Python 2.6's optparse's HelpFormatter
result = []
opts = self.option_strings[option]
opt_width = self.help_position - self.current_indent - 2
if len(opts) > opt_width:
opts = "%*s%s\n" % (self.current_indent, "", opts)
indent_first = self.help_position
else: # start help on same line as opts
opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
indent_first = 0
result.append(opts)
if option.help:
help_text = self.expand_default(option)
# Added expand program name
help_text = self.parser.expand_prog_name(help_text)
# Modified the generation of help_line
help_lines = []
wrapper = textwrap.TextWrapper(width=self.help_width)
for p in map(wrapper.wrap, help_text.split('\n')):
if p:
help_lines.extend(p)
else:
help_lines.append('')
# End of modification
result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
result.extend(["%*s%s\n" % (self.help_position, "", line)
for line in help_lines[1:]])
elif opts[-1] != "\n":
result.append("\n")
return "".join(result)
# End of BetterFormatter()
#################################################################
#################################################################
#################################################################
class AppendCommaOption(optparse.Option):
'''Option with additional parsing capabilities.
* "," in arguments to options that have the action 'append'
are treated as a list of options. This is what galaxy does,
but generally convenient.
* Option values of "None" and "" are treated as default values.
'''
# def check_value( self, opt, value ):
# do not check type for ',' separated lists
# if "," in value:
# return value
# else:
# return optparse.Option.check_value( self, opt, value )
#
# def take_action(self, action, dest, opt, value, values, parser):
# if action == "append" and "," in value:
# lvalue = value.split(",")
# values.ensure_value(dest, []).extend(lvalue)
# else:
# optparse.Option.take_action(
# self, action, dest, opt, value, values, parser)
#
def convert_value(self, opt, value):
if value is not None:
if self.nargs == 1:
if self.action == "append":
if "," in value:
return [self.check_value(opt, v) for v in
value.split(",") if v != ""]
else:
if value != "":
return self.check_value(opt, value)
else:
return value
else:
return self.check_value(opt, value)
else:
return tuple([self.check_value(opt, v) for v in value])
# why is it necessary to pass action and dest to this function when
# they could be accessed as self.action and self.dest?
def take_action(self, action, dest, opt, value, values, parser):
if action == "append" and type(value) == list:
values.ensure_value(dest, []).extend(value)
else:
optparse.Option.take_action(
self, action, dest, opt, value, values, parser)
class OptionParser(optparse.OptionParser):
'''UMI-tools derivative of OptionParser.
'''
def __init__(self, *args, **kwargs):
# if "--short" is a command line option
# remove usage from kwargs
if "--no-usage" in sys.argv:
kwargs["usage"] = None
optparse.OptionParser.__init__(self, *args,
option_class=AppendCommaOption,
formatter=BetterFormatter(),
**kwargs)
# set new option parser
# parser.formatter = BetterFormatter()
# parser.formatter.set_parser(parser)
if "--no-usage" in sys.argv:
self.add_option("--no-usage", dest="help_no_usage",
action="store_true",
help="output help without usage information")
class OptionGroup(optparse.OptionGroup):
pass
def callbackShortHelp(option, opt, value, parser):
'''output short help (only command line options).'''
# clear usage and description
parser.set_description(None)
parser.set_usage(None)
# output help
parser.print_help()
# exit
parser.exit()
def openFile(filename, mode="r", create_dir=False):
'''open file in *filename* with mode *mode*.
If *create* is set, the directory containing filename
will be created if it does not exist.
gzip - compressed files are recognized by the
suffix ``.gz`` and opened transparently.
Note that there are differences in the file
like objects returned, for example in the
ability to seek.
returns a file or file-like object.
'''
_, ext = os.path.splitext(filename)
if create_dir:
dirname = os.path.dirname(filename)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
if ext.lower() in (".gz", ".z"):
if sys.version_info.major >= 3:
if mode == "r":
return gzip.open(filename, 'rt', encoding="ascii")
elif mode == "w":
return gzip.open(filename, 'wt',
compresslevel=global_options.compresslevel,
encoding="ascii")
else:
raise NotImplementedError(
"mode '{}' not implemented".format(mode))
else:
return gzip.open(filename, mode,
compresslevel=global_options.compresslevel)
else:
return open(filename, mode)
def getHeader():
"""return a header string with command line options and timestamp
"""
system, host, release, version, machine = os.uname()
return "# output generated by %s\n# job started at %s on %s -- %s\n# pid: %i, system: %s %s %s %s" %\
(" ".join(sys.argv),
time.asctime(time.localtime(time.time())),
host,
global_id,
os.getpid(),
system, release, version, machine)
def getParams(options=None):
"""return a string containing script parameters.
Parameters are all variables that start with ``param_``.
"""
result = []
if options:
members = options.__dict__
for k, v in sorted(members.items()):
result.append("# %-40s: %s" % (k, str(v)))
else:
vars = inspect.currentframe().f_back.f_locals
for var in filter(lambda x: re.match("param_", x), vars.keys()):
result.append("# %-40s: %s" %
(var, str(vars[var])))
if result:
return "\n".join(result)
else:
return "# no parameters."
def getFooter():
"""return a header string with command line options and
timestamp.
"""
return "# job finished in %i seconds at %s -- %s -- %s" %\
(time.time() - global_starting_time,
time.asctime(time.localtime(time.time())),
" ".join(map(lambda x: "%5.2f" % x, os.times()[:4])),
global_id)
class MultiLineFormatter(logging.Formatter):
'''logfile formatter: add identation for multi-line entries.'''
def format(self, record):
s = logging.Formatter.format(self, record)
if s.startswith("#"):
prefix = "#"
else:
prefix = ""
if record.message:
header, footer = s.split(record.message)
s = prefix + s.replace('\n', '\n%s' % prefix + ' ' * len(header))
return s
def Start(parser=None,
argv=sys.argv,
quiet=False,
add_pipe_options=True,
add_group_dedup_options=True,
add_sam_options=True,
return_parser=False):
"""set up an experiment.
The :py:func:`Start` method will set up a file logger and add some
default and some optional options to the command line parser. It
will then parse the command line and set up input/output
redirection and start a timer for benchmarking purposes.
The default options added by this method are:
``-v/--verbose``
the :term:`loglevel`
``timeit``
turn on benchmarking information and save to file
``timeit-name``
name to use for timing information,
``timeit-header``
output header for timing information.
``seed``
the random seed. If given, the python random
number generator will be initialized with this
seed.
Optional options added are:
Arguments
---------
param parser : :py:class:`U.OptionParser`
instance with command line options.
argv : list
command line options to parse. Defaults to
:py:data:`sys.argv`
quiet : bool
set :term:`loglevel` to 0 - no logging
return_parser : bool
return the parser object, no parsing. Useful for inspecting
the command line options of a script without running it.
add_pipe_options : bool
add common options for redirecting input/output
add_sam_options : bool
add options for UMI grouping/deduping and counting from a sam
add_group_dedup_options : bool
add options for UMI grouping and deduping
Returns
-------
tuple
(:py:class:`U.OptionParser` object, list of positional
arguments)
"""
if not parser:
parser = OptionParser(
version="%prog version: $Id$")
global global_options, global_args, global_starting_time
# save default values given by user
user_defaults = copy.copy(parser.defaults)
global_starting_time = time.time()
if add_sam_options:
group = OptionGroup(parser, "Input options")
group.add_option("-i", "--in-sam", dest="in_sam", action="store_true",
help="Input file is in sam format [default=%default]",
default=False)
group.add_option("--extract-umi-method", dest="get_umi_method", type="choice",
choices=("read_id", "tag", "umis"), default="read_id",
help="how is the read UMI +/ cell barcode encoded? "
"[default=%default]")
group.add_option("--umi-separator", dest="umi_sep",
type="string", help="separator between read id and UMI",
default="_")
group.add_option("--umi-tag", dest="umi_tag",
type="string", help="tag containing umi",
default='RX')
group.add_option("--umi-tag-split", dest="umi_tag_split",
type="string",
help="split UMI in tag and take the first element",
default=None)
group.add_option("--umi-tag-delimiter", dest="umi_tag_delim",
type="string",
help="concatenate UMI in tag separated by delimiter",
default=None)
group.add_option("--cell-tag", dest="cell_tag",
type="string", help="tag containing cell barcode",
default=None)
group.add_option("--cell-tag-split", dest="cell_tag_split",
type="string",
help=("split cell barcode in tag and take the first element"
"for e.g 10X GEM tags"),
default='-')
group.add_option("--cell-tag-delimiter", dest="cell_tag_delim",
type="string",
help="concatenate cell barcode in tag separated by delimiter",
default=None)
group.add_option("--paired", dest="paired", action="store_true",
default=False,
help="paired BAM. [default=%default]")
group.add_option("--mapping-quality", dest="mapping_quality",
type="int",
help="Minimum mapping quality for a read to be retained"
" [default=%default]",
default=0)
parser.add_option_group(group)
group = OptionGroup(parser, "UMI grouping options")
group.add_option("--method", dest="method", type="choice",
choices=("adjacency", "directional",
"percentile", "unique", "cluster"),
default="directional",
help="method to use for umi grouping [default=%default]")
group.add_option("--edit-distance-threshold", dest="threshold",
type="int",
default=1,
help="Edit distance theshold at which to join two UMIs "
"when grouping UMIs. [default=%default]")
parser.add_option_group(group)
group = OptionGroup(parser, "Single-cell RNA-Seq options")
group.add_option("--per-gene", dest="per_gene", action="store_true",
default=False,
help="Group/Dedup/Count per gene. Must combine with "
"either --gene-tag or --per-contig")
group.add_option("--gene-tag", dest="gene_tag",
type="string",
help="gene is defined by this bam tag [default=%default]",
default=None)
group.add_option("--skip-tags-regex", dest="skip_regex",
type="string",
help="Used with --gene-tag. "
"Ignore reads where the gene-tag matches this regex",
default="^(__|Unassigned)")
group.add_option("--per-contig", dest="per_contig", action="store_true",
default=False,
help="count per contig (field 3 in BAM; RNAME),"
" e.g for transcriptome where contig = gene")
group.add_option("--gene-transcript-map", dest="gene_transcript_map",
type="string",
help="file mapping transcripts to genes (tab separated)",
default=None)
group.add_option("--per-cell", dest="per_cell", action="store_true",
default=False,
help="Group/Dedup/Count per cell")
parser.add_option_group(group)
if add_group_dedup_options:
group = OptionGroup(parser, "Group/Dedup options")
group.add_option("-o", "--out-sam", dest="out_sam", action="store_true",
help="Output alignments in sam format [default=%default]",
default=False)
group.add_option("--no-sort-output", dest="no_sort_output",
action="store_true", default=False,
help="Don't Sort the output")
group.add_option("--buffer-whole-contig", dest="whole_contig",
action="store_true", default=False,
help="Read whole contig before outputting bundles: "
"guarantees that no reads are missed, but increases "
"memory usage")
group.add_option("--whole-contig", dest="whole_contig",
action="store_true", default=False,
help=optparse.SUPPRESS_HELP)
group.add_option("--multimapping-detection-method",
dest="detection_method", type="choice",
choices=("NH", "X0", "XT"),
default=None,
help="Some aligners identify multimapping using bam "
"tags. Setting this option to NH, X0 or XT will "
"use these tags when selecting the best read "
"amongst reads with the same position and umi "
"[default=%default]")
group.add_option("--spliced-is-unique", dest="spliced",
action="store_true",
help="Treat a spliced read as different to an unspliced"
" one [default=%default]",
default=False)
group.add_option("--soft-clip-threshold", dest="soft_clip_threshold",
type="float",
help="number of bases clipped from 5' end before"
"read is counted as spliced [default=%default]",
default=4)
group.add_option("--read-length", dest="read_length",
action="store_true", default=False,
help="use read length in addition to position and UMI"
"to identify possible duplicates [default=%default]")
parser.add_option_group(group)
# options added separately here to maintain better output order
if add_sam_options:
group = OptionGroup(parser, "debug options")
group.add_option("--ignore-umi", dest="ignore_umi",
action="store_true", help="Ignore UMI and dedup"
" only on position", default=False)
group.add_option("--chrom", dest="chrom", type="string",
help="Restrict to one chromosome",
default=None)
group.add_option("--subset", dest="subset", type="float",
help="Use only a fraction of reads, specified by subset",
default=None)
parser.add_option_group(group)
group = OptionGroup(parser, "profiling options")
group.add_option("--timeit", dest='timeit_file', type="string",
help="store timeing information in file [%default].")
group.add_option("--timeit-name", dest='timeit_name', type="string",
help="name in timing file for this class of jobs "
"[%default].")
group.add_option("--timeit-header", dest='timeit_header',
action="store_true",
help="add header for timing information [%default].")
parser.add_option_group(group)
group = OptionGroup(parser, "common options")
group.add_option("-v", "--verbose", dest="loglevel", type="int",
help="loglevel [%default]. The higher, the more output.")
group.add_option("-?", dest="short_help", action="callback",
callback=callbackShortHelp,
help="output short help (command line options only.")
group.add_option("--random-seed", dest='random_seed', type="int",
help="random seed to initialize number generator "
"with [%default].")
parser.add_option_group(group)
if quiet:
parser.set_defaults(loglevel=0)
else:
parser.set_defaults(loglevel=1)
parser.set_defaults(
timeit_file=None,
timeit_name='all',
timeit_header=None,
random_seed=None,
)
if add_pipe_options:
group = OptionGroup(parser, "Input/output options")
group.add_option("-I", "--stdin", dest="stdin", type="string",
help="file to read stdin from [default = stdin].",
metavar="FILE")
group.add_option("-L", "--log", dest="stdlog", type="string",
help="file with logging information "
"[default = stdout].",
metavar="FILE")
group.add_option("-E", "--error", dest="stderr", type="string",
help="file with error information "
"[default = stderr].",
metavar="FILE")
group.add_option("-S", "--stdout", dest="stdout", type="string",
help="file where output is to go "
"[default = stdout].",
metavar="FILE")
group.add_option("--log2stderr", dest="log2stderr",
action="store_true", help="send logging information"
" to stderr [default = False].")
group.add_option("--compresslevel", dest="compresslevel", type="int",
help="Level of Gzip compression to use. Default (6) matches"
"GNU gzip rather than python gzip default (which is 9)")
parser.set_defaults(stderr=sys.stderr)
parser.set_defaults(stdout=sys.stdout)
parser.set_defaults(stdlog=sys.stdout)
parser.set_defaults(stdin=sys.stdin)
parser.set_defaults(log2stderr=False)
parser.set_defaults(compresslevel=6)
parser.add_option_group(group)
# restore user defaults
parser.defaults.update(user_defaults)
if return_parser:
return parser
global_options, global_args = parser.parse_args(argv[1:])
if global_options.random_seed is not None:
random.seed(global_options.random_seed)
if add_pipe_options:
if global_options.stdout != sys.stdout:
global_options.stdout = openFile(global_options.stdout, "w")
if global_options.stderr != sys.stderr:
if global_options.stderr == "stderr":
global_options.stderr = global_options.stderr
else:
global_options.stderr = openFile(global_options.stderr, "w")
if global_options.stdlog != sys.stdout:
global_options.stdlog = openFile(global_options.stdlog, "a")
elif global_options.log2stderr:
global_options.stdlog = global_options.stderr
if global_options.stdin != sys.stdin:
global_options.stdin = openFile(global_options.stdin, "r")
else:
global_options.stderr = sys.stderr
global_options.stdout = sys.stdout
global_options.stdin = sys.stdin
if global_options.log2stderr:
global_options.stdlog = sys.stderr
else:
global_options.stdlog = sys.stdout
# if global_options.loglevel >= 1:
# global_options.stdlog.write(getHeader() + "\n")
# global_options.stdlog.write(getParams(global_options) + "\n")
# global_options.stdlog.flush()
# configure logging
# map from 0-10 to logging scale
# 0: quiet
# 1: little verbositiy
# >1: increased verbosity
if global_options.loglevel == 0:
lvl = logging.ERROR
elif global_options.loglevel == 1:
lvl = logging.INFO
else:
lvl = logging.DEBUG
if global_options.stdout == global_options.stdlog:
format = '# %(asctime)s %(levelname)s %(message)s'
else:
format = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(
level=lvl,
format=format,
stream=global_options.stdlog)
# set up multi-line logging
# Note that .handlers is not part of the API, might change
# Solution is to configure handlers explicitely.
for handler in logging.getLogger().handlers:
handler.setFormatter(MultiLineFormatter(format))
return global_options, global_args
def validateSamOptions(options):
''' Check the validity of the option combinations '''
if options.per_gene:
if options.gene_tag and options.per_contig:
raise ValueError("need to use either --per-contig "
"OR --gene-tag, please do not provide both")
if not options.per_contig and not options.gene_tag:
raise ValueError("for per-gene applications, must supply "
"--per-contig or --gene-tag")
if options.per_contig and not options.per_gene: