Metadata-Version: 2.4
Name: CodonAdaptPy
Version: 1.0.1
Summary: Codon usage, host adaptation, evolutionary analysis, phylogenetics, and sequence design
Author: Naveen Duhan
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/navduhan/CodonAdaptPy
Project-URL: Documentation, https://codonadaptpy.readthedocs.io
Project-URL: Repository, https://github.com/navduhan/CodonAdaptPy
Project-URL: Issues, https://github.com/navduhan/CodonAdaptPy/issues
Keywords: bioinformatics,codon usage,CAI,host adaptation,sequence optimization
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: analysis
Requires-Dist: numpy>=1.24; extra == "analysis"
Requires-Dist: pandas>=2; extra == "analysis"
Requires-Dist: scipy>=1.10; extra == "analysis"
Requires-Dist: scikit-learn>=1.3; extra == "analysis"
Requires-Dist: statsmodels>=0.14; extra == "analysis"
Provides-Extra: io
Requires-Dist: biopython>=1.81; extra == "io"
Requires-Dist: openpyxl>=3.1; extra == "io"
Provides-Extra: plot
Requires-Dist: plotly>=5.18; extra == "plot"
Requires-Dist: kaleido>=0.2; extra == "plot"
Requires-Dist: matplotlib>=3.7; extra == "plot"
Provides-Extra: phylo
Requires-Dist: biopython>=1.81; extra == "phylo"
Requires-Dist: ete3>=3.1.3; extra == "phylo"
Requires-Dist: numpy>=1.24; extra == "phylo"
Requires-Dist: scipy>=1.10; extra == "phylo"
Requires-Dist: matplotlib>=3.7; extra == "phylo"
Provides-Extra: report
Requires-Dist: jinja2>=3.1; extra == "report"
Requires-Dist: openpyxl>=3.1; extra == "report"
Requires-Dist: weasyprint>=61; extra == "report"
Provides-Extra: all
Requires-Dist: numpy>=1.24; extra == "all"
Requires-Dist: pandas>=2; extra == "all"
Requires-Dist: scipy>=1.10; extra == "all"
Requires-Dist: scikit-learn>=1.3; extra == "all"
Requires-Dist: statsmodels>=0.14; extra == "all"
Requires-Dist: biopython>=1.81; extra == "all"
Requires-Dist: ete3>=3.1.3; extra == "all"
Requires-Dist: openpyxl>=3.1; extra == "all"
Requires-Dist: plotly>=5.18; extra == "all"
Requires-Dist: kaleido>=0.2; extra == "all"
Requires-Dist: matplotlib>=3.7; extra == "all"
Requires-Dist: jinja2>=3.1; extra == "all"
Requires-Dist: weasyprint>=61; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.4; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Dynamic: license-file

# CodonAdaptPy

[![CI](https://github.com/navduhan/CodonAdaptPy/actions/workflows/ci.yml/badge.svg)](https://github.com/navduhan/CodonAdaptPy/actions/workflows/ci.yml)
[![Documentation Status](https://readthedocs.org/projects/codonadaptpy/badge/?version=latest)](https://codonadaptpy.readthedocs.io/en/latest/?badge=latest)
[![PyPI version](https://img.shields.io/pypi/v/CodonAdaptPy.svg)](https://pypi.org/project/CodonAdaptPy/)

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](docs/assets/codonadaptpy_graphical_abstract.png)

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:

```bash
python -m pip install CodonAdaptPy
```

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

```bash
python -m pip install "CodonAdaptPy[all]"
```

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

```bash
conda env create -f environment.yml
conda activate codonadaptpy
```

For an existing environment such as `ngs`:

```bash
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:

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

## Command-line quick start

Analyze a multi-FASTA file against a target reference:

```bash
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:

```bash
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:

```bash
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:

```fasta
>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:

```bash
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:

```bash
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:

```bash
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

```python
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:

```python
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:

```python
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:

```json
{
  "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](https://codonadaptpy.readthedocs.io)
- [Metric definitions](docs/metrics.md)
- [Input and validation guide](docs/input_validation.md)
- [Python API and extension guide](docs/api.md)
- [Interpretation and limitations](docs/interpretation.md)

## Project structure

```text
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
```
