gffkit 0.5.0__tar.gz → 0.6.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.
- {gffkit-0.5.0/src/gffkit.egg-info → gffkit-0.6.0}/PKG-INFO +79 -6
- {gffkit-0.5.0 → gffkit-0.6.0}/README.md +76 -3
- {gffkit-0.5.0 → gffkit-0.6.0}/pyproject.toml +3 -3
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit/__init__.py +1 -1
- gffkit-0.6.0/src/gffkit/get_longest_transcript.py +338 -0
- gffkit-0.6.0/src/gffkit/gffstat.py +194 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit/main.py +78 -1
- {gffkit-0.5.0 → gffkit-0.6.0/src/gffkit.egg-info}/PKG-INFO +79 -6
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit.egg-info/SOURCES.txt +3 -0
- gffkit-0.6.0/tests/test_analysis_commands.py +115 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/LICENSE +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/MANIFEST.in +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/setup.cfg +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit/__main__.py +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit/add_utr.py +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit/complement_annotations.py +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit/detect_bridge_merged_genes.py +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit/rename_sort_gff3.py +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit.egg-info/dependency_links.txt +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit.egg-info/entry_points.txt +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/src/gffkit.egg-info/top_level.txt +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/tests/test_complement_sources.py +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/tests/test_parallel_performance.py +0 -0
- {gffkit-0.5.0 → gffkit-0.6.0}/tests/test_rename_sort.py +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: gffkit
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary:
|
|
5
|
-
Author:
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: GFF annotation integration and analysis toolkit
|
|
5
|
+
Author: caijunhao
|
|
6
6
|
License: MIT
|
|
7
7
|
Project-URL: Homepage, https://github.com/qunjie-zhang/gffkit
|
|
8
8
|
Project-URL: Repository, https://github.com/qunjie-zhang/gffkit
|
|
@@ -25,13 +25,19 @@ License-File: LICENSE
|
|
|
25
25
|
|
|
26
26
|
# gffkit
|
|
27
27
|
|
|
28
|
-
`gffkit` is a lightweight toolkit for
|
|
29
|
-
|
|
28
|
+
`gffkit` is a lightweight toolkit for GFF/GTF annotation integration and analysis.
|
|
29
|
+
Version 0.6.0 provides six standalone utilities:
|
|
30
30
|
|
|
31
31
|
1. `detect-bridge`: detect suspicious merged-gene artifacts caused by bridge transcripts.
|
|
32
32
|
2. `complement`: complement/merge annotations, with optional region-swap mode.
|
|
33
33
|
3. `add-utr`: reconstruct `five_prime_UTR` and `three_prime_UTR` features from exon/CDS coordinates.
|
|
34
34
|
4. `rename-sort`: rename gene/transcript/child IDs with a prefix and sort the final GFF3.
|
|
35
|
+
5. `get_longest_transcript`: retain one longest transcript isoform per gene.
|
|
36
|
+
6. `stat`: calculate basic gene-annotation statistics for one GFF or a directory of GFF files.
|
|
37
|
+
|
|
38
|
+
The `integrate` workflow continues to use only the original four integration
|
|
39
|
+
utilities. `get_longest_transcript` and `stat` are independent commands and are
|
|
40
|
+
not automatically run by `integrate`.
|
|
35
41
|
|
|
36
42
|
## Installation
|
|
37
43
|
|
|
@@ -102,6 +108,56 @@ gffkit complement \
|
|
|
102
108
|
-t 8
|
|
103
109
|
```
|
|
104
110
|
|
|
111
|
+
### Extract the longest transcript
|
|
112
|
+
|
|
113
|
+
For each gene, `get_longest_transcript` selects the isoform with the longest
|
|
114
|
+
concatenated CDS. If none of a gene's isoforms has CDS features, it uses the
|
|
115
|
+
longest concatenated exon length. Ties retain the first isoform encountered in
|
|
116
|
+
the input file.
|
|
117
|
+
|
|
118
|
+
Process one GFF/GFF3 file:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
gffkit get_longest_transcript \
|
|
122
|
+
-i annotation.gff3 \
|
|
123
|
+
-o longest_gff
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Process all `.gff`/`.gff3` files directly inside a directory:
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
gffkit get_longest_transcript \
|
|
130
|
+
-f input_gff_directory \
|
|
131
|
+
-o longest_gff
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Compressed `.gff.gz` and `.gff3.gz` inputs are also supported by this command.
|
|
135
|
+
Output files are named `*.longest.gff` or `*.longest.gff3`. Existing output
|
|
136
|
+
files are refused unless `--force` is supplied.
|
|
137
|
+
|
|
138
|
+
### Calculate annotation statistics
|
|
139
|
+
|
|
140
|
+
Process one GFF/GFF3 file and write the default `gffstat.txt`:
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
gffkit stat -i annotation.gff3
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Process all `.gff`/`.gff3` files directly inside a directory and select an
|
|
147
|
+
output path:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
gffkit stat \
|
|
151
|
+
-f input_gff_directory \
|
|
152
|
+
-o annotation.gffstat.txt
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The tab-separated output contains species/file name, gene count, average gene
|
|
156
|
+
span, average transcript span, average CDS length per gene, average exon count
|
|
157
|
+
per gene, average exon length, and average UTR length per gene. Gene and
|
|
158
|
+
transcript lengths use their GFF genomic spans (`end - start + 1`); they are not
|
|
159
|
+
spliced mature-transcript lengths.
|
|
160
|
+
|
|
105
161
|
## Command overview
|
|
106
162
|
|
|
107
163
|
```bash
|
|
@@ -110,13 +166,15 @@ gffkit detect-bridge --help
|
|
|
110
166
|
gffkit complement --help
|
|
111
167
|
gffkit add-utr --help
|
|
112
168
|
gffkit rename-sort --help
|
|
169
|
+
gffkit get_longest_transcript --help
|
|
170
|
+
gffkit stat --help
|
|
113
171
|
gffkit integrate --help
|
|
114
172
|
```
|
|
115
173
|
|
|
116
174
|
## Parallel Processing
|
|
117
175
|
|
|
118
176
|
Use `-t/--threads` to select the number of worker processes. The option name is
|
|
119
|
-
kept for command-line compatibility, but version 0.5.0 uses processes for
|
|
177
|
+
kept for command-line compatibility, but version 0.5.0 and later uses processes for
|
|
120
178
|
CPU-bound work so that Python's GIL does not restrict execution to one core.
|
|
121
179
|
|
|
122
180
|
- `detect-bridge` analyzes genes with a process pool and batches tasks to reduce process communication overhead.
|
|
@@ -142,6 +200,7 @@ large annotations.
|
|
|
142
200
|
- UTR features are reconstructed after merging using an exon-minus-CDS strategy.
|
|
143
201
|
- Version 0.4.0 and later run `rename-sort` as the final `integrate` step. The final GFF3 keeps chromosome-mounted records, removes unplaced/scaffold/contig records, sorts features, rewrites `ID`/`Parent`, and writes an ID map next to the output.
|
|
144
202
|
- Version 0.5.0 replaces CPU-bound threads with worker processes and adds a dynamic interval index for faster annotation overlap searches.
|
|
203
|
+
- Version 0.6.0 adds the independent `get_longest_transcript` and `stat` commands. Neither command is included in `integrate`.
|
|
145
204
|
- When multiple tools annotate the same gene locus, the GFF source column is combined with `|`, for example `EviAnn|ANNEVO`.
|
|
146
205
|
|
|
147
206
|
## Rename and Sort
|
|
@@ -159,6 +218,16 @@ gffkit rename-sort \
|
|
|
159
218
|
|
|
160
219
|
This writes `sample.renamed.sorted.gff3` and `sample.renamed.sorted.gff3.id_map.tsv`.
|
|
161
220
|
|
|
221
|
+
## Version 0.6.0 changes
|
|
222
|
+
|
|
223
|
+
- Added `gffkit get_longest_transcript` using the longest-CDS/longest-exon selection logic from `get_longest_transcript.py`.
|
|
224
|
+
- Added mutually exclusive `-i/--input` single-file and `-f/--folder` directory input modes for longest-transcript extraction.
|
|
225
|
+
- Added `gffkit stat` using the GFF statistics implementation from `gffstat.py`.
|
|
226
|
+
- Added mutually exclusive `-i/--input` single-file and `-f/--folder` directory input modes for annotation statistics.
|
|
227
|
+
- Kept both new commands independent from the four-step `gffkit integrate` workflow.
|
|
228
|
+
- Updated the package version from 0.5.0 to 0.6.0.
|
|
229
|
+
- Updated package author and credits to `caijunhao`.
|
|
230
|
+
|
|
162
231
|
## Maintainer notes
|
|
163
232
|
|
|
164
233
|
When command-line options or behavior changes, update this `README.md` in the versioned package directory before building and uploading to PyPI.
|
|
@@ -166,3 +235,7 @@ When command-line options or behavior changes, update this `README.md` in the ve
|
|
|
166
235
|
## License
|
|
167
236
|
|
|
168
237
|
MIT License.
|
|
238
|
+
|
|
239
|
+
## Credits
|
|
240
|
+
|
|
241
|
+
Author: caijunhao
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
# gffkit
|
|
2
2
|
|
|
3
|
-
`gffkit` is a lightweight toolkit for
|
|
4
|
-
|
|
3
|
+
`gffkit` is a lightweight toolkit for GFF/GTF annotation integration and analysis.
|
|
4
|
+
Version 0.6.0 provides six standalone utilities:
|
|
5
5
|
|
|
6
6
|
1. `detect-bridge`: detect suspicious merged-gene artifacts caused by bridge transcripts.
|
|
7
7
|
2. `complement`: complement/merge annotations, with optional region-swap mode.
|
|
8
8
|
3. `add-utr`: reconstruct `five_prime_UTR` and `three_prime_UTR` features from exon/CDS coordinates.
|
|
9
9
|
4. `rename-sort`: rename gene/transcript/child IDs with a prefix and sort the final GFF3.
|
|
10
|
+
5. `get_longest_transcript`: retain one longest transcript isoform per gene.
|
|
11
|
+
6. `stat`: calculate basic gene-annotation statistics for one GFF or a directory of GFF files.
|
|
12
|
+
|
|
13
|
+
The `integrate` workflow continues to use only the original four integration
|
|
14
|
+
utilities. `get_longest_transcript` and `stat` are independent commands and are
|
|
15
|
+
not automatically run by `integrate`.
|
|
10
16
|
|
|
11
17
|
## Installation
|
|
12
18
|
|
|
@@ -77,6 +83,56 @@ gffkit complement \
|
|
|
77
83
|
-t 8
|
|
78
84
|
```
|
|
79
85
|
|
|
86
|
+
### Extract the longest transcript
|
|
87
|
+
|
|
88
|
+
For each gene, `get_longest_transcript` selects the isoform with the longest
|
|
89
|
+
concatenated CDS. If none of a gene's isoforms has CDS features, it uses the
|
|
90
|
+
longest concatenated exon length. Ties retain the first isoform encountered in
|
|
91
|
+
the input file.
|
|
92
|
+
|
|
93
|
+
Process one GFF/GFF3 file:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
gffkit get_longest_transcript \
|
|
97
|
+
-i annotation.gff3 \
|
|
98
|
+
-o longest_gff
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Process all `.gff`/`.gff3` files directly inside a directory:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
gffkit get_longest_transcript \
|
|
105
|
+
-f input_gff_directory \
|
|
106
|
+
-o longest_gff
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Compressed `.gff.gz` and `.gff3.gz` inputs are also supported by this command.
|
|
110
|
+
Output files are named `*.longest.gff` or `*.longest.gff3`. Existing output
|
|
111
|
+
files are refused unless `--force` is supplied.
|
|
112
|
+
|
|
113
|
+
### Calculate annotation statistics
|
|
114
|
+
|
|
115
|
+
Process one GFF/GFF3 file and write the default `gffstat.txt`:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
gffkit stat -i annotation.gff3
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Process all `.gff`/`.gff3` files directly inside a directory and select an
|
|
122
|
+
output path:
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
gffkit stat \
|
|
126
|
+
-f input_gff_directory \
|
|
127
|
+
-o annotation.gffstat.txt
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The tab-separated output contains species/file name, gene count, average gene
|
|
131
|
+
span, average transcript span, average CDS length per gene, average exon count
|
|
132
|
+
per gene, average exon length, and average UTR length per gene. Gene and
|
|
133
|
+
transcript lengths use their GFF genomic spans (`end - start + 1`); they are not
|
|
134
|
+
spliced mature-transcript lengths.
|
|
135
|
+
|
|
80
136
|
## Command overview
|
|
81
137
|
|
|
82
138
|
```bash
|
|
@@ -85,13 +141,15 @@ gffkit detect-bridge --help
|
|
|
85
141
|
gffkit complement --help
|
|
86
142
|
gffkit add-utr --help
|
|
87
143
|
gffkit rename-sort --help
|
|
144
|
+
gffkit get_longest_transcript --help
|
|
145
|
+
gffkit stat --help
|
|
88
146
|
gffkit integrate --help
|
|
89
147
|
```
|
|
90
148
|
|
|
91
149
|
## Parallel Processing
|
|
92
150
|
|
|
93
151
|
Use `-t/--threads` to select the number of worker processes. The option name is
|
|
94
|
-
kept for command-line compatibility, but version 0.5.0 uses processes for
|
|
152
|
+
kept for command-line compatibility, but version 0.5.0 and later uses processes for
|
|
95
153
|
CPU-bound work so that Python's GIL does not restrict execution to one core.
|
|
96
154
|
|
|
97
155
|
- `detect-bridge` analyzes genes with a process pool and batches tasks to reduce process communication overhead.
|
|
@@ -117,6 +175,7 @@ large annotations.
|
|
|
117
175
|
- UTR features are reconstructed after merging using an exon-minus-CDS strategy.
|
|
118
176
|
- Version 0.4.0 and later run `rename-sort` as the final `integrate` step. The final GFF3 keeps chromosome-mounted records, removes unplaced/scaffold/contig records, sorts features, rewrites `ID`/`Parent`, and writes an ID map next to the output.
|
|
119
177
|
- Version 0.5.0 replaces CPU-bound threads with worker processes and adds a dynamic interval index for faster annotation overlap searches.
|
|
178
|
+
- Version 0.6.0 adds the independent `get_longest_transcript` and `stat` commands. Neither command is included in `integrate`.
|
|
120
179
|
- When multiple tools annotate the same gene locus, the GFF source column is combined with `|`, for example `EviAnn|ANNEVO`.
|
|
121
180
|
|
|
122
181
|
## Rename and Sort
|
|
@@ -134,6 +193,16 @@ gffkit rename-sort \
|
|
|
134
193
|
|
|
135
194
|
This writes `sample.renamed.sorted.gff3` and `sample.renamed.sorted.gff3.id_map.tsv`.
|
|
136
195
|
|
|
196
|
+
## Version 0.6.0 changes
|
|
197
|
+
|
|
198
|
+
- Added `gffkit get_longest_transcript` using the longest-CDS/longest-exon selection logic from `get_longest_transcript.py`.
|
|
199
|
+
- Added mutually exclusive `-i/--input` single-file and `-f/--folder` directory input modes for longest-transcript extraction.
|
|
200
|
+
- Added `gffkit stat` using the GFF statistics implementation from `gffstat.py`.
|
|
201
|
+
- Added mutually exclusive `-i/--input` single-file and `-f/--folder` directory input modes for annotation statistics.
|
|
202
|
+
- Kept both new commands independent from the four-step `gffkit integrate` workflow.
|
|
203
|
+
- Updated the package version from 0.5.0 to 0.6.0.
|
|
204
|
+
- Updated package author and credits to `caijunhao`.
|
|
205
|
+
|
|
137
206
|
## Maintainer notes
|
|
138
207
|
|
|
139
208
|
When command-line options or behavior changes, update this `README.md` in the versioned package directory before building and uploading to PyPI.
|
|
@@ -141,3 +210,7 @@ When command-line options or behavior changes, update this `README.md` in the ve
|
|
|
141
210
|
## License
|
|
142
211
|
|
|
143
212
|
MIT License.
|
|
213
|
+
|
|
214
|
+
## Credits
|
|
215
|
+
|
|
216
|
+
Author: caijunhao
|
|
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "gffkit"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "
|
|
7
|
+
version = "0.6.0"
|
|
8
|
+
description = "GFF annotation integration and analysis toolkit"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.8"
|
|
11
11
|
license = {text = "MIT"}
|
|
12
12
|
authors = [
|
|
13
|
-
{name = "
|
|
13
|
+
{name = "caijunhao"}
|
|
14
14
|
]
|
|
15
15
|
keywords = ["GFF3", "GTF", "genome annotation", "bioinformatics", "UTR", "gene annotation"]
|
|
16
16
|
classifiers = [
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Extract longest isoforms from GFF3 files using AGAT's selection logic.
|
|
3
|
+
|
|
4
|
+
For each gene, if one or more isoforms have CDS features, keep the isoform
|
|
5
|
+
with the longest concatenated CDS. If no isoform has CDS features, keep the
|
|
6
|
+
isoform with the longest concatenated exons. Ties are resolved by retaining
|
|
7
|
+
the isoform that appears first in the input GFF3 file.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import gzip
|
|
14
|
+
import sys
|
|
15
|
+
from collections import defaultdict
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import TextIO
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
TRANSCRIPT_TYPES = {
|
|
22
|
+
"mrna",
|
|
23
|
+
"transcript",
|
|
24
|
+
"lnc_rna",
|
|
25
|
+
"ncrna",
|
|
26
|
+
"rrna",
|
|
27
|
+
"trna",
|
|
28
|
+
"snrna",
|
|
29
|
+
"snorna",
|
|
30
|
+
"mirna",
|
|
31
|
+
"pre_mirna",
|
|
32
|
+
"pseudogenic_transcript",
|
|
33
|
+
}
|
|
34
|
+
GFF_SUFFIXES = (".gff", ".gff3", ".gff.gz", ".gff3.gz")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class Transcript:
|
|
39
|
+
transcript_id: str
|
|
40
|
+
gene_ids: tuple[str, ...]
|
|
41
|
+
order: int
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def parse_args() -> argparse.Namespace:
|
|
45
|
+
parser = argparse.ArgumentParser(
|
|
46
|
+
description=(
|
|
47
|
+
"Extract the longest transcript of each gene from one GFF/GFF3 "
|
|
48
|
+
"file or all GFF/GFF3 files directly under an input directory."
|
|
49
|
+
)
|
|
50
|
+
)
|
|
51
|
+
inputs = parser.add_mutually_exclusive_group(required=True)
|
|
52
|
+
inputs.add_argument(
|
|
53
|
+
"-i", "--input", type=Path,
|
|
54
|
+
help="Single input .gff/.gff3 file",
|
|
55
|
+
)
|
|
56
|
+
inputs.add_argument(
|
|
57
|
+
"-f", "--folder", type=Path,
|
|
58
|
+
help="Directory containing input .gff/.gff3 files (non-recursive)",
|
|
59
|
+
)
|
|
60
|
+
parser.add_argument("-o", "--output-dir", required=True, type=Path,
|
|
61
|
+
help="Directory in which output GFF3 files are written")
|
|
62
|
+
parser.add_argument(
|
|
63
|
+
"--force",
|
|
64
|
+
action="store_true",
|
|
65
|
+
help="Overwrite output files that already exist (default: refuse)",
|
|
66
|
+
)
|
|
67
|
+
return parser.parse_args()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def open_text(path: Path, mode: str) -> TextIO:
|
|
71
|
+
if path.name.lower().endswith(".gz"):
|
|
72
|
+
return gzip.open(path, mode + "t", encoding="utf-8")
|
|
73
|
+
return path.open(mode, encoding="utf-8")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def parse_attributes(text: str) -> dict[str, str]:
|
|
77
|
+
attributes: dict[str, str] = {}
|
|
78
|
+
for item in text.strip().strip(";").split(";"):
|
|
79
|
+
if not item:
|
|
80
|
+
continue
|
|
81
|
+
key, separator, value = item.partition("=")
|
|
82
|
+
if separator:
|
|
83
|
+
attributes[key] = value
|
|
84
|
+
return attributes
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def split_parents(attributes: dict[str, str]) -> tuple[str, ...]:
|
|
88
|
+
return tuple(value for value in attributes.get("Parent", "").split(",") if value)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def output_name(input_path: Path) -> str:
|
|
92
|
+
lower_name = input_path.name.lower()
|
|
93
|
+
if lower_name.endswith(".gff3.gz"):
|
|
94
|
+
return input_path.name[:-8] + ".longest.gff3.gz"
|
|
95
|
+
if lower_name.endswith(".gff.gz"):
|
|
96
|
+
return input_path.name[:-7] + ".longest.gff.gz"
|
|
97
|
+
if lower_name.endswith(".gff3"):
|
|
98
|
+
return input_path.name[:-5] + ".longest.gff3"
|
|
99
|
+
return input_path.name[:-4] + ".longest.gff"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def is_input_gff(path: Path) -> bool:
|
|
103
|
+
name = path.name.lower()
|
|
104
|
+
return (
|
|
105
|
+
path.is_file()
|
|
106
|
+
and name.endswith(GFF_SUFFIXES)
|
|
107
|
+
and ".longest.gff" not in name
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def collect_input_files(args: argparse.Namespace) -> list[Path]:
|
|
112
|
+
if args.input is not None:
|
|
113
|
+
input_path = args.input.expanduser().resolve()
|
|
114
|
+
if not input_path.is_file():
|
|
115
|
+
raise ValueError(
|
|
116
|
+
f"input file does not exist or is not a regular file: {input_path}"
|
|
117
|
+
)
|
|
118
|
+
if not input_path.name.lower().endswith(GFF_SUFFIXES):
|
|
119
|
+
raise ValueError(
|
|
120
|
+
f"input file must end in .gff, .gff3, .gff.gz, or .gff3.gz: "
|
|
121
|
+
f"{input_path}"
|
|
122
|
+
)
|
|
123
|
+
return [input_path]
|
|
124
|
+
|
|
125
|
+
input_dir = args.folder.expanduser().resolve()
|
|
126
|
+
if not input_dir.is_dir():
|
|
127
|
+
raise ValueError(f"input directory does not exist: {input_dir}")
|
|
128
|
+
|
|
129
|
+
input_files = sorted(path for path in input_dir.iterdir() if is_input_gff(path))
|
|
130
|
+
if not input_files:
|
|
131
|
+
raise ValueError(f"no .gff/.gff3 files found in: {input_dir}")
|
|
132
|
+
return input_files
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def parse_feature_line(line: str, path: Path, line_number: int) -> list[str]:
|
|
136
|
+
fields = line.rstrip("\n\r").split("\t")
|
|
137
|
+
if len(fields) != 9:
|
|
138
|
+
raise ValueError(
|
|
139
|
+
f"{path}:{line_number}: expected 9 tab-separated GFF columns, "
|
|
140
|
+
f"found {len(fields)}"
|
|
141
|
+
)
|
|
142
|
+
return fields
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def find_longest_transcripts(path: Path) -> tuple[set[str], int, int, int]:
|
|
146
|
+
transcripts: dict[str, Transcript] = {}
|
|
147
|
+
exon_lengths: dict[str, int] = defaultdict(int)
|
|
148
|
+
cds_lengths: dict[str, int] = defaultdict(int)
|
|
149
|
+
transcript_order = 0
|
|
150
|
+
in_fasta = False
|
|
151
|
+
|
|
152
|
+
with open_text(path, "r") as handle:
|
|
153
|
+
for line_number, line in enumerate(handle, 1):
|
|
154
|
+
if line.startswith("##FASTA"):
|
|
155
|
+
in_fasta = True
|
|
156
|
+
continue
|
|
157
|
+
if in_fasta or not line.strip() or line.startswith("#"):
|
|
158
|
+
continue
|
|
159
|
+
|
|
160
|
+
fields = parse_feature_line(line, path, line_number)
|
|
161
|
+
feature_type = fields[2].lower()
|
|
162
|
+
attributes = parse_attributes(fields[8])
|
|
163
|
+
|
|
164
|
+
if feature_type in TRANSCRIPT_TYPES:
|
|
165
|
+
transcript_id = attributes.get("ID")
|
|
166
|
+
gene_ids = split_parents(attributes)
|
|
167
|
+
if not gene_ids and attributes.get("geneID"):
|
|
168
|
+
gene_ids = (attributes["geneID"],)
|
|
169
|
+
if not transcript_id or not gene_ids:
|
|
170
|
+
raise ValueError(
|
|
171
|
+
f"{path}:{line_number}: transcript feature lacks ID or Parent/geneID"
|
|
172
|
+
)
|
|
173
|
+
if transcript_id in transcripts:
|
|
174
|
+
raise ValueError(
|
|
175
|
+
f"{path}:{line_number}: duplicate transcript ID {transcript_id!r}"
|
|
176
|
+
)
|
|
177
|
+
transcripts[transcript_id] = Transcript(
|
|
178
|
+
transcript_id, gene_ids, transcript_order
|
|
179
|
+
)
|
|
180
|
+
transcript_order += 1
|
|
181
|
+
elif feature_type in {"exon", "cds"}:
|
|
182
|
+
parents = split_parents(attributes)
|
|
183
|
+
if not parents:
|
|
184
|
+
continue
|
|
185
|
+
try:
|
|
186
|
+
feature_length = int(fields[4]) - int(fields[3]) + 1
|
|
187
|
+
except ValueError as exc:
|
|
188
|
+
raise ValueError(
|
|
189
|
+
f"{path}:{line_number}: start/end is not an integer"
|
|
190
|
+
) from exc
|
|
191
|
+
length_table = exon_lengths if feature_type == "exon" else cds_lengths
|
|
192
|
+
for parent in parents:
|
|
193
|
+
length_table[parent] += feature_length
|
|
194
|
+
|
|
195
|
+
transcripts_by_gene: dict[str, list[Transcript]] = defaultdict(list)
|
|
196
|
+
for transcript in transcripts.values():
|
|
197
|
+
for gene_id in transcript.gene_ids:
|
|
198
|
+
transcripts_by_gene[gene_id].append(transcript)
|
|
199
|
+
|
|
200
|
+
selected: set[str] = set()
|
|
201
|
+
no_length_feature_count = 0
|
|
202
|
+
for isoforms in transcripts_by_gene.values():
|
|
203
|
+
# AGAT first asks whether any isoform has CDS. If so, exon and UTR
|
|
204
|
+
# lengths do not contribute, and isoforms without CDS are excluded.
|
|
205
|
+
candidates = [
|
|
206
|
+
transcript for transcript in isoforms
|
|
207
|
+
if transcript.transcript_id in cds_lengths
|
|
208
|
+
]
|
|
209
|
+
length_table = cds_lengths
|
|
210
|
+
|
|
211
|
+
# Only when none of the isoforms has CDS does AGAT compare the sum of
|
|
212
|
+
# exon lengths.
|
|
213
|
+
if not candidates:
|
|
214
|
+
candidates = [
|
|
215
|
+
transcript for transcript in isoforms
|
|
216
|
+
if transcript.transcript_id in exon_lengths
|
|
217
|
+
]
|
|
218
|
+
length_table = exon_lengths
|
|
219
|
+
|
|
220
|
+
if candidates:
|
|
221
|
+
# max() returns the first item when keys are equal, matching AGAT's
|
|
222
|
+
# strict ">" comparison and therefore its first-seen tie-break.
|
|
223
|
+
longest = max(
|
|
224
|
+
candidates,
|
|
225
|
+
key=lambda transcript: length_table[transcript.transcript_id],
|
|
226
|
+
)
|
|
227
|
+
else:
|
|
228
|
+
# AGAT has no length criterion for isoforms lacking both CDS and
|
|
229
|
+
# exon. Keep the first one so this extractor still emits one
|
|
230
|
+
# deterministic isoform per gene, and report how often this occurs.
|
|
231
|
+
longest = isoforms[0]
|
|
232
|
+
no_length_feature_count += 1
|
|
233
|
+
selected.add(longest.transcript_id)
|
|
234
|
+
|
|
235
|
+
return (
|
|
236
|
+
selected,
|
|
237
|
+
len(transcripts_by_gene),
|
|
238
|
+
len(transcripts),
|
|
239
|
+
no_length_feature_count,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def replace_parent_attribute(attribute_text: str, parents: list[str]) -> str:
|
|
244
|
+
items = attribute_text.rstrip("\n\r").split(";")
|
|
245
|
+
for index, item in enumerate(items):
|
|
246
|
+
if item.startswith("Parent="):
|
|
247
|
+
items[index] = "Parent=" + ",".join(parents)
|
|
248
|
+
break
|
|
249
|
+
return ";".join(items)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def write_selected_features(input_path: Path, output_path: Path,
|
|
253
|
+
selected: set[str]) -> None:
|
|
254
|
+
# IDs of retained descendants allow nested GFF3 structures to be preserved.
|
|
255
|
+
retained_ids = set(selected)
|
|
256
|
+
in_fasta = False
|
|
257
|
+
|
|
258
|
+
with open_text(input_path, "r") as source, open_text(output_path, "w") as target:
|
|
259
|
+
for line_number, line in enumerate(source, 1):
|
|
260
|
+
if in_fasta:
|
|
261
|
+
target.write(line)
|
|
262
|
+
continue
|
|
263
|
+
if line.startswith("##FASTA"):
|
|
264
|
+
in_fasta = True
|
|
265
|
+
target.write(line)
|
|
266
|
+
continue
|
|
267
|
+
if not line.strip() or line.startswith("#"):
|
|
268
|
+
target.write(line)
|
|
269
|
+
continue
|
|
270
|
+
|
|
271
|
+
fields = parse_feature_line(line, input_path, line_number)
|
|
272
|
+
feature_type = fields[2].lower()
|
|
273
|
+
attributes = parse_attributes(fields[8])
|
|
274
|
+
feature_id = attributes.get("ID")
|
|
275
|
+
parents = list(split_parents(attributes))
|
|
276
|
+
|
|
277
|
+
if feature_type in TRANSCRIPT_TYPES:
|
|
278
|
+
keep = feature_id in selected
|
|
279
|
+
elif not parents:
|
|
280
|
+
# Keep top-level features such as gene, pseudogene and region.
|
|
281
|
+
keep = True
|
|
282
|
+
else:
|
|
283
|
+
kept_parents = [parent for parent in parents if parent in retained_ids]
|
|
284
|
+
keep = bool(kept_parents)
|
|
285
|
+
if keep and kept_parents != parents:
|
|
286
|
+
fields[8] = replace_parent_attribute(fields[8], kept_parents)
|
|
287
|
+
line = "\t".join(fields) + "\n"
|
|
288
|
+
|
|
289
|
+
if keep:
|
|
290
|
+
target.write(line)
|
|
291
|
+
if feature_id:
|
|
292
|
+
retained_ids.add(feature_id)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def main() -> int:
|
|
296
|
+
args = parse_args()
|
|
297
|
+
output_dir = args.output_dir.expanduser().resolve()
|
|
298
|
+
input_files = collect_input_files(args)
|
|
299
|
+
|
|
300
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
301
|
+
output_paths = [output_dir / output_name(path) for path in input_files]
|
|
302
|
+
existing = [path for path in output_paths if path.exists()]
|
|
303
|
+
if existing and not args.force:
|
|
304
|
+
print("ERROR: output file(s) already exist; use --force to overwrite:",
|
|
305
|
+
file=sys.stderr)
|
|
306
|
+
for path in existing:
|
|
307
|
+
print(f" {path}", file=sys.stderr)
|
|
308
|
+
return 2
|
|
309
|
+
|
|
310
|
+
print(f"Found {len(input_files)} GFF file(s).")
|
|
311
|
+
for index, (input_path, output_path) in enumerate(
|
|
312
|
+
zip(input_files, output_paths), 1
|
|
313
|
+
):
|
|
314
|
+
print(f"[{index}/{len(input_files)}] {input_path.name}", flush=True)
|
|
315
|
+
selected, gene_count, transcript_count, fallback_count = (
|
|
316
|
+
find_longest_transcripts(input_path)
|
|
317
|
+
)
|
|
318
|
+
write_selected_features(input_path, output_path, selected)
|
|
319
|
+
print(
|
|
320
|
+
f" genes={gene_count:,}; transcripts={transcript_count:,}; "
|
|
321
|
+
f"selected={len(selected):,}; output={output_path.name}"
|
|
322
|
+
)
|
|
323
|
+
if fallback_count:
|
|
324
|
+
print(
|
|
325
|
+
f" WARNING: {fallback_count:,} gene(s) had no CDS or exon; "
|
|
326
|
+
"the first isoform was retained."
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
print(f"Done. Output directory: {output_dir}")
|
|
330
|
+
return 0
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
if __name__ == "__main__":
|
|
334
|
+
try:
|
|
335
|
+
raise SystemExit(main())
|
|
336
|
+
except (OSError, ValueError) as error:
|
|
337
|
+
print(f"ERROR: {error}", file=sys.stderr)
|
|
338
|
+
raise SystemExit(1)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Calculate basic gene annotation statistics from GFF/GFF3 files."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import csv
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Iterable
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
HEADER = [
|
|
14
|
+
"species",
|
|
15
|
+
"Gene Number",
|
|
16
|
+
"Average Gene Length(bp)",
|
|
17
|
+
"Average Transcripts Length(bp)",
|
|
18
|
+
"Average CDS Length(bp)",
|
|
19
|
+
"Average exons per gene",
|
|
20
|
+
"Average exon Length(bp)",
|
|
21
|
+
"Average UTR Length(bp)",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
# Common GFF3 transcript feature types. Matching is case-insensitive.
|
|
25
|
+
TRANSCRIPT_TYPES = {
|
|
26
|
+
"mrna",
|
|
27
|
+
"transcript",
|
|
28
|
+
"primary_transcript",
|
|
29
|
+
"ncrna",
|
|
30
|
+
"lnc_rna",
|
|
31
|
+
"trna",
|
|
32
|
+
"rrna",
|
|
33
|
+
"snrna",
|
|
34
|
+
"snorna",
|
|
35
|
+
"mirna",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_args() -> argparse.Namespace:
|
|
40
|
+
parser = argparse.ArgumentParser(
|
|
41
|
+
description=(
|
|
42
|
+
"统计单个 GFF/GFF3 文件或目录中所有 GFF/GFF3 文件,并输出制表符分隔的统计表。"
|
|
43
|
+
)
|
|
44
|
+
)
|
|
45
|
+
inputs = parser.add_mutually_exclusive_group(required=True)
|
|
46
|
+
inputs.add_argument("-i", "--input", type=Path, help="单个 .gff 或 .gff3 文件")
|
|
47
|
+
inputs.add_argument(
|
|
48
|
+
"-f", "--folder", type=Path, help="包含 .gff/.gff3 文件的目录(不递归)"
|
|
49
|
+
)
|
|
50
|
+
parser.add_argument(
|
|
51
|
+
"-o",
|
|
52
|
+
"--output",
|
|
53
|
+
type=Path,
|
|
54
|
+
default=Path("gffstat.txt"),
|
|
55
|
+
help="输出文件(默认:当前目录下的 gffstat.txt)",
|
|
56
|
+
)
|
|
57
|
+
return parser.parse_args()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def species_name(gff_path: Path) -> str:
|
|
61
|
+
"""Return the complete filename before its final .gff/.gff3 suffix."""
|
|
62
|
+
name_lower = gff_path.name.lower()
|
|
63
|
+
for suffix in (".gff3", ".gff"):
|
|
64
|
+
if name_lower.endswith(suffix):
|
|
65
|
+
return gff_path.name[: -len(suffix)]
|
|
66
|
+
raise ValueError(f"不是 .gff 或 .gff3 文件:{gff_path}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def mean(total: int, number: int) -> float:
|
|
70
|
+
return total / number if number else 0.0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def calculate_statistics(gff_path: Path) -> list[str | int]:
|
|
74
|
+
gene_count = 0
|
|
75
|
+
transcript_count = 0
|
|
76
|
+
exon_count = 0
|
|
77
|
+
gene_length = 0
|
|
78
|
+
transcript_length = 0
|
|
79
|
+
exon_length = 0
|
|
80
|
+
cds_length = 0
|
|
81
|
+
utr_length = 0
|
|
82
|
+
|
|
83
|
+
with gff_path.open("r", encoding="utf-8") as handle:
|
|
84
|
+
for line_number, line in enumerate(handle, start=1):
|
|
85
|
+
if not line.strip() or line.startswith("#"):
|
|
86
|
+
continue
|
|
87
|
+
|
|
88
|
+
fields = line.rstrip("\n\r").split("\t")
|
|
89
|
+
if len(fields) != 9:
|
|
90
|
+
print(
|
|
91
|
+
f"警告:跳过 {gff_path} 第 {line_number} 行(不是 9 列)",
|
|
92
|
+
file=sys.stderr,
|
|
93
|
+
)
|
|
94
|
+
continue
|
|
95
|
+
|
|
96
|
+
feature_type = fields[2].lower()
|
|
97
|
+
try:
|
|
98
|
+
start = int(fields[3])
|
|
99
|
+
end = int(fields[4])
|
|
100
|
+
except ValueError:
|
|
101
|
+
print(
|
|
102
|
+
f"警告:跳过 {gff_path} 第 {line_number} 行(坐标不是整数)",
|
|
103
|
+
file=sys.stderr,
|
|
104
|
+
)
|
|
105
|
+
continue
|
|
106
|
+
|
|
107
|
+
if start < 1 or end < start:
|
|
108
|
+
print(
|
|
109
|
+
f"警告:跳过 {gff_path} 第 {line_number} 行(坐标范围无效)",
|
|
110
|
+
file=sys.stderr,
|
|
111
|
+
)
|
|
112
|
+
continue
|
|
113
|
+
|
|
114
|
+
length = end - start + 1
|
|
115
|
+
if feature_type == "gene":
|
|
116
|
+
gene_count += 1
|
|
117
|
+
gene_length += length
|
|
118
|
+
elif feature_type in TRANSCRIPT_TYPES:
|
|
119
|
+
transcript_count += 1
|
|
120
|
+
transcript_length += length
|
|
121
|
+
elif feature_type == "exon":
|
|
122
|
+
exon_count += 1
|
|
123
|
+
exon_length += length
|
|
124
|
+
elif feature_type == "cds":
|
|
125
|
+
cds_length += length
|
|
126
|
+
elif "utr" in feature_type:
|
|
127
|
+
# Includes UTR, five_prime_UTR, three_prime_UTR and common variants.
|
|
128
|
+
utr_length += length
|
|
129
|
+
|
|
130
|
+
return [
|
|
131
|
+
species_name(gff_path),
|
|
132
|
+
gene_count,
|
|
133
|
+
f"{mean(gene_length, gene_count):.2f}",
|
|
134
|
+
f"{mean(transcript_length, transcript_count):.2f}",
|
|
135
|
+
f"{mean(cds_length, gene_count):.2f}",
|
|
136
|
+
f"{mean(exon_count, gene_count):.2f}",
|
|
137
|
+
f"{mean(exon_length, exon_count):.2f}",
|
|
138
|
+
f"{mean(utr_length, gene_count):.2f}",
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def collect_gff_files(args: argparse.Namespace) -> list[Path]:
|
|
143
|
+
if args.input is not None:
|
|
144
|
+
path = args.input
|
|
145
|
+
if not path.is_file():
|
|
146
|
+
raise ValueError(f"输入文件不存在或不是普通文件:{path}")
|
|
147
|
+
if path.suffix.lower() not in {".gff", ".gff3"}:
|
|
148
|
+
raise ValueError(f"输入文件后缀必须是 .gff 或 .gff3:{path}")
|
|
149
|
+
return [path]
|
|
150
|
+
|
|
151
|
+
folder = args.folder
|
|
152
|
+
if not folder.is_dir():
|
|
153
|
+
raise ValueError(f"输入目录不存在或不是目录:{folder}")
|
|
154
|
+
|
|
155
|
+
files = sorted(
|
|
156
|
+
(
|
|
157
|
+
path
|
|
158
|
+
for path in folder.iterdir()
|
|
159
|
+
if path.is_file() and path.suffix.lower() in {".gff", ".gff3"}
|
|
160
|
+
),
|
|
161
|
+
key=lambda path: path.name,
|
|
162
|
+
)
|
|
163
|
+
if not files:
|
|
164
|
+
raise ValueError(f"目录中没有 .gff 或 .gff3 文件:{folder}")
|
|
165
|
+
return files
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def write_table(rows: Iterable[list[str | int]], output_path: Path) -> None:
|
|
169
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
with output_path.open("w", encoding="utf-8", newline="") as handle:
|
|
171
|
+
writer = csv.writer(handle, delimiter="\t", lineterminator="\n")
|
|
172
|
+
writer.writerow(HEADER)
|
|
173
|
+
writer.writerows(rows)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def main() -> int:
|
|
177
|
+
args = parse_args()
|
|
178
|
+
try:
|
|
179
|
+
gff_files = collect_gff_files(args)
|
|
180
|
+
output_resolved = args.output.resolve()
|
|
181
|
+
if any(path.resolve() == output_resolved for path in gff_files):
|
|
182
|
+
raise ValueError("输出文件不能与输入 GFF 文件相同")
|
|
183
|
+
rows = [calculate_statistics(path) for path in gff_files]
|
|
184
|
+
write_table(rows, args.output)
|
|
185
|
+
except (OSError, UnicodeError, ValueError) as error:
|
|
186
|
+
print(f"错误:{error}", file=sys.stderr)
|
|
187
|
+
return 1
|
|
188
|
+
|
|
189
|
+
print(f"已统计 {len(gff_files)} 个文件,结果写入:{args.output}")
|
|
190
|
+
return 0
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
if __name__ == "__main__":
|
|
194
|
+
raise SystemExit(main())
|
|
@@ -60,6 +60,34 @@ def cmd_rename_sort(args: argparse.Namespace, extra: List[str]) -> int:
|
|
|
60
60
|
return _run_legacy_main(mod.main, "gffkit rename-sort", cli)
|
|
61
61
|
|
|
62
62
|
|
|
63
|
+
def cmd_get_longest_transcript(args: argparse.Namespace, extra: List[str]) -> int:
|
|
64
|
+
"""Run longest-transcript extraction as a standalone command."""
|
|
65
|
+
from . import get_longest_transcript as mod
|
|
66
|
+
|
|
67
|
+
cli = ["-i", args.input] if args.input else ["-f", args.folder]
|
|
68
|
+
cli += ["-o", args.output_dir]
|
|
69
|
+
if args.force:
|
|
70
|
+
cli.append("--force")
|
|
71
|
+
cli += extra
|
|
72
|
+
try:
|
|
73
|
+
return _run_legacy_main(
|
|
74
|
+
mod.main, "gffkit get_longest_transcript", cli
|
|
75
|
+
)
|
|
76
|
+
except (OSError, ValueError) as error:
|
|
77
|
+
print(f"ERROR: {error}", file=sys.stderr)
|
|
78
|
+
return 1
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def cmd_stat(args: argparse.Namespace, extra: List[str]) -> int:
|
|
82
|
+
"""Calculate GFF annotation statistics as a standalone command."""
|
|
83
|
+
from . import gffstat as mod
|
|
84
|
+
|
|
85
|
+
cli = ["-i", args.input] if args.input else ["-f", args.folder]
|
|
86
|
+
cli += ["-o", args.output]
|
|
87
|
+
cli += extra
|
|
88
|
+
return _run_legacy_main(mod.main, "gffkit stat", cli)
|
|
89
|
+
|
|
90
|
+
|
|
63
91
|
def cmd_integrate(args: argparse.Namespace, extra: List[str]) -> int:
|
|
64
92
|
"""Run the full annotation integration workflow."""
|
|
65
93
|
from . import detect_bridge_merged_genes as detect_mod
|
|
@@ -138,7 +166,10 @@ def cmd_integrate(args: argparse.Namespace, extra: List[str]) -> int:
|
|
|
138
166
|
def build_parser() -> argparse.ArgumentParser:
|
|
139
167
|
parser = argparse.ArgumentParser(
|
|
140
168
|
prog="gffkit",
|
|
141
|
-
description=
|
|
169
|
+
description=(
|
|
170
|
+
"Utilities for GFF annotation integration, longest-transcript "
|
|
171
|
+
"selection, and annotation statistics."
|
|
172
|
+
),
|
|
142
173
|
)
|
|
143
174
|
parser.add_argument("--version", action="version", version=f"gffkit {__version__}")
|
|
144
175
|
|
|
@@ -186,6 +217,52 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
186
217
|
p.add_argument("--keep-old-ids", action="store_true", help="Keep old ID/Parent as old_ID/old_Parent.")
|
|
187
218
|
p.set_defaults(handler=cmd_rename_sort)
|
|
188
219
|
|
|
220
|
+
p = subparsers.add_parser(
|
|
221
|
+
"get_longest_transcript",
|
|
222
|
+
help="Keep the longest transcript isoform for each gene.",
|
|
223
|
+
description=(
|
|
224
|
+
"Select one transcript per gene using the longest concatenated "
|
|
225
|
+
"CDS, or concatenated exons when no isoform has CDS. This is a "
|
|
226
|
+
"standalone command and is not part of integrate."
|
|
227
|
+
),
|
|
228
|
+
)
|
|
229
|
+
inputs = p.add_mutually_exclusive_group(required=True)
|
|
230
|
+
inputs.add_argument("-i", "--input", help="Single input .gff/.gff3 file.")
|
|
231
|
+
inputs.add_argument(
|
|
232
|
+
"-f", "--folder",
|
|
233
|
+
help="Directory containing .gff/.gff3 files (non-recursive).",
|
|
234
|
+
)
|
|
235
|
+
p.add_argument(
|
|
236
|
+
"-o", "--output-dir", required=True,
|
|
237
|
+
help="Directory in which longest-transcript GFF files are written.",
|
|
238
|
+
)
|
|
239
|
+
p.add_argument(
|
|
240
|
+
"--force", action="store_true",
|
|
241
|
+
help="Overwrite output files that already exist (default: refuse).",
|
|
242
|
+
)
|
|
243
|
+
p.set_defaults(handler=cmd_get_longest_transcript)
|
|
244
|
+
|
|
245
|
+
p = subparsers.add_parser(
|
|
246
|
+
"stat",
|
|
247
|
+
help="Calculate basic annotation statistics for GFF files.",
|
|
248
|
+
description=(
|
|
249
|
+
"Calculate gene, transcript, CDS, exon, and UTR statistics for "
|
|
250
|
+
"one GFF file or a directory of GFF files. This is a standalone "
|
|
251
|
+
"command and is not part of integrate."
|
|
252
|
+
),
|
|
253
|
+
)
|
|
254
|
+
inputs = p.add_mutually_exclusive_group(required=True)
|
|
255
|
+
inputs.add_argument("-i", "--input", help="Single input .gff/.gff3 file.")
|
|
256
|
+
inputs.add_argument(
|
|
257
|
+
"-f", "--folder",
|
|
258
|
+
help="Directory containing .gff/.gff3 files (non-recursive).",
|
|
259
|
+
)
|
|
260
|
+
p.add_argument(
|
|
261
|
+
"-o", "--output", default="gffstat.txt",
|
|
262
|
+
help="Output TSV file. Default: gffstat.txt.",
|
|
263
|
+
)
|
|
264
|
+
p.set_defaults(handler=cmd_stat)
|
|
265
|
+
|
|
189
266
|
p = subparsers.add_parser(
|
|
190
267
|
"integrate",
|
|
191
268
|
help="Run the full A/B region-aware integration, UTR, rename, and sort workflow.",
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: gffkit
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary:
|
|
5
|
-
Author:
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: GFF annotation integration and analysis toolkit
|
|
5
|
+
Author: caijunhao
|
|
6
6
|
License: MIT
|
|
7
7
|
Project-URL: Homepage, https://github.com/qunjie-zhang/gffkit
|
|
8
8
|
Project-URL: Repository, https://github.com/qunjie-zhang/gffkit
|
|
@@ -25,13 +25,19 @@ License-File: LICENSE
|
|
|
25
25
|
|
|
26
26
|
# gffkit
|
|
27
27
|
|
|
28
|
-
`gffkit` is a lightweight toolkit for
|
|
29
|
-
|
|
28
|
+
`gffkit` is a lightweight toolkit for GFF/GTF annotation integration and analysis.
|
|
29
|
+
Version 0.6.0 provides six standalone utilities:
|
|
30
30
|
|
|
31
31
|
1. `detect-bridge`: detect suspicious merged-gene artifacts caused by bridge transcripts.
|
|
32
32
|
2. `complement`: complement/merge annotations, with optional region-swap mode.
|
|
33
33
|
3. `add-utr`: reconstruct `five_prime_UTR` and `three_prime_UTR` features from exon/CDS coordinates.
|
|
34
34
|
4. `rename-sort`: rename gene/transcript/child IDs with a prefix and sort the final GFF3.
|
|
35
|
+
5. `get_longest_transcript`: retain one longest transcript isoform per gene.
|
|
36
|
+
6. `stat`: calculate basic gene-annotation statistics for one GFF or a directory of GFF files.
|
|
37
|
+
|
|
38
|
+
The `integrate` workflow continues to use only the original four integration
|
|
39
|
+
utilities. `get_longest_transcript` and `stat` are independent commands and are
|
|
40
|
+
not automatically run by `integrate`.
|
|
35
41
|
|
|
36
42
|
## Installation
|
|
37
43
|
|
|
@@ -102,6 +108,56 @@ gffkit complement \
|
|
|
102
108
|
-t 8
|
|
103
109
|
```
|
|
104
110
|
|
|
111
|
+
### Extract the longest transcript
|
|
112
|
+
|
|
113
|
+
For each gene, `get_longest_transcript` selects the isoform with the longest
|
|
114
|
+
concatenated CDS. If none of a gene's isoforms has CDS features, it uses the
|
|
115
|
+
longest concatenated exon length. Ties retain the first isoform encountered in
|
|
116
|
+
the input file.
|
|
117
|
+
|
|
118
|
+
Process one GFF/GFF3 file:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
gffkit get_longest_transcript \
|
|
122
|
+
-i annotation.gff3 \
|
|
123
|
+
-o longest_gff
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Process all `.gff`/`.gff3` files directly inside a directory:
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
gffkit get_longest_transcript \
|
|
130
|
+
-f input_gff_directory \
|
|
131
|
+
-o longest_gff
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Compressed `.gff.gz` and `.gff3.gz` inputs are also supported by this command.
|
|
135
|
+
Output files are named `*.longest.gff` or `*.longest.gff3`. Existing output
|
|
136
|
+
files are refused unless `--force` is supplied.
|
|
137
|
+
|
|
138
|
+
### Calculate annotation statistics
|
|
139
|
+
|
|
140
|
+
Process one GFF/GFF3 file and write the default `gffstat.txt`:
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
gffkit stat -i annotation.gff3
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Process all `.gff`/`.gff3` files directly inside a directory and select an
|
|
147
|
+
output path:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
gffkit stat \
|
|
151
|
+
-f input_gff_directory \
|
|
152
|
+
-o annotation.gffstat.txt
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The tab-separated output contains species/file name, gene count, average gene
|
|
156
|
+
span, average transcript span, average CDS length per gene, average exon count
|
|
157
|
+
per gene, average exon length, and average UTR length per gene. Gene and
|
|
158
|
+
transcript lengths use their GFF genomic spans (`end - start + 1`); they are not
|
|
159
|
+
spliced mature-transcript lengths.
|
|
160
|
+
|
|
105
161
|
## Command overview
|
|
106
162
|
|
|
107
163
|
```bash
|
|
@@ -110,13 +166,15 @@ gffkit detect-bridge --help
|
|
|
110
166
|
gffkit complement --help
|
|
111
167
|
gffkit add-utr --help
|
|
112
168
|
gffkit rename-sort --help
|
|
169
|
+
gffkit get_longest_transcript --help
|
|
170
|
+
gffkit stat --help
|
|
113
171
|
gffkit integrate --help
|
|
114
172
|
```
|
|
115
173
|
|
|
116
174
|
## Parallel Processing
|
|
117
175
|
|
|
118
176
|
Use `-t/--threads` to select the number of worker processes. The option name is
|
|
119
|
-
kept for command-line compatibility, but version 0.5.0 uses processes for
|
|
177
|
+
kept for command-line compatibility, but version 0.5.0 and later uses processes for
|
|
120
178
|
CPU-bound work so that Python's GIL does not restrict execution to one core.
|
|
121
179
|
|
|
122
180
|
- `detect-bridge` analyzes genes with a process pool and batches tasks to reduce process communication overhead.
|
|
@@ -142,6 +200,7 @@ large annotations.
|
|
|
142
200
|
- UTR features are reconstructed after merging using an exon-minus-CDS strategy.
|
|
143
201
|
- Version 0.4.0 and later run `rename-sort` as the final `integrate` step. The final GFF3 keeps chromosome-mounted records, removes unplaced/scaffold/contig records, sorts features, rewrites `ID`/`Parent`, and writes an ID map next to the output.
|
|
144
202
|
- Version 0.5.0 replaces CPU-bound threads with worker processes and adds a dynamic interval index for faster annotation overlap searches.
|
|
203
|
+
- Version 0.6.0 adds the independent `get_longest_transcript` and `stat` commands. Neither command is included in `integrate`.
|
|
145
204
|
- When multiple tools annotate the same gene locus, the GFF source column is combined with `|`, for example `EviAnn|ANNEVO`.
|
|
146
205
|
|
|
147
206
|
## Rename and Sort
|
|
@@ -159,6 +218,16 @@ gffkit rename-sort \
|
|
|
159
218
|
|
|
160
219
|
This writes `sample.renamed.sorted.gff3` and `sample.renamed.sorted.gff3.id_map.tsv`.
|
|
161
220
|
|
|
221
|
+
## Version 0.6.0 changes
|
|
222
|
+
|
|
223
|
+
- Added `gffkit get_longest_transcript` using the longest-CDS/longest-exon selection logic from `get_longest_transcript.py`.
|
|
224
|
+
- Added mutually exclusive `-i/--input` single-file and `-f/--folder` directory input modes for longest-transcript extraction.
|
|
225
|
+
- Added `gffkit stat` using the GFF statistics implementation from `gffstat.py`.
|
|
226
|
+
- Added mutually exclusive `-i/--input` single-file and `-f/--folder` directory input modes for annotation statistics.
|
|
227
|
+
- Kept both new commands independent from the four-step `gffkit integrate` workflow.
|
|
228
|
+
- Updated the package version from 0.5.0 to 0.6.0.
|
|
229
|
+
- Updated package author and credits to `caijunhao`.
|
|
230
|
+
|
|
162
231
|
## Maintainer notes
|
|
163
232
|
|
|
164
233
|
When command-line options or behavior changes, update this `README.md` in the versioned package directory before building and uploading to PyPI.
|
|
@@ -166,3 +235,7 @@ When command-line options or behavior changes, update this `README.md` in the ve
|
|
|
166
235
|
## License
|
|
167
236
|
|
|
168
237
|
MIT License.
|
|
238
|
+
|
|
239
|
+
## Credits
|
|
240
|
+
|
|
241
|
+
Author: caijunhao
|
|
@@ -7,6 +7,8 @@ src/gffkit/__main__.py
|
|
|
7
7
|
src/gffkit/add_utr.py
|
|
8
8
|
src/gffkit/complement_annotations.py
|
|
9
9
|
src/gffkit/detect_bridge_merged_genes.py
|
|
10
|
+
src/gffkit/get_longest_transcript.py
|
|
11
|
+
src/gffkit/gffstat.py
|
|
10
12
|
src/gffkit/main.py
|
|
11
13
|
src/gffkit/rename_sort_gff3.py
|
|
12
14
|
src/gffkit.egg-info/PKG-INFO
|
|
@@ -14,6 +16,7 @@ src/gffkit.egg-info/SOURCES.txt
|
|
|
14
16
|
src/gffkit.egg-info/dependency_links.txt
|
|
15
17
|
src/gffkit.egg-info/entry_points.txt
|
|
16
18
|
src/gffkit.egg-info/top_level.txt
|
|
19
|
+
tests/test_analysis_commands.py
|
|
17
20
|
tests/test_complement_sources.py
|
|
18
21
|
tests/test_parallel_performance.py
|
|
19
22
|
tests/test_rename_sort.py
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
|
|
3
|
+
from gffkit import main as gffkit_main
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def write_multi_isoform_gff(path):
|
|
7
|
+
path.write_text(
|
|
8
|
+
"\n".join(
|
|
9
|
+
[
|
|
10
|
+
"##gff-version 3",
|
|
11
|
+
"chr1\ttest\tgene\t1\t500\t.\t+\t.\tID=g1",
|
|
12
|
+
"chr1\ttest\tmRNA\t1\t200\t.\t+\t.\tID=t1;Parent=g1",
|
|
13
|
+
"chr1\ttest\texon\t1\t100\t.\t+\t.\tID=e1;Parent=t1",
|
|
14
|
+
"chr1\ttest\tCDS\t1\t90\t.\t+\t0\tID=c1;Parent=t1",
|
|
15
|
+
"chr1\ttest\tfive_prime_UTR\t91\t100\t.\t+\t.\tID=u1;Parent=t1",
|
|
16
|
+
"chr1\ttest\tmRNA\t1\t500\t.\t+\t.\tID=t2;Parent=g1",
|
|
17
|
+
"chr1\ttest\texon\t1\t250\t.\t+\t.\tID=e2;Parent=t2",
|
|
18
|
+
"chr1\ttest\tCDS\t1\t240\t.\t+\t0\tID=c2;Parent=t2",
|
|
19
|
+
"chr1\ttest\tthree_prime_UTR\t241\t250\t.\t+\t.\tID=u2;Parent=t2",
|
|
20
|
+
"",
|
|
21
|
+
]
|
|
22
|
+
),
|
|
23
|
+
encoding="utf-8",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_get_longest_transcript_subcommand_single_file(tmp_path):
|
|
28
|
+
input_gff = tmp_path / "sample.gff3"
|
|
29
|
+
output_dir = tmp_path / "longest"
|
|
30
|
+
write_multi_isoform_gff(input_gff)
|
|
31
|
+
|
|
32
|
+
result = gffkit_main.main(
|
|
33
|
+
[
|
|
34
|
+
"get_longest_transcript",
|
|
35
|
+
"-i",
|
|
36
|
+
str(input_gff),
|
|
37
|
+
"-o",
|
|
38
|
+
str(output_dir),
|
|
39
|
+
]
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
assert result == 0
|
|
43
|
+
output_text = (output_dir / "sample.longest.gff3").read_text(
|
|
44
|
+
encoding="utf-8"
|
|
45
|
+
)
|
|
46
|
+
assert "ID=t2;Parent=g1" in output_text
|
|
47
|
+
assert "ID=t1;Parent=g1" not in output_text
|
|
48
|
+
assert "ID=e2;Parent=t2" in output_text
|
|
49
|
+
assert "ID=e1;Parent=t1" not in output_text
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_get_longest_transcript_subcommand_folder(tmp_path):
|
|
53
|
+
input_dir = tmp_path / "inputs"
|
|
54
|
+
input_dir.mkdir()
|
|
55
|
+
write_multi_isoform_gff(input_dir / "sample_a.gff3")
|
|
56
|
+
write_multi_isoform_gff(input_dir / "sample_b.gff")
|
|
57
|
+
(input_dir / "ignore.txt").write_text("not a GFF\n", encoding="utf-8")
|
|
58
|
+
output_dir = tmp_path / "longest"
|
|
59
|
+
|
|
60
|
+
result = gffkit_main.main(
|
|
61
|
+
[
|
|
62
|
+
"get_longest_transcript",
|
|
63
|
+
"-f",
|
|
64
|
+
str(input_dir),
|
|
65
|
+
"-o",
|
|
66
|
+
str(output_dir),
|
|
67
|
+
]
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
assert result == 0
|
|
71
|
+
assert sorted(path.name for path in output_dir.iterdir()) == [
|
|
72
|
+
"sample_a.longest.gff3",
|
|
73
|
+
"sample_b.longest.gff",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_stat_subcommand_single_file(tmp_path):
|
|
78
|
+
input_gff = tmp_path / "sample.gff3"
|
|
79
|
+
output_tsv = tmp_path / "gffstat.txt"
|
|
80
|
+
write_multi_isoform_gff(input_gff)
|
|
81
|
+
|
|
82
|
+
result = gffkit_main.main(
|
|
83
|
+
["stat", "-i", str(input_gff), "-o", str(output_tsv)]
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
assert result == 0
|
|
87
|
+
with output_tsv.open(encoding="utf-8") as handle:
|
|
88
|
+
rows = list(csv.DictReader(handle, delimiter="\t"))
|
|
89
|
+
|
|
90
|
+
assert len(rows) == 1
|
|
91
|
+
assert rows[0]["species"] == "sample"
|
|
92
|
+
assert rows[0]["Gene Number"] == "1"
|
|
93
|
+
assert rows[0]["Average Gene Length(bp)"] == "500.00"
|
|
94
|
+
assert rows[0]["Average Transcripts Length(bp)"] == "350.00"
|
|
95
|
+
assert rows[0]["Average CDS Length(bp)"] == "330.00"
|
|
96
|
+
assert rows[0]["Average exons per gene"] == "2.00"
|
|
97
|
+
assert rows[0]["Average exon Length(bp)"] == "175.00"
|
|
98
|
+
assert rows[0]["Average UTR Length(bp)"] == "20.00"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_stat_subcommand_folder(tmp_path):
|
|
102
|
+
input_dir = tmp_path / "inputs"
|
|
103
|
+
input_dir.mkdir()
|
|
104
|
+
write_multi_isoform_gff(input_dir / "sample_a.gff3")
|
|
105
|
+
write_multi_isoform_gff(input_dir / "sample_b.gff")
|
|
106
|
+
output_tsv = tmp_path / "folder.gffstat.txt"
|
|
107
|
+
|
|
108
|
+
result = gffkit_main.main(
|
|
109
|
+
["stat", "-f", str(input_dir), "-o", str(output_tsv)]
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
assert result == 0
|
|
113
|
+
with output_tsv.open(encoding="utf-8") as handle:
|
|
114
|
+
rows = list(csv.DictReader(handle, delimiter="\t"))
|
|
115
|
+
assert [row["species"] for row in rows] == ["sample_a", "sample_b"]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|