Metadata-Version: 2.1
Name: gffkit
Version: 1.1.0
Summary: GFF annotation integration and analysis toolkit
Author: caijunhao
License: MIT
Project-URL: Homepage, https://github.com/qunjie-zhang/gffkit
Project-URL: Repository, https://github.com/qunjie-zhang/gffkit
Project-URL: Issues, https://github.com/qunjie-zhang/gffkit/issues
Keywords: GFF3,GTF,genome annotation,bioinformatics,UTR,gene annotation
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: isoseq
Requires-Dist: pysam >=0.22 ; extra == 'isoseq'
Requires-Dist: biopython >=1.80 ; extra == 'isoseq'

# gffkit

`gffkit` is a lightweight toolkit for GFF/GTF annotation integration and analysis.
Version 1.1.0 provides seven standalone utilities:

1. `detect-bridge`: detect suspicious merged-gene artifacts caused by bridge transcripts.
2. `complement`: complement/merge annotations, with optional region-swap mode.
3. `add-utr`: reconstruct `five_prime_UTR` and `three_prime_UTR` features from exon/CDS coordinates.
4. `rename-sort`: rename gene/transcript/child IDs with a prefix and sort the final GFF3.
5. `get_longest_transcript`: retain one longest transcript isoform per gene.
6. `stat`: calculate basic gene-annotation statistics for one GFF or a directory of GFF files.
7. `repair-oversplit`: evaluate adjacent or overlapping genes for Iso-Seq-supported reconstruction.

The `integrate` workflow uses the original four integration utilities by
default. With `--repair-over-split-genes`, a post-integration repair step runs
before UTR reconstruction and ID renaming. `get_longest_transcript` and `stat`
remain independent commands.

Design documentation:

- `docs/gffkit_auto_bridge_detection_design.md`
- `docs/gffkit_oversplit_repair_design.md`

## Installation

```bash
pip install "gffkit[isoseq]"
```


## Quick start

### Full integration pipeline

```bash
gffkit integrate \
  --annotation-a EviAnn.gff3 \
  --annotation-b ANNEVO.gff3 \
  --isoseq-bam isoseq_bams.txt \
  --genome mapping_reference.fa \
  --protein-fasta original_protein_evidence.fa \
  --diamond /path/to/diamond \
  --repair-over-split-genes \
  --outdir gffkit_out \
  --prefix sample \
  -t 8
```

Outputs:

- `gffkit_out/sample.suspicious.tsv`
- `gffkit_out/sample.merged.pre_oversplit.gff3`
- `gffkit_out/sample.oversplit_candidates.tsv`
- `gffkit_out/sample.oversplit_evidence.tsv`
- `gffkit_out/sample.merged.gff3`
- `gffkit_out/sample.final.withUTR.gff3.pre_rename.gff3`
- `gffkit_out/sample.final.withUTR.gff3`
- `gffkit_out/sample.final.withUTR.gff3.id_map.tsv`

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`.

### Step-by-step usage

```bash
# 1. Detect suspicious merged genes in Annotation A
gffkit detect-bridge -i EviAnn.gff3 -o suspicious.tsv -t 8

# 2. Use A globally and replace only suspicious A gene IDs with same-strand B models
gffkit complement \
  --ref EviAnn.gff3 \
  --add ANNEVO.gff3 \
  --swap_region_tsv suspicious.tsv \
  --swap_region_flank 100 \
  --output merged.gff3 \
  -t 8

# 3. Optionally repair adjacent or overlapping over-split genes after integration
gffkit repair-oversplit \
  -i merged.gff3 \
  --isoseq-bam isoseq_bams.txt \
  --genome mapping_reference.fa \
  --protein-fasta original_protein_evidence.fa \
  --diamond /path/to/diamond \
  --candidates oversplit_candidates.tsv \
  --evidence oversplit_evidence.tsv \
  -o merged.repaired.gff3 \
  -t 8

# 4. Add UTR features
gffkit add-utr -i merged.repaired.gff3 -o final.annotation.withUTR.pre_rename.gff3

# 5. Rename IDs, drop unplaced seqids, and sort the final GFF3
gffkit rename-sort \
  -i final.annotation.withUTR.pre_rename.gff3 \
  -o final.annotation.withUTR.gff3 \
  --prefix sample
```

### Adaptive bridge threshold scan

The default detector keeps the fixed `--min-gap 10000` behavior. To scan an
annotation-specific threshold range, use:

```bash
gffkit detect-bridge \
  -i EviAnn.gff3 \
  -o suspicious.auto.tsv \
  --threshold-mode auto
```

Auto mode deduplicates introns by chromosome, strand, and coordinates, then
uses Q95 through `max(Q99.5, --min-gap)` as its search range. It evaluates only
thresholds where a transcript's bridge classification can change. Candidate
rows include the threshold ranges that support the call, the selected
representative threshold, and a threshold stability label. The adjacent
`suspicious.auto.tsv.meta.json` records the background size, quantile method,
and search range. With fewer than 1,000 unique introns, auto mode reports that
it fell back to the fixed threshold; this fallback is not considered stable.

A bridge must overlap actual exon blocks from at least two core transcript
clusters. Overlap with a cluster's broad genomic span alone is insufficient.
Missing exon/CDS structure is excluded from bridge evidence. `integrate
--threshold-mode auto` uses only `stable_candidate` rows for region swapping;
the standalone detector still reports sensitive candidates for review.
Threshold stability is a screening measure, not a calibrated probability.

### Optional Iso-Seq genome-wide discovery

Iso-Seq BAM input is supported on both `detect-bridge` and `integrate`.
Install the optional BAM dependency with `pip install
'.[isoseq]'`. Commands without BAM input do not require `pysam`.

Create a text file with one coordinate-sorted and indexed BAM path per tissue
or sample. Blank lines and lines beginning with `#` are ignored. Relative BAM
paths are resolved from the directory containing the text file.

```text
# B73_isoseq_bams.txt
/path/to/B73_ear.bam
/path/to/B73_embryo.bam
/path/to/B73_endosperm.bam
/path/to/B73_pollen.bam
/path/to/B73_root.bam
/path/to/B73_tassel.bam
```

Pass the text file to `--isoseq-bam`:

```bash
gffkit detect-bridge \
  -i annotation.gff3 \
  -o suspicious.tsv \
  --isoseq-bam B73_isoseq_bams.txt
```

Iso-Seq mode scans each BAM across the whole genome and collects anchored CIGAR
`N` junctions of at least `--min-gap`. It combines minimap2 `ts:A:+/-` with the
SAM reverse flag to determine genomic transcript strand. Secondary,
supplementary, duplicate-marked, QC-failed, low-MAPQ, and known multimapping
records are excluded.

A long junction becomes a BAM bridge candidate when the same sample contains
the required number of exact junction templates and independent non-bridge
templates on both flanks. BAM candidates are mapped to GFF genes where
possible, then unioned and deduplicated with GFF structural candidates:

```text
suspicious.tsv = GFF structural candidates ∪ Iso-Seq BAM candidates
```

GFF candidates remain in the output when Iso-Seq has no coverage. Iso-Seq can
also add candidates absent from the GFF structural screen. The genome-wide
report defaults to `OUTPUT.isoseq.tsv`; use `--isoseq-report` to choose another
path.

| Option | Default | Meaning |
| --- | --- | --- |
| `--isoseq-bam` | none | TXT file containing one coordinate-sorted, indexed BAM path per line. |
| `--isoseq-report` | `OUTPUT.isoseq.tsv` | Genome-wide long-junction evidence report. |
| `--isoseq-min-mapq` | `20` | Minimum mapping quality. |
| `--isoseq-min-anchor` | `10` | Minimum aligned bases on each side of a CIGAR `N`. |
| `--isoseq-min-junction-reads` | `1` | Exact long-junction templates required in one sample. |
| `--isoseq-min-flank-reads` | `2` | Non-bridge templates required on each flank in the same sample. |
| `--isoseq-min-samples` | `1` | Samples meeting both junction and flank thresholds. |
| `--isoseq-flank-window` | `100` | Bases inspected on each side of a junction. |

`integrate` accepts the same options and passes them to its detection step:

```bash
gffkit integrate \
  --annotation-a EviAnn.gff3 \
  --annotation-b Helixer.gff3 \
  --outdir gffkit_isoseq_out \
  --prefix B73 \
  --isoseq-bam B73_isoseq_bams.txt
```

Iso-Seq evidence is a screening heuristic. A supported long intron may be a
normal isoform or readthrough transcript, so review `suspicious.tsv` before
automatic biological interpretation.

Transcript evidence fetches indexed exonic windows sequentially, opening each BAM once;
`-t` still controls the existing structural detection and complement workers.
Memory for template tracking scales with local coverage. In BAM mode the
candidate TSV and RNA report must be new paths; existing files are refused.

Implementation references: [pysam API](https://pysam.readthedocs.io/en/stable/api.html)
and [SAM format specification](https://samtools.github.io/hts-specs/SAMv1.pdf).

### Merge three or more annotations

Use repeated `--add` arguments. Files are merged in the order provided.

```bash
gffkit complement \
  --ref EviAnn.gff3 \
  --add ANNEVO.gff3 \
  --add Helixer.gff3 \
  --add PASA.gff3 \
  --output merged.multi.gff3 \
  -t 8
```

### Extract the longest transcript

For each gene, `get_longest_transcript` selects the isoform with the longest
concatenated CDS. If none of a gene's isoforms has CDS features, it uses the
longest concatenated exon length. Ties retain the first isoform encountered in
the input file.

Process one GFF/GFF3 file:

```bash
gffkit get_longest_transcript \
  -i annotation.gff3 \
  -o longest_gff
```

Process all `.gff`/`.gff3` files directly inside a directory:

```bash
gffkit get_longest_transcript \
  -f input_gff_directory \
  -o longest_gff
```

Compressed `.gff.gz` and `.gff3.gz` inputs are also supported by this command.
Output files are named `*.longest.gff` or `*.longest.gff3`. Existing output
files are refused unless `--force` is supplied.

### Calculate annotation statistics

Process one GFF/GFF3 file and write the default `gffstat.txt`:

```bash
gffkit stat -i annotation.gff3
```

Process all `.gff`/`.gff3` files directly inside a directory and select an
output path:

```bash
gffkit stat \
  -f input_gff_directory \
  -o annotation.gffstat.txt
```

The tab-separated output contains species/file name, gene count, average gene
span, average mature-transcript length, average CDS length per gene, average
exon count per gene, average exon length, and average UTR length per gene.

Version 0.9.0 first selects one transcript per gene using the largest sum of
that transcript's exon lengths. All transcript-derived values (mature
transcript, CDS, exon, and UTR statistics) are calculated only from those
selected transcripts. Their per-gene averages use only genes with at least one
recognized transcript feature; genes without a transcript still contribute to
gene count and average gene span, but not to transcript-derived denominators.
Average exon length is calculated across selected exons. Mature-transcript
length is the sum of exon lengths, not the genomic `mRNA` span. Gene length
remains the GFF gene span (`end - start + 1`). Transcripts with equal exon sums
are resolved by keeping the one that appears first in the input GFF.

## Command overview

```bash
gffkit --help
gffkit detect-bridge --help
gffkit complement --help
gffkit add-utr --help
gffkit rename-sort --help
gffkit get_longest_transcript --help
gffkit stat --help
gffkit integrate --help
```

## Parallel Processing

Use `-t/--threads` to select the number of worker processes. The option name is
kept for command-line compatibility, but version 0.5.0 and later uses processes for
CPU-bound work so that Python's GIL does not restrict execution to one core.

- `detect-bridge` analyzes genes with a process pool and batches tasks to reduce process communication overhead.
- `complement` parses the reference and supplementary files in parallel, then merges them in the original command-line order.
- `complement` uses a dynamic chromosome interval index to compare each supplementary gene only with nearby overlapping reference genes.
- `integrate` passes the worker count to the detect and complement steps. `add-utr` and `rename-sort` remain single-process.

Example:

```bash
gffkit integrate --annotation-a EviAnn.gff3 --annotation-b ANNEVO.gff3 -t 16
```

During `detect-bridge`, multiple worker processes should be visible in `top` or
`htop`. CPU usage naturally drops during the single-process UTR and rename/sort
steps. More workers also increase memory use; start with `-t 4` or `-t 8` for
large annotations.

## Annotation integration strategy

- Annotation A, for example EviAnn GFF, is used as the global primary reference.
- Annotation B, for example ANNEVO/deep-learning GFF, replaces only the suspicious Annotation A gene IDs on the same strand; neighboring genes are protected.
- `--repair-over-split-genes` defaults to `--reconstruction-mode supported`: repeated compatible partial Iso-Seq bridges can join original transcript segments, with explicit endpoint provenance and bounded terminal CDS inference. Complete ORFs, per-gene coding/homology support, canonical splices and translation roundtrip remain required. Use `--reconstruction-mode strict` for v3 full-CDS-read rules. `--min-protein-identity` defaults to 0.8 (supported) or 0.9 (strict); bidirectional protein coverage remains 0.9. See `docs/gffkit_oversplit_repair_design.md` for all thresholds and review outputs.
- UTR features are reconstructed after merging using an exon-minus-CDS strategy.
- 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.
- Version 0.5.0 replaces CPU-bound threads with worker processes and adds a dynamic interval index for faster annotation overlap searches.
- Version 0.6.0 adds the independent `get_longest_transcript` and `stat` commands. Neither command is included in `integrate`.
- When multiple tools annotate the same gene locus, the GFF source column is combined with `|`, for example `EviAnn|ANNEVO`.

## Rename and Sort

Run this step independently when you already have a merged GFF3:

```bash
gffkit rename-sort \
  -i merged.withUTR.gff3 \
  -o sample.renamed.sorted.gff3 \
  --prefix sample \
  --digits 5 \
  --keep-old-ids
```

This writes `sample.renamed.sorted.gff3` and `sample.renamed.sorted.gff3.id_map.tsv`.

## Version 1.0.0 changes

- Added supported-mode partial-read / annotation-guided reconstruction; retained strict observed-chain mode and explicit report-only decisions.
- Added `integrate --repair-over-split-genes` after A/B integration and before UTR reconstruction and renaming.
- Required primary unique Iso-Seq splice alignments with configurable read, sample, anchor, mapping-quality, and gap thresholds.
- Merged Iso-Seq-supported adjacent genes directly without reusing an Annotation B/Helixer replacement model.
- Preserved each original transcript/exon/CDS subtree and changed only its top-level gene parent.
- Added pre-repair GFF, candidate summary, and read-level evidence outputs.
- Preserved precise same-strand, gene-ID-based replacement for suspicious merged-gene regions.
- Included the mature-transcript statistics updates introduced in 0.9.0.
- Updated the package version to 1.0.0.

## Version 0.9.0 changes

- Changed `gffkit stat` to select the transcript with the largest summed exon
  length for each gene.
- Changed average transcript length from the genomic mRNA span to the summed
  exon length of each selected mature transcript.
- Restricted CDS, exon-count, exon-length, and UTR statistics to the same
  selected transcript so all transcript-derived columns use one consistent
  per-gene model.
- Preserved the existing TSV column names and command-line interface for
  compatibility.
- Updated the package version to 0.9.0.

## Version 0.8.0 changes

- Added genome-wide Iso-Seq BAM discovery to `detect-bridge` and `integrate`.
- Added `--isoseq-bam` and Iso-Seq-specific threshold/report options.
- Removed short-read RNA-seq BAM parameters, filtering, boundary classification, and implementation code.
- Combined minimap2 `ts` with SAM alignment orientation for genomic strand assignment.
- Unioned and deduplicated Iso-Seq BAM candidates with GFF structural candidates.
- Updated the package version to 0.8.0.

## Version 0.7.0 changes

- Added `detect-bridge --threshold-mode auto`, which deduplicates introns, derives a per-annotation search range, and scans only thresholds that can change bridge classification.
- Added candidate threshold ranges, selected threshold, stability classification, and a JSON metadata sidecar to auto-mode output; sparse backgrounds are marked as fixed-threshold fallback.
- Changed bridge confirmation to require overlap with actual core exon/CDS blocks instead of broad cluster spans; transcripts without usable exon/CDS structure cannot support a bridge call.
- Made `integrate --threshold-mode auto` use only stable candidates for region replacement and aligned RNA boundary reconstruction to the selected threshold.
- Preserved fixed-threshold mode as the default and retained its original TSV columns.
- Updated the package version to 0.7.0.

## Version 0.6.0 changes

- Added `gffkit get_longest_transcript` using the longest-CDS/longest-exon selection logic from `get_longest_transcript.py`.
- Added mutually exclusive `-i/--input` single-file and `-f/--folder` directory input modes for longest-transcript extraction.
- Added `gffkit stat` using the GFF statistics implementation from `gffstat.py`.
- Added mutually exclusive `-i/--input` single-file and `-f/--folder` directory input modes for annotation statistics.
- Kept both new commands independent from the four-step `gffkit integrate` workflow.
- Updated the package version from 0.5.0 to 0.6.0.
- Updated package author and credits to `caijunhao`.

## Maintainer notes

When command-line options or behavior changes, update this `README.md` in the versioned package directory before building and uploading to PyPI.

## License

MIT License.

## Credits

Author: caijunhao

### Reconstruct across multiple gene fragments with local Iso-Seq paths

Add `--chain-reconstruction --reconstruction-mode supported` to
`repair-oversplit` or `integrate`. Optional limits:
`--max-chain-span 100000 --max-intermediate-gap 25000 --max-genes-per-chain 5`.
Compatible overlapping local reads can reconstruct missing internal exons
without one read spanning the full transcript. Each corridor still requires
replicated read/RG support and coding/homology validation. Weak, ambiguous or
complex paths remain review-only. Intermediate genes are not silently removed.
See `docs/gffkit_oversplit_repair_design.md` for evidence and provenance details.

`--reconstruction-mode supported` selects the reconstruction and acceptance
rules; `--chain-reconstruction` additionally enables local path assembly across
three or more gene fragments. Chain reconstruction is opt-in and is supported
only in `supported` mode. Candidate CDS models are reconstructed and validated
at candidate loci; this is not a genome-wide rerun of gene prediction.

For automatic coding-model acceptance, provide `--genome` and
`--protein-fasta`. `--diamond` is optional: it searches the supplied protein
FASTA against candidate ORFs and requires both `--genome` and
`--protein-fasta`. If DIAMOND is omitted, gffkit checks proteins linked through
the input annotation's `EvidenceProteinID`; it does not search the full FASTA
library. Without a genome or usable protein evidence, gffkit keeps the original
genes and reports candidates rather than accepting a reconstructed coding
model. Install the optional dependencies with `pip install 'gffkit[isoseq]'`.

Example without the optional full-library DIAMOND search:

```bash
gffkit integrate \
  --annotation-a EviAnn.gff3 \
  --annotation-b Helixer.gff3 \
  --outdir gffkit_out --prefix B73 \
  --isoseq-bam B73_isoseq_bams.txt \
  --genome B73_v5.chr.fasta \
  --protein-fasta proteins.fa \
  --repair-over-split-genes \
  --chain-reconstruction \
  --reconstruction-mode supported \
  --threads 16
```

### Overlapping over-split candidates (2026-11-24)

Candidate discovery includes all overlapping gene pairs on the same chromosome and strand, including nested and non-adjacent models. Negative intergenic gaps are retained in reports. Separated pairs retain the adjacent-pair maximum-gap rule. Candidate inclusion does not imply automatic merging: chain span limits, Iso-Seq support and reconstruction/ORF validation still apply. Opposite-strand genes are not combined.

## Version 1.1.0 changes

- Same-strand overlapping gene pairs, including nested and non-adjacent overlaps, are included in Iso-Seq candidate discovery.
- Supported pair components are grouped as graph connected components so interleaved edges cannot split or duplicate a gene across candidates.
- Overlapping Iso-Seq paths retain their full observed exon chain after both gene models are anchored; corridor clipping is no longer allowed to discard paths when its cuts cross.
- Candidate pairs above the reconstruction span limit remain in evidence/diagnostic reports and supported candidates are explicitly marked report-only instead of being silently filtered out.
- Added tests for overlapping, nested, interleaved, path-clipping, and over-span cases.
