Codon usage, host adaptation, evolutionary analysis, phylogenetics, and sequence design
Project description
CodonAdaptPy
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.
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
- Read the Docs
- Metric definitions
- Input and validation guide
- Python API and extension guide
- Interpretation and limitations
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file codonadaptpy-1.0.2.tar.gz.
File metadata
- Download URL: codonadaptpy-1.0.2.tar.gz
- Upload date:
- Size: 352.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c2f73948079878b481344a4d1e80bded76e003c8e0289e98405e91b7986be515
|
|
| MD5 |
14a54b501eeb168c87479c1ce8d13736
|
|
| BLAKE2b-256 |
6ca86f45c0b948f9284713d14582782036491f17f748146cf889ee8d0e58969e
|
Provenance
The following attestation bundles were made for codonadaptpy-1.0.2.tar.gz:
Publisher:
release.yml on navduhan/CodonAdaptPy
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
codonadaptpy-1.0.2.tar.gz -
Subject digest:
c2f73948079878b481344a4d1e80bded76e003c8e0289e98405e91b7986be515 - Sigstore transparency entry: 2279318406
- Sigstore integration time:
-
Permalink:
navduhan/CodonAdaptPy@020ac061e5cc8b41119e1e9b3819c35b3da2e49b -
Branch / Tag:
refs/tags/v1.0.2 - Owner: https://github.com/navduhan
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@020ac061e5cc8b41119e1e9b3819c35b3da2e49b -
Trigger Event:
release
-
Statement type:
File details
Details for the file codonadaptpy-1.0.2-py3-none-any.whl.
File metadata
- Download URL: codonadaptpy-1.0.2-py3-none-any.whl
- Upload date:
- Size: 84.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
73fb1bc4ef17cad259e3f96aac0102419993f73fcc298198cade0db2d0036763
|
|
| MD5 |
a09137b6c8d3c434774337a4188a8830
|
|
| BLAKE2b-256 |
9f98b3bee0f667a009033ced3b5f970ec64fd8aecafca64a5885962b7624da78
|
Provenance
The following attestation bundles were made for codonadaptpy-1.0.2-py3-none-any.whl:
Publisher:
release.yml on navduhan/CodonAdaptPy
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
codonadaptpy-1.0.2-py3-none-any.whl -
Subject digest:
73fb1bc4ef17cad259e3f96aac0102419993f73fcc298198cade0db2d0036763 - Sigstore transparency entry: 2279318411
- Sigstore integration time:
-
Permalink:
navduhan/CodonAdaptPy@020ac061e5cc8b41119e1e9b3819c35b3da2e49b -
Branch / Tag:
refs/tags/v1.0.2 - Owner: https://github.com/navduhan
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@020ac061e5cc8b41119e1e9b3819c35b3da2e49b -
Trigger Event:
release
-
Statement type: