gffkit 0.3.1__tar.gz → 0.5.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: gffkit
3
- Version: 0.3.1
3
+ Version: 0.5.0
4
4
  Summary: Region-aware GFF annotation integration toolkit
5
5
  Author: Qunjie Zhang
6
6
  License: MIT
@@ -26,11 +26,12 @@ License-File: LICENSE
26
26
  # gffkit
27
27
 
28
28
  `gffkit` is a lightweight toolkit for region-aware GFF/GTF annotation integration.
29
- It combines three utilities:
29
+ It combines four 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
+ 4. `rename-sort`: rename gene/transcript/child IDs with a prefix and sort the final GFF3.
34
35
 
35
36
  ## Installation
36
37
 
@@ -56,7 +57,11 @@ Outputs:
56
57
 
57
58
  - `gffkit_out/sample.suspicious.tsv`
58
59
  - `gffkit_out/sample.merged.gff3`
60
+ - `gffkit_out/sample.final.withUTR.gff3.pre_rename.gff3`
59
61
  - `gffkit_out/sample.final.withUTR.gff3`
62
+ - `gffkit_out/sample.final.withUTR.gff3.id_map.tsv`
63
+
64
+ 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`.
60
65
 
61
66
  ### Step-by-step usage
62
67
 
@@ -74,7 +79,13 @@ gffkit complement \
74
79
  -t 8
75
80
 
76
81
  # 3. Add UTR features
77
- gffkit add-utr -i merged.gff3 -o final.annotation.withUTR.gff3
82
+ gffkit add-utr -i merged.gff3 -o final.annotation.withUTR.pre_rename.gff3
83
+
84
+ # 4. Rename IDs, drop unplaced seqids, and sort the final GFF3
85
+ gffkit rename-sort \
86
+ -i final.annotation.withUTR.pre_rename.gff3 \
87
+ -o final.annotation.withUTR.gff3 \
88
+ --prefix sample
78
89
  ```
79
90
 
80
91
  ### Merge three or more annotations
@@ -98,16 +109,20 @@ gffkit --help
98
109
  gffkit detect-bridge --help
99
110
  gffkit complement --help
100
111
  gffkit add-utr --help
112
+ gffkit rename-sort --help
101
113
  gffkit integrate --help
102
114
  ```
103
115
 
104
- ## Threads
116
+ ## Parallel Processing
105
117
 
106
- Version 0.3 and later add `-t/--threads`.
118
+ 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
120
+ CPU-bound work so that Python's GIL does not restrict execution to one core.
107
121
 
108
- - `detect-bridge` analyzes genes in parallel.
109
- - `complement` pre-parses multiple `--add` files in parallel, then merges them in the original command-line order.
110
- - `integrate` passes the thread count to the detect and complement steps.
122
+ - `detect-bridge` analyzes genes with a process pool and batches tasks to reduce process communication overhead.
123
+ - `complement` parses the reference and supplementary files in parallel, then merges them in the original command-line order.
124
+ - `complement` uses a dynamic chromosome interval index to compare each supplementary gene only with nearby overlapping reference genes.
125
+ - `integrate` passes the worker count to the detect and complement steps. `add-utr` and `rename-sort` remain single-process.
111
126
 
112
127
  Example:
113
128
 
@@ -115,13 +130,35 @@ Example:
115
130
  gffkit integrate --annotation-a EviAnn.gff3 --annotation-b ANNEVO.gff3 -t 16
116
131
  ```
117
132
 
133
+ During `detect-bridge`, multiple worker processes should be visible in `top` or
134
+ `htop`. CPU usage naturally drops during the single-process UTR and rename/sort
135
+ steps. More workers also increase memory use; start with `-t 4` or `-t 8` for
136
+ large annotations.
137
+
118
138
  ## Annotation integration strategy
119
139
 
120
140
  - Annotation A, for example EviAnn/RNA-seq-supported GFF, is used as the global primary reference.
121
141
  - Annotation B, for example ANNEVO/deep-learning GFF, is used as the local primary reference only in suspicious merged-gene regions.
122
142
  - UTR features are reconstructed after merging using an exon-minus-CDS strategy.
143
+ - 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
+ - Version 0.5.0 replaces CPU-bound threads with worker processes and adds a dynamic interval index for faster annotation overlap searches.
123
145
  - When multiple tools annotate the same gene locus, the GFF source column is combined with `|`, for example `EviAnn|ANNEVO`.
124
146
 
147
+ ## Rename and Sort
148
+
149
+ Run this step independently when you already have a merged GFF3:
150
+
151
+ ```bash
152
+ gffkit rename-sort \
153
+ -i merged.withUTR.gff3 \
154
+ -o sample.renamed.sorted.gff3 \
155
+ --prefix sample \
156
+ --digits 5 \
157
+ --keep-old-ids
158
+ ```
159
+
160
+ This writes `sample.renamed.sorted.gff3` and `sample.renamed.sorted.gff3.id_map.tsv`.
161
+
125
162
  ## Maintainer notes
126
163
 
127
164
  When command-line options or behavior changes, update this `README.md` in the versioned package directory before building and uploading to PyPI.
gffkit-0.5.0/README.md ADDED
@@ -0,0 +1,143 @@
1
+ # gffkit
2
+
3
+ `gffkit` is a lightweight toolkit for region-aware GFF/GTF annotation integration.
4
+ It combines four 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
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install gffkit
15
+ ```
16
+
17
+
18
+ ## Quick start
19
+
20
+ ### Full integration pipeline
21
+
22
+ ```bash
23
+ gffkit integrate \
24
+ --annotation-a EviAnn.gff3 \
25
+ --annotation-b ANNEVO.gff3 \
26
+ --outdir gffkit_out \
27
+ --prefix sample \
28
+ -t 8
29
+ ```
30
+
31
+ Outputs:
32
+
33
+ - `gffkit_out/sample.suspicious.tsv`
34
+ - `gffkit_out/sample.merged.gff3`
35
+ - `gffkit_out/sample.final.withUTR.gff3.pre_rename.gff3`
36
+ - `gffkit_out/sample.final.withUTR.gff3`
37
+ - `gffkit_out/sample.final.withUTR.gff3.id_map.tsv`
38
+
39
+ 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`.
40
+
41
+ ### Step-by-step usage
42
+
43
+ ```bash
44
+ # 1. Detect suspicious merged genes in Annotation A
45
+ gffkit detect-bridge -i EviAnn.gff3 -o suspicious.tsv -t 8
46
+
47
+ # 2. Use A as the global reference, but switch to B in suspicious regions
48
+ gffkit complement \
49
+ --ref EviAnn.gff3 \
50
+ --add ANNEVO.gff3 \
51
+ --swap_region_tsv suspicious.tsv \
52
+ --swap_region_flank 100 \
53
+ --output merged.gff3 \
54
+ -t 8
55
+
56
+ # 3. Add UTR features
57
+ gffkit add-utr -i merged.gff3 -o final.annotation.withUTR.pre_rename.gff3
58
+
59
+ # 4. Rename IDs, drop unplaced seqids, and sort the final GFF3
60
+ gffkit rename-sort \
61
+ -i final.annotation.withUTR.pre_rename.gff3 \
62
+ -o final.annotation.withUTR.gff3 \
63
+ --prefix sample
64
+ ```
65
+
66
+ ### Merge three or more annotations
67
+
68
+ Use repeated `--add` arguments. Files are merged in the order provided.
69
+
70
+ ```bash
71
+ gffkit complement \
72
+ --ref EviAnn.gff3 \
73
+ --add ANNEVO.gff3 \
74
+ --add Helixer.gff3 \
75
+ --add PASA.gff3 \
76
+ --output merged.multi.gff3 \
77
+ -t 8
78
+ ```
79
+
80
+ ## Command overview
81
+
82
+ ```bash
83
+ gffkit --help
84
+ gffkit detect-bridge --help
85
+ gffkit complement --help
86
+ gffkit add-utr --help
87
+ gffkit rename-sort --help
88
+ gffkit integrate --help
89
+ ```
90
+
91
+ ## Parallel Processing
92
+
93
+ 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
95
+ CPU-bound work so that Python's GIL does not restrict execution to one core.
96
+
97
+ - `detect-bridge` analyzes genes with a process pool and batches tasks to reduce process communication overhead.
98
+ - `complement` parses the reference and supplementary files in parallel, then merges them in the original command-line order.
99
+ - `complement` uses a dynamic chromosome interval index to compare each supplementary gene only with nearby overlapping reference genes.
100
+ - `integrate` passes the worker count to the detect and complement steps. `add-utr` and `rename-sort` remain single-process.
101
+
102
+ Example:
103
+
104
+ ```bash
105
+ gffkit integrate --annotation-a EviAnn.gff3 --annotation-b ANNEVO.gff3 -t 16
106
+ ```
107
+
108
+ During `detect-bridge`, multiple worker processes should be visible in `top` or
109
+ `htop`. CPU usage naturally drops during the single-process UTR and rename/sort
110
+ steps. More workers also increase memory use; start with `-t 4` or `-t 8` for
111
+ large annotations.
112
+
113
+ ## Annotation integration strategy
114
+
115
+ - Annotation A, for example EviAnn/RNA-seq-supported GFF, is used as the global primary reference.
116
+ - Annotation B, for example ANNEVO/deep-learning GFF, is used as the local primary reference only in suspicious merged-gene regions.
117
+ - UTR features are reconstructed after merging using an exon-minus-CDS strategy.
118
+ - 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
+ - Version 0.5.0 replaces CPU-bound threads with worker processes and adds a dynamic interval index for faster annotation overlap searches.
120
+ - When multiple tools annotate the same gene locus, the GFF source column is combined with `|`, for example `EviAnn|ANNEVO`.
121
+
122
+ ## Rename and Sort
123
+
124
+ Run this step independently when you already have a merged GFF3:
125
+
126
+ ```bash
127
+ gffkit rename-sort \
128
+ -i merged.withUTR.gff3 \
129
+ -o sample.renamed.sorted.gff3 \
130
+ --prefix sample \
131
+ --digits 5 \
132
+ --keep-old-ids
133
+ ```
134
+
135
+ This writes `sample.renamed.sorted.gff3` and `sample.renamed.sorted.gff3.id_map.tsv`.
136
+
137
+ ## Maintainer notes
138
+
139
+ When command-line options or behavior changes, update this `README.md` in the versioned package directory before building and uploading to PyPI.
140
+
141
+ ## License
142
+
143
+ MIT License.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "gffkit"
7
- version = "0.3.1"
7
+ version = "0.5.0"
8
8
  description = "Region-aware GFF annotation integration toolkit"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -38,6 +38,7 @@ gffkit = "gffkit.main:main"
38
38
  gffkit-detect-bridge = "gffkit.detect_bridge_merged_genes:main"
39
39
  gffkit-complement = "gffkit.complement_annotations:main"
40
40
  gffkit-add-utr = "gffkit.add_utr:main"
41
+ gffkit-rename-sort = "gffkit.rename_sort_gff3:main"
41
42
 
42
43
  [tool.setuptools]
43
44
  package-dir = {"" = "src"}
@@ -1,3 +1,3 @@
1
1
  """gffkit: region-aware GFF annotation integration utilities."""
2
2
 
3
- __version__ = "0.3.1"
3
+ __version__ = "0.5.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")