Skip to main content

Integrated codon-usage, host-adaptation, evolutionary analysis, and sequence optimization

Project description

CodonAdaptPy

CI Documentation Status

CodonAdaptPy 1.0.0 is a standalone, class-based Python package for coding-sequence validation, codon-usage analysis, multi-host comparison, evolutionary diagnostics, reproducible reporting, and constrained codon optimization or deoptimization.

CodonAdaptPy workflow from validated coding sequences through modular codon analysis to auditable molecular-evolution evidence

Author: Naveen Duhan
License: GNU General Public License v3 or later
Python: 3.10+

Highlights

  • Input: pasted DNA/RNA, FASTA/multi-FASTA, GenBank, CSV/TSV, and ZIP archives of FASTA files.
  • Quality control: frame, start/stop, internal stops, partial CDS, RNA conversion, ambiguity, unsupported characters, duplicates, and genetic-code validation.
  • Metrics: CAI, simulated/expected CAI distribution, sliding CAI, RSCU, ENC, FOP, CBI, ICDI, RCDI, tAI, GC/GC1/GC2/GC3/GC3s, AT1/AT2/AT3, third-position bases, amino-acid composition, all 16 dinucleotide O/E ratios, trinucleotide frequencies, and codon-pair scores.
  • Host analysis: multi-host CAI/RCDI, exact 59-codon SiD, RSCU distance, cosine/Euclidean distance, Jensen-Shannon divergence, Pearson/Spearman correlation, and a transparent composite score.
  • Analysis scopes: individual genes, boundary-aware genome-wide CDS pooling per isolate, and arbitrary focus genes such as F.
  • Evolutionary and comparative analysis: ENC-GC3s expectation, group-specific neutrality regression, PR2, group summaries, reported normality diagnostics, estimand-first paired/unpaired inference, explicit Welch/Mann-Whitney tests, effect sizes, bootstrap intervals, FDR correction, correspondence analysis, correlation matrices, PCA, repeated grouped LDA with held-out evaluation, hierarchical clustering, and distances.
  • Phylogenetics: MAFFT alignment, mandatory trimAL publication trimming, IQ-TREE ModelFinder/ultrafast bootstrap or FastTree inference, ETE3-backed tree rendering, root-to-tip temporal signal, exploratory strict-clock time trees, lineage-through-time trajectories, and whole-genome/F-gene Robinson-Foulds concordance.
  • Design: ranked synonymous candidates with CAI/GC/CpG/UpA objectives, motif and restriction-site constraints, homopolymer limits, pair scores, deterministic seeds, and visible trade-offs.
  • Output: CSV, TSV, JSON, Excel, HTML, optional PDF, SVG/PNG/HTML plots, and optimized FASTA. Publication plots include PCA/LDA, confusion matrices, 59-codon RSCU profiles, nucleotide composition, ENC-GC3s/neutrality/PR2 diagnostics, all-16-dinucleotide profiles and heatmaps, and multi-host CAI/RCDI comparisons.

Codon-usage similarity is descriptive. It is not direct proof of increased expression, replication, virulence, host switching, transmission, or biological fitness.

Installation

Install the dependency-free core and CLI:

python -m pip install .

Install every standalone analysis, input, plot, and reporting feature:

python -m pip install ".[all]"

Phylogenetic workflows additionally require command-line programs. The recommended complete environment installs them explicitly:

conda env create -f environment.yml
conda activate codonadaptpy

For an existing environment such as ngs:

conda install -n ngs -c bioconda -c conda-forge mafft trimal iqtree fasttree ete3
python -m pip install ".[phylo]"

CodonAdaptPy reports a missing executable instead of silently substituting a different method. Publication mode requires trimAL unless --no-trim is explicitly selected.

For development:

python -m pip install -e ".[dev,all]"
pytest -q
ruff check .

Command-line quick start

Analyze a multi-FASTA file against a target reference:

codonadaptpy analyze coding_sequences.fasta \
  --reference human_reference.json \
  --formats json,csv,html \
  --plots \
  --output results

Compare the same sequences with multiple hosts:

codonadaptpy compare coding_sequences.fasta \
  --host chicken.json \
  --host turkey.json \
  --host human.json \
  --output host_comparison

Analyze every gene, pool CDSs genome-wide by isolate, and report F separately:

codonadaptpy analyze isolate_cds.csv \
  --aggregate-by isolate \
  --gene-key gene \
  --focus-gene F \
  --host chicken.json \
  --host turkey.json \
  --output ampv_analysis

The input table may contain identifier,sequence,isolate,gene,genotype,... columns. Alternatively, FASTA descriptions may carry key/value metadata:

>isolate1_N isolate=isolate1 gene=N genotype=A
ATG...TAA
>isolate1_F isolate=isolate1 gene=F genotype=A
ATG...TAA

For a FASTA plus a separate metadata file, pass --metadata metadata.csv. During genome-wide aggregation every CDS is validated independently, its reading frame starts again at position zero, its terminal stop is removed, and no nucleotide or codon pair is counted across gene boundaries.

Build a versioned reference profile from highly expressed coding sequences:

codonadaptpy reference build highly_expressed_cds.fasta \
  --name chicken_high_expression \
  --reference-version 2026.1 \
  --source "Ensembl release X; documented gene selection" \
  --output chicken.json

Generate several constrained candidates:

codonadaptpy optimize gene.fasta \
  --reference chicken.json \
  --direction optimize \
  --candidates 10 \
  --target-gc 0.52 \
  --avoid-motif AATAAA \
  --remove-site GAATTC \
  --seed 42 \
  --output optimized_gene

Run codonadaptpy COMMAND --help for all options.

Infer an ML tree and use a metadata sampling-year column for exploratory temporal diagnostics:

codonadaptpy phylogeny f_gene_sequences.fasta \
  --metadata samples.csv \
  --group-key genotype \
  --date-key year \
  --temporal \
  --tree-method iqtree \
  --bootstrap 1000 \
  --threads 4 \
  --output phylogeny_results

This produces ML and time-tree figures, a root-to-tip regression, dated Newick, lineage-through-time output, and JSON provenance. The deterministic time tree and LTT curve are rapid deterministic diagnostics—not relaxed-clock posterior dating, effective population-size inference, or 95% HPD intervals.

Python API

from codonadaptpy import CodonAnalyzer, SequenceRecord, ValidationConfig
from codonadaptpy.analyzer import AnalysisConfig
from codonadaptpy.references import ReferenceManager

manager = ReferenceManager()
reference = manager.load("chicken.json")

analyzer = CodonAnalyzer(
    AnalysisConfig(validation=ValidationConfig(genetic_code=1)),
    reference=reference,
)
result = analyzer.analyze(
    SequenceRecord("example_gene", "ATGGCTGCTGACTAA")
)

print(result.metrics["cai"])
print(result.metrics["enc"])
print(result.metrics["gc3"])

Create a publication-ready figure through the package:

from codonadaptpy import PublicationPlotManager

plots = PublicationPlotManager()
figure = plots.evolutionary_diagnostics(
    results,
    group_key="Genotype",
    title="F-gene evolutionary diagnostics",
)
plots.save(figure, "f_gene_diagnostics.pdf")
plots.save(figure, "f_gene_diagnostics.png", dpi=600)

Run phylogenetics through the class-based API:

from codonadaptpy import ETE3TreePlotter, PhylogeneticAnalyzer, TemporalAnalyzer

run = PhylogeneticAnalyzer().run(
    records,
    "phylogeny_results/inference",
    tree_method="iqtree",
    bootstrap=1000,
    trim=True,
    trim_required=True,
    threads=4,
)
signal = TemporalAnalyzer().temporal_signal(run.tree, sample_dates, optimize_root=True)
dated_tree = TemporalAnalyzer().date_tree(run.tree, signal)
figure = ETE3TreePlotter().tree(dated_tree, groups=groups, time_scaled=True)
ETE3TreePlotter.save(figure, "phylogeny_results/time_tree.pdf")

Reference profile format

JSON profiles preserve provenance and versioning:

{
  "name": "host_high_expression",
  "counts": {"AAA": 120, "AAG": 240},
  "genetic_code": 1,
  "version": "2026.1",
  "source": "Database release and gene-selection method",
  "description": "Reference CDS profile",
  "metadata": {"taxon_id": 0000, "biological": true}
}

Missing sense codons are completed with zero counts during validation. CSV/TSV profiles use codon,count or codon,frequency columns. The only bundled profile is uniform_standard, an explicitly non-biological testing baseline; real host tables must retain a documented source and release.

CAI edge-case policy

  • CAI is calculated in logarithmic space.
  • Stop and ambiguous codons do not contribute.
  • Methionine and tryptophan contribute normally, usually with weight 1.
  • A zero-frequency sense codon receives the configured positive floor (default 0.01).
  • A sense codon missing from a custom weight mapping is skipped; non-positive supplied weights are rejected.
  • Alternative NCBI codes require Biopython (CodonAdaptPy[io]).
  • Very short sequences are accepted only when validation policy permits them; CAI still requires one eligible sense codon.

Output reproducibility

Every analysis captures CodonAdaptPy and Python versions, UTC analysis time, genetic code, reading frame, input SHA-256, random seed, and reference name/version. CLI runs also write the full quoted command and JSON configuration.

Documentation

Project structure

src/codonadaptpy/
├── aggregation.py       # Per-isolate gene and genome-wide CDS scopes
├── analyzer.py          # Main class-based API
├── comparative.py       # Group and multivariate analysis
├── genetic_code.py      # Translation tables and codon families
├── metrics/             # Adaptation, usage, composition, pair, host, evolution
├── models.py            # Shared result and validation dataclasses
├── optimizer.py         # Constrained synonymous design
├── parsers.py           # FASTA, GenBank, tables, and ZIP input
├── phylogenetics.py     # Alignment, ML trees, temporal signal, topology tests
├── phylo_visualization.py # ETE3-backed publication tree and LTT figures
├── references.py        # Versioned reference management
├── reporting.py         # JSON/CSV/Excel/HTML/PDF/FASTA output
├── validation.py        # Coding-sequence quality control
├── visualization.py     # Interactive and static plots
└── cli.py               # Standalone subcommands

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

codonadaptpy-1.0.0.tar.gz (341.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

codonadaptpy-1.0.0-py3-none-any.whl (78.3 kB view details)

Uploaded Python 3

File details

Details for the file codonadaptpy-1.0.0.tar.gz.

File metadata

  • Download URL: codonadaptpy-1.0.0.tar.gz
  • Upload date:
  • Size: 341.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for codonadaptpy-1.0.0.tar.gz
Algorithm Hash digest
SHA256 ddcdf3b2aa67d672999111f7ebeca1c1aa4cb4fd8ea11f040eb5eeb49fab05ec
MD5 122f6cdb5090ebac33060f33945d0f64
BLAKE2b-256 b0b05003e29e6983502ae8df57db424404c9a7f0226900a147cb12ecf38897f2

See more details on using hashes here.

Provenance

The following attestation bundles were made for codonadaptpy-1.0.0.tar.gz:

Publisher: release.yml on navduhan/CodonAdaptPy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file codonadaptpy-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: codonadaptpy-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 78.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for codonadaptpy-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ba029c65de0b370852b44ac6eaed0563ece6990d240993080677bac8e41a13d8
MD5 b462a5f620bd7794659ec09eb3629c17
BLAKE2b-256 ecd35b870796aa4503323846c206c9217fc854b9639e703574de0336d8ad2866

See more details on using hashes here.

Provenance

The following attestation bundles were made for codonadaptpy-1.0.0-py3-none-any.whl:

Publisher: release.yml on navduhan/CodonAdaptPy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page