Skip to main content

Codon usage, host adaptation, evolutionary analysis, phylogenetics, and sequence design

Project description

CodonAdaptPy

CI Documentation Status PyPI version

CodonAdaptPy 1.0.1 is a 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 CodonAdaptPy

Install all optional analysis, input, plotting, and reporting dependencies:

python -m pip install "CodonAdaptPy[all]"

Phylogenetic workflows also require external command-line programs. The supplied Conda environment installs them together with CodonAdaptPy:

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 "CodonAdaptPy[phylo]"

CodonAdaptPy reports a missing executable instead of silently substituting an alternative 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 against multiple host reference profiles:

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 restarts at position zero, its terminal stop is removed, and no nucleotide word 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 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 with CodonAdaptPy:

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 Python 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 represented by 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; biological host profiles 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 analysis 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               # Command-line 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.1.tar.gz (341.6 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.1-py3-none-any.whl (78.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: codonadaptpy-1.0.1.tar.gz
  • Upload date:
  • Size: 341.6 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.1.tar.gz
Algorithm Hash digest
SHA256 c17fcccd0b70d7a9813bf5be9ae5046d4bc42d482e88f97e3952b4bf899206c1
MD5 967bd9db5848b95c9e47966e0b11e224
BLAKE2b-256 2304d4c97d6c5719bd660f248064d628d2d45405959c4debb926ba49e4dd6b0d

See more details on using hashes here.

Provenance

The following attestation bundles were made for codonadaptpy-1.0.1.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.1-py3-none-any.whl.

File metadata

  • Download URL: codonadaptpy-1.0.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 321f0cb819e2755391f56711ebfebf11fce5a36741a1b0f81681dafd195ab46b
MD5 8b4da99557a8b1e61a52e5995499fe86
BLAKE2b-256 d439186faad99b42dfbf15c4308eb4f1dd79ddcbb418439604efd138249d0992

See more details on using hashes here.

Provenance

The following attestation bundles were made for codonadaptpy-1.0.1-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