gtfparse 2.8.1__tar.gz → 2.9.0__tar.gz

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.
Files changed (31) hide show
  1. {gtfparse-2.8.1 → gtfparse-2.9.0}/PKG-INFO +48 -3
  2. gtfparse-2.9.0/README.md +90 -0
  3. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse/__init__.py +1 -1
  4. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse/attribute_parsing.py +39 -24
  5. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse/read_gtf.py +80 -22
  6. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse/write_gtf.py +4 -7
  7. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse.egg-info/PKG-INFO +48 -3
  8. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse.egg-info/SOURCES.txt +2 -0
  9. gtfparse-2.9.0/tests/test_attribute_values.py +80 -0
  10. gtfparse-2.9.0/tests/test_progress.py +162 -0
  11. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_write_gtf.py +4 -8
  12. gtfparse-2.8.1/README.md +0 -45
  13. {gtfparse-2.8.1 → gtfparse-2.9.0}/LICENSE +0 -0
  14. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse/create_missing_features.py +0 -0
  15. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse/parsing_error.py +0 -0
  16. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse.egg-info/dependency_links.txt +0 -0
  17. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse.egg-info/requires.txt +0 -0
  18. {gtfparse-2.8.1 → gtfparse-2.9.0}/gtfparse.egg-info/top_level.txt +0 -0
  19. {gtfparse-2.8.1 → gtfparse-2.9.0}/pyproject.toml +0 -0
  20. {gtfparse-2.8.1 → gtfparse-2.9.0}/requirements.txt +0 -0
  21. {gtfparse-2.8.1 → gtfparse-2.9.0}/setup.cfg +0 -0
  22. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_create_missing_features.py +0 -0
  23. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_ensembl_gtf.py +0 -0
  24. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_expand_attribute_column_false.py +0 -0
  25. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_expand_attributes.py +0 -0
  26. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_gencode_gtf.py +0 -0
  27. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_multiple_values_for_tag_attribute.py +0 -0
  28. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_parse_gtf_lines.py +0 -0
  29. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_polars_compatibility.py +0 -0
  30. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_read_stringtie_gtf.py +0 -0
  31. {gtfparse-2.8.1 → gtfparse-2.9.0}/tests/test_refseq_gtf.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gtfparse
3
- Version: 2.8.1
3
+ Version: 2.9.0
4
4
  Summary: Parsing library for extracting data frames of genomic features from GTF files
5
5
  Author-email: Alex Rubinsteyn <alex.rubinsteyn@unc.edu>
6
6
  Project-URL: Homepage, https://github.com/openvax/gtfparse
@@ -40,6 +40,53 @@ gtfparse
40
40
  ========
41
41
  Parsing tools for GTF (gene transfer format) files.
42
42
 
43
+ ## Reporting parsing progress
44
+
45
+ Pass `progress_callback(stage, completed, total)` to `read_gtf` to connect
46
+ parsing to your own progress UI. The callback runs synchronously; exceptions
47
+ from it stop parsing and propagate to the caller. Without a callback, gtfparse
48
+ does not display a progress bar or add a progress-library dependency.
49
+
50
+ | Stage | Reports |
51
+ | --- | --- |
52
+ | `read` | `(0, None)` before Polars loads/filters the file; `(rows, rows)` after it succeeds |
53
+ | `attributes` | `(0, rows)`, then every 10,000 rows, then `(rows, rows)` |
54
+ | `convert` | `(0, None)` before output conversion/transforms; `(rows, rows)` after success |
55
+
56
+ Counts refer to rows retained after `features` filtering, not bytes or overall
57
+ percentages. `None` means the total is unknown: loading and conversion expose
58
+ only stage boundaries, so use an indeterminate indicator during those steps.
59
+ Attribute expansion is omitted when `expand_attribute_column=False`. A stage
60
+ that fails does not emit completion. An empty filtered result is supported;
61
+ its attributes stage emits a single `(0, 0)` event. Empty input files retain
62
+ the existing Polars `NoDataError` behavior.
63
+
64
+ For example, with the optional `tqdm` package installed:
65
+
66
+ ```python
67
+ from gtfparse import read_gtf
68
+ from tqdm.auto import tqdm
69
+
70
+ with tqdm(unit="rows") as bar:
71
+ def show_progress(stage, completed, total):
72
+ if stage != bar.desc:
73
+ bar.total = total
74
+ bar.reset()
75
+ bar.set_description_str(stage)
76
+ bar.total = total
77
+ bar.update(completed - bar.n)
78
+ bar.refresh()
79
+
80
+ df = read_gtf("gene_annotations.gtf", progress_callback=show_progress)
81
+ ```
82
+
83
+ `parse_gtf` reports the `read` stage, `parse_gtf_and_expand_attributes` reports
84
+ `read` and `attributes`, `parse_gtf_pandas` reports `read` and `convert`, and
85
+ `expand_attribute_strings` reports only `attributes` using the same callback.
86
+
87
+ Quoted attribute values preserve spaces, semicolons, and apostrophes. Raw
88
+ attributes (`expand_attribute_column=False`) retain their original quote marks.
89
+
43
90
  # Example usage
44
91
 
45
92
  ## Parsing all rows of a GTF file into a Pandas DataFrame
@@ -73,5 +120,3 @@ gene_fpkms = {
73
120
  if feature == "gene"
74
121
  }
75
122
  ```
76
-
77
-
@@ -0,0 +1,90 @@
1
+ [![Tests](https://github.com/openvax/gtfparse/actions/workflows/tests.yml/badge.svg)](https://github.com/openvax/gtfparse/actions/workflows/tests.yml)
2
+ [![Coverage Status](https://coveralls.io/repos/openvax/gtfparse/badge.svg?branch=master&service=github)](https://coveralls.io/github/openvax/gtfparse?branch=master)
3
+ <a href="https://pypi.python.org/pypi/gtfparse/">
4
+ <img src="https://img.shields.io/pypi/v/gtfparse.svg?maxAge=1000" alt="PyPI" />
5
+ </a>
6
+
7
+ gtfparse
8
+ ========
9
+ Parsing tools for GTF (gene transfer format) files.
10
+
11
+ ## Reporting parsing progress
12
+
13
+ Pass `progress_callback(stage, completed, total)` to `read_gtf` to connect
14
+ parsing to your own progress UI. The callback runs synchronously; exceptions
15
+ from it stop parsing and propagate to the caller. Without a callback, gtfparse
16
+ does not display a progress bar or add a progress-library dependency.
17
+
18
+ | Stage | Reports |
19
+ | --- | --- |
20
+ | `read` | `(0, None)` before Polars loads/filters the file; `(rows, rows)` after it succeeds |
21
+ | `attributes` | `(0, rows)`, then every 10,000 rows, then `(rows, rows)` |
22
+ | `convert` | `(0, None)` before output conversion/transforms; `(rows, rows)` after success |
23
+
24
+ Counts refer to rows retained after `features` filtering, not bytes or overall
25
+ percentages. `None` means the total is unknown: loading and conversion expose
26
+ only stage boundaries, so use an indeterminate indicator during those steps.
27
+ Attribute expansion is omitted when `expand_attribute_column=False`. A stage
28
+ that fails does not emit completion. An empty filtered result is supported;
29
+ its attributes stage emits a single `(0, 0)` event. Empty input files retain
30
+ the existing Polars `NoDataError` behavior.
31
+
32
+ For example, with the optional `tqdm` package installed:
33
+
34
+ ```python
35
+ from gtfparse import read_gtf
36
+ from tqdm.auto import tqdm
37
+
38
+ with tqdm(unit="rows") as bar:
39
+ def show_progress(stage, completed, total):
40
+ if stage != bar.desc:
41
+ bar.total = total
42
+ bar.reset()
43
+ bar.set_description_str(stage)
44
+ bar.total = total
45
+ bar.update(completed - bar.n)
46
+ bar.refresh()
47
+
48
+ df = read_gtf("gene_annotations.gtf", progress_callback=show_progress)
49
+ ```
50
+
51
+ `parse_gtf` reports the `read` stage, `parse_gtf_and_expand_attributes` reports
52
+ `read` and `attributes`, `parse_gtf_pandas` reports `read` and `convert`, and
53
+ `expand_attribute_strings` reports only `attributes` using the same callback.
54
+
55
+ Quoted attribute values preserve spaces, semicolons, and apostrophes. Raw
56
+ attributes (`expand_attribute_column=False`) retain their original quote marks.
57
+
58
+ # Example usage
59
+
60
+ ## Parsing all rows of a GTF file into a Pandas DataFrame
61
+
62
+ ```python
63
+ from gtfparse import read_gtf
64
+
65
+ # returns GTF with essential columns such as "feature", "seqname", "start", "end"
66
+ # alongside the names of any optional keys which appeared in the attribute column
67
+ df = read_gtf("gene_annotations.gtf")
68
+
69
+ # filter DataFrame to gene entries on chrY
70
+ df_genes = df[df["feature"] == "gene"]
71
+ df_genes_chrY = df_genes[df_genes["seqname"] == "Y"]
72
+ ```
73
+
74
+
75
+ ## Getting gene FPKM values from a StringTie GTF file
76
+
77
+ ```python
78
+ from gtfparse import read_gtf
79
+
80
+ df = read_gtf(
81
+ "Transcripts.gtf",
82
+ column_converters={"FPKM": float})
83
+
84
+ gene_fpkms = {
85
+ gene_name: fpkm
86
+ for (gene_name, fpkm, feature)
87
+ in zip(df["seqname"], df["FPKM"], df["feature"])
88
+ if feature == "gene"
89
+ }
90
+ ```
@@ -24,7 +24,7 @@ from .read_gtf import (
24
24
  )
25
25
  from .write_gtf import write_gtf
26
26
 
27
- __version__ = "2.8.1"
27
+ __version__ = "2.9.0"
28
28
 
29
29
  __all__ = [
30
30
  "GENCODE_BIOTYPE_ALIASES",
@@ -11,25 +11,37 @@
11
11
  # limitations under the License.
12
12
 
13
13
  import logging
14
+ import re
14
15
  from collections import OrderedDict
15
16
  from sys import intern
16
17
 
17
18
  logger = logging.getLogger(__name__)
18
19
 
20
+ # Quoted values may contain semicolons. Keep this compatible with both Python's
21
+ # re module and Polars' regex engine so the low-level split column agrees with
22
+ # attribute expansion. Unquoted values and single quotes are accepted as well.
23
+ ATTRIBUTE_PATTERN = r"""[^\s;]+[ \t]+(?:"[^"]*"|'[^']*'|[^;]+)"""
24
+ _ATTRIBUTE_PAIRS = re.compile(ATTRIBUTE_PATTERN)
19
25
 
20
- def expand_attribute_strings(attribute_strings, quote_char="'", missing_value="", usecols=None):
26
+
27
+ def expand_attribute_strings(
28
+ attribute_strings, quote_char="'", missing_value="", usecols=None, *, progress_callback=None
29
+ ):
21
30
  """
22
31
  The last column of GTF has a variable number of key value pairs
23
32
  of the format: "key1 value1; key2 value2;"
24
33
  Parse these into a dictionary mapping each key onto a list of values,
25
- where the value is None for any row where the key was missing.
34
+ using missing_value for any row where the key was missing.
26
35
 
27
36
  Parameters
28
37
  ----------
29
- attribute_strings : list of str
38
+ attribute_strings : sequence of str or sequences of str
39
+ Raw attribute fields or already separated key/value pairs per row.
40
+ None represents a row with no attributes.
30
41
 
31
42
  quote_char : str
32
- Quote character to remove from values
43
+ Additional surrounding quote character to remove from values.
44
+ Standard double quotes are always recognized.
33
45
 
34
46
  missing_value : any
35
47
  If an attribute is missing from a row, give it this value.
@@ -38,6 +50,11 @@ def expand_attribute_strings(attribute_strings, quote_char="'", missing_value=""
38
50
  If not None, then only expand columns included in this set,
39
51
  otherwise use all columns.
40
52
 
53
+ progress_callback : callable, optional
54
+ Called as ``callback("attributes", completed_rows, total_rows)`` at
55
+ the start, every 10,000 rows, and at completion. An empty input emits
56
+ one ``("attributes", 0, 0)`` event. Callback exceptions propagate.
57
+
41
58
  Returns OrderedDict of column->value list mappings, in the order they
42
59
  appeared in the attribute strings.
43
60
  """
@@ -46,29 +63,23 @@ def expand_attribute_strings(attribute_strings, quote_char="'", missing_value=""
46
63
  extra_columns = {}
47
64
  column_order = []
48
65
 
49
- #
50
- # SOME NOTES ABOUT THE BIZARRE STRING INTERNING GOING ON BELOW
51
- #
52
66
  # While parsing millions of repeated strings (e.g. "gene_id" and "TP53"),
53
67
  # we can save a lot of memory by making sure there's only one string
54
- # object per unique string. The canonical way to do this is using
55
- # the 'intern' function. One problem is that Py2 won't let you intern
56
- # unicode objects, so to get around this we call intern(str(...)).
57
- #
58
- # It also turns out to be faster to check interned strings ourselves
59
- # using a local dictionary, hence the two dictionaries below
60
- # and pair of try/except blocks in the loop.
68
+ # object per unique column name. Cache interned names locally as well.
61
69
  column_interned_strings = {}
62
70
 
71
+ if progress_callback is not None:
72
+ progress_callback("attributes", 0, n)
73
+
63
74
  for i, kv_strings in enumerate(attribute_strings):
64
- if type(kv_strings) is str:
65
- kv_strings = kv_strings.split(";")
75
+ if isinstance(kv_strings, str):
76
+ kv_strings = _ATTRIBUTE_PAIRS.findall(kv_strings)
77
+ elif kv_strings is None:
78
+ kv_strings = ()
66
79
  for kv in kv_strings:
67
- # We're slicing the first two elements out of split() because
68
- # Ensembl release 79 added values like:
69
- # transcript_support_level "1 (assigned to previous version 5)";
70
- # ...which gets mangled by splitting on spaces.
71
- parts = kv.strip().split(" ", 2)[:2]
80
+ # Split once: values such as transcript_support_level may include
81
+ # spaces, and whitespace between a key and its value may vary.
82
+ parts = kv.strip().split(None, 1)
72
83
 
73
84
  if len(parts) != 2:
74
85
  continue
@@ -78,14 +89,14 @@ def expand_attribute_strings(attribute_strings, quote_char="'", missing_value=""
78
89
  try:
79
90
  column_name = column_interned_strings[column_name]
80
91
  except KeyError:
81
- column_name = intern(str(column_name))
92
+ column_name = intern(column_name)
82
93
  column_interned_strings[column_name] = column_name
83
94
 
84
95
  if usecols is not None and column_name not in usecols:
85
96
  continue
86
97
 
87
- if value[0] == quote_char:
88
- value = value.replace(quote_char, "")
98
+ if len(value) >= 2 and value[0] in ('"', quote_char) and value[-1] == value[0]:
99
+ value = value[1:-1]
89
100
 
90
101
  try:
91
102
  column = extra_columns[column_name]
@@ -102,5 +113,9 @@ def expand_attribute_strings(attribute_strings, quote_char="'", missing_value=""
102
113
  extra_columns[column_name] = column
103
114
  column_order.append(column_name)
104
115
 
116
+ completed = i + 1
117
+ if progress_callback is not None and (completed % 10_000 == 0 or completed == n):
118
+ progress_callback("attributes", completed, n)
119
+
105
120
  logger.info("Extracted GTF attributes: %s", column_order)
106
121
  return OrderedDict((column_name, extra_columns[column_name]) for column_name in column_order)
@@ -16,7 +16,7 @@ from os.path import exists
16
16
  import pandas as pd
17
17
  import polars
18
18
 
19
- from .attribute_parsing import expand_attribute_strings
19
+ from .attribute_parsing import ATTRIBUTE_PATTERN, expand_attribute_strings
20
20
  from .parsing_error import ParsingError
21
21
 
22
22
  logger = logging.getLogger(__name__)
@@ -108,7 +108,7 @@ DEFAULT_COLUMN_DTYPES = {
108
108
 
109
109
 
110
110
  def parse_with_polars_lazy(
111
- filepath_or_buffer, split_attributes=True, features=None, fix_quotes_columns=["attribute"]
111
+ filepath_or_buffer, split_attributes=True, features=None, fix_quotes_columns=None
112
112
  ):
113
113
  # Categories shares categorical mappings on modern Polars. Older releases
114
114
  # need the global string cache for categoricals from separate reads to match.
@@ -120,6 +120,7 @@ def parse_with_polars_lazy(
120
120
  "comment_prefix": "#",
121
121
  "null_values": ".",
122
122
  "schema_overrides": DEFAULT_COLUMN_DTYPES,
123
+ "quote_char": None,
123
124
  }
124
125
  try:
125
126
  df = polars.read_csv(filepath_or_buffer, new_columns=REQUIRED_COLUMNS, **kwargs).lazy()
@@ -129,11 +130,9 @@ def parse_with_polars_lazy(
129
130
  # Drop empty lines that may appear as all-null rows
130
131
  df = df.filter(polars.col("seqname").is_not_null())
131
132
 
132
- df = df.with_columns(
133
- [polars.col("frame").fill_null(0), polars.col("attribute").str.replace_all('"', "'")]
134
- )
133
+ df = df.with_columns(polars.col("frame").fill_null(0))
135
134
 
136
- for fix_quotes_column in fix_quotes_columns:
135
+ for fix_quotes_column in fix_quotes_columns or ():
137
136
  # Catch mistaken semicolons by replacing "xyz;" with "xyz"
138
137
  # Required to do this since the Ensembl GTF for Ensembl
139
138
  # release 78 has mistakes such as:
@@ -147,28 +146,55 @@ def parse_with_polars_lazy(
147
146
  df = df.filter(polars.col("feature").is_in(features))
148
147
 
149
148
  if split_attributes:
150
- df = df.with_columns([polars.col("attribute").str.split(";").alias("attribute_split")])
149
+ df = df.with_columns(
150
+ polars.col("attribute").str.extract_all(ATTRIBUTE_PATTERN).alias("attribute_split")
151
+ )
151
152
  return df
152
153
 
153
154
 
154
155
  def parse_gtf(
155
- filepath_or_buffer, split_attributes=True, features=None, fix_quotes_columns=["attribute"]
156
+ filepath_or_buffer,
157
+ split_attributes=True,
158
+ features=None,
159
+ fix_quotes_columns=None,
160
+ *,
161
+ progress_callback=None,
156
162
  ):
163
+ """Read the fixed GTF columns, preserving raw attribute text.
164
+
165
+ If split_attributes is True, add an attribute_split list column with
166
+ quoted key/value pairs kept intact. Legacy semicolon cleanup is available
167
+ by explicitly setting fix_quotes_columns; it is disabled by default.
168
+ progress_callback follows read_gtf's contract and emits only the read stage.
169
+ """
170
+ if progress_callback is not None:
171
+ progress_callback("read", 0, None)
157
172
  df_lazy = parse_with_polars_lazy(
158
173
  filepath_or_buffer=filepath_or_buffer,
159
174
  split_attributes=split_attributes,
160
175
  features=features,
161
176
  fix_quotes_columns=fix_quotes_columns,
162
177
  )
163
- return df_lazy.collect()
178
+ df = df_lazy.collect()
179
+ if progress_callback is not None:
180
+ progress_callback("read", len(df), len(df))
181
+ return df
164
182
 
165
183
 
166
184
  def parse_gtf_pandas(*args, **kwargs):
167
- return parse_gtf(*args, **kwargs).to_pandas()
185
+ """Like parse_gtf, returning pandas and reporting read/convert progress."""
186
+ df = parse_gtf(*args, **kwargs)
187
+ progress_callback = kwargs.get("progress_callback")
188
+ if progress_callback is not None:
189
+ progress_callback("convert", 0, None)
190
+ result = df.to_pandas()
191
+ if progress_callback is not None:
192
+ progress_callback("convert", len(result), len(result))
193
+ return result
168
194
 
169
195
 
170
196
  def parse_gtf_and_expand_attributes(
171
- filepath_or_buffer, restrict_attribute_columns=None, features=None
197
+ filepath_or_buffer, restrict_attribute_columns=None, features=None, *, progress_callback=None
172
198
  ):
173
199
  """
174
200
  Parse lines into column->values dictionary and then expand
@@ -181,26 +207,34 @@ def parse_gtf_and_expand_attributes(
181
207
  ----------
182
208
  filepath_or_buffer : str or buffer object
183
209
 
184
- chunksize : int
185
-
186
210
  restrict_attribute_columns : list/set of str or None
187
211
  If given, then only use these attribute columns.
188
212
 
189
213
  features : set or None
190
214
  Ignore entries which don't correspond to one of the supplied features
215
+
216
+ progress_callback : callable, optional
217
+ Follows read_gtf's callback contract, emitting read and attributes stages.
191
218
  """
192
- df = parse_gtf(filepath_or_buffer=filepath_or_buffer, features=features, split_attributes=True)
219
+ df = parse_gtf(
220
+ filepath_or_buffer=filepath_or_buffer,
221
+ features=features,
222
+ split_attributes=False,
223
+ progress_callback=progress_callback,
224
+ )
193
225
  if type(restrict_attribute_columns) is str:
194
226
  restrict_attribute_columns = {restrict_attribute_columns}
195
227
  elif restrict_attribute_columns:
196
228
  restrict_attribute_columns = set(restrict_attribute_columns)
197
- df.drop_in_place("attribute")
198
- attribute_pairs = df.drop_in_place("attribute_split")
229
+ attributes = df.drop_in_place("attribute")
199
230
  return df.with_columns(
200
231
  [
201
232
  polars.Series(k, vs)
202
- for (k, vs) in expand_attribute_strings(attribute_pairs).items()
203
- if restrict_attribute_columns is None or k in restrict_attribute_columns
233
+ for (k, vs) in expand_attribute_strings(
234
+ attributes,
235
+ usecols=restrict_attribute_columns,
236
+ progress_callback=progress_callback,
237
+ ).items()
204
238
  ]
205
239
  )
206
240
 
@@ -275,9 +309,11 @@ def read_gtf(
275
309
  result_type="polars",
276
310
  attribute_aliases=None,
277
311
  cast_version_columns=True,
312
+ *,
313
+ progress_callback=None,
278
314
  ):
279
315
  """
280
- Parse a GTF into a dictionary mapping column names to sequences of values.
316
+ Parse a GTF into a Polars DataFrame, pandas DataFrame, or dictionary.
281
317
 
282
318
  Parameters
283
319
  ----------
@@ -330,7 +366,20 @@ def read_gtf(
330
366
  `protein_version`, `exon_version`) from strings to pandas
331
367
  nullable Int64 when present. Set to False to keep them as
332
368
  strings.
369
+
370
+ progress_callback : callable, optional
371
+ Called synchronously as ``callback(stage, completed, total)``. Counts
372
+ are rows retained after feature filtering. Stages occur in order:
373
+ ``read``, ``attributes`` (if expanded), and ``convert``. Read and convert
374
+ emit ``(stage, 0, None)`` before work and ``(stage, rows, rows)`` after
375
+ success; None means the total is unknown, so show an indeterminate
376
+ indicator. Attribute expansion reports a known total at the start,
377
+ every 10,000 rows, and at completion (one event for zero rows).
378
+ Exceptions, including those raised by the callback, propagate without
379
+ reporting completion of the failed stage. Default: no callback or UI.
333
380
  """
381
+ if result_type not in ("polars", "pandas", "dict"):
382
+ raise ValueError("result_type must be one of 'polars', 'pandas', or 'dict'")
334
383
  if type(filepath_or_buffer) is str and not exists(filepath_or_buffer):
335
384
  raise ValueError("GTF file does not exist: %s" % filepath_or_buffer)
336
385
 
@@ -352,13 +401,21 @@ def read_gtf(
352
401
  filepath_or_buffer,
353
402
  restrict_attribute_columns=parse_usecols,
354
403
  features=features,
404
+ progress_callback=progress_callback,
355
405
  )
356
406
  else:
357
407
  # When the caller opts out of attribute expansion they want the raw
358
408
  # 'attribute' column verbatim — no need to also produce the
359
409
  # 'attribute_split' helper that parse_gtf adds by default.
360
- result_df = parse_gtf(filepath_or_buffer, features=features, split_attributes=False)
410
+ result_df = parse_gtf(
411
+ filepath_or_buffer,
412
+ features=features,
413
+ split_attributes=False,
414
+ progress_callback=progress_callback,
415
+ )
361
416
 
417
+ if progress_callback is not None:
418
+ progress_callback("convert", 0, None)
362
419
  # converting back to pandas here because Polars bugs manifest
363
420
  # as `pyo3_runtime.PanicException: assertion `left == right` failed: impl error`
364
421
  # and are generally insane to chase down
@@ -417,11 +474,12 @@ def read_gtf(
417
474
  valid_columns = [c for c in usecols if c in column_names]
418
475
  result_df = result_df[valid_columns]
419
476
 
420
- result = None
421
477
  if result_type == "pandas":
422
478
  result = result_df
423
479
  elif result_type == "polars":
424
480
  result = polars.from_pandas(result_df)
425
- elif result_type == "dict":
481
+ else:
426
482
  result = result_df.to_dict()
483
+ if progress_callback is not None:
484
+ progress_callback("convert", len(result_df), len(result_df))
427
485
  return result
@@ -142,13 +142,10 @@ def write_gtf(
142
142
 
143
143
  Notes
144
144
  -----
145
- GTF has no escaping mechanism for the structural characters ``"`` and
146
- ``;`` inside attribute values (nor for the tab and newline that delimit
147
- columns and rows), and read_gtf strips quotes and splits on ``;`` when
148
- parsing. Values returned by read_gtf therefore never contain those
149
- characters, so any DataFrame obtained from read_gtf round-trips exactly. A
150
- DataFrame built by hand whose attribute values contain ``"``, ``;``, a tab,
151
- or a newline cannot be represented losslessly and will not round-trip.
145
+ Attribute values are enclosed in double quotes, so spaces, apostrophes,
146
+ and semicolons round-trip. This writer does not escape embedded double
147
+ quotes, tabs, or newlines; values containing those characters are outside
148
+ its round-trip guarantees. Empty and missing attributes are both omitted.
152
149
  """
153
150
  # Accept a pandas DataFrame too, since read_gtf(result_type="pandas")
154
151
  # returns one; convert to polars so the formatting below is uniform.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gtfparse
3
- Version: 2.8.1
3
+ Version: 2.9.0
4
4
  Summary: Parsing library for extracting data frames of genomic features from GTF files
5
5
  Author-email: Alex Rubinsteyn <alex.rubinsteyn@unc.edu>
6
6
  Project-URL: Homepage, https://github.com/openvax/gtfparse
@@ -40,6 +40,53 @@ gtfparse
40
40
  ========
41
41
  Parsing tools for GTF (gene transfer format) files.
42
42
 
43
+ ## Reporting parsing progress
44
+
45
+ Pass `progress_callback(stage, completed, total)` to `read_gtf` to connect
46
+ parsing to your own progress UI. The callback runs synchronously; exceptions
47
+ from it stop parsing and propagate to the caller. Without a callback, gtfparse
48
+ does not display a progress bar or add a progress-library dependency.
49
+
50
+ | Stage | Reports |
51
+ | --- | --- |
52
+ | `read` | `(0, None)` before Polars loads/filters the file; `(rows, rows)` after it succeeds |
53
+ | `attributes` | `(0, rows)`, then every 10,000 rows, then `(rows, rows)` |
54
+ | `convert` | `(0, None)` before output conversion/transforms; `(rows, rows)` after success |
55
+
56
+ Counts refer to rows retained after `features` filtering, not bytes or overall
57
+ percentages. `None` means the total is unknown: loading and conversion expose
58
+ only stage boundaries, so use an indeterminate indicator during those steps.
59
+ Attribute expansion is omitted when `expand_attribute_column=False`. A stage
60
+ that fails does not emit completion. An empty filtered result is supported;
61
+ its attributes stage emits a single `(0, 0)` event. Empty input files retain
62
+ the existing Polars `NoDataError` behavior.
63
+
64
+ For example, with the optional `tqdm` package installed:
65
+
66
+ ```python
67
+ from gtfparse import read_gtf
68
+ from tqdm.auto import tqdm
69
+
70
+ with tqdm(unit="rows") as bar:
71
+ def show_progress(stage, completed, total):
72
+ if stage != bar.desc:
73
+ bar.total = total
74
+ bar.reset()
75
+ bar.set_description_str(stage)
76
+ bar.total = total
77
+ bar.update(completed - bar.n)
78
+ bar.refresh()
79
+
80
+ df = read_gtf("gene_annotations.gtf", progress_callback=show_progress)
81
+ ```
82
+
83
+ `parse_gtf` reports the `read` stage, `parse_gtf_and_expand_attributes` reports
84
+ `read` and `attributes`, `parse_gtf_pandas` reports `read` and `convert`, and
85
+ `expand_attribute_strings` reports only `attributes` using the same callback.
86
+
87
+ Quoted attribute values preserve spaces, semicolons, and apostrophes. Raw
88
+ attributes (`expand_attribute_column=False`) retain their original quote marks.
89
+
43
90
  # Example usage
44
91
 
45
92
  ## Parsing all rows of a GTF file into a Pandas DataFrame
@@ -73,5 +120,3 @@ gene_fpkms = {
73
120
  if feature == "gene"
74
121
  }
75
122
  ```
76
-
77
-
@@ -14,6 +14,7 @@ gtfparse.egg-info/dependency_links.txt
14
14
  gtfparse.egg-info/requires.txt
15
15
  gtfparse.egg-info/top_level.txt
16
16
  gtfparse/../requirements.txt
17
+ tests/test_attribute_values.py
17
18
  tests/test_create_missing_features.py
18
19
  tests/test_ensembl_gtf.py
19
20
  tests/test_expand_attribute_column_false.py
@@ -22,6 +23,7 @@ tests/test_gencode_gtf.py
22
23
  tests/test_multiple_values_for_tag_attribute.py
23
24
  tests/test_parse_gtf_lines.py
24
25
  tests/test_polars_compatibility.py
26
+ tests/test_progress.py
25
27
  tests/test_read_stringtie_gtf.py
26
28
  tests/test_refseq_gtf.py
27
29
  tests/test_write_gtf.py
@@ -0,0 +1,80 @@
1
+ from io import StringIO
2
+
3
+ import pytest
4
+
5
+ from gtfparse import expand_attribute_strings, parse_gtf, read_gtf
6
+
7
+
8
+ def gtf_line(attributes):
9
+ return "1\ttest\tgene\t1\t100\t.\t+\t.\t%s\n" % attributes
10
+
11
+
12
+ @pytest.mark.parametrize(
13
+ "value",
14
+ [
15
+ "two words",
16
+ "1 (assigned to previous version 5)",
17
+ "part1; part2",
18
+ "A;B",
19
+ "PRAMEF6;-201",
20
+ "O'Brien",
21
+ " padded ",
22
+ "",
23
+ ],
24
+ )
25
+ def test_quoted_values_survive_all_parsing_paths(value):
26
+ attributes = 'description "%s"; gene_id "G1";' % value
27
+ expected = {"description": [value], "gene_id": ["G1"]}
28
+ assert expand_attribute_strings([attributes]) == expected
29
+ parsed = parse_gtf(StringIO(gtf_line(attributes)))
30
+ assert parsed["attribute"][0] == attributes
31
+ assert expand_attribute_strings(parsed["attribute_split"]) == expected
32
+ result = read_gtf(StringIO(gtf_line(attributes)))
33
+ assert result["description"].to_list() == [value]
34
+ assert result["gene_id"].to_list() == ["G1"]
35
+
36
+
37
+ def test_single_quotes_unquoted_values_and_repeated_tags():
38
+ attributes = "gene_id 'G1'; note 'one; two'; count 0; tag basic; tag more words;"
39
+ expected = {
40
+ "gene_id": ["G1"],
41
+ "note": ["one; two"],
42
+ "count": ["0"],
43
+ "tag": ["basic,more words"],
44
+ }
45
+ assert expand_attribute_strings([attributes]) == expected
46
+ assert read_gtf(StringIO(gtf_line(attributes)))["tag"].to_list() == ["basic,more words"]
47
+
48
+
49
+ def test_whitespace_missing_attributes_and_restricted_columns():
50
+ attributes = [None, "", '; malformed; gene_id "G1"; note "x; y";', 'gene_id "G2";']
51
+ assert expand_attribute_strings(attributes, usecols={"gene_id"}) == {
52
+ "gene_id": ["", "", "G1", "G2"]
53
+ }
54
+ assert expand_attribute_strings(['gene_id\t"G1";']) == {"gene_id": ["G1"]}
55
+
56
+
57
+ def test_raw_attributes_are_preserved():
58
+ attributes = 'gene_id "G1"; note "O\'Brien; part2;-suffix";'
59
+ result = read_gtf(StringIO(gtf_line(attributes)), expand_attribute_column=False)
60
+ assert result["attribute"].to_list() == [attributes]
61
+
62
+
63
+ def test_missing_attribute_column_values():
64
+ text = gtf_line(".") + gtf_line('gene_id "G1";')
65
+ result = read_gtf(StringIO(text))
66
+ assert result["gene_id"].to_list() == ["", "G1"]
67
+
68
+
69
+ def test_legacy_semicolon_cleanup_is_explicit():
70
+ attributes = 'gene_name "PRAMEF6;"; transcript_name "PRAMEF6;-201";'
71
+ result = parse_gtf(StringIO(gtf_line(attributes)), fix_quotes_columns=["attribute"])
72
+ assert result["attribute"][0] == 'gene_name "PRAMEF6"; transcript_name "PRAMEF6-201";'
73
+
74
+
75
+ def test_pre_split_attributes_keep_missing_and_repeated_values():
76
+ rows = [["broken", 'gene_id "G1"', 'tag "first; value"', 'tag "second"'], []]
77
+ assert expand_attribute_strings(rows) == {
78
+ "gene_id": ["G1", ""],
79
+ "tag": ["first; value,second", ""],
80
+ }
@@ -0,0 +1,162 @@
1
+ import gzip
2
+ from io import BytesIO, StringIO
3
+
4
+ import pandas as pd
5
+ import polars
6
+ import pytest
7
+ from polars.testing import assert_frame_equal
8
+
9
+ from gtfparse import (
10
+ expand_attribute_strings,
11
+ parse_gtf,
12
+ parse_gtf_and_expand_attributes,
13
+ parse_gtf_pandas,
14
+ read_gtf,
15
+ )
16
+
17
+ GTF = (
18
+ '1\ttest\tgene\t1\t100\t.\t+\t.\tgene_id "G1"; gene_version "2";\n'
19
+ '1\ttest\texon\t1\t50\t.\t+\t0\tgene_id "G1"; tag "basic";\n'
20
+ )
21
+
22
+
23
+ @pytest.mark.parametrize("result_type", ["polars", "pandas", "dict"])
24
+ @pytest.mark.parametrize("expand", [True, False])
25
+ @pytest.mark.parametrize("features,rows", [(None, 2), ({"gene"}, 1), ({"CDS"}, 0)])
26
+ def test_read_progress_preserves_results(result_type, expand, features, rows, capsys):
27
+ events = []
28
+ kwargs = {
29
+ "result_type": result_type,
30
+ "expand_attribute_column": expand,
31
+ "features": features,
32
+ "attribute_aliases": {"gene_id": "gene"},
33
+ "usecols": ["feature", "start", "gene", "gene_version", "attribute"],
34
+ }
35
+ expected = read_gtf(StringIO(GTF), **kwargs)
36
+ actual = read_gtf(
37
+ StringIO(GTF), progress_callback=lambda *event: events.append(event), **kwargs
38
+ )
39
+ if result_type == "polars":
40
+ assert_frame_equal(actual, expected)
41
+ elif result_type == "pandas":
42
+ pd.testing.assert_frame_equal(actual, expected)
43
+ else:
44
+ assert actual == expected
45
+ expected_events = [("read", 0, None), ("read", rows, rows)]
46
+ if expand:
47
+ expected_events += [("attributes", 0, rows)]
48
+ if rows:
49
+ expected_events.append(("attributes", rows, rows))
50
+ expected_events += [("convert", 0, None), ("convert", rows, rows)]
51
+ assert events == expected_events
52
+ assert capsys.readouterr() == ("", "")
53
+
54
+
55
+ @pytest.mark.parametrize("kind", ["path", "gzip", "bytes", "text"])
56
+ def test_progress_with_supported_inputs(kind, tmp_path):
57
+ if kind == "path":
58
+ source = tmp_path / "test.gtf"
59
+ source.write_text(GTF)
60
+ elif kind == "gzip":
61
+ source = tmp_path / "test.gtf.gz"
62
+ source.write_bytes(gzip.compress(GTF.encode()))
63
+ elif kind == "bytes":
64
+ source = BytesIO(GTF.encode())
65
+ else:
66
+ source = StringIO(GTF)
67
+ events = []
68
+ result = read_gtf(source, progress_callback=lambda *event: events.append(event))
69
+ assert result.height == 2
70
+ assert events[-1] == ("convert", 2, 2)
71
+
72
+
73
+ @pytest.mark.parametrize(
74
+ "parser,stages",
75
+ [
76
+ (parse_gtf, ["read"]),
77
+ (parse_gtf_and_expand_attributes, ["read", "attributes"]),
78
+ (parse_gtf_pandas, ["read", "convert"]),
79
+ ],
80
+ )
81
+ def test_lower_level_progress(parser, stages):
82
+ events = []
83
+ parser(StringIO(GTF), progress_callback=lambda *event: events.append(event))
84
+ assert [event[0] for event in events[::2]] == stages
85
+ assert all(event[1:] == (2, 2) for event in events[1::2])
86
+
87
+
88
+ @pytest.mark.parametrize("rows", [0, 1, 10_000, 20_003])
89
+ def test_attribute_progress_counts_rows_and_is_bounded(rows):
90
+ events = []
91
+ attributes = ['gene_id "G1";'] * rows
92
+ result = expand_attribute_strings(
93
+ attributes, progress_callback=lambda *event: events.append(event)
94
+ )
95
+ assert events[0] == ("attributes", 0, rows)
96
+ assert events[-1] == ("attributes", rows, rows)
97
+ counts = [event[1] for event in events]
98
+ assert counts == sorted(set(counts))
99
+ assert len(events) <= rows // 10_000 + 2
100
+ assert result.get("gene_id", []) == ["G1"] * rows
101
+
102
+
103
+ @pytest.mark.parametrize("stage", ["read", "attributes", "convert"])
104
+ def test_callback_errors_propagate_without_completion(stage):
105
+ events = []
106
+ error = RuntimeError("cancel parsing")
107
+
108
+ def callback(*event):
109
+ events.append(event)
110
+ if event[0] == stage:
111
+ raise error
112
+
113
+ source = StringIO(GTF)
114
+ with pytest.raises(RuntimeError) as caught:
115
+ read_gtf(source, progress_callback=callback)
116
+ assert caught.value is error
117
+ assert events[-1][0:2] == (stage, 0)
118
+ assert not any(event[0] == stage and event[1] == 2 for event in events)
119
+ if stage == "read":
120
+ assert source.tell() == 0
121
+
122
+
123
+ def test_conversion_errors_do_not_report_completion():
124
+ events = []
125
+ with pytest.raises(ValueError):
126
+ read_gtf(
127
+ StringIO(GTF),
128
+ column_converters={"gene_id": int},
129
+ progress_callback=lambda *event: events.append(event),
130
+ )
131
+ assert events[-1] == ("convert", 0, None)
132
+
133
+
134
+ def test_callback_can_cancel_during_attribute_expansion():
135
+ events = []
136
+
137
+ def callback(*event):
138
+ events.append(event)
139
+ if event[:2] == ("attributes", 10_000):
140
+ raise RuntimeError("cancel during expansion")
141
+
142
+ with pytest.raises(RuntimeError, match="cancel during expansion"):
143
+ read_gtf(StringIO(GTF * 10_000), progress_callback=callback)
144
+ assert events[-1] == ("attributes", 10_000, 20_000)
145
+ assert not any(event[0] == "convert" for event in events)
146
+
147
+
148
+ def test_empty_file_keeps_existing_error_without_completion():
149
+ events = []
150
+ with pytest.raises(polars.exceptions.NoDataError):
151
+ read_gtf(StringIO(""), progress_callback=lambda *event: events.append(event))
152
+ assert events == [("read", 0, None)]
153
+
154
+
155
+ @pytest.mark.parametrize("invalid", ["numpy", "Pandas", "", None, []])
156
+ def test_invalid_result_type_rejected_before_reading(invalid):
157
+ source = StringIO(GTF)
158
+ events = []
159
+ with pytest.raises(ValueError, match="result_type"):
160
+ read_gtf(source, result_type=invalid, progress_callback=lambda *event: events.append(event))
161
+ assert source.tell() == 0
162
+ assert events == []
@@ -192,17 +192,13 @@ def test_missing_value_fixed_columns_use_dot(tmp_path):
192
192
  assert fields[7] == "." # frame
193
193
 
194
194
 
195
- def test_structural_characters_are_not_round_trippable(tmp_path):
196
- """GTF has no escaping for '"' or ';'; read_gtf strips quotes and splits on
197
- ';'. Pin that such values cannot round-trip so a future change is noticed."""
198
- df = _minimal_df(gene_id=["A;B"], note=['say "hi"'])
195
+ def test_quoted_attribute_values_round_trip(tmp_path):
196
+ df = _minimal_df(gene_id=["A;B"], note=["O'Brien; says hello"])
199
197
  out_path = tmp_path / "special.gtf"
200
198
  write_gtf(df, out_path)
201
199
  recovered = read_gtf(str(out_path))
202
- # the semicolon split the value apart
203
- assert recovered["gene_id"].to_list() != ["A;B"]
204
- # the double quotes were stripped from the value
205
- assert '"' not in recovered["note"][0]
200
+ assert recovered["gene_id"].to_list() == ["A;B"]
201
+ assert recovered["note"].to_list() == ["O'Brien; says hello"]
206
202
 
207
203
 
208
204
  def test_header_lines_are_written(tmp_path):
gtfparse-2.8.1/README.md DELETED
@@ -1,45 +0,0 @@
1
- [![Tests](https://github.com/openvax/gtfparse/actions/workflows/tests.yml/badge.svg)](https://github.com/openvax/gtfparse/actions/workflows/tests.yml)
2
- [![Coverage Status](https://coveralls.io/repos/openvax/gtfparse/badge.svg?branch=master&service=github)](https://coveralls.io/github/openvax/gtfparse?branch=master)
3
- <a href="https://pypi.python.org/pypi/gtfparse/">
4
- <img src="https://img.shields.io/pypi/v/gtfparse.svg?maxAge=1000" alt="PyPI" />
5
- </a>
6
-
7
- gtfparse
8
- ========
9
- Parsing tools for GTF (gene transfer format) files.
10
-
11
- # Example usage
12
-
13
- ## Parsing all rows of a GTF file into a Pandas DataFrame
14
-
15
- ```python
16
- from gtfparse import read_gtf
17
-
18
- # returns GTF with essential columns such as "feature", "seqname", "start", "end"
19
- # alongside the names of any optional keys which appeared in the attribute column
20
- df = read_gtf("gene_annotations.gtf")
21
-
22
- # filter DataFrame to gene entries on chrY
23
- df_genes = df[df["feature"] == "gene"]
24
- df_genes_chrY = df_genes[df_genes["seqname"] == "Y"]
25
- ```
26
-
27
-
28
- ## Getting gene FPKM values from a StringTie GTF file
29
-
30
- ```python
31
- from gtfparse import read_gtf
32
-
33
- df = read_gtf(
34
- "Transcripts.gtf",
35
- column_converters={"FPKM": float})
36
-
37
- gene_fpkms = {
38
- gene_name: fpkm
39
- for (gene_name, fpkm, feature)
40
- in zip(df["seqname"], df["FPKM"], df["feature"])
41
- if feature == "gene"
42
- }
43
- ```
44
-
45
-
File without changes
File without changes
File without changes
File without changes