Repository: WhyAdr/genbank-parser
Target branch: main
Recommended release: 0.2.1
Purpose: Follow-up implementation plan after the 0.2.0 architectural overhaul. This patch should focus on correctness, regression hardening, test reliability, and aligning documentation/changelog claims with actual behavior before adding further scientific features.
The 0.2.0 overhaul successfully implemented the most important architectural changes:
- a typed
GenBankDocument -> GenBankRecord -> GenBankFeaturemodel; - preservation of Biopython
FeatureLocation/CompoundLocation; - biological sequence extraction via
location.extract(record.seq); - distinction between biological feature length and genomic span;
- canonical GenBank parsing through
read_genbank(); - package restructuring under
src/genbank_parser/; - a unified
gbparseCLI; pyproject.toml,py.typed, pytest scaffolding, and GitHub Actions configuration.
The core redesign is therefore sound and should not be replaced.
However, the current implementation still contains several correctness regressions and partially implemented roadmap items. The most important are:
- pytest fixtures referenced by the test suite appear not to be committed because
.gitignoreexcludes*.gb,*.gbk, and*.gbff; find_locus()often returns thegenefeature instead of the correspondingCDS, causing incorrect neighborhood and region behavior;region.pycan create internally inconsistent GenBank coordinates and destroys compound locations;- GFF3 phase handling still ignores
codon_start, and synthetic hierarchy generation can duplicate IDs; - compatibility accessors reintroduce incorrect strand semantics for strand
0/None; - codon analysis remains hard-coded to translation table 11;
discover.pyadvertises functionality that is not currently implemented (operon_gap, dark-matter analysis, TSV output);- comparative, phylogenomic, and CRISPR modules remain annotation-based rather than implementing the planned sequence/HMM layers;
- several changelog and README claims are stronger than the implementation currently supports.
This patch should therefore be treated as a correctness-and-truthfulness release, not a feature-expansion release.
- Make a clean clone installable and testable.
- Eliminate silent wrong-result behavior.
- Preserve location semantics end-to-end.
- Make GFF3 output biologically and structurally safer.
- Reconcile public claims with actual functionality.
- Add regression tests for every bug fixed here.
- Avoid adding major new scientific dependencies in this patch.
The following should be deferred to a later 0.3.0 scientific-depth release:
- MMseqs2 / DIAMOND / BLAST sequence-aware comparative validation;
- reciprocal best-hit analysis;
- HMM-based GTDB/BUSCO phylogenomic marker recovery;
- MinCED / CRISPRCasTyper integration;
- full orthogroup inference;
- advanced evidence-weighted biological hypothesis scoring.
tests/conftest.py references:
tests/fixtures/simple_cds.gb
tests/fixtures/compound_joined.gb
tests/fixtures/special_cds.gb
tests/fixtures/multi_record_circular.gb
tests/fixtures/duplicate_locus.gb
but repository-wide .gitignore contains:
*.gbff
*.gbk
*.gbThis likely caused locally generated synthetic test fixtures to remain untracked.
A test suite that exists only in the developer working tree is not a regression suite.
Add exceptions:
# Ignore general GenBank datasets
*.gbff
*.gbk
*.gb
# But always retain synthetic regression fixtures
!tests/fixtures/
!tests/fixtures/*.gb
!tests/fixtures/*.gbk
!tests/fixtures/*.gbffIf they already exist locally:
git add -f tests/fixtures/Confirm:
git ls-files tests/fixtures/Expected output should include all five synthetic fixtures.
From a fresh temporary clone:
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
pip install -e .[test]
pytest -vDo not use an existing editable install or developer environment for this verification.
The GitHub Actions matrix must pass on all supported Python versions.
A normal bacterial GenBank annotation often contains both:
gene
/locus_tag="ABC_001"
CDS
/locus_tag="ABC_001"
Current GenBankRecord.find_locus() returns the first matching feature.
In Biopython feature order, the gene feature frequently appears before the CDS.
Consequences:
gbparse neighborhood ABC_001may receive agenetarget but search a CDS-only list;- the failure path currently falls back to
target_idx = 0; - this can silently show the neighborhood around the first CDS on the contig;
gbparse region --locus ABC_001 --flank-genes Nmay silently fail to apply the requested gene window.
Silent wrong biological output is a P0 issue.
Add explicit locus resolution methods.
def find_locus_features(self, locus_tag: str) -> list[GenBankFeature]:
return [
f for f in self.features
if f.locus_tag == locus_tag
]
def find_locus(
self,
locus_tag: str,
prefer_type: str | None = "CDS",
) -> GenBankFeature | None:
matches = self.find_locus_features(locus_tag)
if not matches:
return None
if prefer_type is not None:
for feat in matches:
if feat.type.casefold() == prefer_type.casefold():
return feat
return matches[0]Mirror the same preference:
def find_locus(
self,
locus_tag: str,
prefer_type: str | None = "CDS",
) -> tuple[GenBankRecord, GenBankFeature] | None:
...Optional convenience:
def find_cds(self, locus_tag: str):
return self.find_locus(locus_tag, prefer_type="CDS")Replace:
except ValueError:
target_idx = 0with an explicit error.
Never silently substitute a different locus.
Suggested behavior:
raise ValueError(
f"Resolved target {locus_tag!r} is not present in CDS ordering"
)or re-resolve the locus as a CDS before constructing the window.
Add fixture containing a normal paired gene + CDS with identical locus tag.
Tests:
def test_find_locus_prefers_cds(...):
...
def test_neighborhood_target_is_requested_cds(...):
...
def test_neighborhood_never_falls_back_to_first_cds(...):
...
def test_region_flank_genes_uses_cds_for_paired_gene_feature(...):
...The test should deliberately place the requested locus far from the first CDS so the old failure mode is obvious.
Affected file:
src/genbank_parser/region.py
This module needs a focused rewrite.
The returned SeqRecord.seq is always a sliced subsequence:
sub_seq = full_seq[target_start - 1:target_end]but when rebase=False, feature locations can remain approximately parent-genome coordinates.
That produces impossible records such as:
sequence length = 20,000 bp
feature location = 2,005,000..2,006,000
A standalone GenBank SeqRecord must use coordinates relative to its own sequence.
All returned region features should use local coordinates.
The extracted record should always be internally equivalent to:
region nucleotide 1 == original target_start
Original coordinates should be preserved as metadata, not feature coordinates.
Possible qualifiers:
/original_record="chromosome"
/original_location="2005000..2006000"
/original_start="2005000"
/original_end="2006000"
or record annotations:
sub_record.annotations["parent_record"] = target_rec.id
sub_record.annotations["parent_start"] = target_start
sub_record.annotations["parent_end"] = target_endKeep --rebase temporarily for compatibility, but either:
- deprecate it because local rebasing is required for valid standalone records, or
- reinterpret it only as whether original-coordinate metadata is emitted.
Do not create a sliced SeqRecord with parent-coordinate feature locations.
Every retained feature is rebuilt as:
FeatureLocation(new_st, new_en, strand=f.strand)which turns:
join(100..150,200..250)
into one continuous interval.
That violates the central architecture goal of preserving biological location semantics.
Operate on the original Biopython location.
For every location part:
- intersect it with the requested region;
- clip only if necessary;
- shift local coordinates by
-(target_start - 1); - preserve strand;
- reconstruct a
CompoundLocationif multiple parts survive.
Pseudo-interface:
def _clip_and_shift_location(
location,
region_start_1based: int,
region_end_1based: int,
):
...The function should handle:
FeatureLocation
CompoundLocation
BeforePosition
AfterPosition
as safely as practical.
If exact fuzzy-boundary preservation cannot be guaranteed after clipping, preserve the original location in metadata and document the limitation.
For circular records, support requested windows that cross origin.
Example:
record length = 5,000,000
target near 4,999,000
flank = 5,000 bp
Expected sequence:
4,994,000..5,000,000
+
1..4,000
This should produce a valid local region record.
Implement only if feasible in this patch; otherwise explicitly reject origin-crossing extraction with a clear error instead of silently truncating.
def test_region_flank_genes_on_gene_cds_pair(...):
...
def test_region_coordinates_are_local_even_without_rebase_flag(...):
...
def test_region_preserves_compound_location(...):
...
def test_region_preserves_reverse_strand_compound_location(...):
...
def test_region_output_feature_end_never_exceeds_subrecord_length(...):
...Optional:
def test_region_circular_origin_wrap(...):
...Affected file:
src/genbank_parser/gff.py
The original ordinary-feature join_segments bug is fixed. Preserve that fix.
Additional corrections are still required.
Current logic starts every CDS with:
current_phase = 0and ordinary CDSs use:
phase=0This is incomplete for CDSs carrying:
/codon_start=2
/codon_start=3
Use the feature's codon offset as the initial phase where appropriate:
initial_phase = f.codon_start - 1Then propagate phase over compound segments in biological 5' -> 3' order.
Be cautious with partial CDSs; document any assumptions.
Current joined-CDS fixture only verifies an easy case where phases happen to be:
0, 0
Add cases that necessarily yield:
0 -> 1
0 -> 2
1 -> ...
2 -> ...
for both strands.
A normal GenBank file may already contain a gene feature with:
/locus_tag="ABC_001"
If a compound CDS with the same locus tag is later encountered, synthetic generation of:
gene:ABC_001
can duplicate the ID already emitted for the real gene.
Pre-index features per locus tag:
locus_features[tag] = [...]When exporting a CDS:
- if a corresponding real
genefeature exists, reference its ID; - do not synthesize another gene;
- synthesize transcript-level hierarchy only when needed and only with globally unique IDs.
Maintain a global emitted-ID set:
emitted_ids: set[str]and assert uniqueness before writing.
Do not claim full circular-origin GFF correctness unless it is actually tested.
At minimum:
- preserve segment-level output correctly;
- avoid representing an origin-spanning parent as a misleading whole-replicon span;
- add a test fixture for an origin-crossing compound feature on a circular record.
If a fully standards-compliant parent representation is deferred, document this limitation.
def test_gff_phase_respects_codon_start_2(...):
...
def test_gff_phase_respects_codon_start_3(...):
...
def test_gff_compound_phase_nonzero_transition(...):
...
def test_gff_ids_are_globally_unique(...):
...
def test_gff_existing_gene_not_duplicated(...):
...
def test_gff_origin_spanning_compound_feature(...):
...The typed model correctly maps:
+1 -> +
-1 -> -
0 -> ?
None -> .
but compatibility methods currently use:
'-' if self.strand == -1 else '+'for:
feature['strand']
feature.to_dict()['strand']This reintroduces the old bug.
Use:
self.strand_symboleverywhere.
Required test:
def test_legacy_dict_preserves_unknown_and_unstranded_state(...):
...Create synthetic features with strand 0 and None directly if GenBank fixture generation is awkward.
Affected file:
src/genbank_parser/validate.py
The validator is now substantially improved and should retain its present architecture.
Current report computes global feature coordinate span:
max(feature.end) - min(feature.start) + 1across all records.
For multiple contigs, this is not total genome length.
Use:
doc.total_lengthfor total genome size.
Optionally report per-record span separately.
Do not treat all CDSs as ordinary genetic-code translations.
Recognize presence of:
/transl_except
/exception
and related exceptional biology.
Examples:
- selenocysteine;
- pyrrolysine;
- programmed ribosomal frameshifting;
- RNA editing;
- translational exceptions.
If exceptional translation qualifiers are present:
- emit an
INFOfinding such as:
EXCEPTIONAL_TRANSLATION_ANNOTATION
- do not escalate a computed mismatch or internal stop to normal severity unless explicitly justified.
Future releases can implement exact exception reconstruction.
Do not silently fall back to table 11 without reporting it.
Current behavior:
except Exception:
translate(table=11)Instead:
WARNING: UNKNOWN_TRANSLATION_TABLE
and skip strict comparison, or explicitly mark fallback behavior.
def test_validator_total_length_multirecord(...):
...
def test_validator_transl_except_does_not_false_error(...):
...
def test_validator_unknown_translation_table_is_reported(...):
...Affected file:
src/genbank_parser/codon.py
Current model exposes f.transl_table, but codon analysis remains hard-coded to code 11.
This should be corrected for architectural consistency.
Use Biopython codon tables:
from Bio.Data import CodonTableFor each transl_table:
- construct codon -> amino-acid mapping;
- construct synonymous codon families;
- count genes by translation table.
If a file contains multiple translation tables, either:
Best scientifically.
or:
Use the most common table and warn about excluded CDSs from other tables.
Do not silently reinterpret all CDSs as table 11.
Current total_codons includes stops, but stop codons are not emitted in RSCU rows.
Choose one consistent definition:
- exclude terminal stops from
total_codons, or - explicitly output stop codon counts separately.
Preferred:
sense_codons
terminal_stop_codons
ambiguous_codons
translation_tables_encountered
cds_excluded_partial
cds_excluded_pseudo
cds_excluded_nontriplet
ambiguous_codons
terminal_stops
Current coding density sums all CDS biological lengths:
sum(f.length for f in CDSs)This double-counts overlapping CDSs.
Compute the union of CDS nucleotide intervals per record.
For compound CDSs:
- add each location part independently;
- merge overlapping/adjacent intervals;
- compute nonredundant covered nucleotides.
Expose:
cds_feature_bp_sum
nonredundant_coding_bp
coding_density
Use nonredundant coverage for coding_density.
Affected file:
src/genbank_parser/discover.py
Current implementation and public description are inconsistent.
The CLI accepts:
--operon-gapbut discover_clusters() does not use it.
Choose one:
Actually invoke the shared operon/proximity logic.
Remove operon_gap from this module until implemented.
Do not keep inert CLI parameters.
CLI accepts:
--format tsvbut the code falls through to text mode.
Implement a real TSV branch.
Suggested columns:
record
cluster_id
cluster_start
cluster_end
locus_tag
gene
product
strand
rule_id
matched_term
weight
total_feature_score
The previous implementation contained explicit hypothetical/unknown-function cluster analysis.
Current module no longer performs that analysis.
Choose one:
- restore it; or
- stop calling this module a dark-matter detector.
For Patch 2, option 2 is acceptable.
Move built-in rules into package resources:
src/genbank_parser/rulesets/
mobilome.yaml
xenobiotics.yaml
Use:
importlib.resourcesto load them.
Avoid keeping a second copy of default mobilome rules hard-coded in Python.
CLI proposal:
gbparse discover input.gbff --ruleset mobilome
gbparse discover input.gbff --ruleset xenobiotics
gbparse discover input.gbff --rules custom.yamlAllow multiple built-ins later.
Current flat schema:
terms:
weight:
category:is adequate for Patch 2.
Do not claim KO/domain-aware evidence unless implemented.
For 0.3.0, evolve toward:
id: alkane_monooxygenase
category: Alkane degradation
weight: 3
evidence:
gene:
- ladA
product:
- long-chain alkane monooxygenase
ko:
- K20938
pfam:
- ...
negative_patterns:
- DNA repair AlkBAffected file:
src/genbank_parser/compare.py
Current product matching uses:
t_low in prodwhich can generate substring false positives.
Restore token/word-boundary logic.
Example helper:
def _word_in(needle: str, haystack: str) -> bool:
return bool(
re.search(
r'(?<![\w-])' + re.escape(needle) + r'(?![\w-])',
haystack,
re.IGNORECASE,
)
)Typed xref matches should remain exact.
Until sequence-based validation is implemented, describe this command as:
annotation/xref marker scanner
not an ortholog inference engine.
Affected file:
src/genbank_parser/phylo.py
The current implementation silently keeps the first hit per marker.
This loses useful safety behavior from the previous version.
For each marker collect all candidates:
marker -> list[GenBankFeature]Classify:
0 hits -> ABSENT
1 hit -> SINGLE_COPY
>1 hits -> MULTI_COPY / REVIEW
Restore:
- minimum translation length;
- explicit multi-copy warnings;
- optional gene/product mismatch warnings.
Do not create a concatenated multi-marker “alignment” unless actual per-marker alignment is implemented.
Until HMM orthology is implemented:
annotation-based phylogenetic marker candidates
is more accurate than “validated phylogenomic markers”.
Affected file:
src/genbank_parser/crispr.py
The module is useful as an annotation scanner, but not a sequence-level CRISPR detector.
Use one interval-distance helper:
def interval_distance(a_start, a_end, b_start, b_end):
if a_end < b_start:
return b_start - a_end
if b_end < a_start:
return a_start - b_end
return 0Filter using the same value that is later printed.
Current behavior can return:
'colocalized': []in one case and:
'colocalized': 3in another.
Use a stable schema:
{
"arrays": [...],
"cas_genes": [...],
"colocalized": [...],
"colocalized_count": 3,
}Rename wording to:
CRISPR/Cas annotation scanner
until sequence-level detection is added.
Affected file:
src/genbank_parser/diff.py
Current matching identity:
(record_id, start, end, strand)
means any boundary shift becomes:
one removed CDS
+
one added CDS
rather than a coordinate shift.
Use a staged matching approach:
same locus_tag
same protein_id
For unmatched features:
same record
same strand
reciprocal overlap >= threshold
Suggested threshold:
>= 80%
If translations are present:
SHA-256(sequence)
can identify identical proteins despite coordinate/locus-tag changes.
Report:
unchanged
product_changed
gene_changed
xref_changed
boundary_shifted
added
removed
possible_split
possible_merge
Full split/merge classification may be deferred.
The changelog currently claims KO/EC differences, but code only compares KOs.
Add EC comparison or weaken documentation.
Current project metadata says:
requires-python = ">=3.8"but source code uses PEP 604 union syntax:
str | Path
int | NoneThis requires Python 3.10+.
Change:
requires-python = ">=3.10"Update README badge and installation docs accordingly.
CI already begins at Python 3.10, which is appropriate.
Add:
LICENSE
containing the MIT license.
Do not rely only on README badge / package metadata.
Current version exists in:
pyproject.toml
src/genbank_parser/__init__.py
Prefer metadata lookup:
from importlib.metadata import version
__version__ = version("genbank-parser")Keep package version only in pyproject.toml.
Several current claims should be narrowed until later roadmap stages are implemented.
100% backward compatibility
Legacy script paths are preserved through lightweight wrappers.
Some command-line argument contracts changed in 0.2.0; users should prefer
the unified `gbparse` CLI.
accurate GFF3 phase calculation
Only retain if codon_start, compound transitions, and reverse-strand cases are tested.
phylogenomic marker extraction
annotation-based candidate phylogenetic marker extraction
until HMM validation exists.
CRISPR detector
CRISPR/Cas annotation scanner
until sequence-level array detection exists.
dark-matter discovery
Remove unless dark-matter clustering is restored.
coordinate shifts
Only claim this after overlap/identifier-aware diff matching is implemented.
The following test set should exist before tagging 0.2.1.
- ordinary forward CDS;
- ordinary reverse CDS;
- strand
None; - strand
0; - joined forward CDS;
- joined reverse CDS;
- partial start;
- partial end;
codon_start=2;codon_start=3;- alternate
transl_table; - pseudogene;
- exceptional translation qualifier;
- multi-record chromosome + plasmid;
- circular record.
- paired
gene+CDSlocus prefers CDS; - requested target is never replaced by index 0;
- circular neighborhood wraps correctly;
- linear neighborhood clamps correctly.
- locus extraction;
- ±N gene extraction;
- bp-flanked extraction;
- valid local coordinates;
- preserved compound location;
- reverse-strand compound location;
- all feature coordinates <= output sequence length;
- optional circular-origin extraction or explicit rejection.
- ordinary feature not split;
- compound feature split correctly;
- phase 0;
- phase 1;
- phase 2;
codon_start=2;codon_start=3;- reverse-strand joined CDS;
- globally unique IDs;
- no duplicate synthetic gene;
- complete
##sequence-region; - circular-origin feature fixture.
- missing product;
- missing translation;
- pseudogene tolerance;
- translation mismatch;
- internal stop;
- alternative start;
- alternate translation table;
- exceptional translation;
- duplicate locus tag;
- out-of-bounds coordinate;
- total genome length across multiple records.
- compound CDS biological extraction;
- reverse strand;
- translation table awareness;
- terminal stop accounting;
- ambiguous codon accounting;
- pseudogene exclusion.
- built-in YAML loads after package install;
- custom YAML loads;
--format text;--format json;--format tsv;- no unused/inert CLI arguments.
- exact gene match;
- exact KO match;
- product word match;
- substring false-positive regression.
- zero-hit marker;
- one-hit marker;
- multi-copy marker;
- short-fragment exclusion.
- interval-distance boundary;
- stable schema for zero hits;
- stable schema for positive hits.
- identical feature;
- product rename;
- gene rename;
- KO change;
- EC change;
- 1–3 bp boundary shift recognized as shift rather than add/remove.
Smoke-test every subcommand:
gbparse validate
gbparse summary
gbparse extract
gbparse search
gbparse locus
gbparse neighborhood
gbparse region
gbparse fasta
gbparse sequence
gbparse codon
gbparse functional
gbparse discover
gbparse compare
gbparse diff
gbparse phylo
gbparse crispr
gbparse gff
gbparse batch-summaryAlso smoke-test retained scripts where backward wrappers are intentionally supported.
test: commit GenBank fixtures and harden clean-clone CI
.gitignoreexceptions;- add fixture files;
- verify pytest from fresh environment.
fix: prefer CDS locus resolution and remove silent neighborhood fallback
model.py;neighborhood.py;region.py;- regression tests.
fix: preserve compound locations and valid local coordinates in region exports
fix: handle codon_start phases and unique feature hierarchy in GFF3
fix: refine exceptional translation validation and genetic-code-aware codon analysis
fix: reconcile discovery output contracts and restore safe marker matching
fix: restore marker-copy safeguards and stabilize CRISPR/diff semantics
chore: align package metadata, licensing, changelog, and documented capabilities
Then tag:
v0.2.1
Do not tag the patch until all of the following are true:
-
pip install -e .[test]succeeds from a fresh clone. - All committed tests run without private/untracked fixtures.
- GitHub Actions passes on every supported Python version.
-
find_locus()cannot silently resolve a gene when a CDS is required. - neighborhood never silently falls back to the first CDS.
- region output always has internally valid coordinates.
- compound feature locations survive region extraction.
- GFF phase tests exercise 0, 1, and 2.
- GFF IDs are globally unique.
- compatibility strand output preserves
?and.. - validator reports total multi-record genome length correctly.
- codon analysis is translation-table aware or explicitly rejects unsupported mixtures.
-
discover --format tsvactually emits TSV. - all advertised discovery CLI options affect behavior.
- compare product matching is token/word safe.
- phylo reports multi-copy candidates rather than silently choosing the first.
- CRISPR return schema is stable.
- diff documentation matches actual shift/xref detection.
-
requires-pythonis>=3.10. -
LICENSEexists. - package version has one source of truth.
- README/SKILL/changelog no longer overclaim unimplemented P2 features.
After 0.2.1 is stable, scientific expansion can proceed without destabilizing the core parser.
Add optional:
annotation evidence
+ protein similarity
+ reciprocal best hit
+ HMM profile
+ neighborhood conservation
Potential backends:
- MMseqs2;
- DIAMOND;
- BLAST+.
Add:
gbparse phylo --backend annotation
gbparse phylo --backend hmmPotential marker sets:
- GTDB bacterial markers;
- GTDB archaeal markers;
- BUSCO lineage sets;
- user-provided HMM panels.
Expand YAML schema to support:
gene symbol
product
KO
COG
Pfam
HMM
negative evidence
neighborhood evidence
copy number
strand/orientation
Return an evidence trace explaining every score.
Potential hooks:
MinCED
CRISPRCasTyper
Output:
repeat consensus
repeat count
spacer count
Cas subtype
array–Cas distance
confidence
Add sequence- and overlap-aware matching to classify:
boundary shifts
splits
merges
renames
protein-preserving gene-model changes
The 0.2.0 makeover should be preserved as the new architectural base.
The next patch should not be another rewrite.
The strongest path is:
typed architecture
↓
adversarial regression tests
↓
correctness hardening
↓
truthful documentation
↓
0.2.1 stable core
↓
0.3.0 scientific-depth features
The central principle for every future module should remain:
Preserve the full biological semantics of the source annotation, and never silently replace uncertainty or failure with plausible-looking output.