gtfparse 3.2.0__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.
Files changed (58) hide show
  1. {gtfparse-3.2.0/gtfparse.egg-info → gtfparse-3.3.0}/PKG-INFO +1 -1
  2. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse/__init__.py +4 -1
  3. gtfparse-3.3.0/gtfparse/completeness.py +163 -0
  4. gtfparse-3.3.0/gtfparse/create_missing_features.py +221 -0
  5. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse/read_gtf.py +37 -6
  6. {gtfparse-3.2.0 → gtfparse-3.3.0/gtfparse.egg-info}/PKG-INFO +1 -1
  7. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse.egg-info/SOURCES.txt +2 -0
  8. gtfparse-3.3.0/tests/test_completeness.py +167 -0
  9. gtfparse-3.3.0/tests/test_create_missing_features.py +355 -0
  10. gtfparse-3.2.0/gtfparse/create_missing_features.py +0 -119
  11. gtfparse-3.2.0/tests/test_create_missing_features.py +0 -141
  12. {gtfparse-3.2.0 → gtfparse-3.3.0}/LICENSE +0 -0
  13. {gtfparse-3.2.0 → gtfparse-3.3.0}/MANIFEST.in +0 -0
  14. {gtfparse-3.2.0 → gtfparse-3.3.0}/README.md +0 -0
  15. {gtfparse-3.2.0 → gtfparse-3.3.0}/benchmarks/README.md +0 -0
  16. {gtfparse-3.2.0 → gtfparse-3.3.0}/benchmarks/compare_readers.py +0 -0
  17. {gtfparse-3.2.0 → gtfparse-3.3.0}/benchmarks/compare_releases.py +0 -0
  18. {gtfparse-3.2.0 → gtfparse-3.3.0}/benchmarks/optimization-results.json +0 -0
  19. {gtfparse-3.2.0 → gtfparse-3.3.0}/benchmarks/optimization.md +0 -0
  20. {gtfparse-3.2.0 → gtfparse-3.3.0}/benchmarks/results.json +0 -0
  21. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse/_polars.py +0 -0
  22. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse/_read_csv.py +0 -0
  23. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse/attribute_parsing.py +0 -0
  24. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse/columns.py +0 -0
  25. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse/parsing_error.py +0 -0
  26. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse/write_gtf.py +0 -0
  27. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse.egg-info/dependency_links.txt +0 -0
  28. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse.egg-info/requires.txt +0 -0
  29. {gtfparse-3.2.0 → gtfparse-3.3.0}/gtfparse.egg-info/top_level.txt +0 -0
  30. {gtfparse-3.2.0 → gtfparse-3.3.0}/lint.sh +0 -0
  31. {gtfparse-3.2.0 → gtfparse-3.3.0}/pyproject.toml +0 -0
  32. {gtfparse-3.2.0 → gtfparse-3.3.0}/requirements.txt +0 -0
  33. {gtfparse-3.2.0 → gtfparse-3.3.0}/setup.cfg +0 -0
  34. {gtfparse-3.2.0 → gtfparse-3.3.0}/test.sh +0 -0
  35. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/__init__.py +0 -0
  36. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/data/B16.stringtie.head.gtf +0 -0
  37. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/data/ensembl_grch37.head.gtf +0 -0
  38. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/data/ensembl_grch37.head.gtf.gz +0 -0
  39. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/data/gencode.head.gtf +0 -0
  40. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/data/gencode.real.head.gtf +0 -0
  41. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/data/refseq.ucsc.small.gtf +0 -0
  42. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/data.py +0 -0
  43. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_attribute_optimization.py +0 -0
  44. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_attribute_values.py +0 -0
  45. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_columns.py +0 -0
  46. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_ensembl_gtf.py +0 -0
  47. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_expand_attribute_column_false.py +0 -0
  48. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_expand_attributes.py +0 -0
  49. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_gencode_gtf.py +0 -0
  50. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_multiple_values_for_tag_attribute.py +0 -0
  51. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_parse_gtf_lines.py +0 -0
  52. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_polars_compatibility.py +0 -0
  53. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_polars_lazy_adapter.py +0 -0
  54. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_progress.py +0 -0
  55. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_read_stringtie_gtf.py +0 -0
  56. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_reader.py +0 -0
  57. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_refseq_gtf.py +0 -0
  58. {gtfparse-3.2.0 → gtfparse-3.3.0}/tests/test_write_gtf.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gtfparse
3
- Version: 3.2.0
3
+ Version: 3.3.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
@@ -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.2.0"
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)
@@ -21,6 +21,10 @@ from ._polars import require_polars
21
21
  from ._read_csv import read_fixed_columns
22
22
  from .attribute_parsing import ATTRIBUTE_PATTERN, expand_attribute_strings
23
23
  from .columns import REQUIRED_COLUMNS as REQUIRED_COLUMNS
24
+ from .completeness import (
25
+ DEFAULT_REQUIRED_CODING_FEATURES,
26
+ attach_transcript_completeness,
27
+ )
24
28
 
25
29
  logger = logging.getLogger(__name__)
26
30
 
@@ -363,6 +367,7 @@ def read_gtf(
363
367
  attribute_aliases=None,
364
368
  cast_version_columns=True,
365
369
  *,
370
+ flag_incomplete_transcripts=False,
366
371
  progress_callback=None,
367
372
  ):
368
373
  """
@@ -420,6 +425,15 @@ def read_gtf(
420
425
  nullable Int64 when present. Set to False to keep them as
421
426
  strings.
422
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
+
423
437
  progress_callback : callable, optional
424
438
  Called synchronously as ``callback(stage, completed, total)``. Counts
425
439
  are rows retained after feature filtering. Stages occur in order:
@@ -435,6 +449,8 @@ def read_gtf(
435
449
  raise ValueError("result_type must be one of 'polars', 'pandas', or 'dict'")
436
450
  if result_type == "polars":
437
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")
438
454
  if type(filepath_or_buffer) is str and not exists(filepath_or_buffer):
439
455
  raise ValueError("GTF file does not exist: %s" % filepath_or_buffer)
440
456
 
@@ -444,12 +460,16 @@ def read_gtf(
444
460
  # time before _apply_attribute_aliases can see it. The end-of-function
445
461
  # usecols filter still narrows the result down to the canonical name.
446
462
  parse_usecols = usecols
447
- if usecols is not None and attribute_aliases:
463
+ if usecols is not None:
448
464
  usecols_set = set(usecols)
449
- parse_usecols = set(usecols_set)
450
- for alias, canonical in attribute_aliases.items():
451
- if canonical in usecols_set:
452
- parse_usecols.add(alias)
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
453
473
 
454
474
  if expand_attribute_column:
455
475
  result_df = parse_gtf_and_expand_attributes(
@@ -520,9 +540,20 @@ def read_gtf(
520
540
  logger.info("Using column 'source' to replace missing 'transcript_biotype'")
521
541
  result_df["transcript_biotype"] = result_df["source"]
522
542
 
543
+ if flag_incomplete_transcripts:
544
+ result_df = attach_transcript_completeness(result_df)
545
+
523
546
  if usecols is not None:
524
547
  column_names = set(result_df.columns)
525
- valid_columns = [c for c in usecols if c in column_names]
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]
526
557
  result_df = result_df[valid_columns]
527
558
 
528
559
  if result_type == "pandas":
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gtfparse
3
- Version: 3.2.0
3
+ Version: 3.3.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
@@ -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