Implement writing to compressed files for qseq2fastq
[htsworkflow.git] / htsworkflow / pipelines / qseq2fastq.py
1 #!/usr/bin/env python
2 """Convert a collection of qseq or a tar file of qseq files to a fastq file
3 """
4 from __future__ import print_function, unicode_literals
5 from glob import glob
6 import os
7 from optparse import OptionParser
8 import numpy
9 import sys
10 import tarfile
11
12 from htsworkflow.util.version import version
13 from htsworkflow.util.conversion import parse_slice
14 from htsworkflow.pipelines.desplit_fastq import open_output
15
16
17 def main(cmdline=None):
18     """Command line driver: [None, '-i', 'tarfile', '-o', 'target.fastq']
19     """
20     parser = make_parser()
21     opts, args = parser.parse_args(cmdline)
22
23     if opts.version:
24         print(version())
25         return 0
26
27     if opts.infile is not None:
28         qseq_generator = tarfile_generator(opts.infile)
29     elif len(args) > 0:
30         qseq_generator = file_generator(args)
31     else:
32         qseq_generator = [sys.stdin]
33
34     if opts.output is not None:
35         output = open_output(opts.output, opts)
36     else:
37         output = sys.stdout
38
39     if opts.nopass_output is not None:
40         nopass_output = open_output(opts.nopass_output, opts)
41     else:
42         nopass_output = None
43
44     qseq_parser = Qseq2Fastq(qseq_generator, output, nopass_output)
45     qseq_parser.fastq = not opts.fasta
46     qseq_parser.flowcell_id = opts.flowcell
47     qseq_parser.trim = parse_slice(opts.slice)
48     qseq_parser.reportFilter = opts.pf
49
50     qseq_parser.run()
51
52
53 def make_parser():
54     """Return option parser"""
55     usage = "%prog: [options] *_qseq.txt\nProduces Phred33 files by default"
56     parser = OptionParser(usage)
57     parser.add_option("-a", "--fasta", default=False, action="store_true",
58                       help="produce fasta files instead of fastq files")
59     parser.add_option("-f", "--flowcell", default=None,
60                       help="Set flowcell ID for output file")
61     parser.add_option("-i", "--infile", default=None,
62                       help='source tar file (if reading from an archive '\
63                            'instead of a directory)')
64     parser.add_option("-o", "--output", default=None,
65                       help="output fastq file")
66     parser.add_option("-n", "--nopass-output", default=None,
67                       help="if provided send files that failed "\
68                            "illumina filter to a differentfile")
69     parser.add_option("-s", "--slice",
70                       help="specify python slice, e.g. 0:75, 0:-1",
71                       default=None)
72     parser.add_option("--pf", help="report pass filter flag", default=False,
73                       action="store_true")
74     parser.add_option('--gzip', default=False, action='store_true',
75                       help='gzip output')
76     parser.add_option('--bzip', default=False, action='store_true',
77                       help='bzip output')
78     parser.add_option("--version", default=False, action="store_true",
79                       help="report software version")
80
81     return parser
82
83
84 def file_generator(pattern_list):
85     """Given a list of glob patterns yield open streams for matching files"""
86     for pattern in pattern_list:
87         for filename in glob(pattern):
88             yield open(filename, "r")
89
90
91 def tarfile_generator(tarfilename):
92     """Yield open streams for files inside a tarfile"""
93     archive = tarfile.open(tarfilename, 'r|*')
94     for tarinfo in archive:
95         yield archive.extractfile(tarinfo)
96
97
98 class Qseq2Fastq(object):
99     """
100     Convert qseq files to fastq (or fasta) files.
101     """
102     def __init__(self, sources, pass_destination, nopass_destination=None):
103         self.sources = sources
104         self.pass_destination = pass_destination
105         if nopass_destination is not None:
106             self.nopass_destination = nopass_destination
107         else:
108             self.nopass_destination = pass_destination
109
110         self.fastq = True
111         self.flowcell_id = None
112         self.trim = slice(None)
113         self.report_filter = False
114
115     def _format_flowcell_id(self):
116         """
117         Return formatted flowcell ID
118         """
119         if self.flowcell_id is not None:
120             return self.flowcell_id + "_"
121         else:
122             return ""
123
124     def run(self):
125         """Run conversion
126         (Used to match threading/multiprocessing API)
127         """
128         if self.fastq:
129             header_template = '@'
130         else:
131             # fasta case
132             header_template = '>'
133         header_template += self._format_flowcell_id() + \
134                            '%s_%s:%s:%s:%s:%s/%s%s%s'
135
136         for qstream in self.sources:
137             for line in qstream:
138                 # parse line
139                 record = line.rstrip().split('\t')
140                 machine_name = record[0]
141                 run_number = record[1]
142                 lane_number = record[2]
143                 tile = record[3]
144                 x = record[4]
145                 y = record[5]
146                 #index = record[6]
147                 read = record[7]
148                 sequence = record[8].replace('.', 'N')
149                 quality = convert_illumina_quality(record[9])
150
151                 # add pass qc filter if we want it
152                 pass_qc = int(record[10])
153                 if self.report_filter:
154                     pass_qc_msg = " pf=%s" % (pass_qc)
155                 else:
156                     pass_qc_msg = ""
157
158                 header = header_template % ( \
159                     machine_name,
160                     run_number,
161                     lane_number,
162                     tile,
163                     x,
164                     y,
165                     read,
166                     pass_qc_msg,
167                     os.linesep)
168
169                 # if we passed the filter write to the "good" file
170                 if pass_qc:
171                     destination = self.pass_destination
172                 else:
173                     destination = self.nopass_destination
174
175                 destination.write(header)
176                 destination.write(sequence[self.trim])
177                 destination.write(os.linesep)
178                 if self.fastq:
179                     destination.write('+')
180                     destination.write(os.linesep)
181                     destination.write(quality[self.trim].tostring())
182                     destination.write(os.linesep)
183
184 def convert_illumina_quality(illumina_quality):
185     """Convert an Illumina quality score to a Phred ASCII quality score.
186     """
187     # Illumina scores are Phred + 64
188     # Fastq scores are Phread + 33
189     # the following code grabs the string, converts to short ints and
190     # subtracts 31 (64-33) to convert between the two score formats.
191     # The numpy solution is twice as fast as some of my other
192     # ideas for the conversion.
193     # sorry about the uglyness in changing from character, to 8-bit int
194     # and back to a character array
195     quality = numpy.asarray(illumina_quality, 'c')
196     quality.dtype = numpy.uint8
197     quality -= 31
198      # I'd like to know what the real numpy char type is
199     quality.dtype = '|S1'
200     return quality
201
202
203 if __name__ == "__main__":
204     main()