gtfparse 2.8.1__tar.gz → 2.9.1__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 (42) hide show
  1. gtfparse-2.9.1/MANIFEST.in +3 -0
  2. {gtfparse-2.8.1 → gtfparse-2.9.1}/PKG-INFO +49 -4
  3. gtfparse-2.9.1/README.md +90 -0
  4. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse/__init__.py +1 -1
  5. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse/attribute_parsing.py +39 -24
  6. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse/read_gtf.py +84 -26
  7. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse/write_gtf.py +5 -9
  8. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse.egg-info/PKG-INFO +49 -4
  9. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse.egg-info/SOURCES.txt +14 -1
  10. gtfparse-2.9.1/lint.sh +13 -0
  11. {gtfparse-2.8.1 → gtfparse-2.9.1}/pyproject.toml +6 -5
  12. gtfparse-2.9.1/test.sh +108 -0
  13. gtfparse-2.9.1/tests/__init__.py +0 -0
  14. gtfparse-2.9.1/tests/data/B16.stringtie.head.gtf +1001 -0
  15. gtfparse-2.9.1/tests/data/ensembl_grch37.head.gtf +1000 -0
  16. gtfparse-2.9.1/tests/data/ensembl_grch37.head.gtf.gz +0 -0
  17. gtfparse-2.9.1/tests/data/gencode.head.gtf +10 -0
  18. gtfparse-2.9.1/tests/data/gencode.real.head.gtf +13 -0
  19. gtfparse-2.9.1/tests/data/refseq.ucsc.small.gtf +24 -0
  20. gtfparse-2.9.1/tests/data.py +8 -0
  21. gtfparse-2.9.1/tests/test_attribute_values.py +80 -0
  22. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_expand_attribute_column_false.py +1 -4
  23. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_gencode_gtf.py +4 -4
  24. gtfparse-2.9.1/tests/test_progress.py +162 -0
  25. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_write_gtf.py +4 -8
  26. gtfparse-2.8.1/README.md +0 -45
  27. {gtfparse-2.8.1 → gtfparse-2.9.1}/LICENSE +0 -0
  28. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse/create_missing_features.py +0 -0
  29. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse/parsing_error.py +0 -0
  30. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse.egg-info/dependency_links.txt +0 -0
  31. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse.egg-info/requires.txt +0 -0
  32. {gtfparse-2.8.1 → gtfparse-2.9.1}/gtfparse.egg-info/top_level.txt +0 -0
  33. {gtfparse-2.8.1 → gtfparse-2.9.1}/requirements.txt +0 -0
  34. {gtfparse-2.8.1 → gtfparse-2.9.1}/setup.cfg +0 -0
  35. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_create_missing_features.py +0 -0
  36. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_ensembl_gtf.py +0 -0
  37. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_expand_attributes.py +0 -0
  38. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_multiple_values_for_tag_attribute.py +0 -0
  39. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_parse_gtf_lines.py +0 -0
  40. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_polars_compatibility.py +0 -0
  41. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_read_stringtie_gtf.py +0 -0
  42. {gtfparse-2.8.1 → gtfparse-2.9.1}/tests/test_refseq_gtf.py +0 -0
@@ -0,0 +1,3 @@
1
+ include lint.sh test.sh
2
+ recursive-include tests *.py
3
+ recursive-include tests/data *.gtf *.gtf.gz
@@ -1,15 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gtfparse
3
- Version: 2.8.1
3
+ Version: 2.9.1
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
+ License-Expression: Apache-2.0
6
7
  Project-URL: Homepage, https://github.com/openvax/gtfparse
7
8
  Project-URL: Bug Tracker, https://github.com/openvax/gtfparse/issues
8
9
  Classifier: Development Status :: 4 - Beta
9
10
  Classifier: Environment :: Console
10
11
  Classifier: Operating System :: OS Independent
11
12
  Classifier: Intended Audience :: Science/Research
12
- Classifier: License :: OSI Approved :: Apache Software License
13
13
  Classifier: Programming Language :: Python
14
14
  Classifier: Programming Language :: Python :: 3
15
15
  Classifier: Programming Language :: Python :: 3.9
@@ -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.1"
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,60 +146,95 @@ 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
- Parse lines into column->values dictionary and then expand
200
+ Parse a GTF into a Polars DataFrame and then expand
175
201
  the 'attribute' column into multiple columns. This expansion happens
176
202
  by replacing strings of semi-colon separated key-value values in the
177
203
  'attribute' column with one column per distinct key, with a list of
178
- values for each row (using None for rows where key didn't occur).
204
+ values for each row (using empty strings for rows where the key didn't occur).
179
205
 
180
206
  Parameters
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
  ----------
@@ -288,7 +324,7 @@ def read_gtf(
288
324
  expand_attribute_column : bool
289
325
  Replace strings of semi-colon separated key-value values in the
290
326
  'attribute' column with one column per distinct key, with a list of
291
- values for each row (using None for rows where key didn't occur).
327
+ values for each row (using empty strings for rows where the key didn't occur).
292
328
 
293
329
  infer_biotype_column : bool
294
330
  Due to the annoying ambiguity of the second GTF column across multiple
@@ -302,7 +338,7 @@ def read_gtf(
302
338
 
303
339
  column_cast_types : dict, optional
304
340
  Dictionary mapping column names to dtypes. Will cast columns to given
305
- Polars types.
341
+ pandas-compatible types.
306
342
 
307
343
  usecols : list of str or None
308
344
  Restrict which columns are loaded to the give set. If None, then
@@ -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
@@ -59,8 +59,7 @@ def _attribute_expr(attribute_columns: list[str]) -> polars.Expr:
59
59
  empty string (string columns) and cannot distinguish absent from
60
60
  present-but-empty, so we treat both null and "" as absent. Values that are
61
61
  merely falsy but non-empty -- notably the string "0" -- are written and
62
- survive a round trip (this is the regression that the naive ``if value:``
63
- check in earlier drafts got wrong).
62
+ survive a round trip.
64
63
  """
65
64
  if not attribute_columns:
66
65
  return polars.lit("")
@@ -142,13 +141,10 @@ def write_gtf(
142
141
 
143
142
  Notes
144
143
  -----
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.
144
+ Attribute values are enclosed in double quotes, so spaces, apostrophes,
145
+ and semicolons round-trip. This writer does not escape embedded double
146
+ quotes, tabs, or newlines; values containing those characters are outside
147
+ its round-trip guarantees. Empty and missing attributes are both omitted.
152
148
  """
153
149
  # Accept a pandas DataFrame too, since read_gtf(result_type="pandas")
154
150
  # returns one; convert to polars so the formatting below is uniform.
@@ -1,15 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gtfparse
3
- Version: 2.8.1
3
+ Version: 2.9.1
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
+ License-Expression: Apache-2.0
6
7
  Project-URL: Homepage, https://github.com/openvax/gtfparse
7
8
  Project-URL: Bug Tracker, https://github.com/openvax/gtfparse/issues
8
9
  Classifier: Development Status :: 4 - Beta
9
10
  Classifier: Environment :: Console
10
11
  Classifier: Operating System :: OS Independent
11
12
  Classifier: Intended Audience :: Science/Research
12
- Classifier: License :: OSI Approved :: Apache Software License
13
13
  Classifier: Programming Language :: Python
14
14
  Classifier: Programming Language :: Python :: 3
15
15
  Classifier: Programming Language :: Python :: 3.9
@@ -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
-