gtfparse 2.9.1__tar.gz → 3.0.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.
- {gtfparse-2.9.1 → gtfparse-3.0.0}/MANIFEST.in +1 -0
- {gtfparse-2.9.1/gtfparse.egg-info → gtfparse-3.0.0}/PKG-INFO +41 -6
- {gtfparse-2.9.1 → gtfparse-3.0.0}/README.md +37 -3
- gtfparse-3.0.0/benchmarks/README.md +110 -0
- gtfparse-3.0.0/benchmarks/compare_readers.py +279 -0
- gtfparse-3.0.0/benchmarks/results.json +8335 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse/__init__.py +1 -1
- gtfparse-3.0.0/gtfparse/_polars.py +16 -0
- gtfparse-3.0.0/gtfparse/_read_csv.py +138 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse/attribute_parsing.py +1 -1
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse/read_gtf.py +46 -93
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse/write_gtf.py +38 -72
- {gtfparse-2.9.1 → gtfparse-3.0.0/gtfparse.egg-info}/PKG-INFO +41 -6
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse.egg-info/SOURCES.txt +6 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse.egg-info/requires.txt +4 -2
- {gtfparse-2.9.1 → gtfparse-3.0.0}/lint.sh +1 -1
- {gtfparse-2.9.1 → gtfparse-3.0.0}/pyproject.toml +1 -0
- gtfparse-3.0.0/requirements.txt +2 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/test.sh +3 -3
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/data.py +5 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_create_missing_features.py +0 -1
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_expand_attribute_column_false.py +2 -1
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_gencode_gtf.py +3 -1
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_parse_gtf_lines.py +2 -2
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_polars_compatibility.py +14 -3
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_progress.py +11 -6
- gtfparse-3.0.0/tests/test_reader.py +201 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_write_gtf.py +11 -11
- gtfparse-2.9.1/requirements.txt +0 -3
- {gtfparse-2.9.1 → gtfparse-3.0.0}/LICENSE +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse/create_missing_features.py +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse/parsing_error.py +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse.egg-info/dependency_links.txt +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/gtfparse.egg-info/top_level.txt +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/setup.cfg +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/__init__.py +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/data/B16.stringtie.head.gtf +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/data/ensembl_grch37.head.gtf +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/data/ensembl_grch37.head.gtf.gz +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/data/gencode.head.gtf +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/data/gencode.real.head.gtf +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/data/refseq.ucsc.small.gtf +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_attribute_values.py +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_ensembl_gtf.py +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_expand_attributes.py +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_multiple_values_for_tag_attribute.py +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_read_stringtie_gtf.py +0 -0
- {gtfparse-2.9.1 → gtfparse-3.0.0}/tests/test_refseq_gtf.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: gtfparse
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.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
|
License-Expression: Apache-2.0
|
|
@@ -20,9 +20,10 @@ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
|
20
20
|
Requires-Python: >=3.9
|
|
21
21
|
Description-Content-Type: text/markdown
|
|
22
22
|
License-File: LICENSE
|
|
23
|
-
Requires-Dist: polars>=0.20.2
|
|
24
23
|
Requires-Dist: pyarrow>=18.0.0
|
|
25
|
-
Requires-Dist: pandas>=2.
|
|
24
|
+
Requires-Dist: pandas>=2.2.2
|
|
25
|
+
Provides-Extra: polars
|
|
26
|
+
Requires-Dist: polars>=0.20.31; extra == "polars"
|
|
26
27
|
Provides-Extra: dev
|
|
27
28
|
Requires-Dist: pytest; extra == "dev"
|
|
28
29
|
Requires-Dist: pytest-cov; extra == "dev"
|
|
@@ -40,6 +41,41 @@ gtfparse
|
|
|
40
41
|
========
|
|
41
42
|
Parsing tools for GTF (gene transfer format) files.
|
|
42
43
|
|
|
44
|
+
## Version 3 migration
|
|
45
|
+
|
|
46
|
+
`read_gtf`, `parse_gtf`, and `parse_gtf_and_expand_attributes` now return pandas
|
|
47
|
+
DataFrames by default. GTF reading uses PyArrow; attribute processing and writing
|
|
48
|
+
use pandas. Polars is no longer a required dependency and is imported only for
|
|
49
|
+
explicit Polars conversion. Ordinary installations need only pandas and PyArrow.
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
pip install gtfparse
|
|
53
|
+
# Optional, for applications that still request Polars frames:
|
|
54
|
+
pip install 'gtfparse[polars]'
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from gtfparse import read_gtf, write_gtf
|
|
59
|
+
|
|
60
|
+
df = read_gtf("gene_annotations.gtf") # pandas.DataFrame
|
|
61
|
+
write_gtf(df, "gene_annotations.gtf.gz")
|
|
62
|
+
|
|
63
|
+
# Requires the optional extra:
|
|
64
|
+
polars_df = read_gtf("gene_annotations.gtf", result_type="polars")
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Existing pandas and dictionary callers retain their output shape, fixed-column
|
|
68
|
+
dtypes, attribute handling, filters, converters and progress callbacks. Applications
|
|
69
|
+
that used the previous default Polars output should add `result_type="polars"`
|
|
70
|
+
and install the extra, or use pandas methods. `write_gtf` accepts either frame
|
|
71
|
+
type. The legacy `parse_with_polars_lazy` helper remains an optional adapter:
|
|
72
|
+
it reads the file eagerly and returns a Polars LazyFrame, as before.
|
|
73
|
+
|
|
74
|
+
Empty or malformed GTF fields now raise `gtfparse.ParsingError`, including wrong
|
|
75
|
+
field counts and invalid numeric fields. Whole comment lines are ignored;
|
|
76
|
+
literal `#` inside attributes is preserved. Text and binary streams stay open
|
|
77
|
+
after parsing, and gzip is detected from its contents.
|
|
78
|
+
|
|
43
79
|
## Reporting parsing progress
|
|
44
80
|
|
|
45
81
|
Pass `progress_callback(stage, completed, total)` to `read_gtf` to connect
|
|
@@ -49,7 +85,7 @@ does not display a progress bar or add a progress-library dependency.
|
|
|
49
85
|
|
|
50
86
|
| Stage | Reports |
|
|
51
87
|
| --- | --- |
|
|
52
|
-
| `read` | `(0, None)` before
|
|
88
|
+
| `read` | `(0, None)` before loading/filtering the file; `(rows, rows)` after it succeeds |
|
|
53
89
|
| `attributes` | `(0, rows)`, then every 10,000 rows, then `(rows, rows)` |
|
|
54
90
|
| `convert` | `(0, None)` before output conversion/transforms; `(rows, rows)` after success |
|
|
55
91
|
|
|
@@ -58,8 +94,7 @@ percentages. `None` means the total is unknown: loading and conversion expose
|
|
|
58
94
|
only stage boundaries, so use an indeterminate indicator during those steps.
|
|
59
95
|
Attribute expansion is omitted when `expand_attribute_column=False`. A stage
|
|
60
96
|
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
|
|
62
|
-
the existing Polars `NoDataError` behavior.
|
|
97
|
+
its attributes stage emits a single `(0, 0)` event. Empty input files raise `gtfparse.ParsingError`.
|
|
63
98
|
|
|
64
99
|
For example, with the optional `tqdm` package installed:
|
|
65
100
|
|
|
@@ -8,6 +8,41 @@ gtfparse
|
|
|
8
8
|
========
|
|
9
9
|
Parsing tools for GTF (gene transfer format) files.
|
|
10
10
|
|
|
11
|
+
## Version 3 migration
|
|
12
|
+
|
|
13
|
+
`read_gtf`, `parse_gtf`, and `parse_gtf_and_expand_attributes` now return pandas
|
|
14
|
+
DataFrames by default. GTF reading uses PyArrow; attribute processing and writing
|
|
15
|
+
use pandas. Polars is no longer a required dependency and is imported only for
|
|
16
|
+
explicit Polars conversion. Ordinary installations need only pandas and PyArrow.
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
pip install gtfparse
|
|
20
|
+
# Optional, for applications that still request Polars frames:
|
|
21
|
+
pip install 'gtfparse[polars]'
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from gtfparse import read_gtf, write_gtf
|
|
26
|
+
|
|
27
|
+
df = read_gtf("gene_annotations.gtf") # pandas.DataFrame
|
|
28
|
+
write_gtf(df, "gene_annotations.gtf.gz")
|
|
29
|
+
|
|
30
|
+
# Requires the optional extra:
|
|
31
|
+
polars_df = read_gtf("gene_annotations.gtf", result_type="polars")
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Existing pandas and dictionary callers retain their output shape, fixed-column
|
|
35
|
+
dtypes, attribute handling, filters, converters and progress callbacks. Applications
|
|
36
|
+
that used the previous default Polars output should add `result_type="polars"`
|
|
37
|
+
and install the extra, or use pandas methods. `write_gtf` accepts either frame
|
|
38
|
+
type. The legacy `parse_with_polars_lazy` helper remains an optional adapter:
|
|
39
|
+
it reads the file eagerly and returns a Polars LazyFrame, as before.
|
|
40
|
+
|
|
41
|
+
Empty or malformed GTF fields now raise `gtfparse.ParsingError`, including wrong
|
|
42
|
+
field counts and invalid numeric fields. Whole comment lines are ignored;
|
|
43
|
+
literal `#` inside attributes is preserved. Text and binary streams stay open
|
|
44
|
+
after parsing, and gzip is detected from its contents.
|
|
45
|
+
|
|
11
46
|
## Reporting parsing progress
|
|
12
47
|
|
|
13
48
|
Pass `progress_callback(stage, completed, total)` to `read_gtf` to connect
|
|
@@ -17,7 +52,7 @@ does not display a progress bar or add a progress-library dependency.
|
|
|
17
52
|
|
|
18
53
|
| Stage | Reports |
|
|
19
54
|
| --- | --- |
|
|
20
|
-
| `read` | `(0, None)` before
|
|
55
|
+
| `read` | `(0, None)` before loading/filtering the file; `(rows, rows)` after it succeeds |
|
|
21
56
|
| `attributes` | `(0, rows)`, then every 10,000 rows, then `(rows, rows)` |
|
|
22
57
|
| `convert` | `(0, None)` before output conversion/transforms; `(rows, rows)` after success |
|
|
23
58
|
|
|
@@ -26,8 +61,7 @@ percentages. `None` means the total is unknown: loading and conversion expose
|
|
|
26
61
|
only stage boundaries, so use an indeterminate indicator during those steps.
|
|
27
62
|
Attribute expansion is omitted when `expand_attribute_column=False`. A stage
|
|
28
63
|
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
|
|
30
|
-
the existing Polars `NoDataError` behavior.
|
|
64
|
+
its attributes stage emits a single `(0, 0)` event. Empty input files raise `gtfparse.ParsingError`.
|
|
31
65
|
|
|
32
66
|
For example, with the optional `tqdm` package installed:
|
|
33
67
|
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# GTF reader backend comparison
|
|
2
|
+
|
|
3
|
+
Version 3 uses PyArrow for fixed-column parsing and pandas for attribute
|
|
4
|
+
processing and writing. Polars is an optional output adapter. This directory
|
|
5
|
+
contains the measurement harness and the evidence for that decision.
|
|
6
|
+
|
|
7
|
+
## Reproduction
|
|
8
|
+
|
|
9
|
+
The recorded runs use Python 3.12.6, NumPy 2.5.3, PyArrow 25.0.1, Polars 1.44.2,
|
|
10
|
+
and pandas 2.3.3 or 3.0.6. Install the checkout with `pip install '.[dev,polars]'`
|
|
11
|
+
in isolated environments. Run one fresh process at a time with four threads:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
POLARS_MAX_THREADS=4 python benchmarks/compare_readers.py sample.gtf --backend production
|
|
15
|
+
POLARS_MAX_THREADS=4 python benchmarks/compare_readers.py sample.gtf --backend pandas
|
|
16
|
+
POLARS_MAX_THREADS=4 python benchmarks/compare_readers.py sample.gtf --backend arrow
|
|
17
|
+
POLARS_MAX_THREADS=4 python benchmarks/compare_readers.py sample.gtf --backend arrow-extension
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
For the old production baseline, extract commit `3e0912c` (gtfparse 2.9.1) into
|
|
21
|
+
a separate directory and use the same harness with `--library-root /path/to/baseline`.
|
|
22
|
+
Repeat each combination three times, interleaving readers and reversing their
|
|
23
|
+
order for the second repetition. Imports and validation are outside wall/CPU
|
|
24
|
+
timing. Peak RSS is the process high-water mark, including imports, captured
|
|
25
|
+
before checksumming or constructing a reference frame. OS caches are not flushed.
|
|
26
|
+
The shared workstation and short runs limit precise throughput claims.
|
|
27
|
+
|
|
28
|
+
Each invocation emits JSON with wall/CPU time, stage timings, pre-validation
|
|
29
|
+
peak RSS, versions, dimensions, column order and a content checksum. Hashing
|
|
30
|
+
normalizes equivalent string/categorical representations and ordinary numeric
|
|
31
|
+
representations. The corpus coordinates are below float64's exact-integer limit;
|
|
32
|
+
separate regression tests verify exact parsing of larger int64 coordinates.
|
|
33
|
+
Use `--verify` for DataFrame equality against production on small inputs.
|
|
34
|
+
`--features exon`, `--usecols seqname start end gene_id transcript_id`, and
|
|
35
|
+
`--result-type polars` exercise selective reads and optional conversion.
|
|
36
|
+
|
|
37
|
+
## Corpus and equivalence
|
|
38
|
+
|
|
39
|
+
- [Ensembl release 114, human GRCh38](https://ftp.ensembl.org/pub/release-114/gtf/homo_sapiens/Homo_sapiens.GRCh38.114.gtf.gz)
|
|
40
|
+
- [GENCODE v48, human primary assembly](https://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_48/gencode.v48.primary_assembly.annotation.gtf.gz)
|
|
41
|
+
|
|
42
|
+
The repeated sweep uses the first 250,000 annotation rows of each source with
|
|
43
|
+
its original header, in plain and gzip form. The full GENCODE gzip file provides
|
|
44
|
+
a separate scaling check on 4,119,244 rows. Original GTFs are not committed.
|
|
45
|
+
Input byte sizes, SHA-256 hashes, source URLs and selection rules are in
|
|
46
|
+
[results.json](results.json), alongside all 122 retained measurement records,
|
|
47
|
+
three-run medians/ranges and stage medians. Discarded production measurements
|
|
48
|
+
from before the final filtering changes are excluded.
|
|
49
|
+
|
|
50
|
+
All measured readers produce matching hashes, including the full-file pair.
|
|
51
|
+
The five real repository fixtures also pass 50 old/new API comparisons and
|
|
52
|
+
30 prototype comparisons on each pandas version (160 checks). The API checks
|
|
53
|
+
include raw attributes, filtering, selection, aliases, version casts, biotype
|
|
54
|
+
inference and converters; separate regressions cover streams, nullable fields,
|
|
55
|
+
comments, malformed inputs and progress/cancellation semantics.
|
|
56
|
+
|
|
57
|
+
## Production results
|
|
58
|
+
|
|
59
|
+
The table shows three-run medians for equivalent pandas output. Complete load
|
|
60
|
+
time includes fixed-column reading, attribute expansion, assembly and transforms.
|
|
61
|
+
|
|
62
|
+
| pandas | Input (250k rows) | Old seconds | New seconds | Old peak MiB | New peak MiB |
|
|
63
|
+
| --- | --- | ---: | ---: | ---: | ---: |
|
|
64
|
+
| 2.3.3 | ensembl-250k.gtf | 2.51 | 2.75 | 560 | 614 |
|
|
65
|
+
| 2.3.3 | ensembl-250k.gtf.gz | 2.54 | 2.79 | 561 | 613 |
|
|
66
|
+
| 2.3.3 | gencode-250k.gtf | 2.08 | 2.42 | 567 | 581 |
|
|
67
|
+
| 2.3.3 | gencode-250k.gtf.gz | 2.16 | 2.42 | 568 | 581 |
|
|
68
|
+
| 3.0.6 | ensembl-250k.gtf | 2.28 | 2.69 | 552 | 601 |
|
|
69
|
+
| 3.0.6 | ensembl-250k.gtf.gz | 2.27 | 2.69 | 553 | 603 |
|
|
70
|
+
| 3.0.6 | gencode-250k.gtf | 2.01 | 2.41 | 560 | 597 |
|
|
71
|
+
| 3.0.6 | gencode-250k.gtf.gz | 2.03 | 2.44 | 560 | 592 |
|
|
72
|
+
|
|
73
|
+
Across these subsets, the new reader takes 1.10–1.20x the old total time and
|
|
74
|
+
1.03–1.10x the peak RSS. The single full GENCODE check with pandas 2.3.3 takes
|
|
75
|
+
38.88s / 6189 MiB for the baseline and 45.40s / 5348 MiB for version 3: matching
|
|
76
|
+
content, 1.17x time, and lower peak memory. This pair verifies scaling and
|
|
77
|
+
correctness; one observation per reader does not establish stable throughput.
|
|
78
|
+
|
|
79
|
+
The complete-load result meets #69's proposed 1.5x total-time threshold. The
|
|
80
|
+
callback `read` stages are different contracts for timing: version 3 includes
|
|
81
|
+
stream preprocessing and Arrow-to-pandas conversion; the old reader constructs
|
|
82
|
+
Polars frames and converts to pandas later. The reported read-stage times do
|
|
83
|
+
not establish the proposed 3x raw-CSV threshold. This migration is justified by
|
|
84
|
+
the measured complete-load cost and the user's preference to remove the required
|
|
85
|
+
Polars dependency, rather than a claim that Arrow is faster at raw CSV parsing.
|
|
86
|
+
Python attribute expansion remains the largest stage (roughly 1.7–1.8s on these
|
|
87
|
+
subsets). Eliminating it or changing its semantics is outside this change.
|
|
88
|
+
|
|
89
|
+
## Candidate evaluation and limits
|
|
90
|
+
|
|
91
|
+
The pandas C prototype is slower end to end on this corpus. The direct Arrow
|
|
92
|
+
and Arrow-extension prototypes have similar complete-load costs; extension
|
|
93
|
+
scalars introduce iteration/conversion overhead, and nullable dictionary casts
|
|
94
|
+
need an object bridge on pandas 2.3.3. These costs are included in the results.
|
|
95
|
+
The conventional Arrow-to-pandas path avoids that bridge and preserves the
|
|
96
|
+
established fixed-column and attribute output types.
|
|
97
|
+
|
|
98
|
+
The three prototypes are measurement tools. They support the paths, gzip,
|
|
99
|
+
filters, column selection and result types used here, but not the entire public
|
|
100
|
+
API. They omit buffers, custom converters, aliases, biotype inference, quote
|
|
101
|
+
cleanup, raw mode and complete progress/failure behavior. The pandas prototype
|
|
102
|
+
skips leading comments; the Arrow prototypes skip comment rows only on a field
|
|
103
|
+
count mismatch. The production reader implements whole-line comment filtering,
|
|
104
|
+
BOM and stream handling, exact field counts, declared numeric types and filtering
|
|
105
|
+
before pandas conversion so discarded null coordinates do not change dtypes.
|
|
106
|
+
|
|
107
|
+
Pandas reader behavior is documented in
|
|
108
|
+
[read_csv](https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html),
|
|
109
|
+
and Arrow's typed CSV options in its
|
|
110
|
+
[CSV guide](https://arrow.apache.org/docs/python/csv.html).
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Backend experiment, not an alternative supported reader.
|
|
2
|
+
|
|
3
|
+
Run each invocation in a fresh process. See README.md for corpus provenance,
|
|
4
|
+
repetition, equivalence checks, and limitations of the experimental readers.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import csv
|
|
9
|
+
import gzip
|
|
10
|
+
import hashlib
|
|
11
|
+
import importlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import platform
|
|
15
|
+
import resource
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from time import perf_counter, process_time
|
|
19
|
+
|
|
20
|
+
import pandas as pd
|
|
21
|
+
import pyarrow as pa
|
|
22
|
+
import pyarrow.compute as pc
|
|
23
|
+
import pyarrow.csv as pacsv
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
import polars as pl
|
|
27
|
+
except ModuleNotFoundError as error:
|
|
28
|
+
if error.name != "polars":
|
|
29
|
+
raise
|
|
30
|
+
pl = None
|
|
31
|
+
|
|
32
|
+
# Use the requested checkout before importing gtfparse, for baseline comparisons.
|
|
33
|
+
import_options = argparse.ArgumentParser(add_help=False)
|
|
34
|
+
import_options.add_argument("--library-root", type=Path)
|
|
35
|
+
import_args, _ = import_options.parse_known_args()
|
|
36
|
+
library_root = import_args.library_root or Path(__file__).resolve().parents[1]
|
|
37
|
+
if not (library_root / "gtfparse" / "__init__.py").is_file():
|
|
38
|
+
import_options.error("--library-root must contain the gtfparse package")
|
|
39
|
+
sys.path.insert(0, str(library_root))
|
|
40
|
+
package = importlib.import_module("gtfparse")
|
|
41
|
+
__version__ = package.__version__
|
|
42
|
+
expand_attribute_strings = package.expand_attribute_strings
|
|
43
|
+
read_gtf = package.read_gtf
|
|
44
|
+
|
|
45
|
+
reader = importlib.import_module("gtfparse.read_gtf")
|
|
46
|
+
CATEGORIES = ("seqname", "source", "feature", "strand")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Timings:
|
|
50
|
+
def __init__(self):
|
|
51
|
+
self.stages = {}
|
|
52
|
+
self.starts = {}
|
|
53
|
+
|
|
54
|
+
def callback(self, stage, completed, total):
|
|
55
|
+
if completed == 0:
|
|
56
|
+
self.starts[stage] = perf_counter()
|
|
57
|
+
if total is not None and completed == total:
|
|
58
|
+
self.stages[stage] = perf_counter() - self.starts[stage]
|
|
59
|
+
|
|
60
|
+
def run(self, stage, fn):
|
|
61
|
+
start = perf_counter()
|
|
62
|
+
result = fn()
|
|
63
|
+
self.stages[stage] = perf_counter() - start
|
|
64
|
+
return result
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def leading_comments(path):
|
|
68
|
+
opener = gzip.open if str(path).endswith(".gz") else open
|
|
69
|
+
with opener(path, "rt") as stream:
|
|
70
|
+
count = 0
|
|
71
|
+
for line in stream:
|
|
72
|
+
if not line.startswith("#"):
|
|
73
|
+
break
|
|
74
|
+
count += 1
|
|
75
|
+
return count
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def pandas_read(path, features):
|
|
79
|
+
# Explicit object strings match Polars.to_pandas and avoid pandas' default
|
|
80
|
+
# NA vocabulary interpreting valid names such as "NA" as missing values.
|
|
81
|
+
types = dict.fromkeys(CATEGORIES, "category")
|
|
82
|
+
types.update(start="int64", end="int64", score="float32", frame="float64", attribute=object)
|
|
83
|
+
frame = pd.read_csv(
|
|
84
|
+
path,
|
|
85
|
+
sep="\t",
|
|
86
|
+
header=None,
|
|
87
|
+
names=reader.REQUIRED_COLUMNS,
|
|
88
|
+
dtype=types,
|
|
89
|
+
engine="c",
|
|
90
|
+
quoting=csv.QUOTE_NONE,
|
|
91
|
+
skiprows=leading_comments(path),
|
|
92
|
+
keep_default_na=False,
|
|
93
|
+
na_values=[".", ""],
|
|
94
|
+
)
|
|
95
|
+
frame = frame.loc[frame.seqname.notna()]
|
|
96
|
+
frame["frame"] = frame["frame"].fillna(0).astype("uint32")
|
|
97
|
+
if features:
|
|
98
|
+
frame = frame.loc[frame.feature.isin(features)]
|
|
99
|
+
frame["attribute"] = frame.attribute.where(frame.attribute.notna(), None)
|
|
100
|
+
return frame.reset_index(drop=True)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def arrow_read(path, features, extension=False):
|
|
104
|
+
types = dict.fromkeys(CATEGORIES, pa.dictionary(pa.int32(), pa.string()))
|
|
105
|
+
types.update(
|
|
106
|
+
start=pa.int64(),
|
|
107
|
+
end=pa.int64(),
|
|
108
|
+
score=pa.float32(),
|
|
109
|
+
frame=pa.uint32(),
|
|
110
|
+
attribute=pa.string(),
|
|
111
|
+
)
|
|
112
|
+
table = pacsv.read_csv(
|
|
113
|
+
path,
|
|
114
|
+
read_options=pacsv.ReadOptions(column_names=reader.REQUIRED_COLUMNS),
|
|
115
|
+
parse_options=pacsv.ParseOptions(
|
|
116
|
+
delimiter="\t",
|
|
117
|
+
quote_char=False,
|
|
118
|
+
invalid_row_handler=lambda row: "skip" if row.text.startswith("#") else "error",
|
|
119
|
+
),
|
|
120
|
+
convert_options=pacsv.ConvertOptions(
|
|
121
|
+
column_types=types, null_values=[".", ""], strings_can_be_null=True
|
|
122
|
+
),
|
|
123
|
+
)
|
|
124
|
+
table = table.filter(pc.is_valid(table["seqname"]))
|
|
125
|
+
table = table.set_column(7, "frame", pc.fill_null(table["frame"], 0))
|
|
126
|
+
if features:
|
|
127
|
+
table = table.filter(pc.is_in(table["feature"], value_set=pa.array(features)))
|
|
128
|
+
return table.to_pandas(types_mapper=pd.ArrowDtype if extension else None)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def prototype(path, backend, timings, features, usecols, result_type):
|
|
132
|
+
if backend == "pandas":
|
|
133
|
+
frame = timings.run("read", lambda: pandas_read(path, features))
|
|
134
|
+
else:
|
|
135
|
+
frame = timings.run(
|
|
136
|
+
"read", lambda: arrow_read(path, features, backend == "arrow-extension")
|
|
137
|
+
)
|
|
138
|
+
attributes = frame.pop("attribute")
|
|
139
|
+
# Arrow extension scalars use pd.NA; the production expander accepts None.
|
|
140
|
+
values = (None if value is pd.NA else value for value in attributes)
|
|
141
|
+
if backend == "arrow-extension":
|
|
142
|
+
# Materialization belongs in the measured expansion time.
|
|
143
|
+
class SizedValues:
|
|
144
|
+
def __len__(self):
|
|
145
|
+
return len(attributes)
|
|
146
|
+
|
|
147
|
+
def __iter__(self):
|
|
148
|
+
return values
|
|
149
|
+
|
|
150
|
+
attributes_for_expansion = SizedValues()
|
|
151
|
+
else:
|
|
152
|
+
attributes_for_expansion = attributes
|
|
153
|
+
expanded = timings.run(
|
|
154
|
+
"attributes", lambda: expand_attribute_strings(attributes_for_expansion, usecols=usecols)
|
|
155
|
+
)
|
|
156
|
+
# Match pandas 2 object strings / pandas 3 inferred StringDtype, as returned
|
|
157
|
+
# by the production reader's Arrow-to-pandas conversion on each version.
|
|
158
|
+
frame = timings.run("assemble", lambda: pd.concat([frame, pd.DataFrame(expanded)], axis=1))
|
|
159
|
+
attributes = attributes_for_expansion = values = expanded = None
|
|
160
|
+
|
|
161
|
+
def finish():
|
|
162
|
+
nonlocal frame
|
|
163
|
+
if backend == "arrow-extension":
|
|
164
|
+
for name in CATEGORIES:
|
|
165
|
+
# pandas 2.3 cannot directly cast an Arrow dictionary with
|
|
166
|
+
# null indices to category (its zero-copy conversion fails).
|
|
167
|
+
# Include the object bridge in this prototype's measured cost.
|
|
168
|
+
frame[name] = frame[name].astype(object).astype("category")
|
|
169
|
+
for name, dtype in {
|
|
170
|
+
"start": "int64",
|
|
171
|
+
"end": "int64",
|
|
172
|
+
"score": "float32",
|
|
173
|
+
"frame": "uint32",
|
|
174
|
+
}.items():
|
|
175
|
+
frame[name] = frame[name].astype(dtype)
|
|
176
|
+
frame = reader._cast_version_columns(frame)
|
|
177
|
+
if usecols is not None:
|
|
178
|
+
frame = frame[[name for name in usecols if name in frame]]
|
|
179
|
+
return pl.from_pandas(frame) if result_type == "polars" else frame
|
|
180
|
+
|
|
181
|
+
return timings.run("convert", finish)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def checksum(frame):
|
|
185
|
+
"""Hash all values and column order, ignoring categorical dictionary order."""
|
|
186
|
+
if pl is not None and isinstance(frame, pl.DataFrame):
|
|
187
|
+
frame = frame.to_pandas()
|
|
188
|
+
digest = hashlib.sha256(json.dumps(list(frame.columns)).encode())
|
|
189
|
+
for name in frame.columns:
|
|
190
|
+
values = frame[name]
|
|
191
|
+
if pd.api.types.is_numeric_dtype(values.dtype):
|
|
192
|
+
values = values.astype("float64")
|
|
193
|
+
else:
|
|
194
|
+
values = values.astype(object).where(values.notna(), None)
|
|
195
|
+
digest.update(pd.util.hash_pandas_object(values, index=False).values.tobytes())
|
|
196
|
+
return digest.hexdigest()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def main():
|
|
200
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
201
|
+
parser.add_argument("path", type=Path)
|
|
202
|
+
parser.add_argument("--library-root", type=Path, help="Read from another gtfparse checkout")
|
|
203
|
+
parser.add_argument(
|
|
204
|
+
"--backend",
|
|
205
|
+
choices=["production", "pandas", "arrow", "arrow-extension"],
|
|
206
|
+
default="production",
|
|
207
|
+
)
|
|
208
|
+
parser.add_argument("--threads", type=int, default=4)
|
|
209
|
+
parser.add_argument("--result-type", choices=["pandas", "polars"], default="pandas")
|
|
210
|
+
parser.add_argument("--features", nargs="+")
|
|
211
|
+
parser.add_argument("--usecols", nargs="+")
|
|
212
|
+
parser.add_argument(
|
|
213
|
+
"--verify",
|
|
214
|
+
action="store_true",
|
|
215
|
+
help="Compare to production output after timing (small inputs).",
|
|
216
|
+
)
|
|
217
|
+
args = parser.parse_args()
|
|
218
|
+
if args.result_type == "polars" and pl is None:
|
|
219
|
+
parser.error("Polars output requires pip install 'gtfparse[polars]'")
|
|
220
|
+
if pl is not None and pl.thread_pool_size() != args.threads:
|
|
221
|
+
parser.error("Set POLARS_MAX_THREADS before starting the process to match --threads")
|
|
222
|
+
pa.set_cpu_count(args.threads)
|
|
223
|
+
timings = Timings()
|
|
224
|
+
start, cpu_start = perf_counter(), process_time()
|
|
225
|
+
if args.backend == "production":
|
|
226
|
+
frame = read_gtf(
|
|
227
|
+
str(args.path),
|
|
228
|
+
result_type=args.result_type,
|
|
229
|
+
features=args.features,
|
|
230
|
+
usecols=args.usecols,
|
|
231
|
+
progress_callback=timings.callback,
|
|
232
|
+
)
|
|
233
|
+
else:
|
|
234
|
+
frame = prototype(
|
|
235
|
+
str(args.path), args.backend, timings, args.features, args.usecols, args.result_type
|
|
236
|
+
)
|
|
237
|
+
elapsed, cpu = perf_counter() - start, process_time() - cpu_start
|
|
238
|
+
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
|
239
|
+
peak_mib = peak / (1024**2 if sys.platform == "darwin" else 1024)
|
|
240
|
+
# Capture the high-water mark BEFORE hashing, comparison, or output sizing.
|
|
241
|
+
timings.stages["other"] = elapsed - sum(timings.stages.values())
|
|
242
|
+
output = {
|
|
243
|
+
"path": str(args.path),
|
|
244
|
+
"input_bytes": args.path.stat().st_size,
|
|
245
|
+
"backend": args.backend,
|
|
246
|
+
"result_type": args.result_type,
|
|
247
|
+
"features": args.features,
|
|
248
|
+
"usecols": args.usecols,
|
|
249
|
+
"threads": args.threads,
|
|
250
|
+
"wall_seconds": elapsed,
|
|
251
|
+
"cpu_seconds": cpu,
|
|
252
|
+
"peak_rss_mib": peak_mib,
|
|
253
|
+
"stages": timings.stages,
|
|
254
|
+
"rows": len(frame),
|
|
255
|
+
"columns": list(frame.columns),
|
|
256
|
+
"checksum": checksum(frame),
|
|
257
|
+
"versions": {
|
|
258
|
+
"gtfparse": __version__,
|
|
259
|
+
"pandas": pd.__version__,
|
|
260
|
+
"polars": pl.__version__ if pl is not None else None,
|
|
261
|
+
"pyarrow": pa.__version__,
|
|
262
|
+
"python": platform.python_version(),
|
|
263
|
+
},
|
|
264
|
+
"platform": platform.platform(),
|
|
265
|
+
"cpu_count": os.cpu_count(),
|
|
266
|
+
}
|
|
267
|
+
if args.verify:
|
|
268
|
+
reference = read_gtf(
|
|
269
|
+
str(args.path), result_type="pandas", features=args.features, usecols=args.usecols
|
|
270
|
+
)
|
|
271
|
+
actual = frame.to_pandas() if pl is not None and isinstance(frame, pl.DataFrame) else frame
|
|
272
|
+
pd.testing.assert_frame_equal(reference, actual, check_categorical=False)
|
|
273
|
+
assert checksum(reference) == output["checksum"]
|
|
274
|
+
output["verified"] = True
|
|
275
|
+
print(json.dumps(output, sort_keys=True))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
if __name__ == "__main__":
|
|
279
|
+
main()
|