gtfparse 2.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1,37 @@
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
+ from .attribute_parsing import expand_attribute_strings
14
+ from .create_missing_features import create_missing_features
15
+ from .parsing_error import ParsingError
16
+ from .read_gtf import (
17
+ read_gtf,
18
+ parse_gtf,
19
+ parse_gtf_pandas,
20
+ parse_gtf_and_expand_attributes,
21
+ REQUIRED_COLUMNS,
22
+ )
23
+
24
+ __version__ = "2.1.0"
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "expand_attribute_strings",
29
+ "create_missing_features",
30
+
31
+ "parse_gtf_and_expand_attributes",
32
+ "REQUIRED_COLUMNS",
33
+ "ParsingError",
34
+ "read_gtf",
35
+ "parse_gtf",
36
+ "parse_gtf_pandas",
37
+ ]
@@ -0,0 +1,116 @@
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
+ from sys import intern
16
+
17
+ logging.basicConfig(level=logging.INFO)
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+
22
+ def expand_attribute_strings(
23
+ attribute_strings,
24
+ quote_char="'",
25
+ missing_value="",
26
+ usecols=None):
27
+ """
28
+ The last column of GTF has a variable number of key value pairs
29
+ of the format: "key1 value1; key2 value2;"
30
+ Parse these into a dictionary mapping each key onto a list of values,
31
+ where the value is None for any row where the key was missing.
32
+
33
+ Parameters
34
+ ----------
35
+ attribute_strings : list of str
36
+
37
+ quote_char : str
38
+ Quote character to remove from values
39
+
40
+ missing_value : any
41
+ If an attribute is missing from a row, give it this value.
42
+
43
+ usecols : list of str or None
44
+ If not None, then only expand columns included in this set,
45
+ otherwise use all columns.
46
+
47
+ Returns OrderedDict of column->value list mappings, in the order they
48
+ appeared in the attribute strings.
49
+ """
50
+ n = len(attribute_strings)
51
+
52
+ extra_columns = {}
53
+ column_order = []
54
+
55
+ #
56
+ # SOME NOTES ABOUT THE BIZARRE STRING INTERNING GOING ON BELOW
57
+ #
58
+ # While parsing millions of repeated strings (e.g. "gene_id" and "TP53"),
59
+ # we can save a lot of memory by making sure there's only one string
60
+ # object per unique string. The canonical way to do this is using
61
+ # the 'intern' function. One problem is that Py2 won't let you intern
62
+ # unicode objects, so to get around this we call intern(str(...)).
63
+ #
64
+ # It also turns out to be faster to check interned strings ourselves
65
+ # using a local dictionary, hence the two dictionaries below
66
+ # and pair of try/except blocks in the loop.
67
+ column_interned_strings = {}
68
+
69
+ for (i, kv_strings) in enumerate(attribute_strings):
70
+ if type(kv_strings) is str:
71
+ kv_strings = kv_strings.split(";")
72
+ for kv in kv_strings:
73
+ # We're slicing the first two elements out of split() because
74
+ # Ensembl release 79 added values like:
75
+ # transcript_support_level "1 (assigned to previous version 5)";
76
+ # ...which gets mangled by splitting on spaces.
77
+ parts = kv.strip().split(" ", 2)[:2]
78
+
79
+ if len(parts) != 2:
80
+ continue
81
+
82
+ column_name, value = parts
83
+
84
+ try:
85
+ column_name = column_interned_strings[column_name]
86
+ except KeyError:
87
+ column_name = intern(str(column_name))
88
+ column_interned_strings[column_name] = column_name
89
+
90
+ if usecols is not None and column_name not in usecols:
91
+ continue
92
+
93
+ if value[0] == quote_char:
94
+ value = value.replace(quote_char, "")
95
+
96
+ try:
97
+ column = extra_columns[column_name]
98
+ # if an attribute is used repeatedly then
99
+ # keep track of all its values in a list
100
+ old_value = column[i]
101
+ if old_value is missing_value:
102
+ column[i] = value
103
+ else:
104
+ column[i] = "%s,%s" % (old_value, value)
105
+ except KeyError:
106
+ column = [missing_value] * n
107
+ column[i] = value
108
+ extra_columns[column_name] = column
109
+ column_order.append(column_name)
110
+
111
+
112
+
113
+ logging.info("Extracted GTF attributes: %s" % column_order)
114
+ return OrderedDict(
115
+ (column_name, extra_columns[column_name])
116
+ for column_name in column_order)
@@ -0,0 +1,118 @@
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
+ logging.basicConfig(level=logging.INFO)
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def create_missing_features(
23
+ dataframe,
24
+ unique_keys={},
25
+ extra_columns={},
26
+ missing_value=None):
27
+ """
28
+ Helper function used to construct a missing feature such as 'transcript'
29
+ or 'gene'. Some GTF files only have 'exon' and 'CDS' entries, but have
30
+ transcript_id and gene_id annotations which allow us to construct those
31
+ missing features.
32
+
33
+ Parameters
34
+ ----------
35
+ dataframe : pandas.DataFrame
36
+ Should contain at least the core GTF columns, such as "seqname",
37
+ "start", and "end"
38
+
39
+ unique_keys : dict
40
+ Mapping from feature names to the name of the column which should
41
+ act as a unique key for that feature. Example: {"gene": "gene_id"}
42
+
43
+ extra_columns : dict
44
+ By default the constructed feature row will include only the 8
45
+ core columns and its unique key. Any other columns that should
46
+ be included should be associated with the feature name in this
47
+ dict.
48
+
49
+ missing_value : any
50
+ Which value to fill in for columns that we don't infer values for.
51
+
52
+ Returns original dataframe along with all extra rows created for missing
53
+ features.
54
+ """
55
+ extra_dataframes = []
56
+
57
+ existing_features = set(dataframe["feature"])
58
+ existing_columns = set(dataframe.columns)
59
+
60
+ for (feature_name, groupby_key) in unique_keys.items():
61
+ if feature_name in existing_features:
62
+ logging.info(
63
+ "Feature '%s' already exists in GTF data" % feature_name)
64
+ continue
65
+ logging.info("Creating rows for missing feature '%s'" % feature_name)
66
+
67
+ # don't include rows where the groupby key was missing
68
+ empty_key_values = dataframe[groupby_key].map(
69
+ lambda x: x == "" or x is None)
70
+ row_groups = dataframe[~empty_key_values].groupby(groupby_key)
71
+
72
+ # Each group corresponds to a unique feature entry for which the
73
+ # other columns may or may not be uniquely defined. Start off by
74
+ # assuming the values for every column are missing and fill them in
75
+ # where possible.
76
+ feature_values = OrderedDict([
77
+ (column_name, [missing_value] * row_groups.ngroups)
78
+ for column_name in dataframe.keys()
79
+ ])
80
+
81
+ # User specifies which non-required columns should we try to infer
82
+ # values for
83
+ feature_columns = list(extra_columns.get(feature_name, []))
84
+
85
+ for i, (feature_id, group) in enumerate(row_groups):
86
+ # fill in the required columns by assuming that this feature
87
+ # is the union of all intervals of other features that were
88
+ # tagged with its unique ID (e.g. union of exons which had a
89
+ # particular gene_id).
90
+ feature_values["feature"][i] = feature_name
91
+ feature_values[groupby_key][i] = feature_id
92
+ # set the source to 'gtfparse' to indicate that we made this
93
+ # entry up from other data
94
+ feature_values["source"][i] = "gtfparse"
95
+ feature_values["start"][i] = group["start"].min()
96
+ feature_values["end"][i] = group["end"].max()
97
+
98
+ # assume that seqname and strand are the same for all other
99
+ # entries in the GTF which shared this unique ID
100
+ feature_values["seqname"][i] = group["seqname"].iat[0]
101
+ feature_values["strand"][i] = group["strand"].iat[0]
102
+
103
+ # there's probably no rigorous way to set the values of
104
+ # 'score' or 'frame' columns so leave them empty
105
+ for column_name in feature_columns:
106
+ if column_name not in existing_columns:
107
+ raise ValueError(
108
+ "Column '%s' does not exist in GTF, columns = %s" % (
109
+ column_name, existing_columns))
110
+
111
+ # expect that all entries related to a reconstructed feature
112
+ # are related and are thus within the same interval of
113
+ # positions on the same chromosome
114
+ unique_values = group[column_name].dropna().unique()
115
+ if len(unique_values) == 1:
116
+ feature_values[column_name][i] = unique_values[0]
117
+ extra_dataframes.append(pd.DataFrame(feature_values))
118
+ return pd.concat([dataframe] + extra_dataframes, ignore_index=True)
@@ -0,0 +1,14 @@
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
+ class ParsingError(Exception):
14
+ pass
gtfparse/read_gtf.py ADDED
@@ -0,0 +1,297 @@
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 os.path import exists
15
+ from io import StringIO
16
+ import gzip
17
+
18
+ import polars
19
+
20
+ from .attribute_parsing import expand_attribute_strings
21
+ from .parsing_error import ParsingError
22
+
23
+
24
+ logging.basicConfig(level=logging.INFO)
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ """
29
+ Columns of a GTF file:
30
+
31
+ seqname - name of the chromosome or scaffold; chromosome names
32
+ without a 'chr' in Ensembl (but sometimes with a 'chr'
33
+ elsewhere)
34
+ source - name of the program that generated this feature, or
35
+ the data source (database or project name)
36
+ feature - feature type name.
37
+ Features currently in Ensembl GTFs:
38
+ gene
39
+ transcript
40
+ exon
41
+ CDS
42
+ Selenocysteine
43
+ start_codon
44
+ stop_codon
45
+ UTR
46
+ Older Ensembl releases may be missing some of these features.
47
+ start - start position of the feature, with sequence numbering
48
+ starting at 1.
49
+ end - end position of the feature, with sequence numbering
50
+ starting at 1.
51
+ score - a floating point value indiciating the score of a feature
52
+ strand - defined as + (forward) or - (reverse).
53
+ frame - one of '0', '1' or '2'. Frame indicates the number of base pairs
54
+ before you encounter a full codon. '0' indicates the feature
55
+ begins with a whole codon. '1' indicates there is an extra
56
+ base (the 3rd base of the prior codon) at the start of this feature.
57
+ '2' indicates there are two extra bases (2nd and 3rd base of the
58
+ prior exon) before the first codon. All values are given with
59
+ relation to the 5' end.
60
+ attribute - a semicolon-separated list of tag-value pairs (separated by a space),
61
+ providing additional information about each feature. A key can be
62
+ repeated multiple times.
63
+
64
+ (from ftp://ftp.ensembl.org/pub/release-75/gtf/homo_sapiens/README)
65
+ """
66
+
67
+ REQUIRED_COLUMNS = [
68
+ "seqname",
69
+ "source",
70
+ "feature",
71
+ "start",
72
+ "end",
73
+ "score",
74
+ "strand",
75
+ "frame",
76
+ "attribute",
77
+ ]
78
+
79
+
80
+ def parse_with_polars_lazy(
81
+ filepath_or_buffer,
82
+ split_attributes=True,
83
+ features=None,
84
+ fix_quotes_columns=["attribute"]):
85
+ # use a global string cache so that all strings get intern'd into
86
+ # a single numbering system
87
+ polars.enable_string_cache()
88
+ kwargs = dict(
89
+ has_header=False,
90
+ separator="\t",
91
+ comment_prefix="#",
92
+ null_values=".",
93
+ dtypes={
94
+ "seqname": polars.Categorical,
95
+ "source": polars.Categorical,
96
+
97
+ "start": polars.Int64,
98
+ "end": polars.Int64,
99
+ "score": polars.Float32,
100
+
101
+ "feature": polars.Categorical,
102
+ "strand": polars.Categorical,
103
+ "frame": polars.UInt32,
104
+ })
105
+ try:
106
+ if type(filepath_or_buffer) is StringIO:
107
+ df = polars.read_csv(
108
+ filepath_or_buffer,
109
+ new_columns=REQUIRED_COLUMNS,
110
+ **kwargs).lazy()
111
+ elif filepath_or_buffer.endswith(".gz") or filepath_or_buffer.endswith(".gzip"):
112
+ with gzip.open(filepath_or_buffer) as f:
113
+ df = polars.read_csv(
114
+ f,
115
+ new_columns=REQUIRED_COLUMNS,
116
+ **kwargs).lazy()
117
+ else:
118
+ df = polars.scan_csv(
119
+ filepath_or_buffer,
120
+ with_column_names=lambda cols: REQUIRED_COLUMNS,
121
+ **kwargs).lazy()
122
+ except polars.ShapeError:
123
+ raise ParsingError("Wrong number of columns")
124
+
125
+ df = df.with_columns([
126
+ polars.col("frame").fill_null(0),
127
+ polars.col("attribute").str.replace_all('"', "'")
128
+ ])
129
+
130
+ for fix_quotes_column in fix_quotes_columns:
131
+ # Catch mistaken semicolons by replacing "xyz;" with "xyz"
132
+ # Required to do this since the Ensembl GTF for Ensembl
133
+ # release 78 has mistakes such as:
134
+ # gene_name = "PRAMEF6;" transcript_name = "PRAMEF6;-201"
135
+ df = df.with_columns([
136
+ polars.col(fix_quotes_column).str.replace(';\"', '\"').str.replace(";-", "-")
137
+ ])
138
+
139
+ if features is not None:
140
+ features = sorted(set(features))
141
+ df = df.filter(polars.col("feature").is_in(features))
142
+
143
+
144
+ if split_attributes:
145
+ df = df.with_columns([
146
+ polars.col("attribute").str.split(";").alias("attribute_split")
147
+ ])
148
+ return df
149
+
150
+ def parse_gtf(
151
+ filepath_or_buffer,
152
+ split_attributes=True,
153
+ features=None,
154
+ fix_quotes_columns=["attribute"]):
155
+ df_lazy = parse_with_polars_lazy(
156
+ filepath_or_buffer=filepath_or_buffer,
157
+ split_attributes=split_attributes,
158
+ features=features,
159
+ fix_quotes_columns=fix_quotes_columns)
160
+ return df_lazy.collect()
161
+
162
+ def parse_gtf_pandas(*args, **kwargs):
163
+ return parse_gtf(*args, **kwargs).to_pandas()
164
+
165
+
166
+ def parse_gtf_and_expand_attributes(
167
+ filepath_or_buffer,
168
+ restrict_attribute_columns=None,
169
+ features=None):
170
+ """
171
+ Parse lines into column->values dictionary and then expand
172
+ the 'attribute' column into multiple columns. This expansion happens
173
+ by replacing strings of semi-colon separated key-value values in the
174
+ 'attribute' column with one column per distinct key, with a list of
175
+ values for each row (using None for rows where key didn't occur).
176
+
177
+ Parameters
178
+ ----------
179
+ filepath_or_buffer : str or buffer object
180
+
181
+ chunksize : int
182
+
183
+ restrict_attribute_columns : list/set of str or None
184
+ If given, then only use these attribute columns.
185
+
186
+ features : set or None
187
+ Ignore entries which don't correspond to one of the supplied features
188
+ """
189
+ df = parse_gtf(
190
+ filepath_or_buffer=filepath_or_buffer,
191
+ features=features,
192
+ split_attributes=True)
193
+ if type(restrict_attribute_columns) is str:
194
+ restrict_attribute_columns = {restrict_attribute_columns}
195
+ elif restrict_attribute_columns:
196
+ restrict_attribute_columns = set(restrict_attribute_columns)
197
+ df.drop_in_place("attribute")
198
+ attribute_pairs = df.drop_in_place("attribute_split")
199
+ return df.with_columns([
200
+ polars.Series(k, vs)
201
+ for (k, vs) in
202
+ expand_attribute_strings(attribute_pairs).items()
203
+ if restrict_attribute_columns is None or k in restrict_attribute_columns
204
+ ])
205
+
206
+
207
+ def read_gtf(
208
+ filepath_or_buffer,
209
+ expand_attribute_column=True,
210
+ infer_biotype_column=False,
211
+ column_converters={},
212
+ usecols=None,
213
+ features=None,
214
+ result_type='polars'):
215
+ """
216
+ Parse a GTF into a dictionary mapping column names to sequences of values.
217
+
218
+ Parameters
219
+ ----------
220
+ filepath_or_buffer : str or buffer object
221
+ Path to GTF file (may be gzip compressed) or buffer object
222
+ such as StringIO
223
+
224
+ expand_attribute_column : bool
225
+ Replace strings of semi-colon separated key-value values in the
226
+ 'attribute' column with one column per distinct key, with a list of
227
+ values for each row (using None for rows where key didn't occur).
228
+
229
+ infer_biotype_column : bool
230
+ Due to the annoying ambiguity of the second GTF column across multiple
231
+ Ensembl releases, figure out if an older GTF's source column is actually
232
+ the gene_biotype or transcript_biotype.
233
+
234
+ column_converters : dict, optional
235
+ Dictionary mapping column names to conversion functions. Will replace
236
+ empty strings with None and otherwise passes them to given conversion
237
+ function.
238
+
239
+ usecols : list of str or None
240
+ Restrict which columns are loaded to the give set. If None, then
241
+ load all columns.
242
+
243
+ features : set of str or None
244
+ Drop rows which aren't one of the features in the supplied set
245
+
246
+ result_type : One of 'polars', 'pandas', or 'dict'
247
+ Default behavior is to return a Polars DataFrame, but will convert to
248
+ Pandas DataFrame or dictionary if specified.
249
+ """
250
+ if type(filepath_or_buffer) is str and not exists(filepath_or_buffer):
251
+ raise ValueError("GTF file does not exist: %s" % filepath_or_buffer)
252
+
253
+ if expand_attribute_column:
254
+ result_df = parse_gtf_and_expand_attributes(
255
+ filepath_or_buffer,
256
+ restrict_attribute_columns=usecols,
257
+ features=features)
258
+ else:
259
+ result_df = parse_gtf(result_df, features=features)
260
+
261
+ result_df = result_df.with_columns(
262
+ [
263
+ polars.col(column_name).map_elements(lambda x: column_type(x) if len(x) > 0 else None)
264
+ for column_name, column_type in column_converters.items()
265
+ ]
266
+ )
267
+
268
+ # Hackishly infer whether the values in the 'source' column of this GTF
269
+ # are actually representing a biotype by checking for the most common
270
+ # gene_biotype and transcript_biotype value 'protein_coding'
271
+ if infer_biotype_column:
272
+ unique_source_values = set(result_df["source"])
273
+ if "protein_coding" in unique_source_values:
274
+ column_names = set(result_df.columns)
275
+ # Disambiguate between the two biotypes by checking if
276
+ # gene_biotype is already present in another column. If it is,
277
+ # the 2nd column is the transcript_biotype (otherwise, it's the
278
+ # gene_biotype)
279
+ if "gene_biotype" not in column_names:
280
+ logging.info("Using column 'source' to replace missing 'gene_biotype'")
281
+ result_df = result_df.with_column(polars.col("source").alias("gene_biotype"))
282
+ if "transcript_biotype" not in column_names:
283
+ logging.info("Using column 'source' to replace missing 'transcript_biotype'")
284
+ result_df = result_df.with_column(polars.col("source").alias("transcript_biotype"))
285
+
286
+ if usecols is not None:
287
+ column_names = set(result_df.columns)
288
+ valid_columns = [c for c in usecols if c in column_names]
289
+ result_df = result_df.select(valid_columns)
290
+
291
+ if result_type == "pandas":
292
+ result = result_df.to_pandas()
293
+ elif result_type == "polars":
294
+ result = result_df
295
+ elif result_type == "dict":
296
+ result = result_df.to_dict()
297
+ return result
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.1
2
+ Name: gtfparse
3
+ Version: 2.1.0
4
+ Summary: Parsing library for extracting data frames of genomic features from GTF files
5
+ Author-email: Alex Rubinsteyn <alex.rubinsteyn@unc.edu>
6
+ Project-URL: Homepage, https://github.com/openvax/gtfparse
7
+ Project-URL: Bug Tracker, https://github.com/openvax/gtfparse
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Environment :: Console
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
15
+ Requires-Python: >=3.7
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: polars <0.21.0,>=0.20.2
19
+ Requires-Dist: pyarrow <14.1.0,>=14.0.2
20
+
21
+ [![Build Status](https://travis-ci.org/openvax/gtfparse.svg?branch=master)](https://travis-ci.org/openvax/gtfparse) [![Coverage Status](https://coveralls.io/repos/openvax/gtfparse/badge.svg?branch=master&service=github)](https://coveralls.io/github/openvax/gtfparse?branch=master)
22
+ <a href="https://pypi.python.org/pypi/gtfparse/">
23
+ <img src="https://img.shields.io/pypi/v/gtfparse.svg?maxAge=1000" alt="PyPI" />
24
+ </a>
25
+
26
+ gtfparse
27
+ ========
28
+ Parsing tools for GTF (gene transfer format) files.
29
+
30
+ # Example usage
31
+
32
+ ## Parsing all rows of a GTF file into a Pandas DataFrame
33
+
34
+ ```python
35
+ from gtfparse import read_gtf
36
+
37
+ # returns GTF with essential columns such as "feature", "seqname", "start", "end"
38
+ # alongside the names of any optional keys which appeared in the attribute column
39
+ df = read_gtf("gene_annotations.gtf")
40
+
41
+ # filter DataFrame to gene entries on chrY
42
+ df_genes = df[df["feature"] == "gene"]
43
+ df_genes_chrY = df_genes[df_genes["seqname"] == "Y"]
44
+ ```
45
+
46
+
47
+ ## Getting gene FPKM values from a StringTie GTF file
48
+
49
+ ```python
50
+ from gtfparse import read_gtf
51
+
52
+ df = read_gtf(
53
+ "Transcripts.gtf",
54
+ column_converters={"FPKM": float})
55
+
56
+ gene_fpkms = {
57
+ gene_name: fpkm
58
+ for (gene_name, fpkm, feature)
59
+ in zip(df["seqname"], df["FPKM"], df["feature"])
60
+ if feature == "gene"
61
+ }
62
+ ```
63
+
64
+
@@ -0,0 +1,11 @@
1
+ requirements.txt,sha256=7ScTRNppQy5B2g6C7SL-AorMzyr5PC0KLt3tlRREfGg,47
2
+ gtfparse/__init__.py,sha256=FUhwxf_r14CWWYOLSo-pVLEDCQjEofpVgEg7uqnbbPY,1102
3
+ gtfparse/attribute_parsing.py,sha256=U579OuulIBhRdHsPmS33wePwiJ0qxsfNNY7y-1-KBuo,4134
4
+ gtfparse/create_missing_features.py,sha256=CGwxlyS9trrse7u3KKg8mFmuGoli2wFEBJ-n4XEzlpw,5016
5
+ gtfparse/parsing_error.py,sha256=dWjxGGIhpZDEnWjrRp0hxk3Ut7BaYujYT-8DhlCnBMI,585
6
+ gtfparse/read_gtf.py,sha256=D7vCaKOBy8wqvmQEXcMcykh8_dFYFs6bd3sngsrnfng,10986
7
+ gtfparse-2.1.0.dist-info/LICENSE,sha256=xllut76FgcGL5zbIRvuRc7aezPbvlMUTWJPsVr2Sugg,11358
8
+ gtfparse-2.1.0.dist-info/METADATA,sha256=p5hbzxLHX9tIo4Ecr7rNpsA1EfKeBN_2ZZ06tbSJYQ4,2108
9
+ gtfparse-2.1.0.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
10
+ gtfparse-2.1.0.dist-info/top_level.txt,sha256=7j2M9WSTNQye5-GDW_wLZfLoa10e4YfFKw-cAeVxFPM,9
11
+ gtfparse-2.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ gtfparse
requirements.txt ADDED
@@ -0,0 +1,2 @@
1
+ polars>=0.20.2,<0.21.0
2
+ pyarrow>=14.0.2,<14.1.0