HTSeq 2.1.2__cp313-cp313-macosx_10_15_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/features.py ADDED
@@ -0,0 +1,489 @@
1
+ '''GFF format utilities'''
2
+ import itertools
3
+ import warnings
4
+ import os
5
+ import shlex
6
+ import sys
7
+
8
+ import HTSeq
9
+ from HTSeq._HTSeq import *
10
+ from HTSeq.utils import FileOrSequence
11
+
12
+
13
+ # GFF regular expressions for cache
14
+ _re_attr_main = re.compile(r"\s*([^\s\=]+)[\s=]+(.*)")
15
+ _re_attr_empty = re.compile(r"^\s*$")
16
+ _re_gff_meta_comment = re.compile(r"##\s*(\S+)\s+(\S*)")
17
+
18
+
19
+
20
+ class GenomicFeature(object):
21
+ """A genomic feature, i.e., an interval on a genome with metadata.
22
+
23
+ At minimum, the following information should be provided by slots:
24
+
25
+ name: a string identifying the feature (e.g., a gene symbol)
26
+ type: a string giving the feature type (e.g., "gene", "exon")
27
+ iv: a GenomicInterval object specifying the feature locus
28
+ """
29
+
30
+ def __init__(self, name, type_, interval):
31
+ self.name = name
32
+ self.type = sys.intern(type_)
33
+ self.iv = interval
34
+
35
+ def __repr__(self):
36
+ return "<%s: %s '%s' at %s: %d -> %d (strand '%s')>" % \
37
+ (self.__class__.__name__, self.type, self.name,
38
+ self.iv.chrom, self.iv.start_d, self.iv.end_d, self.iv.strand)
39
+
40
+ def __eq__(self, other):
41
+ if not isinstance(other, GenomicFeature):
42
+ return False
43
+ return self.name == other.name and self.type == other.type and \
44
+ self.iv == other.iv
45
+
46
+ def __neq__(self, other):
47
+ if not isinstance(other, GenomicFeature):
48
+ return True
49
+ return not self.__eq__(other)
50
+
51
+ def __hash__(self):
52
+ return (self.name, self.type, self.iv).__hash__()
53
+
54
+ def get_gff_line(self, with_equal_sign=False):
55
+ try:
56
+ source = self.source
57
+ except AttributeError:
58
+ source = "."
59
+ try:
60
+ score = self.score
61
+ except AttributeError:
62
+ score = "."
63
+ try:
64
+ frame = self.frame
65
+ except AttributeError:
66
+ frame = "."
67
+ try:
68
+ attr = self.attr
69
+ except AttributeError:
70
+ attr = {'ID': self.name}
71
+ if with_equal_sign:
72
+ sep = "="
73
+ else:
74
+ sep = " "
75
+ attr_str = '; '.join(
76
+ ['%s%s\"%s\"' % (ak, sep, attr[ak]) for ak in attr])
77
+ return "\t".join(str(a) for a in (self.iv.chrom, source,
78
+ self.type, self.iv.start + 1, self.iv.end, score,
79
+ self.iv.strand, frame, attr_str)) + "\n"
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+ class GFF_Reader(FileOrSequence):
88
+ """Parse a GFF file
89
+
90
+ Pass the constructor either a file name or an iterator of lines of a
91
+ GFF files. If a file name is specified, it may refer to a gzip compressed
92
+ file.
93
+
94
+ Iterating over the object then yields GenomicFeature objects.
95
+
96
+ Args:
97
+ filename_or_sequence: input file or iterator of lines
98
+ end_included: whether the end coordinate of intervals is included in
99
+ the interval itself. This is common in GTF but not the Python
100
+ standard, hence this argument.
101
+ gff_version: Which version of the GFF format to use (2 or 3). The None
102
+ default has the following meaning. If the input is a filename, use
103
+ version 2 if it ends with gtf or gtf.gz (case insensitive), else use
104
+ version 3. If an iterator, use version 2 by default. Notice that GFF3
105
+ does not use quotes in gene names et similia, while GTF does.
106
+ """
107
+
108
+ def __init__(self, filename_or_sequence, end_included=True, gff_version=None):
109
+ super().__init__(filename_or_sequence)
110
+ self.end_included = end_included
111
+ self.metadata = {}
112
+ if gff_version is None:
113
+ self._guess_gff_version()
114
+
115
+ def _guess_gff_version(self):
116
+ if not self.fos_is_path:
117
+ gff_version = 2
118
+ else:
119
+ fos = os.fspath(self.fos)
120
+ if fos.lower().endswith((".gtf.gz", ".gtf.gzip", ".gtf")):
121
+ gff_version = 2
122
+ else:
123
+ gff_version = 3
124
+ self.gff_version = gff_version
125
+
126
+ def __iter__(self):
127
+ for line in super().__iter__():
128
+ if isinstance(line, bytes):
129
+ line = line.decode()
130
+ if line == "\n":
131
+ continue
132
+ if line.startswith('#'):
133
+ if line.startswith("##"):
134
+ mo = _re_gff_meta_comment.match(line)
135
+ if mo:
136
+ self.metadata[mo.group(1)] = mo.group(2)
137
+ continue
138
+ (seqname, source, feature, start, end, score,
139
+ strand, frame, attributeStr) = line.split("\t", 8)
140
+ (attr_tuples, name) = self.parse_GFF_attribute_string_as_tuples(
141
+ attributeStr,
142
+ True,
143
+ self.gff_version,
144
+ )
145
+ iv = GenomicInterval(
146
+ seqname,
147
+ int(start) - 1, int(end) - 1 + int(self.end_included),
148
+ strand)
149
+ f = GenomicFeature(name, feature, iv)
150
+ if score != ".":
151
+ score = float(score)
152
+ if frame != ".":
153
+ frame = int(frame)
154
+ f.source = source
155
+ f.score = score
156
+ f.frame = frame
157
+ f.attr_tuples = attr_tuples
158
+ f.attr = dict(attr_tuples)
159
+ yield f
160
+
161
+ @staticmethod
162
+ def parse_GFF_attribute_string_as_tuples(
163
+ attrStr,
164
+ extra_return_first_value=False,
165
+ gff_version=2,
166
+ ):
167
+ """Parses a GFF attribute string and returns it as a list of (tag,value) tuples
168
+
169
+ If 'extra_return_first_value' is set, a pair is returned: the dictionary
170
+ and the value of the first attribute. This might be useful if this is the
171
+ ID.
172
+
173
+ Args:
174
+ attrStr: the GFF attribute string to parse
175
+ extra_return_first_value: whether to return the pair explained above
176
+ gff_version: which GFF format rules to use (2 or 3)
177
+ """
178
+ if attrStr.endswith("\n"):
179
+ attrStr = attrStr[:-1]
180
+ d = []
181
+
182
+ if gff_version == 2:
183
+ iterator = quotesafe_split(attrStr.encode())
184
+ else:
185
+ # GFF3 does not care about quotes
186
+ iterator = attrStr.encode().split(b';')
187
+
188
+ for attr in iterator:
189
+ attr = attr.decode()
190
+ if _re_attr_empty.match(attr):
191
+ continue
192
+
193
+ if (gff_version == 2) and (attr.count('"') not in (0, 2)):
194
+ raise ValueError(
195
+ "The attribute string seems to contain mismatched quotes.")
196
+ mo = _re_attr_main.match(attr)
197
+ if not mo:
198
+ raise ValueError("Failure parsing GFF attribute line")
199
+ val = mo.group(2)
200
+
201
+ # GFF3 does not split quotes
202
+ if (gff_version == 2) and val.startswith('"') and val.endswith('"'):
203
+ val = val[1:-1]
204
+ d.append((sys.intern(mo.group(1)), sys.intern(val)))
205
+
206
+ if extra_return_first_value:
207
+ first_val = "_unnamed_"
208
+ if extra_return_first_value:
209
+ for _key, val in d:
210
+ first_val = val
211
+ break
212
+ return (d, first_val)
213
+ else:
214
+ return d
215
+
216
+ @staticmethod
217
+ def parse_GFF_attribute_string(
218
+ attrStr,
219
+ extra_return_first_value=False,
220
+ gff_version=2,
221
+ ):
222
+ ret = GFF_Reader.parse_GFF_attribute_string_as_tuples(attrStr, extra_return_first_value, gff_version)
223
+ if extra_return_first_value:
224
+ attr_tuples, first_val = ret
225
+ return dict(attr_tuples), first_val
226
+ return dict(ret)
227
+
228
+
229
+ def _parse_feature_query(feature_query):
230
+ if '"' not in feature_query:
231
+ raise ValueError('Invalid feature query')
232
+ if '==' not in feature_query:
233
+ raise ValueError('Invalid feature query')
234
+
235
+ idx_quote1 = feature_query.find('"')
236
+ idx_quote2 = feature_query.rfind('"')
237
+ attr_name = feature_query[idx_quote1+1: idx_quote2]
238
+
239
+ idx_equal = feature_query[:idx_quote1].find('==')
240
+ attr_cat = feature_query[:idx_equal].strip()
241
+
242
+ return {
243
+ 'attr_cat': attr_cat,
244
+ 'attr_name': attr_name,
245
+ }
246
+
247
+
248
+ def make_feature_dict(
249
+ feature_sequence,
250
+ feature_type=None,
251
+ feature_query=None,
252
+ ):
253
+ """Organize a sequence of Feature objects into a nested dictionary.
254
+
255
+ Args:
256
+ feature_sequence (iterable of Feature): A sequence of features, e.g. as
257
+ obtained from GFF_reader('myfile.gtf')
258
+ feature_type (string, sequence of strings, or None): If None, collect
259
+ all features. If a string, restrict to only one type of features,
260
+ e.g. 'exon' (this is the most common situation). If a sequence of
261
+ strings, restrict to the types found in the sequence, e.g.
262
+ ['gene', 'pseudogene']. Using a feature of strings is an uncommon
263
+ need and can lead to a higher number of ambiguous alignments: only
264
+ use if you know what you are doing. Even then, beware that this
265
+ option is designed to work for feature types that are "peers" and
266
+ not obviously overlapping, such as genes and pseudogenes. If you
267
+ select nested features types (e.g. "gene" and "exon"), you are
268
+ likely to end up with meaningless numbers.
269
+ feature_query (string or None): If None, all features of the selected
270
+ types will be collected. If a string, it has to be in the format:
271
+
272
+ <feature_attribute> == <attr_value>
273
+
274
+ e.g.
275
+
276
+ 'gene_id == "Fn1"'
277
+
278
+ (note the double quotes inside).
279
+
280
+ Then only that feature will be collected. Using this argument is more
281
+ efficient than collecting all features and then pruning it down to a
282
+ single one.
283
+
284
+ Returns:
285
+ dict with all the feature types as keys. Each value is again a dict,
286
+ now of feature names. The values of this dict is a list of features.
287
+
288
+ Example: Let's say you load the C. elegans GTF file from Ensembl and make a
289
+ feature dict:
290
+
291
+ >>> gff = HTSeq.GFF_Reader("Caenorhabditis_elegans.WS200.55.gtf.gz")
292
+ >>> worm_features_dict = HTSeq.make_feature_dict(gff)
293
+
294
+ (This command may take a few minutes to deal with the 430,000 features
295
+ in the GTF file. Note that you may need a lot of RAM if you have millions
296
+ of features.)
297
+
298
+ Then, you can simply access, say, exon 0 of gene "F08E10.4" as follows:
299
+ >>> worm_features_dict['exon']['F08E10.4'][0]
300
+ <GenomicFeature: exon 'F08E10.4' at V: 17479353 -> 17479001 (strand '-')>
301
+ """
302
+
303
+ if feature_query is not None:
304
+ feature_qdic = _parse_feature_query(feature_query)
305
+
306
+ features = {}
307
+ for f in feature_sequence:
308
+ if any(ft in (None, f.type) for ft in feature_type):
309
+ if f.type not in features:
310
+ features[f.type] = {}
311
+ res_ftype = features[f.type]
312
+
313
+ if feature_query is not None:
314
+ # Skip the features that don't even have the right attr
315
+ if feature_qdic['attr_cat'] not in f.attr:
316
+ continue
317
+ # Skip the ones with an attribute with a different name
318
+ # from the query (e.g. other genes)
319
+ if f.attr[feature_qdic['attr_cat']] != feature_qdic['attr_name']:
320
+ continue
321
+
322
+ if f.name not in res_ftype:
323
+ res_ftype[f.name] = [f]
324
+ else:
325
+ res_ftype[f.name].append(f)
326
+ return features
327
+
328
+
329
+ def make_feature_genomicarrayofsets(
330
+ feature_sequence,
331
+ id_attribute,
332
+ feature_type=None,
333
+ feature_query=None,
334
+ additional_attributes=None,
335
+ stranded=False,
336
+ verbose=False,
337
+ add_chromosome_info=False,
338
+ ):
339
+ """Organize a sequence of Feature objects into a GenomicArrayOfSets.
340
+
341
+ Args:
342
+ feature_sequence (iterable of Feature): A sequence of features, e.g. as
343
+ obtained from GFF_reader('myfile.gtf')
344
+ id_attribute (string or sequence of strings): An attribute to use to
345
+ identify the feature in the output data structures (e.g.
346
+ 'gene_id'). If this is a list, the combination of all those
347
+ attributes, separated by colons (:), will be used as an identifier.
348
+ For instance, ['gene_id', 'exon_number'] uniquely identifies
349
+ specific exons.
350
+ feature_type (string, sequence of strings, or None): If None, collect
351
+ all features. If a string, restrict to only one type of features,
352
+ e.g. 'exon'. If a sequence of strings, restrict to the types found
353
+ in the sequence, e.g. 'gene' and 'pseudogene'
354
+ feature_query (string or None): If None, all features of the selected
355
+ types will be collected. If a string, it has to be in the format:
356
+
357
+ <feature_attribute> == <attr_value>
358
+
359
+ e.g.
360
+
361
+ 'gene_id == "Fn1"'
362
+
363
+ (note the double quotes inside).
364
+
365
+ Then only that feature will be collected. Using this argument is more
366
+ efficient than collecting all features and then pruning it down to a
367
+ single one.
368
+
369
+ additional_attributes (list or None): A list of additional attributes
370
+ to be collected into a separate dict for the same features, for
371
+ instance ['gene_name']
372
+ stranded (bool): Whether to keep strandedness information
373
+ verbose (bool): Whether to output progress and error messages
374
+ add_chromosome_info (bool): Whether to add chromosome information for
375
+ each feature. If this option is True, the fuction appends at the
376
+ end of the "additional_attributes" list a "Chromosome" attribute.
377
+
378
+ Returns:
379
+ dict with two keys, 'features' with the GenomicArrayOfSets populated
380
+ with the features, and 'attributes' which is itself a dict with
381
+ the id_attribute as keys and the additional attributes as values.
382
+
383
+ Example: Let's say you load the C. elegans GTF file from Ensembl and make a
384
+ feature dict:
385
+
386
+ >>> gff = HTSeq.GFF_Reader("Caenorhabditis_elegans.WS200.55.gtf.gz")
387
+ >>> worm_features = HTSeq.make_feature_genomicarrayofsets(gff)
388
+
389
+ (This command may take a few minutes to deal with the 430,000 features
390
+ in the GTF file. Note that you may need a lot of RAM if you have millions
391
+ of features.)
392
+
393
+ This function is related but distinct from HTSeq.make_feature_dict. This
394
+ function is used in htseq-count and its barcoded twin to count gene
395
+ expression because the output GenomicArrayofSets is very efficient. You
396
+ can use it in performance-critical scans of GFF files.
397
+ """
398
+
399
+ def get_id_attr(f, id_attribute):
400
+ '''Get feature id with a single or multiple attributes'''
401
+ if isinstance(id_attribute, str):
402
+ try:
403
+ feature_id = f.attr[id_attribute]
404
+ except KeyError:
405
+ raise ValueError(
406
+ "Feature %s does not contain a '%s' attribute" %
407
+ (f.name, id_attribute))
408
+ else:
409
+ feature_id = []
410
+ for id_attr in id_attribute:
411
+ try:
412
+ feature_id.append(f.attr[id_attr])
413
+ except KeyError:
414
+ raise ValueError(
415
+ "Feature %s does not contain a '%s' attribute" %
416
+ (f.name, id_attr))
417
+ feature_id = ':'.join(feature_id)
418
+ return feature_id
419
+
420
+ if additional_attributes is None:
421
+ additional_attributes = []
422
+
423
+ if feature_query is not None:
424
+ feature_qdic = _parse_feature_query(feature_query)
425
+
426
+ features = HTSeq.GenomicArrayOfSets("auto", stranded)
427
+ attributes = {}
428
+ i = 0
429
+ try:
430
+ for f in feature_sequence:
431
+ if any(ft in (None, f.type) for ft in feature_type):
432
+ feature_id = get_id_attr(f, id_attribute)
433
+
434
+ if stranded and f.iv.strand == ".":
435
+ raise ValueError(
436
+ "Feature %s at %s does not have strand information but you are "
437
+ "using stranded mode. Try with unstrnded mode." %
438
+ (f.name, f.iv))
439
+
440
+ if feature_query is not None:
441
+ # Skip the features that don't even have the right attr
442
+ if feature_qdic['attr_cat'] not in f.attr:
443
+ continue
444
+ # Skip the ones with an attribute with a different name
445
+ # from the query (e.g. other genes)
446
+ if f.attr[feature_qdic['attr_cat']] != feature_qdic['attr_name']:
447
+ continue
448
+
449
+ features[f.iv] += feature_id
450
+ attributes[feature_id] = [
451
+ f.attr[attr] if attr in f.attr else ''
452
+ for attr in additional_attributes]
453
+ if add_chromosome_info:
454
+ attributes[feature_id] += [f.iv.chrom]
455
+
456
+ i += 1
457
+ if i % 100000 == 0 and verbose:
458
+ if hasattr(feature_sequence, 'get_line_number_string'):
459
+ msg = "{:d} GFF lines processed.".format(i)
460
+ else:
461
+ msg = "{:d} features processed.".format(i)
462
+ sys.stderr.write(msg+'\n')
463
+ sys.stderr.flush()
464
+ except(KeyError, ValueError):
465
+ if verbose:
466
+ if hasattr(feature_sequence, 'get_line_number_string'):
467
+ msg = "Error processing GFF file ({:}):".format(
468
+ feature_sequence.get_line_number_string())
469
+ else:
470
+ msg = "Error processing feature sequence ({:}):".format(
471
+ str(i+1))
472
+ sys.stderr.write(msg+'\n')
473
+ raise
474
+
475
+ if verbose:
476
+ if hasattr(feature_sequence, 'get_line_number_string'):
477
+ msg = "{:d} GFF lines processed.".format(i)
478
+ else:
479
+ msg = "{:d} features processed.".format(i)
480
+ sys.stderr.write(msg+"\n")
481
+ sys.stderr.flush()
482
+
483
+ if add_chromosome_info:
484
+ additional_attributes.append('Chromosome')
485
+
486
+ return {
487
+ 'features': features,
488
+ 'attributes': attributes,
489
+ }
File without changes