gffkit 0.4.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.
Files changed (25) hide show
  1. {gffkit-0.4.0/src/gffkit.egg-info → gffkit-0.6.0}/PKG-INFO +92 -10
  2. gffkit-0.6.0/README.md +216 -0
  3. {gffkit-0.4.0 → gffkit-0.6.0}/pyproject.toml +3 -3
  4. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit/__init__.py +1 -1
  5. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit/complement_annotations.py +104 -32
  6. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit/detect_bridge_merged_genes.py +13 -5
  7. gffkit-0.6.0/src/gffkit/get_longest_transcript.py +338 -0
  8. gffkit-0.6.0/src/gffkit/gffstat.py +194 -0
  9. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit/main.py +81 -4
  10. {gffkit-0.4.0 → gffkit-0.6.0/src/gffkit.egg-info}/PKG-INFO +92 -10
  11. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit.egg-info/SOURCES.txt +4 -0
  12. gffkit-0.6.0/tests/test_analysis_commands.py +115 -0
  13. gffkit-0.6.0/tests/test_parallel_performance.py +81 -0
  14. gffkit-0.4.0/README.md +0 -134
  15. {gffkit-0.4.0 → gffkit-0.6.0}/LICENSE +0 -0
  16. {gffkit-0.4.0 → gffkit-0.6.0}/MANIFEST.in +0 -0
  17. {gffkit-0.4.0 → gffkit-0.6.0}/setup.cfg +0 -0
  18. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit/__main__.py +0 -0
  19. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit/add_utr.py +0 -0
  20. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit/rename_sort_gff3.py +0 -0
  21. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit.egg-info/dependency_links.txt +0 -0
  22. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit.egg-info/entry_points.txt +0 -0
  23. {gffkit-0.4.0 → gffkit-0.6.0}/src/gffkit.egg-info/top_level.txt +0 -0
  24. {gffkit-0.4.0 → gffkit-0.6.0}/tests/test_complement_sources.py +0 -0
  25. {gffkit-0.4.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.0
4
- Summary: Region-aware GFF annotation integration toolkit
5
- Author: Qunjie Zhang
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 region-aware GFF/GTF annotation integration.
29
- It combines four utilities:
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,16 +166,21 @@ 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
- ## Threads
174
+ ## Parallel Processing
117
175
 
118
- Version 0.3 and later add `-t/--threads`.
176
+ Use `-t/--threads` to select the number of worker processes. The option name is
177
+ kept for command-line compatibility, but version 0.5.0 and later uses processes for
178
+ CPU-bound work so that Python's GIL does not restrict execution to one core.
119
179
 
120
- - `detect-bridge` analyzes genes in parallel.
121
- - `complement` pre-parses multiple `--add` files in parallel, then merges them in the original command-line order.
122
- - `integrate` passes the thread count to the detect and complement steps.
180
+ - `detect-bridge` analyzes genes with a process pool and batches tasks to reduce process communication overhead.
181
+ - `complement` parses the reference and supplementary files in parallel, then merges them in the original command-line order.
182
+ - `complement` uses a dynamic chromosome interval index to compare each supplementary gene only with nearby overlapping reference genes.
183
+ - `integrate` passes the worker count to the detect and complement steps. `add-utr` and `rename-sort` remain single-process.
123
184
 
124
185
  Example:
125
186
 
@@ -127,12 +188,19 @@ Example:
127
188
  gffkit integrate --annotation-a EviAnn.gff3 --annotation-b ANNEVO.gff3 -t 16
128
189
  ```
129
190
 
191
+ During `detect-bridge`, multiple worker processes should be visible in `top` or
192
+ `htop`. CPU usage naturally drops during the single-process UTR and rename/sort
193
+ steps. More workers also increase memory use; start with `-t 4` or `-t 8` for
194
+ large annotations.
195
+
130
196
  ## Annotation integration strategy
131
197
 
132
198
  - Annotation A, for example EviAnn/RNA-seq-supported GFF, is used as the global primary reference.
133
199
  - Annotation B, for example ANNEVO/deep-learning GFF, is used as the local primary reference only in suspicious merged-gene regions.
134
200
  - UTR features are reconstructed after merging using an exon-minus-CDS strategy.
135
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.
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`.
136
204
  - When multiple tools annotate the same gene locus, the GFF source column is combined with `|`, for example `EviAnn|ANNEVO`.
137
205
 
138
206
  ## Rename and Sort
@@ -150,6 +218,16 @@ gffkit rename-sort \
150
218
 
151
219
  This writes `sample.renamed.sorted.gff3` and `sample.renamed.sorted.gff3.id_map.tsv`.
152
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
+
153
231
  ## Maintainer notes
154
232
 
155
233
  When command-line options or behavior changes, update this `README.md` in the versioned package directory before building and uploading to PyPI.
@@ -157,3 +235,7 @@ When command-line options or behavior changes, update this `README.md` in the ve
157
235
  ## License
158
236
 
159
237
  MIT License.
238
+
239
+ ## Credits
240
+
241
+ Author: caijunhao
gffkit-0.6.0/README.md ADDED
@@ -0,0 +1,216 @@
1
+ # gffkit
2
+
3
+ `gffkit` is a lightweight toolkit for GFF/GTF annotation integration and analysis.
4
+ Version 0.6.0 provides six standalone utilities:
5
+
6
+ 1. `detect-bridge`: detect suspicious merged-gene artifacts caused by bridge transcripts.
7
+ 2. `complement`: complement/merge annotations, with optional region-swap mode.
8
+ 3. `add-utr`: reconstruct `five_prime_UTR` and `three_prime_UTR` features from exon/CDS coordinates.
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`.
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install gffkit
21
+ ```
22
+
23
+
24
+ ## Quick start
25
+
26
+ ### Full integration pipeline
27
+
28
+ ```bash
29
+ gffkit integrate \
30
+ --annotation-a EviAnn.gff3 \
31
+ --annotation-b ANNEVO.gff3 \
32
+ --outdir gffkit_out \
33
+ --prefix sample \
34
+ -t 8
35
+ ```
36
+
37
+ Outputs:
38
+
39
+ - `gffkit_out/sample.suspicious.tsv`
40
+ - `gffkit_out/sample.merged.gff3`
41
+ - `gffkit_out/sample.final.withUTR.gff3.pre_rename.gff3`
42
+ - `gffkit_out/sample.final.withUTR.gff3`
43
+ - `gffkit_out/sample.final.withUTR.gff3.id_map.tsv`
44
+
45
+ In `integrate`, `--prefix sample` is also used for final ID renaming. Final gene IDs are written like `sample_C01g00001`, transcript IDs like `sample_C01g00001.t1`, and child IDs like `sample_C01g00001.t1.exon1`.
46
+
47
+ ### Step-by-step usage
48
+
49
+ ```bash
50
+ # 1. Detect suspicious merged genes in Annotation A
51
+ gffkit detect-bridge -i EviAnn.gff3 -o suspicious.tsv -t 8
52
+
53
+ # 2. Use A as the global reference, but switch to B in suspicious regions
54
+ gffkit complement \
55
+ --ref EviAnn.gff3 \
56
+ --add ANNEVO.gff3 \
57
+ --swap_region_tsv suspicious.tsv \
58
+ --swap_region_flank 100 \
59
+ --output merged.gff3 \
60
+ -t 8
61
+
62
+ # 3. Add UTR features
63
+ gffkit add-utr -i merged.gff3 -o final.annotation.withUTR.pre_rename.gff3
64
+
65
+ # 4. Rename IDs, drop unplaced seqids, and sort the final GFF3
66
+ gffkit rename-sort \
67
+ -i final.annotation.withUTR.pre_rename.gff3 \
68
+ -o final.annotation.withUTR.gff3 \
69
+ --prefix sample
70
+ ```
71
+
72
+ ### Merge three or more annotations
73
+
74
+ Use repeated `--add` arguments. Files are merged in the order provided.
75
+
76
+ ```bash
77
+ gffkit complement \
78
+ --ref EviAnn.gff3 \
79
+ --add ANNEVO.gff3 \
80
+ --add Helixer.gff3 \
81
+ --add PASA.gff3 \
82
+ --output merged.multi.gff3 \
83
+ -t 8
84
+ ```
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
+
136
+ ## Command overview
137
+
138
+ ```bash
139
+ gffkit --help
140
+ gffkit detect-bridge --help
141
+ gffkit complement --help
142
+ gffkit add-utr --help
143
+ gffkit rename-sort --help
144
+ gffkit get_longest_transcript --help
145
+ gffkit stat --help
146
+ gffkit integrate --help
147
+ ```
148
+
149
+ ## Parallel Processing
150
+
151
+ Use `-t/--threads` to select the number of worker processes. The option name is
152
+ kept for command-line compatibility, but version 0.5.0 and later uses processes for
153
+ CPU-bound work so that Python's GIL does not restrict execution to one core.
154
+
155
+ - `detect-bridge` analyzes genes with a process pool and batches tasks to reduce process communication overhead.
156
+ - `complement` parses the reference and supplementary files in parallel, then merges them in the original command-line order.
157
+ - `complement` uses a dynamic chromosome interval index to compare each supplementary gene only with nearby overlapping reference genes.
158
+ - `integrate` passes the worker count to the detect and complement steps. `add-utr` and `rename-sort` remain single-process.
159
+
160
+ Example:
161
+
162
+ ```bash
163
+ gffkit integrate --annotation-a EviAnn.gff3 --annotation-b ANNEVO.gff3 -t 16
164
+ ```
165
+
166
+ During `detect-bridge`, multiple worker processes should be visible in `top` or
167
+ `htop`. CPU usage naturally drops during the single-process UTR and rename/sort
168
+ steps. More workers also increase memory use; start with `-t 4` or `-t 8` for
169
+ large annotations.
170
+
171
+ ## Annotation integration strategy
172
+
173
+ - Annotation A, for example EviAnn/RNA-seq-supported GFF, is used as the global primary reference.
174
+ - Annotation B, for example ANNEVO/deep-learning GFF, is used as the local primary reference only in suspicious merged-gene regions.
175
+ - UTR features are reconstructed after merging using an exon-minus-CDS strategy.
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.
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`.
179
+ - When multiple tools annotate the same gene locus, the GFF source column is combined with `|`, for example `EviAnn|ANNEVO`.
180
+
181
+ ## Rename and Sort
182
+
183
+ Run this step independently when you already have a merged GFF3:
184
+
185
+ ```bash
186
+ gffkit rename-sort \
187
+ -i merged.withUTR.gff3 \
188
+ -o sample.renamed.sorted.gff3 \
189
+ --prefix sample \
190
+ --digits 5 \
191
+ --keep-old-ids
192
+ ```
193
+
194
+ This writes `sample.renamed.sorted.gff3` and `sample.renamed.sorted.gff3.id_map.tsv`.
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
+
206
+ ## Maintainer notes
207
+
208
+ When command-line options or behavior changes, update this `README.md` in the versioned package directory before building and uploading to PyPI.
209
+
210
+ ## License
211
+
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.4.0"
8
- description = "Region-aware GFF annotation integration toolkit"
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 = "Qunjie Zhang"}
13
+ {name = "caijunhao"}
14
14
  ]
15
15
  keywords = ["GFF3", "GTF", "genome annotation", "bioinformatics", "UTR", "gene annotation"]
16
16
  classifiers = [
@@ -1,3 +1,3 @@
1
1
  """gffkit: region-aware GFF annotation integration utilities."""
2
2
 
3
- __version__ = "0.4.0"
3
+ __version__ = "0.6.0"
@@ -26,7 +26,7 @@ import re
26
26
  import sys
27
27
  from collections import defaultdict
28
28
  from dataclasses import dataclass, field
29
- from concurrent.futures import ThreadPoolExecutor
29
+ from concurrent.futures import ProcessPoolExecutor
30
30
  from typing import Dict, Iterable, List, Optional, Tuple
31
31
 
32
32
 
@@ -256,7 +256,7 @@ class Feature:
256
256
 
257
257
 
258
258
  @dataclass
259
- class AnnotationSet:
259
+ class AnnotationSet:
260
260
  """
261
261
  保存整套注释数据,根节点一般是 gene(也允许是其他顶层特征)。
262
262
  """
@@ -300,7 +300,7 @@ class AnnotationSet:
300
300
  for tag in sorted(counts[level]):
301
301
  eprint(f" {tag}: {counts[level][tag]}")
302
302
 
303
- def write_gff3(self, output_path: Optional[str]) -> None:
303
+ def write_gff3(self, output_path: Optional[str]) -> None:
304
304
  out_fh = open(output_path, "w", encoding="utf-8") if output_path else sys.stdout
305
305
  try:
306
306
  print("##gff-version 3", file=out_fh)
@@ -312,7 +312,56 @@ class AnnotationSet:
312
312
  print(line, file=out_fh)
313
313
  finally:
314
314
  if output_path:
315
- out_fh.close()
315
+ out_fh.close()
316
+
317
+
318
+ class RootIntervalIndex:
319
+ """按 seqid 和固定宽度区间索引一级特征。
320
+
321
+ 索引支持动态追加,因此补充过程中新加入的 gene 会立即参与后续比较。
322
+ query 返回顺序与 ref_set.roots 一致,保持原有合并结果的确定性。
323
+ """
324
+
325
+ BIN_SIZE = 100_000
326
+
327
+ def __init__(self, roots: Iterable[Feature]) -> None:
328
+ self._bins: Dict[str, Dict[int, List[Feature]]] = defaultdict(
329
+ lambda: defaultdict(list)
330
+ )
331
+ self._order: Dict[int, int] = {}
332
+ for root in roots:
333
+ self.add(root)
334
+
335
+ @classmethod
336
+ def _bin_range(cls, start: int, end: int) -> range:
337
+ first = max(0, start - 1) // cls.BIN_SIZE
338
+ last = max(0, end - 1) // cls.BIN_SIZE
339
+ return range(first, last + 1)
340
+
341
+ def add(self, root: Feature) -> None:
342
+ root_key = id(root)
343
+ if root_key in self._order:
344
+ return
345
+ self._order[root_key] = len(self._order)
346
+ for bin_id in self._bin_range(root.start, root.end):
347
+ self._bins[root.seqid][bin_id].append(root)
348
+
349
+ def overlapping(self, feature: Feature) -> List[Feature]:
350
+ candidates: List[Feature] = []
351
+ seen = set()
352
+ seq_bins = self._bins.get(feature.seqid, {})
353
+
354
+ for bin_id in self._bin_range(feature.start, feature.end):
355
+ for root in seq_bins.get(bin_id, []):
356
+ root_key = id(root)
357
+ if root_key in seen:
358
+ continue
359
+ seen.add(root_key)
360
+ if feature.overlaps(root):
361
+ candidates.append(root)
362
+
363
+ candidates.sort(key=lambda root: self._order[id(root)])
364
+ return candidates
316
365
 
317
366
 
318
367
  def make_synthetic_id(prefix: str) -> str:
@@ -617,15 +666,17 @@ def set_tree_source(root: Feature, source: str) -> None:
617
666
  feat.source = source
618
667
 
619
668
 
620
- def update_overlapping_sources(add_root: Feature, ref_roots: List[Feature]) -> List[Feature]:
669
+ def update_overlapping_sources(
670
+ add_root: Feature,
671
+ overlapping_refs: List[Feature],
672
+ ) -> None:
621
673
  """
622
674
  对与 add_root 重叠的已有一级特征,合并双方软件来源并写回第二列。
623
675
 
624
- 返回发生重叠的参考一级特征列表,供后续补充判断复用。
676
+ overlapping_refs 由区间索引计算,避免在这里再次扫描全部参考 gene。
625
677
  """
626
- overlapping_refs = [r for r in ref_roots if add_root.overlaps(r)]
627
678
  if not overlapping_refs:
628
- return []
679
+ return
629
680
 
630
681
  add_sources = collect_source_names(add_root)
631
682
  combined_sources: List[str] = []
@@ -642,10 +693,13 @@ def update_overlapping_sources(add_root: Feature, ref_roots: List[Feature]) -> L
642
693
  for ref_root in overlapping_refs:
643
694
  set_tree_source(ref_root, merged_source)
644
695
 
645
- return overlapping_refs
646
-
647
696
 
648
- def should_add_root(add_root: Feature, ref_roots: List[Feature], size_min: int) -> bool:
697
+ def should_add_root(
698
+ add_root: Feature,
699
+ ref_roots: List[Feature],
700
+ size_min: int,
701
+ overlapping_refs: Optional[List[Feature]] = None,
702
+ ) -> bool:
649
703
  """
650
704
  按原脚本说明中的规则,判断 add_root 是否应该加入参考注释。
651
705
 
@@ -662,7 +716,8 @@ def should_add_root(add_root: Feature, ref_roots: List[Feature], size_min: int)
662
716
  - 只要有一个重叠关系不满足条件,就不加入整个一级特征。
663
717
  这与原说明中“只要有一个 isoform 重叠,就阻止整个 gene 加入”的精神一致。
664
718
  """
665
- overlapping_refs = [r for r in ref_roots if add_root.overlaps(r)]
719
+ if overlapping_refs is None:
720
+ overlapping_refs = [r for r in ref_roots if add_root.overlaps(r)]
666
721
 
667
722
  # 情况 1:完全不与参考一级特征重叠
668
723
  if not overlapping_refs:
@@ -795,19 +850,27 @@ def complement_annotations(ref_set: AnnotationSet, add_set: AnnotationSet, size_
795
850
  把 add_set 中满足条件的一级特征补充到 ref_set 中。
796
851
  返回值:实际添加的一级特征数量。
797
852
  """
798
- added_count = 0
799
- existing_ids = ref_set.all_ids()
800
- existing_names = ref_set.all_names()
853
+ added_count = 0
854
+ existing_ids = ref_set.all_ids()
855
+ existing_names = ref_set.all_names()
856
+ interval_index = RootIntervalIndex(ref_set.roots)
801
857
 
802
858
  for add_root in sorted(
803
859
  add_set.roots,
804
860
  key=lambda x: (x.seqid, x.start, x.end, x.feature_type, x.id or "")
805
861
  ):
806
- update_overlapping_sources(add_root, ref_set.roots)
807
- if should_add_root(add_root, ref_set.roots, size_min):
862
+ overlapping_refs = interval_index.overlapping(add_root)
863
+ update_overlapping_sources(add_root, overlapping_refs)
864
+ if should_add_root(
865
+ add_root,
866
+ ref_set.roots,
867
+ size_min,
868
+ overlapping_refs=overlapping_refs,
869
+ ):
808
870
  cloned = add_root.deep_clone()
809
871
  uniquify_feature_tree(cloned, existing_ids, existing_names)
810
872
  ref_set.roots.append(cloned)
873
+ interval_index.add(cloned)
811
874
  added_count += 1
812
875
 
813
876
  return added_count
@@ -884,7 +947,7 @@ def build_arg_parser() -> argparse.ArgumentParser:
884
947
  parser.add_argument("--output", "--out", "-o", default=None, help="输出文件路径;默认输出到 STDOUT")
885
948
  parser.add_argument(
886
949
  "-t", "--threads", type=int, default=1,
887
- help="并行线程数;多个 --add 文件会并行预解析,但仍按输入顺序合并,默认 1"
950
+ help="并行工作进程数;ref/add 文件并行预解析,但仍按输入顺序合并,默认 1"
888
951
  )
889
952
  parser.add_argument(
890
953
  "-v", "--verbose", type=int, default=1,
@@ -1002,15 +1065,25 @@ def parse_swap_regions_from_tsv(tsv_path: str, flank_bp: int = 100) -> List[Swap
1002
1065
  return regions
1003
1066
 
1004
1067
 
1005
- def parse_add_files(add_files: List[str], threads: int) -> List[Tuple[str, AnnotationSet]]:
1006
- """并行预解析补充注释文件,返回顺序与命令行 --add 顺序一致。"""
1007
- threads = max(1, threads)
1008
- if threads == 1 or len(add_files) <= 1:
1009
- return [(path, parse_annotation_file(path)) for path in add_files]
1068
+ def parse_input_files(
1069
+ ref_file: str,
1070
+ add_files: List[str],
1071
+ processes: int,
1072
+ ) -> Tuple[AnnotationSet, List[Tuple[str, AnnotationSet]]]:
1073
+ """ref/add 文件并行预解析,输出顺序与命令行一致。"""
1074
+ paths = [ref_file] + list(add_files)
1075
+ processes = max(1, min(processes, len(paths)))
1076
+
1077
+ if processes == 1:
1078
+ parsed_sets = [parse_annotation_file(path) for path in paths]
1079
+ else:
1080
+ eprint(f"[INFO] complement parser worker processes: {processes}")
1081
+ with ProcessPoolExecutor(max_workers=processes) as executor:
1082
+ parsed_sets = list(executor.map(parse_annotation_file, paths))
1010
1083
 
1011
- with ThreadPoolExecutor(max_workers=min(threads, len(add_files))) as executor:
1012
- parsed_sets = list(executor.map(parse_annotation_file, add_files))
1013
- return list(zip(add_files, parsed_sets))
1084
+ ref_set = parsed_sets[0]
1085
+ parsed_add_sets = list(zip(add_files, parsed_sets[1:]))
1086
+ return ref_set, parsed_add_sets
1014
1087
 
1015
1088
 
1016
1089
  def main() -> int:
@@ -1034,18 +1107,17 @@ def main() -> int:
1034
1107
  except ValueError as exc:
1035
1108
  parser.error(str(exc))
1036
1109
 
1037
- # 1) 读取参考注释
1038
- ref_set = parse_annotation_file(args.ref)
1039
- eprint(f"{args.ref} parsed")
1040
- ref_set.info()
1110
+ # 1) 并行读取参考和补充注释
1111
+ ref_set, parsed_add_sets = parse_input_files(args.ref, args.add, args.threads)
1112
+ eprint(f"{args.ref} parsed")
1113
+ ref_set.info()
1041
1114
 
1042
1115
  if swap_regions:
1043
1116
  eprint("Configured swap regions:")
1044
1117
  for region in swap_regions:
1045
1118
  eprint(f" - {region.seqid}:{region.start}-{region.end}")
1046
1119
 
1047
- # 2) 按用户给定顺序,逐个补充;多个输入文件可并行预解析
1048
- parsed_add_sets = parse_add_files(args.add, args.threads)
1120
+ # 2) 按用户给定顺序逐个补充
1049
1121
  for next_file, add_set in parsed_add_sets:
1050
1122
  eprint(f"{next_file} parsed")
1051
1123
  add_set.info()
@@ -46,7 +46,7 @@ detect_bridge_merged_genes.py
46
46
  import argparse
47
47
  import sys
48
48
  from collections import defaultdict
49
- from concurrent.futures import ThreadPoolExecutor
49
+ from concurrent.futures import ProcessPoolExecutor
50
50
 
51
51
 
52
52
  # ----------------------------
@@ -437,7 +437,7 @@ def analyze_gene(
437
437
 
438
438
 
439
439
  def analyze_gene_task(task):
440
- """ThreadPoolExecutor 需要顶层函数;返回 (gene_id, result)。"""
440
+ """进程池任务;返回 (gene_id, result)。"""
441
441
  gid, gene, params = task
442
442
  return gid, analyze_gene(gene, **params)
443
443
 
@@ -485,7 +485,7 @@ def main():
485
485
  "-t", "--threads",
486
486
  type=int,
487
487
  default=1,
488
- help="并行分析 gene 的线程数,默认 1"
488
+ help="并行分析 gene 的工作进程数,默认 1"
489
489
  )
490
490
 
491
491
  args = parser.parse_args()
@@ -527,8 +527,16 @@ def main():
527
527
  if args.threads == 1:
528
528
  analyzed = [analyze_gene_task(task) for task in sorted_genes]
529
529
  else:
530
- with ThreadPoolExecutor(max_workers=args.threads) as executor:
531
- analyzed = list(executor.map(analyze_gene_task, sorted_genes))
530
+ worker_count = min(args.threads, max(1, len(sorted_genes)))
531
+ chunksize = max(1, len(sorted_genes) // (worker_count * 4))
532
+ sys.stderr.write(
533
+ f"[INFO] detect-bridge worker processes: {worker_count}; "
534
+ f"task chunksize: {chunksize}\n"
535
+ )
536
+ with ProcessPoolExecutor(max_workers=worker_count) as executor:
537
+ analyzed = list(
538
+ executor.map(analyze_gene_task, sorted_genes, chunksize=chunksize)
539
+ )
532
540
 
533
541
  with open(args.output, "w", encoding="utf-8") as out:
534
542
  out.write("\t".join(out_fields) + "\n")