Smart-Align: Codon-Aware Partitioned Viral Genome Multiple Sequence Aligner
Smart-Align is a codon-aware, synteny-partitioned multiple sequence aligner engineered specifically for multi-gene viral genomes. It partitions viral cohorts into coding (CDS, CDS_OVERLAP) and non-coding (5'UTR, INTERGENIC, 3'UTR) blocks, aligns coding blocks in their biological reading frames via amino acid translation and back-translation, and stitches the full-genome alignment together under a 100% lossless round-trip invariant.
Unlike reference-projection tools (e.g., Nextclade / Nextalign) that discard insertions relative to a single reference, Smart-Align builds a true multiple sequence alignment (MSA) while eliminating manual block slicing and "concatenation" artifacts in downstream tools such as Geneious Prime, IQ-TREE, RAxML, HyPhy, and PAML.
Smart-Align vs. MAFFT / Nextalign / MACSE
Smart-Align orchestrates MAFFT (and optionally miniprot, FAMSA, MACSE, and mash) rather than replacing MAFFT's alignment heuristics. The table below summarizes where Smart-Align fits alongside standard viral alignment tools:
| Capability / Workflow | Smart-Align | MAFFT (nucleotide) | Nextalign / Nextclade | MACSE v2 |
|---|---|---|---|---|
| Primary Output | Full-genome true MSA (FASTA, .geneious, .gbk, .gff3, .ungapped.gff3) + per-gene codon MSAs |
Full-genome nucleotide MSA (FASTA) | Reference-projected CDS + nucleotide alignment (drops non-ref insertions in aligned coordinates) | Single-CDS frameshift-aware codon MSA |
| Codon-Frame Integrity | Yes — partitions CDS / CDS_OVERLAP / UTR / intergenic; aligns CDS via AA back-translation (StopCol, -1/+1 PRF) |
No — nucleotide alignment inserts 1–2 nt gaps inside CDS, shattering reading frames | Yes (per-CDS) — codon-aware relative to a single reference | Yes (single locus) — $O(N^2 L^2)$ DNA/AA DP per CDS |
| Multi-Gene / Spliced / Overlapping ORFs | Yes — GenBank/GFF3 join(...), cumulative phase, -1/+1 PRF, --overlap-mode primary, --block-mode union |
No — unaware of ORFs or overlaps | Partial — single-reference gene map; no union accessory discovery |
No — requires manually sliced single-CDS inputs |
| Frameshift Indel Handling | Yes — 4-case engine (BOUNDARY_TRIMMED, PREMATURE_STOP, FRAMESHIFT_REPAIRED, ABSENT/DEGRADED) + built-in 3-frame DP or optional --frameshift-backend macse |
No | Yes — flags/masks frameshifts relative to reference | Yes — native frameshift-aware alignment |
| Lossless Round-Trip & Provenance | 100% invariant (ungap(aligned) == raw + inverse transform check), --qc-tsv, --manifest, smart-align validate |
Yes (FASTA only; no QC/validation) | No — insertions relative to reference are omitted from reference-coordinate output | Inserts ! / swaps stop symbols unless exported/cleaned |
| When to Choose | Multi-gene viral genomes for IQ-TREE/RAxML (--partitions), HyPhy/PAML (--per-gene-dir --strip-stops), or Geneious |
Unannotated genomes, non-coding loci, or fast rough nucleotide MSAs | Rapid clade assignment, QC, or mutation calling against an established reference | Deep de novo single-CDS frameshift-aware alignment on small cohorts |
Core Scientific Capabilities (v2)
- 100% Lossless Round-Trip Invariant
- Stripping
-gaps from any stitched alignment is verified byte-for-byte against the input nucleotide sequence (ungap(aligned) == original). - When
--auto-orient(reverse-complement) or--circular(origin rotation) is active, dual verification confirms that applying the inverse transform logged in--manifestreproduces every raw input nucleotide sequence bit-for-bit.
- Stripping
- 100% Codon-Column Integrity
- Inside every intact
CDSblock and prioritizedCDS_OVERLAPblock, codon positions 1, 2, and 3 align column-for-column (smart-align validateverifies this independently). - Supports cumulative reading-phase tracking across spliced/joined
CDSfeatures,-1/+1programmed ribosomal frameshift (PRF) slippage junctions (e.g., Arteriviridae / CoronaviridaeORF1ab) on both+and-strands, joint split-codon seam coupling across continuousCDS | CDS_OVERLAPboundaries, and co-transcriptional RNA-editingFeatureSpansynthesis for ParamyxoviridaeP/V/W(/exception,/note,/transl_except). - Supports 27 NCBI genetic code tables (
1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33; default1).
- Inside every intact
- 3-Tier Boundary Anchoring Hierarchy & Pass-2 Refinement
- Tier 1 (Own Orthologous CDS): Anchors each genome's block boundaries directly to its own annotated CDS matched by coordinate overlap with the lifted reference CDS (invariant to naming differences such as
Svs.spike glycoprotein CDS, with coordinate-gated edit-distance-1 typo tolerance such asOFR3 → ORF3and PRF-awareORF1a/ORF1absplitting). - Tier 2 (Optional Protein-Level Transfer via
miniprot): Usesminiprotwhen available (or explicitly requested via--boundary-engine miniprot) to transfer CDS boundaries across divergent cohorts. - Tier 3 (Codon-Snapped Nucleotide Liftover): Snaps lifted nucleotide coordinates to the nearest in-frame start/stop codons within a bounded search window. Failed liftover fails loudly unless
--skip-failed-liftoveris specified. - Pass-2 Refinement (
--refine-boundaries): Re-derives 3' block boundaries from the aligned stop-codon column of the initial codon MSA and re-aligns shifted blocks.
- Tier 1 (Own Orthologous CDS): Anchors each genome's block boundaries directly to its own annotated CDS matched by coordinate overlap with the lifted reference CDS (invariant to naming differences such as
- Terminal Stop-Column Enforcement
- Strips terminal stop codons prior to protein MSA and re-appends them as a dedicated, forced-aligned final stop-codon column (
StopCol), preventing C-terminal length differences from causing stop codons to drift into internal columns.
- Strips terminal stop codons prior to protein MSA and re-appends them as a dedicated, forced-aligned final stop-codon column (
- 4-Case Frameshift-Aware CDS Engine & Per-Sequence QC (
--qc-tsv)- Classifies coding anomalies explicitly rather than blindly ejecting sequences to nucleotide alignment:
- Boundary overrun (
BOUNDARY_TRIMMED): trims trailing overrun bases at the true in-frame stop. - Genuine premature stop (
PREMATURE_STOP): preserves codon alignment (masking internal stops asXduring protein MSA). - True indel frameshift (
FRAMESHIFT_REPAIRED): repairs frame using Smart-Align's built-in frameshift-aware aligner or optional MACSE v2 (--frameshift-backend macse). - Absent or degraded gene (
ABSENT/DEGRADED): aligns at the nucleotide level and flags the record explicitly.
- Boundary overrun (
- Writes a 25-column per-
(record, block)QC TSV (--qc-tsv) with completeness, internal stops, frameshift counts,% N, liftover identity, boundary deltas, outlier flags, and transform metadata.
- Classifies coding anomalies explicitly rather than blindly ejecting sequences to nucleotide alignment:
- Virosphere Generalization (
strand == -1,--auto-orient,--circular,--segmented)- Minus-Strand CDS: Extracts, reverse-complements, applies minus-strand cumulative phase/start/stop logic, codon-aligns, and reverse-complements back before stitching.
--auto-orient: Uses fast canonical 13-mer strand voting (with MAFFT verification for ambiguous records) to detect and reverse-complement oppositely oriented contigs/assemblies against the reference, transforms accompanying annotations consistently, and logs flipped IDs in--qc-tsvand--manifest.--circular: Rotates circular genomes and shifts feature coordinates modulo genome length (preserving origin-wrappedjoin(...)features) to align with the reference origin.--segmented: Clusters multi-segment FASTA/GenBank inputs to reference segments using 13-mer nucleotide containment, singleton verification, and Pass-3 cluster-to-cluster merging (translated 6-frame AA 5-mer containment, MAFFT verification, and/segmentqualifier tie-breakers), then runs the full pipeline per segment.
- Union Block Architecture (
--block-mode {reference,union})reference(default) partitions strictly along the selected reference's synteny.uniondiscovers orthologous CDS clusters across all annotated input genomes, cleanly capturing lineage-specific accessory ORFs (e.g., coronavirusORFx) even when absent from the chosen reference genome.
- Dual-Coding Overlaps (
--overlap-mode,--priority-genes)--overlap-mode primaryroutesCDS_OVERLAPblocks to the codon aligner in the priority gene's frame (configured via--priority-genes, defaulting to the longest/most conserved overlapping CDS) so triplet gaps preserve reading frame across both genes.
- Large-Cohort Scaling & Presets (
--scale-mode,--accuracy,--protein-aligner)--accuracy {fast,default,high}maps to MAFFTFFT-NS-2(--retree 2),--auto, andL-INS-i(--localpair --maxiterate 1000), with optional--protein-aligner {mafft,famsa}.--scale-mode(with--core-size, default100) selects a diverse core viamash(if installed) or fast canonical k-mer farthest-first clustering, builds a high-accuracy core MSA, and places remaining sequences viamafft --add --keeplength --mapoutwhile reconstructing insertions losslessly.- Largest-first parallel block scheduling under a strict global
-t/--threadsbudget across block workers andmafft --thread k, with proportional thread allocation, size-awareFFT-NS-idispatch for large--accuracy defaultblocks, and $O(N \cdot L)$ exact pairwise identity reporting in--report.
- Built-In Validator, Profiling & Provenance (
smart-align validate,--profile,--manifest)smart-align validateverifies uniform alignment length, lossless reconstruction, and per-block / overall codon-column phase consistency against configurable--min-codon-consistencythresholds.--profile(and--report) prints a per-stage wall-clock timing and OS peak RSS table (parse_io,preprocess,liftover,partition_and_collinearity,block_msa,frameshift_dp,stitch,per_gene_msa,export_io).--manifestwrites a JSON provenance record capturing Smart-Align and external tool versions, CLI arguments, reference IDs, block tables, orientation/rotation transforms, QC summaries, per-stagetimings_sec/timings_sub_sec/peak_rss_mb,per_gene_excludedquarantine logs, and SHA-256 input/output checksums.
Requirements & Installation
1. Required Prerequisites
- Python:
>= 3.10(pure Python standard library at runtime; zero required third-party Python runtime packages) - MAFFT (
>= 7.490recommended/tested): required onPATH(or passed via--mafft-path) for nucleotide/protein MSAs, pairwise liftover, and--scale-modeplacement:# macOS (Homebrew) brew install mafft # Ubuntu / Debian sudo apt-get update && sudo apt-get install -y mafft # Conda / Bioconda conda install -c bioconda "mafft>=7.490"
2. Optional Accelerators & Downstream Tools
Smart-Align works out of the box with only Python and mafft. Optional external tools accelerate or specialize specific stages (or run downstream phylogenetic analyses):
# Optional Smart-Align backends / accelerators (Bioconda)
conda install -c bioconda miniprot famsa macse mash
# Alternative macOS / Ubuntu installs where packaged
brew install brewsci/bio/famsa mash # macOS
sudo apt-get install -y mash # Ubuntu / Debian
# Optional downstream phylogenetic / selection tools used in examples
conda install -c bioconda iqtree hyphy
(See Optional External Tools & Built-in Fallbacks for exact behavior when any optional binary is omitted.)
3. Install Smart-Align
git clone https://github.com/jsede/smart-align.git
cd smart-align
# Standard user installation
pip install .
# Or editable installation for local development
pip install -e .
For development, linting, and running the test suite (installs pytest>=7.0, ruff>=0.4, biopython>=1.80):
pip install -e ".[dev]"
Quick Start
Runnable Examples (Shipped in examples/public/)
# 1. Multi-record GenBank cohort (WPDV) with QC report and built-in validation
smart-align examples/public/WPDV.gb -o wpdv_aligned -t 8 --report \
--qc-tsv wpdv_qc.tsv --manifest wpdv_manifest.json
smart-align validate wpdv_aligned.fasta --raw examples/public/WPDV.gb \
--manifest wpdv_manifest.json --qc-tsv wpdv_qc.tsv
# 2. FASTA + GFF3 cohort (Nobecovirus) using union block mode (captures accessory ORFs absent from reference)
smart-align examples/public/Nobeco.fasta \
--gff examples/public/Nobeco.gff \
-r OK067319 \
--block-mode union -o nobeco_union -t 8 \
--qc-tsv nobeco_qc.tsv --manifest nobeco_manifest.json
Expected Quick Start Output (examples/public/WPDV.gb)
Running example #1 above produces the following terminal output:
=== Smart-Align v0.2.0 ===
Input: examples/public/WPDV.gb
Output prefix: wpdv_aligned
MAFFT binary: /opt/homebrew/bin/mafft
Algorithm: auto
Threads: 8
Genetic code: 1
Overlap mode: nucleotide
Loaded 11 viral genome records.
Selected reference genome: MN508192 (13339 bp, 7 CDS features)
Partitioned into 15 blocks (7 coding CDS blocks [0 overlap], 8 non-coding blocks).
Lossless check passed: 100% of sequences match input nucleotide content.
Final aligned length: 13583 bp
Alignment completed successfully in 6.72s!
• Geneious Archive: wpdv_aligned.geneious (1-click import into Geneious Prime with alignment + CDS & block tracks)
• Aligned FASTA: wpdv_aligned.fasta
• Aligned GFF3: wpdv_aligned.gff3 (gapped alignment coordinates)
• Ungapped GFF3: wpdv_aligned.ungapped.gff3 (ungapped sequence coordinates)
• Aligned GenBank: wpdv_aligned.gbk
• Per-Sequence QC: wpdv_qc.tsv
• Run Manifest: wpdv_manifest.json
--- Syntenic Block QC Report ---
Block Name Type Ref Span Frame Aln Len NT Id% Notes
-------------------------------------------------------------------------------------------------------------
5UTR NON_CODING 1..649 - 660 86.4% Nuc MSA
CDS_RdRp1ab_part1_649_6664 CDS 650..6664 +1 6086 78.2% Codon MSA [StopCol]
OVERLAP_RdRp1ab_RdRp1a_6664_6688 NON_CODING 6665..6688 - 96 78.5% Nuc MSA
CDS_RdRp1ab_part2_6688_10754 CDS 6689..10754 +2 4066 82.1% Codon MSA
OVERLAP_RdRp1ab_GP2_10754_10899 NON_CODING 10755..10899 - 145 78.4% Nuc MSA
CDS_GP2_10899_11236 CDS 10900..11236 +2 349 68.4% Codon MSA
OVERLAP_GP2_GP3_11236_11375 NON_CODING 11237..11375 - 139 84.4% Nuc MSA
CDS_GP3_11375_11769 CDS 11376..11769 +2 397 73.1% Codon MSA
OVERLAP_GP3_GP4_11769_11887 NON_CODING 11770..11887 - 118 81.9% Nuc MSA
CDS_GP4_11887_12485 CDS 11888..12485 +2 604 75.4% Codon MSA; Degraded:NC_026811,JN116253
OVERLAP_GP4_M_12485_12549 NON_CODING 12486..12549 - 112 95.8% Nuc MSA
CDS_M_12549_12858 CDS 12550..12858 +2 309 79.6% Codon MSA
OVERLAP_M_N_12858_13028 NON_CODING 12859..13028 - 170 84.5% Nuc MSA
CDS_N_13028_13239 CDS 13029..13239 +3 217 81.4% Codon MSA [StopCol]
3UTR NON_CODING 13240..13339 - 115 93.1% Nuc MSA
--- Stage Timing & Peak RSS Profile ---
Stage Time (s) Share (%)
----------------------------------------------------
parse_io 0.0109 0.2%
preprocess 0.0000 0.0%
auto_orient 0.0000 0.0%
circular_rotate 0.0000 0.0%
assign_segments 0.0000 0.0%
liftover 3.9478 59.4%
partition_and_collinearity 0.4381 6.6%
block_msa 2.1884 32.9%
frameshift_dp 0.0000 0.0%
stitch 0.0093 0.1%
per_gene_msa 0.0000 0.0%
export_io 0.0443 0.7%
----------------------------------------------------
total 6.6476 100.0%
Peak RSS (MB): self=61.42 children=843.30 max=843.30
Validation output:
=== Smart-Align Validation Report ===
Alignment: wpdv_aligned.fasta
Sequences: 11
Aligned length: 13583 bp
Uniform length: PASS
Lossless check: PASS
Threshold: 100.00%
Overall codon %: 100.00%
Block Name Cols Consistent% Status Discordant
--------------------------------------------------------------------------------------------
CDS_RdRp1ab_part1_649_6664 6086 100.00% PASS
CDS_RdRp1ab_part2_6688_10754 4066 100.00% PASS
CDS_GP2_10899_11236 349 100.00% PASS
CDS_GP3_11375_11769 397 100.00% PASS
CDS_GP4_11887_12485 604 100.00% PASS
CDS_M_12549_12858 309 100.00% PASS
CDS_N_13028_13239 211 100.00% PASS
Overall validation: PASS
Illustrative Workflow Templates (Replace with Your Own Input Files)
The following commands illustrate --segmented and --circular flags using placeholder filenames (segmented_cohort.gb and circovirus_cohort.gb are not shipped in examples/public/):
# Multi-segment / ambisense cohort with mixed-orientation contigs
smart-align segmented_cohort.gb -o seg_aligned --segmented --auto-orient -t 8
# Circular genome cohort rotated to the reference origin
smart-align circovirus_cohort.gb -o circo_aligned --circular --auto-orient -t 8
Standard Output Files (-o <prefix>)
| File | Description |
|---|---|
<prefix>.geneious |
Native Geneious Prime alignment archive (.geneious XML inside ZIP) with projected annotations and consensus Smart-Align: Codon MSA / Smart-Align: Nucleotide MSA block tracks. |
<prefix>.fasta |
Aligned multi-FASTA. |
<prefix>.gbk |
Aligned multi-record GenBank flatfile with projected coordinates (or ungapped coordinates with --ungapped-genbank). |
<prefix>.gff3 |
Alignment-coordinate (gapped) GFF3 feature track. |
<prefix>.ungapped.gff3 |
Ungapped sequence-coordinate GFF3 feature track (after any --auto-orient / --circular preprocessing). |
Virosphere Benchmark & Example Results (v0.2.0)
Smart-Align v0.2.0 was re-benchmarked end-to-end against orientation- and rotation-matched MAFFT v7.490 (--auto) across 10 frozen NCBI GenBank viral panels (1,049 records, 18 unified segment clusters, 5,112 annotated CDS features, 5,008 intact input CDSs):
- Validation & HyPhy/PAML Readiness:
smart-align validatepasses on9/10panels (coronaviridae100.00%,hepadnaviridae100.00%,adenoviridae100.00%, up from6/10inv0.1.0;retroviridae99.98%with0NON_COLLINEARandCDS_neffixed, leaving onlyNC_001802's 2-columnCDS_gaggag-pol PRF convention offset). Default--per-gene-dir --strip-stopspasses HyPhy/PAML checks (100.0% mod-3, 100.0% zero internal stops) across10/10panels (116MSAs), up from5/10inv0.1.0. - Segment Merging, Collinearity & Lossless Reconstruction: Pass-3 segment merging unifies
orthomyxoviridae(18 → 8segments) andarenaviridae(11 → 2segments) with 0 false merges; falseNON_COLLINEARwarnings drop10 → 0(10/10clean); lossless round-trip remains10/10PASS. - Frame-Breaking Indels & Speed/Memory: Pooled frame-breaking internal CDS gap runs drop
960 (5.36%) → 754 (4.24%)(hepadnaviridae90 → 0,coronaviridae271 → 68), compared with6,004 (35.41%)in Naive MAFFT (8.35× reduction). Total wall-clock runtime improves 4.24× (2,901.64s → 684.27s) and max peak RSS drops 76.2% (3,786.55 MB → 902.02 MB).
| Family (Scope) | N (Segs) |
Time (v0.1 → v0.2) |
Peak RSS (v0.1 → v0.2) |
validate Cons. (%) |
SA FB Indels (%) [Disr. CDS] | MAFFT FB Indels (%) [Disr. CDS] | HyPhy per_gene |
|---|---|---|---|---|---|---|---|
coronaviridae (PEDV) |
70 (1) | 579.02s → 69.18s | 3,786.5 → 802.5 MB | PASS 100.00% | 6.37% [68/428] | 1.54% [3/428] | PASS (8 MSAs) |
flaviviridae (DENV-1–4) |
90 (1) | 271.17s → 74.43s | 1,258.8 → 902.0 MB | PASS 100.00% | 0.00% [0/88] | 55.15% [88/88] | PASS (1 MSA) |
picornaviridae (Enterovirus A) |
70 (1) | 158.05s → 38.34s | 754.9 → 637.2 MB | PASS 100.00% | 0.00% [0/70] | 42.24% [70/70] | PASS (1 MSA) |
paramyxoviridae (Measles) |
70 (1) | 110.02s → 41.44s | 305.9 → 207.6 MB | PASS 100.00% | 0.00% [0/560] | 0.00% [0/560] | PASS (8 MSAs) |
orthomyxoviridae (Influenza A) |
372 (8) | 437.01s → 109.50s | 159.9 → 126.7 MB | PASS 100.00% | 0.00% [0/531] | 30.04% [95/531] | PASS (12 MSAs) |
arenaviridae (Lassa virus) |
72 (2) | 397.30s → 70.86s | 881.5 → 623.1 MB | PASS 100.00% | 0.00% [0/139] | 44.62% [33/139] | PASS (4 MSAs) |
circoviridae (PCV2) |
90 (1) | 45.60s → 12.28s | 80.8 → 71.0 MB | PASS 100.00% | 0.00% [0/199] | 67.42% [90/199] | PASS (3 MSAs) |
hepadnaviridae (HBV) |
90 (1) | 123.57s → 55.53s | 191.0 → 168.2 MB | PASS 100.00% | 0.00% [0/495] | 25.32% [177/495] | PASS (9 MSAs) |
retroviridae (HIV-1 Group M) |
70 (1) | 499.55s → 94.92s | 774.3 → 195.7 MB | FAIL 99.98% | 6.05% [321/513] | 39.19% [512/513] | PASS (10 MSAs) |
adenoviridae (HAdV-C) |
55 (1) | 280.34s → 117.80s | 365.2 → 396.4 MB | PASS 100.00% | 3.92% [233/1,985] | 30.78% [979/1,985] | PASS (60 MSAs) |
| Total (10 Panels) | 1,049 (18) | 2,901.64s → 684.27s (4.24×) | 3,786.5 → 902.0 MB (-76.2%) | 9/10 PASS | 4.24% [622/5,008] | 35.41% [2,047/5,008] | 10/10 PASS (116 MSAs) |
See benchmarks/virosphere_benchmark_report.md (plus benchmarks/README_SNIPPET.md and examples/showcase/) for the full v0.1.0 → v0.2.0 scorecard, stage-level profiling deltas, and publication figures.
Downstream Phylogenetics & Tooling Workflows
1. IQ-TREE / RAxML Partitioned Phylogenetics (--partitions, --blocks-bed, --blocks-tsv)
Export a complete, disjoint 1-based NEXUS SETS block containing separate charsets for codon positions 1, 2, and 3 (_pos1, _pos2, _pos3) of every coding block, Case-4 insertion columns (_ins), and non-coding blocks (5UTR, INTERGENIC, 3UTR, OVERLAP_*), along with BED6+3 (--blocks-bed) and 16-column coordinate metadata (--blocks-tsv):
smart-align examples/public/WPDV.gb -o wpdv_aligned -t 8 \
--overlap-mode primary \
--partitions wpdv_partitions.nex \
--blocks-tsv wpdv_blocks.tsv \
--blocks-bed wpdv_blocks.bed
Then pass the alignment and partition file to an external phylogenetic tool such as IQ-TREE2 (must be installed separately):
# Illustrative external IQ-TREE2 command
iqtree2 -s wpdv_aligned.fasta -p wpdv_partitions.nex -m MFP+MERGE -B 1000 -T AUTO
2. HyPhy / PAML Selection & dN/dS Analysis (--per-gene-dir, --strip-stops, --include-defective-per-gene)
Generate a full-length, in-frame codon nucleotide MSA (<gene>.fasta) and matching amino acid MSA (<gene>.aa.fasta) for every CDS gene cluster—spanning any internal CDS_OVERLAP boundaries, clustering synonymous GenBank annotations by aligned genomic locus, and slicing single-block genes directly without redundant re-alignment. Add --strip-stops to remove terminal stop codons and trailing all-gap codon columns for HyPhy/codeml compatibility.
By default (v0.2.0), --per-gene-dir produces strictly HyPhy/PAML-clean MSAs (100% mod-3, 0 split-codon gaps, 0 internal * stops) by quarantining records flagged FRAMESHIFT_REPAIRED, DEGRADED, or PREMATURE_STOP (while retaining pure all-gap --- rows for ABSENT records) and logging excluded records to manifest.json["per_gene_excluded"] and <per_gene_dir>/per_gene_excluded.tsv. Pass --include-defective-per-gene to opt defective records back into <gene>.fasta / <gene>.aa.fasta:
# Default HyPhy/PAML-clean per-gene MSAs (quarantines defective records & logs exclusions)
smart-align examples/public/WPDV.gb -o wpdv_aligned -t 8 \
--per-gene-dir wpdv_per_gene --strip-stops --manifest wpdv_manifest.json
# Opt defective/repaired records back into per-gene MSAs
smart-align examples/public/WPDV.gb -o wpdv_aligned_all -t 8 \
--per-gene-dir wpdv_per_gene_all --strip-stops --include-defective-per-gene
Then run HyPhy (must be installed separately) with your gene tree (gene_tree.nwk is user-supplied):
# Illustrative external HyPhy command (requires user-supplied gene_tree.nwk)
hyphy meme --alignment wpdv_per_gene/RdRp1ab.fasta --tree gene_tree.nwk
3. Geneious Prime Import & Inspection
Drag-and-drop <prefix>.geneious into Geneious Prime (or File -> Import -> From File...):
- Opens directly as a single Multiple Sequence Alignment with all
-gaps intact and zero"concatenation"labels. - Carries per-sequence
CDS,gene,UTR, andjoin(...)features plus consensus tracks (Smart-Align: Codon MSA,Smart-Align: Nucleotide MSA) annotating frame, strand, and any frameshift-repaired / fallback blocks. - Per-sequence Smart-Align block annotations are omitted by default to avoid $N \times \text{blocks}$ clutter; pass
--per-seq-annotationsto include them when needed. - Standard
.gbk(or--ungapped-genbank) and.gff3/.ungapped.gff3tracks are written alongside.geneiousfor interoperability.
4. Validation, Profiling & Reproducibility Auditing (smart-align validate, --profile, --qc-tsv, --manifest)
Run smart-align validate in CI or downstream pipelines to enforce lossless reconstruction and codon-column phase consistency, and pass --profile to print per-stage wall-clock timing and peak RSS memory breakdowns (also persisted in --manifest under timings_sec, timings_sub_sec, and peak_rss_mb):
# Produce alignment + metadata + stage timing/memory profile (auto-selected reference)
smart-align examples/public/Nobeco.fasta \
--gff examples/public/Nobeco.gff \
-o nobeco_aligned -t 8 \
--qc-tsv nobeco_qc.tsv \
--blocks-tsv nobeco_blocks.tsv \
--manifest nobeco_manifest.json \
--profile
# Validate with strict 100% codon-column consistency (exits non-zero on failure)
smart-align validate nobeco_aligned.fasta \
--raw examples/public/Nobeco.fasta \
--gff examples/public/Nobeco.gff \
--manifest nobeco_manifest.json \
--qc-tsv nobeco_qc.tsv \
--min-codon-consistency 100.0
# Machine-readable JSON report directly from a .geneious archive
smart-align validate nobeco_aligned.geneious --json
Optional External Tools & Built-in Fallbacks
Smart-Align requires only mafft (>= 7.490 recommended/tested). Optional bioinformatics binaries accelerate or specialize specific stages when installed, with well-defined automatic or built-in fallbacks:
| Tool | CLI Flags | Behavior When Installed | Fallback / Missing-Binary Behavior |
|---|---|---|---|
miniprot |
--boundary-engine {auto,liftover,miniprot} (default: auto)--miniprot-path PATH |
Used in Tier 2 (--boundary-engine auto or miniprot) to transfer protein-level CDS boundaries for unannotated/divergent records. |
auto: silently skips Tier 2 and falls back to Tier-3 codon-snapped nt liftover (unless --miniprot-path is explicitly given and missing, which raises an error).miniprot: exits with a clear missing-binary error if miniprot is not found.liftover: disables miniprot even if installed. |
MACSE v2 |
--frameshift-backend {builtin,macse} (default: builtin)--macse-path PATH (default: macse) |
Invokes macse -prog alignSequences when --frameshift-backend macse is selected to repair Case-3 true indel frameshifts. |
builtin (default): uses Smart-Align's built-in frameshift-aware protein-nucleotide dynamic-programming aligner.macse: exits with a clear missing-binary error if macse is not found/executable. |
FAMSA |
--protein-aligner {mafft,famsa} (default: mafft)--famsa-path PATH |
Uses FAMSA (-t <threads>) to align translated CDS proteins when --protein-aligner famsa is selected. |
mafft (default): aligns CDS translations via mafft --amino.famsa: exits with a clear missing-binary error if famsa is not found/executable. |
mash |
Automatic when --scale-mode is enabled |
Computes pairwise k-mer sketch distances (mash sketch + mash dist) for farthest-first core sequence selection in --scale-mode. |
Transparently falls back to Smart-Align's pure-Python canonical k-mer Jaccard farthest-first clustering with zero extra configuration. |
Scope & Known Limitations
- Macro-Synteny Assumption & Non-Collinear / Rearranged Genomes (
NON_COLLINEAR):- Smart-Align is designed for collinear (macro-syntenic) viral cohorts (plus origin-shifted circular genomes via
--circular, reverse-complemented contigs via--auto-orient, and multi-segment genomes via--segmented). - Genomes carrying large inversions, translocations, or multi-gene deletions (
>= 100 nt, and most24–75 ntinversions above ~55% reverse-complement identity) are flaggedNON_COLLINEARin--qc-tsvand--manifest(rearranged_records) rather than silently corrupting the alignment, andsmart-align validate --raw ...exits non-zero. - Sub-gene
<100 ntmicro-inversion noise floor: Very short sub-gene inversions (< 24 ntinternal inversions, or<= 60 ntinversions at<= 53–54%true reverse-complement identity near hypervariable viral indel noise floors) may not triggerNON_COLLINEAR. Conversely, forcing an extreme outgroup reference in--block-mode unionacross highly divergent accessory loci can occasionally trigger conservative short-windowNON_COLLINEARflags duringsmart-align validate --manifest --qc-tsv; selecting a representative central reference avoids these edge-case flags.
- Smart-Align is designed for collinear (macro-syntenic) viral cohorts (plus origin-shifted circular genomes via
--block-mode unionUnannotated Edge Accessories:- Inter-core unannotated
unionaccessory insertions/inversions are detected when carrier genomes retain flanking core gene annotations. If a carrier has zero annotations or carries an unannotated accessory at a genome edge lacking a trailing core anchor, adjacent CDS boundaries may absorb or truncate it (flaggedDEGRADED/PREMATURE_STOPand caught bysmart-align validate).
- Inter-core unannotated
- Genetic Codes, Paramyxovirus RNA Editing & Stop-Codon Readthrough:
- Supports 27 NCBI genetic code tables (
1–6, 9–16, 21–33; unsupported IDs raiseValueError). All records in a single run share one-gtable. - Paramyxovirus-style co-transcriptional RNA editing: During
parse_genbank(), unjoined non-mod-3 CDS features carrying RNA-editing qualifiers (/exception="RNA editing",/note, or/transl_except) alongside a canonicalA{4,6}G{2,5}slippery motif are automatically synthesized into+1/+2overlapping two-segmentFeatureSpans verified against/translation(0 internal stops). Unannotated non-mod-3 features lacking RNA-editing metadata are classified via the 4-case engine and quarantined from default HyPhy/PAML--per-gene-diroutputs unless--include-defective-per-geneis passed. - Selenocysteine / stop-codon readthrough: Internal in-frame stop codons (e.g.,
UGAreadthrough) are classified asPREMATURE_STOPand masked asXduring protein MSA while preserving exact original nucleotides.
- Supports 27 NCBI genetic code tables (
- Validating Repaired / Degraded Cohorts (
smart-align validate):- Always pass
--qc-tsvand--manifest(plus--blocks-tsvwhen generated) tosmart-align validatewhen validating cohorts containing ONT homopolymer frameshift repairs (FRAMESHIFT_REPAIRED), non-mod-3N-runs,DEGRADED/ABSENTgenes, or unsplit RNA-editing features so the validator accounts for documented QC records.
- Always pass
- Memory, Scale & Short-Fragment / External-Tool Bounds:
- Standard mode aligns full blocks in memory via MAFFT. For large cohorts (
> 100genomes), enable--scale-mode(tuning--core-size, default100) and--accuracy fast(or--protein-aligner famsa) to avoid $O(N^2)$ protein/nucleotide MSA bottlenecks.-t/--threadsacts as a total parallel thread budget distributed proportionally across blocks. - Multi-segment clustering (
--segmented) uses 11-mer / 5-aa anchored2.5 kbsliced MAFFT for segments> 10 kb; short contigs< 250 ntat< 74%nucleotide identity lacking 11-mer/5-aa seeds inside> 10 kbsegments only probe 5'/mid/3'2.5 kbwindows rather than tiling the full segment. mafftis strictly required for standard alignment and segmented clustering; withoutmafft(or on artificial low-complexity8-/12-/22-codon synthetic vocabularies), k-mer heuristics alone can merge unrelated sequences. Optional external tools (miniprot,famsa,macse,iqtree2/iqtree3,hyphy) are not bundled and must be installed separately when explicitly selected.
- Standard mode aligns full blocks in memory via MAFFT. For large cohorts (
Complete CLI Reference
smart-align (Alignment Command)
usage: smart-align [-h] -o OUTPUT_PREFIX [--gff GFF] [-r REFERENCE]
[-t THREADS] [-g GENETIC_CODE]
[--algorithm {auto,localpair,genafpair}]
[--overlap-mode {nucleotide,primary}]
[--priority-genes PRIORITY_GENES] [--mafft-path MAFFT_PATH]
[--boundary-engine {auto,liftover,miniprot}]
[--miniprot-path MINIPROT_PATH] [--refine-boundaries]
[--frameshift-backend {builtin,macse}]
[--macse-path MACSE_PATH] [--qc-tsv QC_TSV]
[--blocks-tsv BLOCKS_TSV] [--blocks-bed BLOCKS_BED]
[--partitions PARTITIONS] [--per-gene-dir PER_GENE_DIR]
[--strip-stops] [--include-defective-per-gene]
[--accuracy {fast,default,high}]
[--protein-aligner {mafft,famsa}] [--famsa-path FAMSA_PATH]
[--scale-mode] [--core-size CORE_SIZE]
[--manifest MANIFEST] [--auto-orient] [--circular]
[--segmented] [--block-mode {reference,union}]
[--skip-failed-liftover] [--per-seq-annotations]
[--ungapped-genbank] [--report] [--profile] [-v]
input
| Argument / Flag | Choices / Type | Default | Description |
|---|---|---|---|
input |
positional path | required | Input viral genome file (.gb, .gbk, .fasta, .fa). |
-h, --help |
flag | — | Show help message and exit (includes smart-align validate subcommand usage). |
-o, --output-prefix |
path prefix | required | Output file prefix (generates .geneious, .fasta, .gbk, .gff3, .ungapped.gff3). |
--gff |
path | None |
Optional GFF3 annotation file (used when input is FASTA). |
-r, --reference |
string | auto | Reference accession/ID to use as synteny template (comma-separated for --segmented). |
-t, --threads |
int | 4 |
Number of parallel workers. |
-g, --genetic-code |
int | 1 |
NCBI genetic code table (1–6, 9–16, 21–33). |
--algorithm |
{auto,localpair,genafpair} |
auto |
MAFFT alignment strategy. |
--overlap-mode |
{nucleotide,primary} |
nucleotide |
Strategy for dual-coding overlaps. |
--priority-genes |
comma-separated str | None |
Gene names to prioritize for primary frame in overlaps (e.g. 'RdRp,GP2'). |
--mafft-path |
path | auto-detect | Explicit path to mafft binary. |
--boundary-engine |
{auto,liftover,miniprot} |
auto |
Boundary resolution tier engine. |
--miniprot-path |
path | auto-detect | Explicit path to miniprot binary. |
--refine-boundaries |
flag | False |
Run Pass-2 stop-column boundary refinement and re-align shifted blocks. |
--frameshift-backend |
{builtin,macse} |
builtin |
Frameshift repair engine for true indel frameshifts. |
--macse-path |
path | macse |
Explicit path to macse binary. |
--qc-tsv |
path | None |
Optional output path for per-sequence coding QC TSV (25 columns). |
--blocks-tsv |
path | None |
Optional output path for aligned block coordinates TSV (16 columns). |
--blocks-bed |
path | None |
Optional output path for 0-based reference block BED (BED6+3). |
--partitions |
path | None |
Optional output path for IQ-TREE/RAxML NEXUS SETS partition file. |
--per-gene-dir |
dir path | None |
Optional output directory for HyPhy/PAML-clean per-gene codon NT (<gene>.fasta), AA (<gene>.aa.fasta), and per_gene_excluded.tsv. |
--strip-stops |
flag | False |
Strip terminal stop codons from --per-gene-dir alignments (HyPhy/PAML ready). |
--include-defective-per-gene |
flag | False |
Include FRAMESHIFT_REPAIRED, DEGRADED, and PREMATURE_STOP records in --per-gene-dir alignments (by default quarantined). |
--accuracy |
{fast,default,high} |
default |
Alignment speed/accuracy preset: fast (FFT-NS-2), default (--auto), high (L-INS-i). |
--protein-aligner |
{mafft,famsa} |
mafft |
Protein alignment backend for CDS codon blocks. |
--famsa-path |
path | None (famsa) |
Explicit path to famsa binary. |
--scale-mode |
flag | False |
Enable large-cohort scaling via diverse core MSA + mafft --add --keeplength. |
--core-size |
int | 100 |
Maximum number of diverse core sequences in --scale-mode. |
--manifest |
path | None |
Optional output path for JSON reproducibility manifest. |
--auto-orient |
flag | False |
Detect and reverse-complement oppositely oriented contigs/genomes against the reference. |
--circular |
flag | False |
Rotate circular genomes and shift annotation coordinates to match the reference origin. |
--segmented |
flag | False |
Cluster multi-segment inputs by reference segment similarity and align each segment independently. |
--block-mode |
{reference,union} |
reference |
Syntenic block construction mode: reference (default) or union (include accessory ORFs absent from reference). |
--skip-failed-liftover |
flag | False |
Warn and exclude records whose pairwise MAFFT liftover fails instead of aborting. |
--per-seq-annotations |
flag | False |
Include per-sequence Smart-Align block annotations inside .geneious output. |
--ungapped-genbank |
flag | False |
Write ungapped sequences and coordinates in .gbk output. |
--report |
flag | False |
Print detailed block alignment QC report (and stage timing / peak RSS summary). |
--profile |
flag | False |
Print per-stage wall-clock timing and peak RSS profile. |
-v, --version |
flag | — | Show program's version number (smart-align 0.2.0) and exit. |
smart-align validate (Validation Subcommand)
usage: smart-align validate [-h] [--raw RAW] [--gff GFF]
[--blocks-tsv BLOCKS_TSV]
[--blocks-bed BLOCKS_BED] [--manifest MANIFEST]
[--qc-tsv QC_TSV]
[--min-codon-consistency MIN_CODON_CONSISTENCY]
[-g GENETIC_CODE]
[--overlap-mode {auto,nucleotide,primary}]
[--priority-genes PRIORITY_GENES]
[--block-mode {auto,reference,union}]
[--segmented] [--circular] [--json]
alignment
| Argument / Flag | Choices / Type | Default | Description |
|---|---|---|---|
alignment |
positional path | required | Alignment file (.fasta, .fa, .gb, .gbk, .geneious). |
-h, --help |
flag | — | Show help message and exit. |
--raw |
path | None |
Optional raw unaligned FASTA or GenBank file for lossless verification. |
--gff |
path | None |
Optional GFF3 annotation file. |
--blocks-tsv |
path | None |
Optional Smart-Align blocks TSV file. |
--blocks-bed |
path | None |
Optional Smart-Align blocks BED file. |
--manifest |
path | None |
Optional Smart-Align manifest JSON file (pass with --qc-tsv for repaired/degraded cohorts). |
--qc-tsv |
path | None |
Optional Smart-Align per-sequence QC TSV file. |
--min-codon-consistency |
float | 100.0 |
Minimum required codon-column consistency percentage in [0, 100] (exits non-zero on failure). |
-g, --genetic-code |
int | 1 |
NCBI genetic code table (1–6, 9–16, 21–33). |
--overlap-mode |
{auto,nucleotide,primary} |
auto |
Overlap block handling when inferring blocks from raw/GFF/GBK/legacy BED. |
--priority-genes |
comma-separated str | None |
Comma-separated priority gene names for CDS_OVERLAP validation. |
--block-mode |
{auto,reference,union} |
auto |
Block inference mode when validating without --blocks-tsv/--manifest. |
--segmented |
flag | False |
Segmented alignment context. |
--circular |
flag | False |
Circular genome alignment context. |
--json |
flag | False |
Emit validation report as JSON. |
Python API Usage
from smart_align import align_file, align_genomes, parse_genbank, validate_alignment
# Align directly from file with v2 downstream outputs
result = align_file(
input_file="examples/public/WPDV.gb",
output_prefix="wpdv_aligned",
threads=8,
overlap_mode="primary",
block_mode="union",
qc_tsv="wpdv_qc.tsv",
partitions="wpdv_partitions.nex",
per_gene_dir="wpdv_per_gene",
strip_stops=True,
manifest="wpdv_manifest.json",
)
print(f"Aligned {len(result.records)} genomes to {result.alignment_length} bp")
# Validate programmatically
report = validate_alignment(
alignment_path="wpdv_aligned.fasta",
raw_path="examples/public/WPDV.gb",
manifest_path="wpdv_manifest.json",
qc_tsv_path="wpdv_qc.tsv",
min_codon_consistency=100.0,
)
assert report["passed"]
# Or operate on ViralRecord objects in memory
records = parse_genbank("examples/public/WPDV.gb")
mem_result = align_genomes(records=records, reference=records[2], threads=4)
Development, Linting & Testing
Continuous Integration (.github/workflows/ci.yml) runs across Python 3.10–3.13 on ubuntu-latest with mafft installed via apt-get, verifying a non-editable pip install . smoke test, ruff, and pytest across the full unit, regression, and end-to-end test suite:
# Lint source and tests
ruff check src tests
# Run the entire test suite (unit/regression + E2E)
pytest
# Run unit/regression tests only, or E2E Tiers 1-4 separately
pytest --ignore=tests/e2e
pytest tests/e2e
# Run milestone-scoped E2E subsets (-m m1 .. -m m5)
pytest -m m1 tests/e2e
License
GNU General Public License v3.0 (GPL-3.0) — see LICENSE. If you use Smart-Align in your research, see CITATION.cff.
Metadata
Release files for smart-align 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| smart_align-0.2.0.tar.gz | 555.5 kB | With provenance | Details for smart_align-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| smart_align-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for smart_align-0.2.0-py3-none-any.whl |
Total release size: 839.7 kB
Release files / smart_align-0.2.0.tar.gz
| Download URL | smart_align-0.2.0.tar.gz |
|---|---|
| Size | 555.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8a0eecec7ed0e5ebf84539934cf27e726c2bae7b7c6982ef423869083643a79f
|
|
BLAKE2b-256 checksum How to use checksums |
a0e3103222bc22f0cc63105dbfa520aad76792ffcacaa21051bb1ed2db5f0455
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.
Transparency logRelease files / smart_align-0.2.0-py3-none-any.whl
| Download URL | smart_align-0.2.0-py3-none-any.whl |
|---|---|
| Size | 284.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4d71db6abb125e27314df0a7d26a4c367bfb1a68a5c17ae6190f84a61e558d55
|
|
BLAKE2b-256 checksum How to use checksums |
6d26821bcf160b703a0c2063ca7075592a3ace26588616b0d95e7eb098124d43
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.
Transparency logSecurity for smart-align 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for smart_align-0.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.