File: qa.py

package info (click to toggle)
htseq 2.0.9%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 103,476 kB
  • sloc: python: 6,280; sh: 211; cpp: 147; makefile: 80
file content (336 lines) | stat: -rw-r--r-- 10,427 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/env python

# HTSeq_QA.py
#
# (c) Simon Anders, European Molecular Biology Laboratory, 2010
# released under GNU General Public License

import sys
import os.path
import argparse
from itertools import islice
import numpy as np
import HTSeq

try:
    import matplotlib
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import Normalize
except ImportError:
    sys.stderr.write("htseq-qa needs 'matplotlib >= 1.5'")
    raise


def get_read_length(readfile, isAlnmntFile):
    readlen = 0
    if isAlnmntFile:
        reads = (a.read for a in readfile)
    else:
        reads = readfile
    for r in islice(reads, 10000):
        if len(r) > readlen:
            readlen = len(r)

    return readlen


def compute_quality(
        readfilename,
        file_type,
        nosplit,
        readlen,
        max_qual,
        gamma,
        primary_only=False,
        max_records=-1,
        ):

    if file_type in ("sam", "bam"):
        readfile = HTSeq.BAM_Reader(readfilename)
        isAlnmntFile = True
    elif file_type == "solexa-export":
        readfile = HTSeq.SolexaExportReader(readfilename)
        isAlnmntFile = True
    elif file_type == "fastq":
        readfile = HTSeq.FastqReader(readfilename)
        isAlnmntFile = False
    elif file_type == "solexa-fastq":
        readfile = HTSeq.FastqReader(readfilename, "solexa")
        isAlnmntFile = False
    else:
        raise ValueError('File format not recognized: {:}'.format(file_type))

    twoColumns = isAlnmntFile and (not nosplit)

    if readlen is None:
        readlen = get_read_length(readfile, isAlnmntFile)

    # Initialize count arrays
    base_arr_U = np.zeros((readlen, 5), np.int64)
    qual_arr_U = np.zeros((readlen, max_qual+1), np.int64)
    if twoColumns:
        base_arr_A = np.zeros((readlen, 5), np.int64)
        qual_arr_A = np.zeros((readlen, max_qual+1), np.int64)

    # Main counting loop
    i = 0
    try:
        for a in readfile:
            if isAlnmntFile:
                r = a.read
            else:
                r = a

            # Exclude non-primary alignments if requested
            if isAlnmntFile and primary_only:
                if a.aligned and a.not_primary_alignment:
                    continue

            if twoColumns and isAlnmntFile and a.aligned:
                r.add_bases_to_count_array(base_arr_A)
                r.add_qual_to_count_array(qual_arr_A)
            else:
                r.add_bases_to_count_array(base_arr_U)
                r.add_qual_to_count_array(qual_arr_U)

            i += 1

            if i == max_records:
                break

            if (i % 200000) == 0:
                if (not isAlnmntFile) or primary_only:
                    print(i, "reads processed")
                else:
                    print(i, "alignments processed")

    except:
        sys.stderr.write("Error occured in: %s\n" %
                         readfile.get_line_number_string())
        raise

    if (not isAlnmntFile) or primary_only:
        print(i, "reads processed")
    else:
        print(i, "alignments processed")

    # Normalize result
    def norm_by_pos(arr):
        arr = np.array(arr, np.float64)
        arr_n = (arr.T / arr.sum(1)).T
        arr_n[arr == 0] = 0
        return arr_n

    def norm_by_start(arr):
        arr = np.array(arr, np.float64)
        arr_n = (arr.T / arr.sum(1)[0]).T
        arr_n[arr == 0] = 0
        return arr_n

    result = {
        'isAlnmntFile': isAlnmntFile,
        'readlen': readlen,
        'twoColumns': twoColumns,
        'base_arr_U_n': norm_by_pos(base_arr_U),
        'qual_arr_U_n': norm_by_start(qual_arr_U),
        'nreads_U': base_arr_U[0, :].sum(),
        }

    if twoColumns:
        result['base_arr_A_n'] = norm_by_pos(base_arr_A)
        result['qual_arr_A_n'] = norm_by_start(qual_arr_A)
        result['nreads_A'] = base_arr_A[0, :].sum()

    return result


def plot(
        result,
        readfilename,
        outfile,
        max_qual,
        gamma,
        primary_only=False,
        ):

    def plot_bases(arr, ax):
        xg = np.arange(readlen)
        ax.plot(xg, arr[:, 0], marker='.', color='red')
        ax.plot(xg, arr[:, 1], marker='.', color='darkgreen')
        ax.plot(xg, arr[:, 2], marker='.', color='lightgreen')
        ax.plot(xg, arr[:, 3], marker='.', color='orange')
        ax.plot(xg, arr[:, 4], marker='.', color='grey')
        ax.set_xlim(0, readlen-1)
        ax.set_ylim(0, 1)
        ax.text(readlen*.70, .9, "A", color="red")
        ax.text(readlen*.75, .9, "C", color="darkgreen")
        ax.text(readlen*.80, .9, "G", color="lightgreen")
        ax.text(readlen*.85, .9, "T", color="orange")
        ax.text(readlen*.90, .9, "N", color="grey")

    if outfile is None:
        outfilename = os.path.basename(readfilename) + ".pdf"
    else:
        outfilename = outfile

    isAlnmntFile = result['isAlnmntFile']
    readlen = result['readlen']
    twoColumns = result['twoColumns']

    base_arr_U_n = result['base_arr_U_n']
    qual_arr_U_n = result['qual_arr_U_n']
    nreads_U = result['nreads_U']

    if twoColumns:
        base_arr_A_n = result['base_arr_A_n']
        qual_arr_A_n = result['qual_arr_A_n']
        nreads_A = result['nreads_A']

    cur_backend = matplotlib.get_backend()

    try:
        matplotlib.use('PDF')

        fig = plt.figure()
        fig.subplots_adjust(top=.85)
        fig.suptitle(os.path.basename(readfilename), fontweight='bold')

        if twoColumns:

            ax = fig.add_subplot(221)
            plot_bases(base_arr_U_n, ax)
            ax.set_ylabel("proportion of base")
            ax.set_title(
                    "non-aligned reads\n{:.0%} ({:.4f} million)".format(
                    1.0 * nreads_U / (nreads_U+nreads_A),
                    1.0 * nreads_U / 1e6,
                    ))

            ax2 = fig.add_subplot(222)
            plot_bases(base_arr_A_n, ax2)
            ax2.set_title(
                    "{:}\n{:.0%} ({:.4f} million)".format(
                        'aligned reads' if primary_only else 'alignments',
                        1.0 * nreads_A / (nreads_U+nreads_A),
                        1.0 * nreads_A / 1e6,
                    ))

            ax3 = fig.add_subplot(223)
            ax3.pcolor(
                    qual_arr_U_n.T ** gamma,
                    cmap=plt.cm.Greens,
                    norm=Normalize(0, 1))
            ax3.set_xlim(0, readlen-1)
            ax3.set_ylim(0, max_qual+1)
            ax3.set_xlabel("position in read")
            ax3.set_ylabel("base-call quality score")

            ax4 = fig.add_subplot(224)
            ax4.pcolor(
                    qual_arr_A_n.T ** gamma,
                    cmap=plt.cm.Greens,
                    norm=Normalize(0, 1))
            ax4.set_xlim(0, readlen-1)
            ax4.set_ylim(0, max_qual+1)
            ax4.set_xlabel("position in read")

        else:

            ax = fig.add_subplot(211)
            plot_bases(base_arr_U_n, ax)
            ax.set_ylabel("proportion of base")
            ax.set_title("{:.3f} million {:}".format(
                1.0 * nreads_U / 1e6,
                'reads' if (not isAlnmntFile) or primary_only else 'alignments',
                ))

            ax2 = fig.add_subplot(212)
            ax2.pcolor(
                    qual_arr_U_n.T ** gamma,
                    cmap=plt.cm.Greens,
                    norm=Normalize(0, 1))
            ax2.set_xlim(0, readlen-1)
            ax2.set_ylim(0, max_qual+1)
            ax2.set_xlabel("position in read")
            ax2.set_ylabel("base-call quality score")

        fig.savefig(outfilename)

    finally:
        matplotlib.use(cur_backend)


def main():

    # **** Parse command line ****
    pa = argparse.ArgumentParser(
        description=
        "This script take a file with high-throughput sequencing reads " +
        "(supported formats: SAM, Solexa _export.txt, FASTQ, Solexa " +
        "_sequence.txt) and performs a simply quality assessment by " +
        "producing plots showing the distribution of called bases and " +
        "base-call quality scores by position within the reads. The " +
        "plots are output as a PDF file.",
        )
    pa.add_argument(
        'readfilename',
        help='The file to count reads in (SAM/BAM or Fastq)',
        )
    pa.add_argument(
        "-t", "--type", type=str, dest="type",
        choices=("sam", "bam", "solexa-export", "fastq", "solexa-fastq"),
        default="sam", help="type of read_file (one of: sam [default], bam, " +
        "solexa-export, fastq, solexa-fastq)")
    pa.add_argument(
        "-o", "--outfile", type=str, dest="outfile",
        help="output filename (default is <read_file>.pdf)")
    pa.add_argument(
        "-r", "--readlength", type=int, dest="readlen",
        help="the maximum read length (when not specified, the script guesses from the file")
    pa.add_argument(
        "-g", "--gamma", type=float, dest="gamma",
        default=0.3,
        help="the gamma factor for the contrast adjustment of the quality score plot")
    pa.add_argument(
        "-n", "--nosplit", action="store_true", dest="nosplit",
        help="do not split reads in unaligned and aligned ones")
    pa.add_argument(
        "-m", "--maxqual", type=int, dest="maxqual", default=41,
        help="the maximum quality score that appears in the data (default: 41)")
    pa.add_argument(
        '--primary-only', action='store_true',
        help="For SAM/BAM input files, ignore alignments that are not primary. " +
        "This only affects 'multimapper' reads that align to several regions " +
        "in the genome. By choosing this option, each read will only count as " +
        "one; without this option, each of its alignments counts as one."
    )
    pa.add_argument(
        '--max-records', type=int, default=-1, dest='max_records',
        help="Limit the analysis to the first N reads/alignments."
        )

    args = pa.parse_args()

    result = compute_quality(
        args.readfilename,
        args.type,
        args.nosplit,
        args.readlen,
        args.maxqual,
        args.gamma,
        args.primary_only,
        args.max_records,
        )

    plot(
        result,
        args.readfilename,
        args.outfile,
        args.maxqual,
        args.gamma,
        args.primary_only,
        )


if __name__ == "__main__":
    main()