gtfparse 3.1.2__tar.gz → 3.3.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-3.1.2/gtfparse.egg-info → gtfparse-3.3.0}/PKG-INFO +1 -1
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse/__init__.py +4 -1
- gtfparse-3.3.0/gtfparse/completeness.py +163 -0
- gtfparse-3.3.0/gtfparse/create_missing_features.py +221 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse/read_gtf.py +89 -11
- {gtfparse-3.1.2 → gtfparse-3.3.0/gtfparse.egg-info}/PKG-INFO +1 -1
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse.egg-info/SOURCES.txt +3 -0
- gtfparse-3.3.0/tests/test_completeness.py +167 -0
- gtfparse-3.3.0/tests/test_create_missing_features.py +355 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_polars_compatibility.py +21 -3
- gtfparse-3.3.0/tests/test_polars_lazy_adapter.py +46 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_progress.py +21 -1
- gtfparse-3.1.2/gtfparse/create_missing_features.py +0 -119
- gtfparse-3.1.2/tests/test_create_missing_features.py +0 -141
- {gtfparse-3.1.2 → gtfparse-3.3.0}/LICENSE +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/MANIFEST.in +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/README.md +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/benchmarks/README.md +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/benchmarks/compare_readers.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/benchmarks/compare_releases.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/benchmarks/optimization-results.json +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/benchmarks/optimization.md +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/benchmarks/results.json +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse/_polars.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse/_read_csv.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse/attribute_parsing.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse/columns.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse/parsing_error.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse/write_gtf.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse.egg-info/dependency_links.txt +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse.egg-info/requires.txt +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/gtfparse.egg-info/top_level.txt +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/lint.sh +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/pyproject.toml +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/requirements.txt +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/setup.cfg +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/test.sh +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/__init__.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/data/B16.stringtie.head.gtf +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/data/ensembl_grch37.head.gtf +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/data/ensembl_grch37.head.gtf.gz +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/data/gencode.head.gtf +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/data/gencode.real.head.gtf +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/data/refseq.ucsc.small.gtf +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/data.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_attribute_optimization.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_attribute_values.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_columns.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_ensembl_gtf.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_expand_attribute_column_false.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_expand_attributes.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_gencode_gtf.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_multiple_values_for_tag_attribute.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_parse_gtf_lines.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_read_stringtie_gtf.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_reader.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_refseq_gtf.py +0 -0
- {gtfparse-3.1.2 → gtfparse-3.3.0}/tests/test_write_gtf.py +0 -0
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
# limitations under the License.
|
|
12
12
|
|
|
13
13
|
from .attribute_parsing import expand_attribute_strings
|
|
14
|
+
from .completeness import attach_transcript_completeness, transcript_completeness
|
|
14
15
|
from .create_missing_features import create_missing_features
|
|
15
16
|
from .parsing_error import ParsingError
|
|
16
17
|
from .read_gtf import (
|
|
@@ -24,7 +25,7 @@ from .read_gtf import (
|
|
|
24
25
|
)
|
|
25
26
|
from .write_gtf import write_gtf
|
|
26
27
|
|
|
27
|
-
__version__ = "3.
|
|
28
|
+
__version__ = "3.3.0"
|
|
28
29
|
|
|
29
30
|
__all__ = [
|
|
30
31
|
"GENCODE_BIOTYPE_ALIASES",
|
|
@@ -32,11 +33,13 @@ __all__ = [
|
|
|
32
33
|
"REQUIRED_COLUMNS",
|
|
33
34
|
"ParsingError",
|
|
34
35
|
"__version__",
|
|
36
|
+
"attach_transcript_completeness",
|
|
35
37
|
"create_missing_features",
|
|
36
38
|
"expand_attribute_strings",
|
|
37
39
|
"parse_gtf",
|
|
38
40
|
"parse_gtf_and_expand_attributes",
|
|
39
41
|
"parse_gtf_pandas",
|
|
40
42
|
"read_gtf",
|
|
43
|
+
"transcript_completeness",
|
|
41
44
|
"write_gtf",
|
|
42
45
|
]
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
2
|
+
# you may not use this file except in compliance with the License.
|
|
3
|
+
# You may obtain a copy of the License at
|
|
4
|
+
#
|
|
5
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
#
|
|
7
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
8
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
9
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
10
|
+
# See the License for the specific language governing permissions and
|
|
11
|
+
# limitations under the License.
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
DEFAULT_REQUIRED_CODING_FEATURES = ("start_codon", "stop_codon")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def transcript_completeness(
|
|
19
|
+
dataframe,
|
|
20
|
+
*,
|
|
21
|
+
required_features=DEFAULT_REQUIRED_CODING_FEATURES,
|
|
22
|
+
coding_feature="CDS",
|
|
23
|
+
transcript_id_column="transcript_id",
|
|
24
|
+
):
|
|
25
|
+
"""Compute per-transcript completeness of required coding features.
|
|
26
|
+
|
|
27
|
+
A transcript with one or more ``coding_feature`` rows (default ``"CDS"``)
|
|
28
|
+
is considered complete when every feature named in ``required_features``
|
|
29
|
+
(default ``("start_codon", "stop_codon")``) also appears for that
|
|
30
|
+
``transcript_id``. Non-coding transcripts (those without any
|
|
31
|
+
``coding_feature`` row) are marked ``transcript_complete = True``.
|
|
32
|
+
|
|
33
|
+
Parameters
|
|
34
|
+
----------
|
|
35
|
+
dataframe : pandas.DataFrame or polars.DataFrame
|
|
36
|
+
Parsed GTF table containing ``feature`` and ``transcript_id_column``.
|
|
37
|
+
|
|
38
|
+
required_features : sequence of str, optional
|
|
39
|
+
Feature names required whenever a transcript has ``coding_feature``
|
|
40
|
+
rows. Defaults to ``("start_codon", "stop_codon")``.
|
|
41
|
+
|
|
42
|
+
coding_feature : str, optional
|
|
43
|
+
Feature name that identifies coding transcripts. Defaults to ``"CDS"``.
|
|
44
|
+
|
|
45
|
+
transcript_id_column : str, optional
|
|
46
|
+
Column containing transcript identifiers. Defaults to
|
|
47
|
+
``"transcript_id"``.
|
|
48
|
+
|
|
49
|
+
Returns
|
|
50
|
+
-------
|
|
51
|
+
pandas.DataFrame
|
|
52
|
+
DataFrame indexed by non-empty ``transcript_id`` values with boolean
|
|
53
|
+
columns ``has_cds`` (or ``has_<coding_feature.lower()>``),
|
|
54
|
+
``has_<feature>`` for each feature in ``required_features``, and
|
|
55
|
+
``transcript_complete``.
|
|
56
|
+
"""
|
|
57
|
+
if hasattr(dataframe, "to_pandas"):
|
|
58
|
+
dataframe = dataframe.to_pandas()
|
|
59
|
+
|
|
60
|
+
if "feature" not in dataframe.columns:
|
|
61
|
+
raise ValueError("DataFrame must contain a 'feature' column")
|
|
62
|
+
|
|
63
|
+
required_features = tuple(required_features)
|
|
64
|
+
coding_col = f"has_{coding_feature.lower()}"
|
|
65
|
+
feature_cols = [(feat, f"has_{feat.lower()}") for feat in required_features]
|
|
66
|
+
output_columns = [coding_col, *(col for _, col in feature_cols), "transcript_complete"]
|
|
67
|
+
|
|
68
|
+
if transcript_id_column not in dataframe.columns or len(dataframe) == 0:
|
|
69
|
+
empty = pd.DataFrame(
|
|
70
|
+
{col: pd.Series(dtype=bool) for col in output_columns},
|
|
71
|
+
index=pd.Index([], name=transcript_id_column),
|
|
72
|
+
)
|
|
73
|
+
return empty
|
|
74
|
+
|
|
75
|
+
tids = dataframe[transcript_id_column]
|
|
76
|
+
valid_mask = tids.notna() & (tids != "")
|
|
77
|
+
if not valid_mask.any():
|
|
78
|
+
empty = pd.DataFrame(
|
|
79
|
+
{col: pd.Series(dtype=bool) for col in output_columns},
|
|
80
|
+
index=pd.Index([], name=transcript_id_column),
|
|
81
|
+
)
|
|
82
|
+
return empty
|
|
83
|
+
|
|
84
|
+
valid_tids = tids[valid_mask]
|
|
85
|
+
valid_features = dataframe.loc[valid_mask, "feature"]
|
|
86
|
+
unique_tids = pd.Index(valid_tids.unique(), name=transcript_id_column)
|
|
87
|
+
|
|
88
|
+
def _has_feature(feature_name):
|
|
89
|
+
matching = set(valid_tids[valid_features == feature_name].unique())
|
|
90
|
+
return unique_tids.isin(matching)
|
|
91
|
+
|
|
92
|
+
data = {coding_col: _has_feature(coding_feature)}
|
|
93
|
+
all_required_present = pd.Series(True, index=unique_tids, dtype=bool)
|
|
94
|
+
for feat, col_name in feature_cols:
|
|
95
|
+
present = _has_feature(feat)
|
|
96
|
+
data[col_name] = present
|
|
97
|
+
all_required_present &= present
|
|
98
|
+
|
|
99
|
+
data["transcript_complete"] = (~data[coding_col]) | all_required_present.to_numpy()
|
|
100
|
+
return pd.DataFrame(data, index=unique_tids)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def attach_transcript_completeness(
|
|
104
|
+
dataframe,
|
|
105
|
+
*,
|
|
106
|
+
required_features=DEFAULT_REQUIRED_CODING_FEATURES,
|
|
107
|
+
coding_feature="CDS",
|
|
108
|
+
transcript_id_column="transcript_id",
|
|
109
|
+
):
|
|
110
|
+
"""Attach per-transcript feature completeness columns to a GTF DataFrame.
|
|
111
|
+
|
|
112
|
+
Adds nullable boolean columns ``has_<feature>`` for each feature in
|
|
113
|
+
``required_features`` (default ``has_start_codon`` and ``has_stop_codon``)
|
|
114
|
+
plus ``transcript_complete``. Rows without a ``transcript_id`` (such as
|
|
115
|
+
``gene`` rows) receive ``pd.NA``.
|
|
116
|
+
|
|
117
|
+
Parameters
|
|
118
|
+
----------
|
|
119
|
+
dataframe : pandas.DataFrame or polars.DataFrame
|
|
120
|
+
Parsed GTF table containing ``feature`` and ``transcript_id_column``.
|
|
121
|
+
|
|
122
|
+
required_features : sequence of str, optional
|
|
123
|
+
Feature names required whenever a transcript has ``coding_feature``
|
|
124
|
+
rows. Defaults to ``("start_codon", "stop_codon")``.
|
|
125
|
+
|
|
126
|
+
coding_feature : str, optional
|
|
127
|
+
Feature name that identifies coding transcripts. Defaults to ``"CDS"``.
|
|
128
|
+
|
|
129
|
+
transcript_id_column : str, optional
|
|
130
|
+
Column containing transcript identifiers. Defaults to
|
|
131
|
+
``"transcript_id"``.
|
|
132
|
+
|
|
133
|
+
Returns
|
|
134
|
+
-------
|
|
135
|
+
pandas.DataFrame
|
|
136
|
+
Copy of ``dataframe`` with the completeness columns attached.
|
|
137
|
+
"""
|
|
138
|
+
if hasattr(dataframe, "to_pandas"):
|
|
139
|
+
dataframe = dataframe.to_pandas()
|
|
140
|
+
|
|
141
|
+
required_features = tuple(required_features)
|
|
142
|
+
summary = transcript_completeness(
|
|
143
|
+
dataframe,
|
|
144
|
+
required_features=required_features,
|
|
145
|
+
coding_feature=coding_feature,
|
|
146
|
+
transcript_id_column=transcript_id_column,
|
|
147
|
+
)
|
|
148
|
+
attach_columns = [*(f"has_{feat.lower()}" for feat in required_features), "transcript_complete"]
|
|
149
|
+
|
|
150
|
+
out = dataframe.copy()
|
|
151
|
+
if transcript_id_column not in out.columns:
|
|
152
|
+
for col_name in attach_columns:
|
|
153
|
+
out[col_name] = pd.Series(pd.NA, index=out.index, dtype="boolean")
|
|
154
|
+
return out
|
|
155
|
+
|
|
156
|
+
tids = out[transcript_id_column]
|
|
157
|
+
valid_mask = tids.notna() & (tids != "")
|
|
158
|
+
for col_name in attach_columns:
|
|
159
|
+
series = pd.Series(pd.NA, index=out.index, dtype="boolean")
|
|
160
|
+
if valid_mask.any():
|
|
161
|
+
series.loc[valid_mask] = tids.loc[valid_mask].map(summary[col_name]).astype("boolean")
|
|
162
|
+
out[col_name] = series
|
|
163
|
+
return out
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
2
|
+
# you may not use this file except in compliance with the License.
|
|
3
|
+
# You may obtain a copy of the License at
|
|
4
|
+
#
|
|
5
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
#
|
|
7
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
8
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
9
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
10
|
+
# See the License for the specific language governing permissions and
|
|
11
|
+
# limitations under the License.
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
from collections import OrderedDict
|
|
15
|
+
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
VALID_STRICT_MODES = ("best_effort", "warn", "raise")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _non_empty_unique(series):
|
|
25
|
+
"""Return unique non-null, non-empty values from a pandas Series."""
|
|
26
|
+
mask = series.notna() & (series != "")
|
|
27
|
+
return series[mask].unique()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def create_missing_features(
|
|
31
|
+
dataframe,
|
|
32
|
+
unique_keys={},
|
|
33
|
+
extra_columns={},
|
|
34
|
+
missing_value=None,
|
|
35
|
+
*,
|
|
36
|
+
strict="best_effort",
|
|
37
|
+
required_attributes_per_feature=None,
|
|
38
|
+
):
|
|
39
|
+
"""
|
|
40
|
+
Helper function used to construct a missing feature such as 'transcript'
|
|
41
|
+
or 'gene'. Some GTF files only have 'exon' and 'CDS' entries, but have
|
|
42
|
+
transcript_id and gene_id annotations which allow us to construct those
|
|
43
|
+
missing features.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
dataframe : pandas.DataFrame
|
|
48
|
+
Should contain at least the core GTF columns, such as "seqname",
|
|
49
|
+
"start", and "end"
|
|
50
|
+
|
|
51
|
+
unique_keys : dict
|
|
52
|
+
Mapping from feature names to the name of the column which should
|
|
53
|
+
act as a unique key for that feature. Example: {"gene": "gene_id"}
|
|
54
|
+
|
|
55
|
+
extra_columns : dict
|
|
56
|
+
By default the constructed feature row will include only the 8
|
|
57
|
+
core columns and its unique key. Any other columns that should
|
|
58
|
+
be included should be associated with the feature name in this
|
|
59
|
+
dict.
|
|
60
|
+
|
|
61
|
+
missing_value : any
|
|
62
|
+
Which value to fill in for columns that we don't infer values for.
|
|
63
|
+
|
|
64
|
+
strict : {"best_effort", "warn", "raise"}, optional
|
|
65
|
+
Policy when a group lacks required attributes or has inconsistent
|
|
66
|
+
parent metadata (conflicting ``seqname``/``strand`` or missing/conflicting
|
|
67
|
+
``extra_columns`` values):
|
|
68
|
+
|
|
69
|
+
- ``"best_effort"`` (default): synthesize rows with available metadata,
|
|
70
|
+
filling ambiguous or missing extra columns with ``missing_value``.
|
|
71
|
+
Groups that fail ``required_attributes_per_feature`` are skipped.
|
|
72
|
+
- ``"warn"``: log a warning and skip the synthesized row.
|
|
73
|
+
- ``"raise"``: raise ``ValueError``.
|
|
74
|
+
|
|
75
|
+
required_attributes_per_feature : dict of str -> iterable of str, optional
|
|
76
|
+
Mapping from feature name to attribute columns that must have at least
|
|
77
|
+
one non-null, non-empty value among a group's child rows in order to
|
|
78
|
+
synthesize that parent row. Example: ``{"transcript": {"exon_id"}}``.
|
|
79
|
+
|
|
80
|
+
Returns
|
|
81
|
+
-------
|
|
82
|
+
pandas.DataFrame
|
|
83
|
+
Original rows (converted to pandas if necessary) together with the
|
|
84
|
+
extra rows created for missing features.
|
|
85
|
+
"""
|
|
86
|
+
if strict not in VALID_STRICT_MODES:
|
|
87
|
+
raise ValueError("strict must be one of %r, got %r" % (VALID_STRICT_MODES, strict))
|
|
88
|
+
|
|
89
|
+
if hasattr(dataframe, "to_pandas"):
|
|
90
|
+
dataframe = dataframe.to_pandas()
|
|
91
|
+
|
|
92
|
+
extra_dataframes = []
|
|
93
|
+
|
|
94
|
+
existing_features = set(dataframe["feature"])
|
|
95
|
+
existing_columns = set(dataframe.columns)
|
|
96
|
+
required_map = required_attributes_per_feature or {}
|
|
97
|
+
|
|
98
|
+
for feature_name, groupby_key in unique_keys.items():
|
|
99
|
+
if feature_name in existing_features:
|
|
100
|
+
logger.info("Feature '%s' already exists in GTF data", feature_name)
|
|
101
|
+
continue
|
|
102
|
+
if groupby_key not in existing_columns:
|
|
103
|
+
msg = "Cannot synthesize feature '%s': key column '%s' does not exist in GTF" % (
|
|
104
|
+
feature_name,
|
|
105
|
+
groupby_key,
|
|
106
|
+
)
|
|
107
|
+
if strict == "warn":
|
|
108
|
+
logger.warning(msg)
|
|
109
|
+
continue
|
|
110
|
+
raise ValueError(msg)
|
|
111
|
+
|
|
112
|
+
logger.info("Creating rows for missing feature '%s'", feature_name)
|
|
113
|
+
|
|
114
|
+
# User specifies which non-required columns we should try to infer
|
|
115
|
+
# values for
|
|
116
|
+
feature_columns = list(extra_columns.get(feature_name, []))
|
|
117
|
+
missing_extra = [c for c in feature_columns if c not in existing_columns]
|
|
118
|
+
if missing_extra:
|
|
119
|
+
msg = "Column '%s' does not exist in GTF, columns = %s" % (
|
|
120
|
+
missing_extra[0],
|
|
121
|
+
existing_columns,
|
|
122
|
+
)
|
|
123
|
+
if strict == "warn":
|
|
124
|
+
logger.warning("Skipping synthesized '%s' rows: %s", feature_name, msg)
|
|
125
|
+
continue
|
|
126
|
+
raise ValueError(msg)
|
|
127
|
+
|
|
128
|
+
required_attrs = sorted(required_map.get(feature_name, ()))
|
|
129
|
+
missing_required_cols = [c for c in required_attrs if c not in existing_columns]
|
|
130
|
+
if missing_required_cols:
|
|
131
|
+
msg = (
|
|
132
|
+
"Cannot synthesize feature '%s': required attribute column(s) %s "
|
|
133
|
+
"do not exist in GTF" % (feature_name, missing_required_cols)
|
|
134
|
+
)
|
|
135
|
+
if strict == "raise":
|
|
136
|
+
raise ValueError(msg)
|
|
137
|
+
if strict == "warn":
|
|
138
|
+
logger.warning(msg)
|
|
139
|
+
continue
|
|
140
|
+
|
|
141
|
+
# don't include rows where the groupby key was missing; the mask keeps
|
|
142
|
+
# the frame's own index, so filtered or re-sorted frames work (#104)
|
|
143
|
+
keys = dataframe[groupby_key]
|
|
144
|
+
has_key = keys.notna() & (keys != "")
|
|
145
|
+
row_groups = dataframe[has_key].groupby(groupby_key)
|
|
146
|
+
|
|
147
|
+
feature_values = OrderedDict([(column_name, []) for column_name in dataframe])
|
|
148
|
+
|
|
149
|
+
for feature_id, group in row_groups:
|
|
150
|
+
problems = []
|
|
151
|
+
|
|
152
|
+
if required_attrs:
|
|
153
|
+
missing_in_group = [
|
|
154
|
+
attr for attr in required_attrs if len(_non_empty_unique(group[attr])) == 0
|
|
155
|
+
]
|
|
156
|
+
if missing_in_group:
|
|
157
|
+
problems.append("missing required attribute(s) %s" % (missing_in_group,))
|
|
158
|
+
|
|
159
|
+
if strict != "best_effort":
|
|
160
|
+
unique_seqnames = _non_empty_unique(group["seqname"])
|
|
161
|
+
if len(unique_seqnames) != 1:
|
|
162
|
+
problems.append("inconsistent seqname values %r" % (list(unique_seqnames),))
|
|
163
|
+
unique_strands = _non_empty_unique(group["strand"])
|
|
164
|
+
if len(unique_strands) != 1:
|
|
165
|
+
problems.append("inconsistent strand values %r" % (list(unique_strands),))
|
|
166
|
+
|
|
167
|
+
inferred_extra = {}
|
|
168
|
+
for column_name in feature_columns:
|
|
169
|
+
if strict == "best_effort":
|
|
170
|
+
unique_values = group[column_name].dropna().unique()
|
|
171
|
+
else:
|
|
172
|
+
unique_values = _non_empty_unique(group[column_name])
|
|
173
|
+
if len(unique_values) == 1:
|
|
174
|
+
inferred_extra[column_name] = unique_values[0]
|
|
175
|
+
elif strict != "best_effort":
|
|
176
|
+
if len(unique_values) == 0:
|
|
177
|
+
problems.append("missing extra column '%s'" % (column_name,))
|
|
178
|
+
else:
|
|
179
|
+
problems.append(
|
|
180
|
+
"ambiguous extra column '%s' values %r"
|
|
181
|
+
% (column_name, list(unique_values))
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
if problems:
|
|
185
|
+
msg = "Cannot faithfully synthesize %s '%s': %s" % (
|
|
186
|
+
feature_name,
|
|
187
|
+
feature_id,
|
|
188
|
+
"; ".join(problems),
|
|
189
|
+
)
|
|
190
|
+
if strict == "raise":
|
|
191
|
+
raise ValueError(msg)
|
|
192
|
+
if strict == "warn":
|
|
193
|
+
logger.warning(msg)
|
|
194
|
+
continue
|
|
195
|
+
|
|
196
|
+
# fill in the required columns by assuming that this feature
|
|
197
|
+
# is the union of all intervals of other features that were
|
|
198
|
+
# tagged with its unique ID (e.g. union of exons which had a
|
|
199
|
+
# particular gene_id).
|
|
200
|
+
row = dict.fromkeys(dataframe, missing_value)
|
|
201
|
+
row["feature"] = feature_name
|
|
202
|
+
row[groupby_key] = feature_id
|
|
203
|
+
# set the source to 'gtfparse' to indicate that we made this
|
|
204
|
+
# entry up from other data
|
|
205
|
+
row["source"] = "gtfparse"
|
|
206
|
+
row["start"] = group["start"].min()
|
|
207
|
+
row["end"] = group["end"].max()
|
|
208
|
+
# assume that seqname and strand are the same for all other
|
|
209
|
+
# entries in the GTF which shared this unique ID
|
|
210
|
+
row["seqname"] = group["seqname"].iat[0]
|
|
211
|
+
row["strand"] = group["strand"].iat[0]
|
|
212
|
+
row.update(inferred_extra)
|
|
213
|
+
|
|
214
|
+
for column_name in dataframe:
|
|
215
|
+
feature_values[column_name].append(row[column_name])
|
|
216
|
+
|
|
217
|
+
if feature_values[groupby_key]:
|
|
218
|
+
extra_dataframes.append(pd.DataFrame(feature_values))
|
|
219
|
+
if not extra_dataframes:
|
|
220
|
+
return dataframe.copy()
|
|
221
|
+
return pd.concat([dataframe, *extra_dataframes], ignore_index=True)
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
# limitations under the License.
|
|
12
12
|
|
|
13
13
|
import logging
|
|
14
|
+
import warnings
|
|
14
15
|
from os.path import exists
|
|
15
16
|
|
|
16
17
|
import pandas as pd
|
|
@@ -20,6 +21,10 @@ from ._polars import require_polars
|
|
|
20
21
|
from ._read_csv import read_fixed_columns
|
|
21
22
|
from .attribute_parsing import ATTRIBUTE_PATTERN, expand_attribute_strings
|
|
22
23
|
from .columns import REQUIRED_COLUMNS as REQUIRED_COLUMNS
|
|
24
|
+
from .completeness import (
|
|
25
|
+
DEFAULT_REQUIRED_CODING_FEATURES,
|
|
26
|
+
attach_transcript_completeness,
|
|
27
|
+
)
|
|
23
28
|
|
|
24
29
|
logger = logging.getLogger(__name__)
|
|
25
30
|
|
|
@@ -48,12 +53,42 @@ INTEGER_VERSION_COLUMNS = (
|
|
|
48
53
|
def parse_with_polars_lazy(
|
|
49
54
|
filepath_or_buffer, split_attributes=True, features=None, fix_quotes_columns=None
|
|
50
55
|
):
|
|
51
|
-
"""
|
|
52
|
-
|
|
53
|
-
|
|
56
|
+
"""Deprecated: read eagerly and return an optional Polars LazyFrame.
|
|
57
|
+
|
|
58
|
+
Despite its name, the whole file is read before this function returns,
|
|
59
|
+
so nothing is scanned lazily. The exact equivalent is
|
|
60
|
+
``polars.from_pandas(parse_gtf(...)).lazy()``, which keeps the unexpanded
|
|
61
|
+
``attribute`` and ``attribute_split`` columns this function returns. For
|
|
62
|
+
attributes expanded into columns (with read_gtf's version-column casts),
|
|
63
|
+
use ``read_gtf(..., result_type="polars").lazy()`` instead.
|
|
54
64
|
Install ``gtfparse[polars]`` to use this compatibility adapter.
|
|
65
|
+
|
|
66
|
+
Deprecated since 3.2.0; will be removed in gtfparse 4.0.
|
|
67
|
+
|
|
68
|
+
Parameters
|
|
69
|
+
----------
|
|
70
|
+
filepath_or_buffer, split_attributes, features, fix_quotes_columns
|
|
71
|
+
Passed to parse_gtf unchanged.
|
|
72
|
+
|
|
73
|
+
Returns
|
|
74
|
+
-------
|
|
75
|
+
polars.LazyFrame
|
|
76
|
+
A lazy view of the frame parse_gtf returns, already held in memory.
|
|
77
|
+
|
|
78
|
+
Warns
|
|
79
|
+
-----
|
|
80
|
+
DeprecationWarning
|
|
81
|
+
On every call.
|
|
55
82
|
"""
|
|
56
83
|
polars = require_polars()
|
|
84
|
+
warnings.warn(
|
|
85
|
+
"parse_with_polars_lazy is deprecated and will be removed in gtfparse 4.0. "
|
|
86
|
+
"It reads the whole file eagerly; the exact equivalent is "
|
|
87
|
+
"polars.from_pandas(parse_gtf(...)).lazy(). For expanded attribute "
|
|
88
|
+
'columns use read_gtf(..., result_type="polars").lazy().',
|
|
89
|
+
DeprecationWarning,
|
|
90
|
+
stacklevel=2,
|
|
91
|
+
)
|
|
57
92
|
return polars.from_pandas(
|
|
58
93
|
parse_gtf(filepath_or_buffer, split_attributes, features, fix_quotes_columns)
|
|
59
94
|
).lazy()
|
|
@@ -121,10 +156,14 @@ def parse_gtf(
|
|
|
121
156
|
|
|
122
157
|
|
|
123
158
|
def parse_gtf_pandas(*args, **kwargs):
|
|
124
|
-
"""
|
|
159
|
+
"""Deprecated: like parse_gtf, also reporting a ``convert`` progress stage.
|
|
125
160
|
|
|
126
161
|
Kept for compatibility from when parse_gtf returned Polars; parse_gtf now
|
|
127
|
-
returns pandas itself, so the conversion stage does no work.
|
|
162
|
+
returns pandas itself, so the conversion stage does no work. Use
|
|
163
|
+
parse_gtf instead. The ``convert`` progress events are still emitted
|
|
164
|
+
while this function remains.
|
|
165
|
+
|
|
166
|
+
Deprecated since 3.2.0; will be removed in gtfparse 4.0.
|
|
128
167
|
|
|
129
168
|
Parameters
|
|
130
169
|
----------
|
|
@@ -135,7 +174,19 @@ def parse_gtf_pandas(*args, **kwargs):
|
|
|
135
174
|
-------
|
|
136
175
|
pandas.DataFrame
|
|
137
176
|
The same frame parse_gtf returns.
|
|
177
|
+
|
|
178
|
+
Warns
|
|
179
|
+
-----
|
|
180
|
+
DeprecationWarning
|
|
181
|
+
On every call.
|
|
138
182
|
"""
|
|
183
|
+
warnings.warn(
|
|
184
|
+
"parse_gtf_pandas is deprecated and will be removed in gtfparse 4.0. "
|
|
185
|
+
"Use parse_gtf, which returns the same pandas DataFrame but does not "
|
|
186
|
+
"emit the no-op 'convert' progress events.",
|
|
187
|
+
DeprecationWarning,
|
|
188
|
+
stacklevel=2,
|
|
189
|
+
)
|
|
139
190
|
df = parse_gtf(*args, **kwargs)
|
|
140
191
|
progress_callback = kwargs.get("progress_callback")
|
|
141
192
|
if progress_callback is not None:
|
|
@@ -316,6 +367,7 @@ def read_gtf(
|
|
|
316
367
|
attribute_aliases=None,
|
|
317
368
|
cast_version_columns=True,
|
|
318
369
|
*,
|
|
370
|
+
flag_incomplete_transcripts=False,
|
|
319
371
|
progress_callback=None,
|
|
320
372
|
):
|
|
321
373
|
"""
|
|
@@ -373,6 +425,15 @@ def read_gtf(
|
|
|
373
425
|
nullable Int64 when present. Set to False to keep them as
|
|
374
426
|
strings.
|
|
375
427
|
|
|
428
|
+
flag_incomplete_transcripts : bool, optional
|
|
429
|
+
When True, aggregate over rows sharing ``transcript_id`` and attach
|
|
430
|
+
nullable boolean columns ``has_start_codon``, ``has_stop_codon``, and
|
|
431
|
+
``transcript_complete``. A transcript with ``CDS`` rows is complete
|
|
432
|
+
when both ``start_codon`` and ``stop_codon`` rows are present;
|
|
433
|
+
non-coding transcripts (without ``CDS``) are marked complete; rows
|
|
434
|
+
without a ``transcript_id`` receive ``pd.NA``. Requires
|
|
435
|
+
``expand_attribute_column=True``. Defaults to False.
|
|
436
|
+
|
|
376
437
|
progress_callback : callable, optional
|
|
377
438
|
Called synchronously as ``callback(stage, completed, total)``. Counts
|
|
378
439
|
are rows retained after feature filtering. Stages occur in order:
|
|
@@ -388,6 +449,8 @@ def read_gtf(
|
|
|
388
449
|
raise ValueError("result_type must be one of 'polars', 'pandas', or 'dict'")
|
|
389
450
|
if result_type == "polars":
|
|
390
451
|
require_polars()
|
|
452
|
+
if flag_incomplete_transcripts and not expand_attribute_column:
|
|
453
|
+
raise ValueError("flag_incomplete_transcripts=True requires expand_attribute_column=True")
|
|
391
454
|
if type(filepath_or_buffer) is str and not exists(filepath_or_buffer):
|
|
392
455
|
raise ValueError("GTF file does not exist: %s" % filepath_or_buffer)
|
|
393
456
|
|
|
@@ -397,12 +460,16 @@ def read_gtf(
|
|
|
397
460
|
# time before _apply_attribute_aliases can see it. The end-of-function
|
|
398
461
|
# usecols filter still narrows the result down to the canonical name.
|
|
399
462
|
parse_usecols = usecols
|
|
400
|
-
if usecols is not None
|
|
463
|
+
if usecols is not None:
|
|
401
464
|
usecols_set = set(usecols)
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
465
|
+
expanded_usecols = set(usecols_set)
|
|
466
|
+
if attribute_aliases:
|
|
467
|
+
for alias, canonical in attribute_aliases.items():
|
|
468
|
+
if canonical in usecols_set:
|
|
469
|
+
expanded_usecols.add(alias)
|
|
470
|
+
if flag_incomplete_transcripts:
|
|
471
|
+
expanded_usecols.update({"feature", "transcript_id"})
|
|
472
|
+
parse_usecols = expanded_usecols if expanded_usecols != usecols_set else usecols
|
|
406
473
|
|
|
407
474
|
if expand_attribute_column:
|
|
408
475
|
result_df = parse_gtf_and_expand_attributes(
|
|
@@ -473,9 +540,20 @@ def read_gtf(
|
|
|
473
540
|
logger.info("Using column 'source' to replace missing 'transcript_biotype'")
|
|
474
541
|
result_df["transcript_biotype"] = result_df["source"]
|
|
475
542
|
|
|
543
|
+
if flag_incomplete_transcripts:
|
|
544
|
+
result_df = attach_transcript_completeness(result_df)
|
|
545
|
+
|
|
476
546
|
if usecols is not None:
|
|
477
547
|
column_names = set(result_df.columns)
|
|
478
|
-
|
|
548
|
+
requested = list(usecols)
|
|
549
|
+
if flag_incomplete_transcripts:
|
|
550
|
+
for col in (
|
|
551
|
+
*(f"has_{feat.lower()}" for feat in DEFAULT_REQUIRED_CODING_FEATURES),
|
|
552
|
+
"transcript_complete",
|
|
553
|
+
):
|
|
554
|
+
if col not in requested:
|
|
555
|
+
requested.append(col)
|
|
556
|
+
valid_columns = [c for c in requested if c in column_names]
|
|
479
557
|
result_df = result_df[valid_columns]
|
|
480
558
|
|
|
481
559
|
if result_type == "pandas":
|
|
@@ -16,6 +16,7 @@ gtfparse/_polars.py
|
|
|
16
16
|
gtfparse/_read_csv.py
|
|
17
17
|
gtfparse/attribute_parsing.py
|
|
18
18
|
gtfparse/columns.py
|
|
19
|
+
gtfparse/completeness.py
|
|
19
20
|
gtfparse/create_missing_features.py
|
|
20
21
|
gtfparse/parsing_error.py
|
|
21
22
|
gtfparse/read_gtf.py
|
|
@@ -30,6 +31,7 @@ tests/data.py
|
|
|
30
31
|
tests/test_attribute_optimization.py
|
|
31
32
|
tests/test_attribute_values.py
|
|
32
33
|
tests/test_columns.py
|
|
34
|
+
tests/test_completeness.py
|
|
33
35
|
tests/test_create_missing_features.py
|
|
34
36
|
tests/test_ensembl_gtf.py
|
|
35
37
|
tests/test_expand_attribute_column_false.py
|
|
@@ -38,6 +40,7 @@ tests/test_gencode_gtf.py
|
|
|
38
40
|
tests/test_multiple_values_for_tag_attribute.py
|
|
39
41
|
tests/test_parse_gtf_lines.py
|
|
40
42
|
tests/test_polars_compatibility.py
|
|
43
|
+
tests/test_polars_lazy_adapter.py
|
|
41
44
|
tests/test_progress.py
|
|
42
45
|
tests/test_read_stringtie_gtf.py
|
|
43
46
|
tests/test_reader.py
|