Skip to main content

CodonAdaptPy

CI Documentation Status PyPI version

CodonAdaptPy 1.0.2 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 and optional PDF reports, browser-independent SVG/PNG/PDF/TIFF 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

--plots writes browser-independent 600-DPI PNG figures by default using Matplotlib only. Choose other raster or vector formats with, for example, --plot-formats png,pdf,svg,tiff. Publication figures are grouped by the genotype metadata field by default; select another field with --plot-group-key host.

Interactive HTML remains available when useful for hovering and zooming: install CodonAdaptPy[interactive] and request --plot-formats html, or mix it with static output as --plot-formats png,html. Each HTML file embeds its JavaScript and needs no internet connection. Kaleido and Chrome automation are not used.

The static collection also includes an UpSet-style preferred-codon plot. It shows exact overlaps of codons whose group-mean RSCU is at least 1.6 across genotypes, hosts, genes, or another selected metadata field. The companion codon_preference_intersections.tsv records every displayed membership and codon. Adjust the definition and display size with --rscu-preference-threshold and --upset-max-intersections.

When supported by the input, the same command also produces an RSCU group-similarity heatmap, a standardized RSCU PCA biplot with influential codon loadings, a codon-metric correlation heatmap, and a multi-host CAI–RCDI landscape whose marker area represents exact 59-codon SiD similarity. plot_manifest.json records every generated figure and explains why data-dependent figures were skipped.

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

Add sample metadata

CodonAdaptPy does not infer biological labels such as genotype, host, or isolate from the nucleotide sequence. Supply these labels in the input table, in FASTA descriptions, or in a separate metadata file. For example, a combined CSV input can contain:

identifier,sequence,isolate,gene,genotype,host,collection_date,country,accession
sample01_N,ATG...TAA,sample01,N,A,chicken,2023-05-10,USA,ABC00001
sample01_F,ATG...TAA,sample01,F,A,chicken,2023-05-10,USA,ABC00002
sample02_N,ATG...TAA,sample02,N,B,turkey,2024-02-17,Canada,ABC00003
sample02_F,ATG...TAA,sample02,F,B,turkey,2024-02-17,Canada,ABC00004

When sequences are stored in FASTA, keep the same unique identifiers in a separate metadata table:

>sample01_F
ATG...TAA
>sample02_F
ATG...TAA
identifier,isolate,gene,genotype,host,collection_date
sample01_F,sample01,F,A,chicken,2023-05-10
sample02_F,sample02,F,B,turkey,2024-02-17

Attach the table by exact identifier matching:

codonadaptpy analyze f_gene_sequences.fasta \
  --metadata metadata.csv \
  --aggregate-by isolate \
  --gene-key gene \
  --focus-gene F \
  --plots \
  --output results

Alternatively, FASTA descriptions may carry key/value metadata directly:

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

Metadata identifiers must be unique, and every sequence must have a matching metadata row. 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. A phylogenetic tree can reveal sequence clusters, but naming those clusters genotype A, B, or another genotype requires supplied labels or a separately validated genotype-classification reference.

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

Release files for CodonAdaptPy 1.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for CodonAdaptPy 1.0.2
File Size Uploaded
codonadaptpy-1.0.2.tar.gz 352.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for CodonAdaptPy 1.0.2
File Interpreter ABI Platform
codonadaptpy-1.0.2-py3-none-any.whl Python 3 none any Details

Total release size: 436.8 kB

Release files / codonadaptpy-1.0.2.tar.gz

Download URL codonadaptpy-1.0.2.tar.gz
Size 352.0 kB
Tags Source
SHA-256 checksum
How to use checksums
c2f73948079878b481344a4d1e80bded76e003c8e0289e98405e91b7986be515
BLAKE2b-256 checksum
How to use checksums
6ca86f45c0b948f9284713d14582782036491f17f748146cf889ee8d0e58969e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

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 Jul 29, 2026.

Transparency log

Release files / codonadaptpy-1.0.2-py3-none-any.whl

Download URL codonadaptpy-1.0.2-py3-none-any.whl
Size 84.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
73fb1bc4ef17cad259e3f96aac0102419993f73fcc298198cade0db2d0036763
BLAKE2b-256 checksum
How to use checksums
9f98b3bee0f667a009033ced3b5f970ec64fd8aecafca64a5885962b7624da78
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

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 Jul 29, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

1.0.2 This release

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page