HTSeq 2.0.7__cp312-cp312-macosx_10_9_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
HTSeq/scripts/count.py ADDED
@@ -0,0 +1,492 @@
1
+ import sys
2
+ import argparse
3
+ import operator
4
+ import itertools
5
+ import warnings
6
+ import traceback
7
+ import os.path
8
+ import multiprocessing
9
+ import numpy as np
10
+ import pysam
11
+
12
+ import HTSeq
13
+ from HTSeq.scripts.count_features.count_features_per_file import count_reads_single_file
14
+ from HTSeq.scripts.utils import (
15
+ my_showwarning,
16
+ _write_output,
17
+ )
18
+
19
+
20
+ def count_reads_in_features(args):
21
+ """Count reads in features, parallelizing by file
22
+
23
+ Args:
24
+ args: ArgumentParser args, i.e. each argument is a property of this
25
+ instance. Check the CLI parsing function below for a full list
26
+ of properties, i.e. command-line options.
27
+
28
+ This function can be conceptually split into the following steps:
29
+
30
+ 1. Load features from GTF file into memory
31
+ 2. Parse the reads from each BAM file in parallel or series
32
+ 3. Write output table
33
+
34
+ Step 2 can be further split into two main components:
35
+
36
+ 1. Find what features overlap with each read/read pair
37
+ 2. Assign that read/pair to a feature (if unique) or a corner case
38
+ (e.g. multimappers)
39
+ """
40
+
41
+ # Load feature GenomicArrayOfSets to mark overlaps
42
+ gff = HTSeq.GFF_Reader(args.featuresfilename)
43
+ feature_scan = HTSeq.make_feature_genomicarrayofsets(
44
+ gff,
45
+ args.idattr,
46
+ feature_type=args.feature_type,
47
+ feature_query=args.feature_query,
48
+ additional_attributes=args.additional_attributes,
49
+ stranded=args.stranded != "no",
50
+ verbose=not args.quiet,
51
+ add_chromosome_info=args.add_chromosome_info,
52
+ )
53
+ features = feature_scan["features"]
54
+ attributes = feature_scan["attributes"]
55
+ feature_attr = sorted(attributes.keys())
56
+ if len(feature_attr) == 0:
57
+ sys.stderr.write("Warning: No features of type '{args.feature_type}' found.\n")
58
+
59
+ # Count reads in parallel or in series
60
+ count_args, attributes = _prepare_args_for_counting(
61
+ features,
62
+ feature_attr,
63
+ attributes,
64
+ args.add_chromosome_info,
65
+ args.additional_attributes,
66
+ args.feature_query,
67
+ args.feature_type,
68
+ args.featuresfilename,
69
+ args.idattr,
70
+ args.max_buffer_size,
71
+ args.minaqual,
72
+ args.nonunique,
73
+ args.order,
74
+ args.mode,
75
+ args.quiet,
76
+ args.samfilenames,
77
+ args.samout_format,
78
+ args.samouts,
79
+ args.secondary_alignments,
80
+ args.stranded,
81
+ args.supplementary_alignments,
82
+ )
83
+ if args.nprocesses > 1:
84
+ with multiprocessing.Pool(args.nprocesses) as pool:
85
+ results = pool.starmap(count_reads_single_file, count_args)
86
+ results.sort(key=operator.itemgetter("isam"))
87
+ else:
88
+ results = list(itertools.starmap(count_reads_single_file, count_args))
89
+
90
+ # Merge and write output
91
+ _write_output(
92
+ results,
93
+ args.samfilenames,
94
+ attributes,
95
+ args.additional_attributes,
96
+ args.output_filename,
97
+ args.output_delimiter,
98
+ args.output_append,
99
+ sparse=args.counts_output_sparse,
100
+ dtype=np.float32,
101
+ add_tsv_header=args.with_header
102
+ )
103
+
104
+
105
+ def _prepare_args_for_counting(
106
+ features,
107
+ feature_attr,
108
+ attributes,
109
+ add_chromosome_info,
110
+ additional_attributes,
111
+ feature_query,
112
+ feature_type,
113
+ gff_filename,
114
+ id_attribute,
115
+ max_buffer_size,
116
+ minaqual,
117
+ multimapped_mode,
118
+ order,
119
+ overlap_mode,
120
+ quiet,
121
+ sam_filenames,
122
+ samout_format,
123
+ samouts,
124
+ secondary_alignment_mode,
125
+ stranded,
126
+ supplementary_alignment_mode,
127
+ ):
128
+ args = []
129
+ for isam, (sam_filename, samout_filename) in enumerate(zip(sam_filenames, samouts)):
130
+ args.append(
131
+ (
132
+ isam,
133
+ sam_filename,
134
+ features,
135
+ feature_attr,
136
+ order,
137
+ max_buffer_size,
138
+ stranded,
139
+ overlap_mode,
140
+ multimapped_mode,
141
+ secondary_alignment_mode,
142
+ supplementary_alignment_mode,
143
+ feature_type,
144
+ id_attribute,
145
+ additional_attributes,
146
+ quiet,
147
+ minaqual,
148
+ samout_format,
149
+ samout_filename,
150
+ )
151
+ )
152
+ return args, attributes
153
+
154
+
155
+ def _check_sam_files(sam_filenames):
156
+ if (len(sam_filenames) != 1) or (sam_filenames[0] != "-"):
157
+ for sam_filename in sam_filenames:
158
+ with pysam.AlignmentFile(sam_filename, "r") as sf:
159
+ pass
160
+
161
+
162
+ def _check_samouts(sam_filenames, samout_format, samouts):
163
+ if len(samouts) != len(sam_filenames):
164
+ raise ValueError("Select the same number of input and output files")
165
+ # Try to open samout files early in case any of them has issues
166
+ if samout_format in ("SAM", "sam"):
167
+ for samout in samouts:
168
+ with open(samout, "w"):
169
+ pass
170
+ else:
171
+ # We don't have a template if the input is stdin
172
+ if (len(sam_filenames) != 1) or (sam_filenames[0] != "-"):
173
+ for sam_filename, samout in zip(sam_filenames, samouts):
174
+ with pysam.AlignmentFile(sam_filename, "r") as sf:
175
+ with pysam.AlignmentFile(samout, "w", template=sf):
176
+ pass
177
+
178
+
179
+ def _parse_sanitize_cmdline_arguments():
180
+ pa = argparse.ArgumentParser(
181
+ add_help=False,
182
+ )
183
+ pa.add_argument(
184
+ "--version", action="store_true", help="Show software version and exit"
185
+ )
186
+ args, argv = pa.parse_known_args()
187
+
188
+ # Version is the only case where the BAM and GTF files are optional
189
+ if args.version:
190
+ print(HTSeq.__version__)
191
+ sys.exit()
192
+
193
+ pa = argparse.ArgumentParser(
194
+ parents=[pa],
195
+ description="This script takes one or more alignment files in SAM/BAM "
196
+ + "format and a feature file in GFF format and calculates for each feature "
197
+ + "the number of reads mapping to it. See "
198
+ + "http://htseq.readthedocs.io/en/master/count.html for details.",
199
+ epilog="Written by Simon Anders (sanders@fs.tum.de), "
200
+ + "European Molecular Biology Laboratory (EMBL), Givanna Putri "
201
+ + "(g.putri@unsw.edu.au) and Fabio Zanini "
202
+ + "(fabio.zanini@unsw.edu.au), UNSW Sydney. (c) 2010-2021. "
203
+ + "Released under the terms of the GNU General Public License v3. "
204
+ + "Please cite the following paper if you use this script: \n"
205
+ + " G. Putri et al. Analysing high-throughput sequencing data in "
206
+ + "Python with HTSeq 2.0. Bioinformatics (2022). "
207
+ + "https://doi.org/10.1093/bioinformatics/btac166.\n"
208
+ + "Part of the 'HTSeq' framework, version %s." % HTSeq.__version__,
209
+ )
210
+
211
+ pa.add_argument(
212
+ "samfilenames",
213
+ nargs="+",
214
+ type=str,
215
+ help="Path to the SAM/BAM files containing the mapped reads. "
216
+ + "If '-' is selected, read from standard input",
217
+ )
218
+ pa.add_argument(
219
+ "featuresfilename",
220
+ type=str,
221
+ help="Path to the GTF file containing the features",
222
+ )
223
+ pa.add_argument(
224
+ "-f",
225
+ "--format",
226
+ dest="samtype",
227
+ choices=("sam", "bam", "auto"),
228
+ default="auto",
229
+ help="Type of <alignment_file> data. DEPRECATED: "
230
+ + "file format is detected automatically. This option is ignored.",
231
+ )
232
+ pa.add_argument(
233
+ "-r",
234
+ "--order",
235
+ dest="order",
236
+ choices=("pos", "name"),
237
+ default="name",
238
+ help="'pos' or 'name'. Sorting order of <alignment_file> (default: name). Paired-end sequencing "
239
+ + "data must be sorted either by position or by read name, and the sorting order "
240
+ + "must be specified. Ignored for single-end data.",
241
+ )
242
+ pa.add_argument(
243
+ "--max-reads-in-buffer",
244
+ dest="max_buffer_size",
245
+ type=int,
246
+ default=30000000,
247
+ help="When <alignment_file> is paired end sorted by position, "
248
+ + "allow only so many reads to stay in memory until the mates are "
249
+ + "found (raising this number will use more memory). Has no effect "
250
+ + "for single end or paired end sorted by name",
251
+ )
252
+ pa.add_argument(
253
+ "-s",
254
+ "--stranded",
255
+ dest="stranded",
256
+ choices=("yes", "no", "reverse"),
257
+ default="yes",
258
+ help="Whether the data is from a strand-specific assay. Specify 'yes', "
259
+ + "'no', or 'reverse' (default: yes). "
260
+ + "'reverse' means 'yes' with reversed strand interpretation",
261
+ )
262
+ pa.add_argument(
263
+ "-a",
264
+ "--minaqual",
265
+ type=int,
266
+ dest="minaqual",
267
+ default=10,
268
+ help="Skip all reads with MAPQ alignment quality lower than the given "
269
+ + "minimum value (default: 10). MAPQ is the 5th column of a SAM/BAM "
270
+ + "file and its usage depends on the software used to map the reads.",
271
+ )
272
+ pa.add_argument(
273
+ "-t",
274
+ "--type",
275
+ type=str,
276
+ dest="feature_type",
277
+ default="exon",
278
+ help="Feature type (3rd column in GTF file) to be used, "
279
+ + "all features of other type are ignored (default, suitable for Ensembl "
280
+ + "GTF files: exon)",
281
+ )
282
+ pa.add_argument(
283
+ "-i",
284
+ "--idattr",
285
+ type=str,
286
+ dest="idattr",
287
+ action="append",
288
+ default=["gene_id"],
289
+ help="GTF attribute to be used as feature ID (default, "
290
+ + "suitable for Ensembl GTF files: gene_id). All feature of the "
291
+ + "right type (see -t option) within the same GTF attribute will "
292
+ + "be added together. The typical way of using this option is to "
293
+ + "count all exonic reads from each gene and add the exons "
294
+ + "but other uses are possible as well. You can call this option "
295
+ + "multiple times: in that case, the combination of all attributes "
296
+ + "separated by colons (:) will be used as a unique identifier, "
297
+ + "e.g. for exons you might use -i gene_id -i exon_number.",
298
+ )
299
+ pa.add_argument(
300
+ "--additional-attr",
301
+ type=str,
302
+ action="append",
303
+ dest='additional_attributes',
304
+ default=[],
305
+ help="Additional feature attributes (default: none, "
306
+ + "suitable for Ensembl GTF files: gene_name). Use multiple times "
307
+ + "for more than one additional attribute. These attributes are "
308
+ + "only used as annotations in the output, while the determination "
309
+ + "of how the counts are added together is done based on option -i.",
310
+ )
311
+ pa.add_argument(
312
+ "--add-chromosome-info",
313
+ action="store_true",
314
+ help="Store information about the chromosome of each feature as "
315
+ + "an additional attribute (e.g. colunm in the TSV output file).",
316
+ )
317
+ pa.add_argument(
318
+ "-m",
319
+ "--mode",
320
+ dest="mode",
321
+ choices=("union", "intersection-strict", "intersection-nonempty"),
322
+ default="union",
323
+ help="Mode to handle reads overlapping more than one feature "
324
+ + "(choices: union, intersection-strict, intersection-nonempty; default: union)",
325
+ )
326
+ pa.add_argument(
327
+ "--nonunique",
328
+ dest="nonunique",
329
+ type=str,
330
+ choices=("none", "all", "fraction", "random"),
331
+ default="none",
332
+ help="Whether and how to score reads that are not uniquely aligned "
333
+ + "or ambiguously assigned to features "
334
+ + "(choices: none, all, fraction, random; default: none)",
335
+ )
336
+ pa.add_argument(
337
+ "--secondary-alignments",
338
+ dest="secondary_alignments",
339
+ type=str,
340
+ choices=("score", "ignore"),
341
+ default="ignore",
342
+ help="Whether to score secondary alignments (0x100 flag)",
343
+ )
344
+ pa.add_argument(
345
+ "--supplementary-alignments",
346
+ dest="supplementary_alignments",
347
+ type=str,
348
+ choices=("score", "ignore"),
349
+ default="ignore",
350
+ help="Whether to score supplementary alignments (0x800 flag)",
351
+ )
352
+ pa.add_argument(
353
+ "-o",
354
+ "--samout",
355
+ type=str,
356
+ dest="samouts",
357
+ action="append",
358
+ default=[],
359
+ help="Write out all SAM alignment records into "
360
+ + "SAM/BAM files (one per input file needed), annotating each line "
361
+ + "with its feature assignment (as an optional field with tag 'XF')"
362
+ + ". See the -p option to use BAM instead of SAM.",
363
+ )
364
+ pa.add_argument(
365
+ "-p",
366
+ "--samout-format",
367
+ type=str,
368
+ dest="samout_format",
369
+ choices=("SAM", "BAM", "sam", "bam"),
370
+ default="SAM",
371
+ help="Format to use with the --samout option.",
372
+ )
373
+ pa.add_argument(
374
+ "-d",
375
+ "--delimiter",
376
+ type=str,
377
+ dest="output_delimiter",
378
+ default="\t",
379
+ help="Column delimiter in output (default: TAB).",
380
+ )
381
+ pa.add_argument(
382
+ "-c",
383
+ "--counts_output",
384
+ type=str,
385
+ dest="output_filename",
386
+ default="",
387
+ help="Filename to output the counts to instead of stdout.",
388
+ )
389
+ pa.add_argument(
390
+ "--counts-output-sparse",
391
+ action="store_true",
392
+ help="Store the counts as a sparse matrix (mtx, h5ad, loom).",
393
+ )
394
+ pa.add_argument(
395
+ "--append-output",
396
+ action="store_true",
397
+ dest="output_append",
398
+ help="Append counts output to an existing file instead of "
399
+ + "creating a new one. This option is useful if you have "
400
+ + "already creates a TSV/CSV/similar file with a header for your "
401
+ + "samples (with additional columns for the feature name and any "
402
+ + "additionl attributes) and want to fill in the rest of the file.",
403
+ )
404
+ pa.add_argument(
405
+ "-n",
406
+ "--nprocesses",
407
+ type=int,
408
+ dest="nprocesses",
409
+ default=1,
410
+ help="Number of parallel CPU processes to use (default: 1). "
411
+ + "This option is useful to process several input files at once. "
412
+ + "Each file will use only 1 CPU. It is possible, of course, to "
413
+ + "split a very large input SAM/BAM files into smaller chunks "
414
+ + "upstream to make use of this option.",
415
+ )
416
+ pa.add_argument(
417
+ "--feature-query",
418
+ type=str,
419
+ dest="feature_query",
420
+ default=None,
421
+ help="Restrict to features descibed in this expression. Currently "
422
+ + 'supports a single kind of expression: attribute == "one attr" to '
423
+ + "restrict the GFF to a single gene or transcript, e.g. "
424
+ + "--feature-query 'gene_name == \"ACTB\"' - notice the single "
425
+ + "quotes around the argument of this option and the double "
426
+ + "quotes around the gene name. Broader queries might become "
427
+ + "available in the future.",
428
+ )
429
+ pa.add_argument(
430
+ "-q",
431
+ "--quiet",
432
+ action="store_true",
433
+ dest="quiet",
434
+ help="Suppress progress report",
435
+ ) # and warnings" )
436
+
437
+ pa.add_argument(
438
+ "--with-header",
439
+ action="store_true",
440
+ dest="with_header",
441
+ help="Whether to add a column header to the output TSV file indicating which column "
442
+ + "corresponds to which input BAM file. Only used if output to console or tsv or csv file. "
443
+ + "Default to False."
444
+ )
445
+
446
+ args = pa.parse_args()
447
+
448
+ # Deal with custom id_attribute lists. This is never shorter than 1 because
449
+ # gene_id is the default. However, if the option was called at least once,
450
+ # that should _override_ the default, which means skipping the first
451
+ # element (i.e., gene_id).
452
+ if len(args.idattr) > 1:
453
+ del args.idattr[0]
454
+
455
+ # Never use more CPUs than files
456
+ args.nprocesses = min(args.nprocesses, len(args.samfilenames))
457
+
458
+ # Check and sanitize annotated SAM/BAM outputs
459
+ if args.samouts != []:
460
+ _check_samouts(args.samfilenames, args.samout_format, args.samouts)
461
+ else:
462
+ args.samouts = [None for x in args.samfilenames]
463
+
464
+ # Try to open samfiles to fail early in case any of them is not there
465
+ _check_sam_files(args.samfilenames)
466
+
467
+ return args
468
+
469
+
470
+ def main():
471
+ '''Main loop for htseq-count'''
472
+
473
+ args = _parse_sanitize_cmdline_arguments()
474
+
475
+ warnings.showwarning = my_showwarning
476
+ try:
477
+ count_reads_in_features(args)
478
+ except:
479
+ sys.stderr.write(" %s\n" % str(sys.exc_info()[1]))
480
+ sys.stderr.write(
481
+ " [Exception type: %s, raised in %s:%d]\n"
482
+ % (
483
+ sys.exc_info()[1].__class__.__name__,
484
+ os.path.basename(traceback.extract_tb(sys.exc_info()[2])[-1][0]),
485
+ traceback.extract_tb(sys.exc_info()[2])[-1][1],
486
+ )
487
+ )
488
+ sys.exit(1)
489
+
490
+
491
+ if __name__ == "__main__":
492
+ main()
File without changes