Metadata-Version: 2.4
Name: trellis-protein
Version: 1.0.0
Summary: Lattice protein synthetic data for evolutionary trajectory models
Author: Trevor Bedford
License: MIT License
        
        Copyright (c) 2026 Trevor Bedford
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
        ## Additional Notes on LLM-Generated Content
        
        This repository contains a mix of code authored by the repository owner and code generated by large language models (LLMs). While the MIT License applies to the code as a whole, I do not assert copyright over any portions of the code that were generated by LLMs, as the copyright status of such content may vary depending on jurisdiction. Users are encouraged to independently verify the copyright status of LLM-generated portions before reuse or redistribution.
        
Project-URL: Repository, https://github.com/holotypebio/trellis
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: numpy>=1.24
Requires-Dist: numba>=0.58
Requires-Dist: zstandard>=0.21
Provides-Extra: aws
Requires-Dist: boto3[crt]>=1.28; extra == "aws"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Dynamic: license-file

# trellis

Lattice protein synthetic data for evolutionary trajectory models.

Trellis generates evolutionary trajectories on a lattice-protein fitness
landscape. Proteins are 18-residue chains on a 2D square lattice, folded by
exhaustive enumeration with a Miyazawa-Jernigan contact potential and numba
JIT-compiled scoring. Fitness is fraction-folded times native binding energy
to a fixed lattice ligand, following Bloom et al. (2004). Evolution proceeds
under SSWM dynamics at the DNA level: single-nucleotide mutations arise and
fix according to Kimura fixation probabilities. Output is written in a FASTA
format compatible with the
[blab/trajectories](https://github.com/blab/trajectories) preprocessing
pipeline.

For technical details, see [FOLDING.md](FOLDING.md) (lattice geometry, MJ
potential, folding algorithms, mean-field pruning) and
[EVOLUTION.md](EVOLUTION.md) (fitness function, genetic code, SSWM dynamics).

The corpus this repository generates, **v2**, is catalogued in
[DATA-V2.md](DATA-V2.md): 1000 ligands, each with its own mutation spectrum and
effective population size, 1000 independent trajectories and one phylogeny per
ligand. Its manifests live in [`v2/`](v2/) and the playbook that produced it is
[GENERATE-V2.md](GENERATE-V2.md). (v1 was an earlier corpus with a uniform
mutation spectrum and a different neutral fixation branch; it is not released,
but the package keeps its sampling rules as the defaults, described in
[EVOLUTION.md](EVOLUTION.md).) [`notes/`](notes/) holds dated design records;
they describe the work as it stood and mention v1 and some scripts that are not
in this repository.

## Install

```bash
pip install trellis-protein
```

Downstream code imports as `trellis` (the PyPI distribution is published as
`trellis-protein` because `trellis` is taken). For local development on
this repo:

```bash
pip install -e ".[dev]"
```

Requires Python >= 3.11. Runtime dependencies: `numpy`, `numba`,
`zstandard`. Optional extras: `[aws]` (boto3, for the AWS Batch scripts) and
`[dev]` (pytest). The scripts under `scripts/` are run from a checkout of this
repository; they are not part of the installed package.

## Fold a single sequence

`scripts/fold_sequence.py` folds a single amino acid or DNA sequence
and prints native energy, partition function, conformation coordinates,
and wall time. With a ligand, it also reports ensemble-averaged binding
energy and fitness.

```bash
# Fold an amino acid sequence
python scripts/fold_sequence.py --aa ACDEFGHIKLMNPQRSTVWY

# Fold with a ligand (reports binding energy and fitness)
python scripts/fold_sequence.py --aa ACDEFGHIKLMNPQRSTVWY --ligand-sequence FWYL

# Machine-readable JSON output
python scripts/fold_sequence.py --aa ACDEFG --json
```

## Generate and visualize a single trajectory

`scripts/generate_viz_trajectory.py` runs a short SSWM trajectory and
writes a JSON snapshot for the `lattice-trajectory` visualization component.

```bash
python scripts/generate_viz_trajectory.py
```

This runs with defaults (`--chain-length 10 --n-steps 100 --Ne 50
--temperature 1.0 --seed 42`) and writes
`viz/lattice-trajectory/data/trajectory.json`. Serve the repo root and open
the component:

```bash
python -m http.server 8000
# open http://localhost:8000/viz/lattice-trajectory/index.html
```

See [`viz/README.md`](viz/README.md) for details.

## Generate trajectories

`scripts/generate_trajectories.py` is a general-purpose CLI for bulk trajectory
generation on a straight ligand. It runs SSWM trajectories in parallel, splits
into train/test sets, and packages them as compressed FASTA shards. It samples
with the package defaults (uniform mutation spectrum, the v1 fixation law), so
it does not reproduce v2 trajectories; for those, see
[Regenerate part of the v2 corpus](#regenerate-part-of-the-v2-corpus).

```bash
# Generate 1000 trajectories for a single ligand
python scripts/generate_trajectories.py \
    --n-trajectories 1000 \
    --n-steps 100 \
    --chain-length 18 \
    --ligand-sequence KEMN \
    --Ne 50 \
    --n-workers 8 \
    --seed 42

# Generate trajectories across multiple random ligands
python scripts/generate_trajectories.py \
    --n-random-ligands 8 \
    --n-trajectories 100 \
    --chain-length 18 \
    --Ne 50 \
    --n-workers 32 \
    --seed 42
```

Output:

```
results/trellis-18aa-KEMN-indep/
├── forwards-train-000.tar.zst
├── forwards-test-000.tar.zst
└── metadata.json
```

Each worker process loads its own MJ matrix, ligand, and conformation
database. Per-trajectory RNG streams are created via `SeedSequence.spawn()`
for reproducibility regardless of worker count. See
[BENCHMARK.md](BENCHMARK.md) for timing data.

## Generate phylogenies

`scripts/generate_phylogeny.py` generates a single phylogenetic tree via
Yule-with-sampling on SSWM dynamics. At each time step, active lineages
may speciate (rate beta), get sampled as tips (rate psi), or continue as
single daughters. Mutations are drawn from SSWM fixation probabilities.
Output is Auspice v2 JSON viewable at [auspice.us](https://auspice.us).
Like `generate_trajectories.py`, it samples with the package defaults.

```bash
# Generate a phylogeny with default parameters
# Default is 18-mer, which may take a while
python scripts/generate_phylogeny.py --output results/phylogeny.json

# Specify ligand and specify protein length
python scripts/generate_phylogeny.py \
    --chain-length 12 \
    --ligand-sequence KEMN \
    --output results/phylogeny.json
```

Key parameters:
- `--beta`: speciation probability per lineage per step (default 0.80)
- `--psi`: sampling probability per lineage per step (default 0.05)
- `--min-active`: minimum active lineages preserved against sampling (default 1)
- `--max-active`: cap on active lineages per step (default 70)
- `--max-nodes`: hard cap on total tree size (default 100000)

## The v2 corpus

The v2 corpus is defined by a single manifest, `v2/parameters.json`, built by
`scripts/build_parameters.py`. Each ligand entry carries a per-ligand random
mutation spectrum `q` (a named 12-vector) and effective population size `Ne`,
drawn once and keyed only on the ligand `id`, plus a pinned `train` /
`ood_val` / `ood_test` `split`. The SSWM proposal is weighted by `q` and the
neutral branch uses the continuous haploid fixation law
(`fixation_probability_haploid`). See
[`notes/2026-08-25-trellis-v2-generation-spec.md`](notes/2026-08-25-trellis-v2-generation-spec.md)
for the full design.

Every unit is seeded directly from `(salt, id, unit_index)` (no `spawn`), so
the corpus is **additive** (more trajectories, more trees, or more ligands is
always an append, never a regeneration) and any single unit can be rebuilt on
its own.

### Generate the whole corpus (AWS Batch)

Two worker/submitter pairs read the manifest and write to your S3 bucket
(`$S3_BUCKET`). [GENERATE-V2.md](GENERATE-V2.md) is the end-to-end playbook
(infrastructure, both Batch runs, Nextstrain, the trajectories pipeline).

```bash
python scripts/v2_indep_submit.py --ids all   # 1000 ligands x 1000 independent trajectories (spot)
python scripts/v2_phylo_submit.py  --ids all   # one ~5000-tip tree per ligand (on-demand)
python scripts/v2_phylo_submit.py  --ids all --tree-id 1   # later: append a second tree per ligand
```

Output on S3 is a per-ligand directory with per-unit indexed filenames, so an
appended unit lands next to the existing data rather than overwriting it:

```
trellis-trajectories-v2/trellis-18aa-<SEQ>-<SHAPE>-ne<NE>-q<ID>-indep/traj_<NNNNNN>.fasta
trellis-phylogenies-v2/trellis-18aa-<SEQ>-<SHAPE>-ne<NE>-q<ID>-phylo/tree_<NNN>.json
```

### Regenerate part of the v2 corpus

`scripts/regenerate.py` rebuilds any trajectory or tree on one machine, with no
AWS. It calls the same generation functions as the Batch workers. Trajectories
come out byte for byte. A tree comes out with the same topology, sequences and
mutations as the corpus's; on a different CPU architecture a few of its stored
fitness values can differ in the last floating-point digit.

```bash
# trajectories 0-9 of ligand 384
python scripts/regenerate.py --id 384 --traj 0-9 --out out

# the same, compared with a released shard instead of written
python scripts/regenerate.py --id 384 --traj 0-9 --against forwards-test-000.tar.zst

# tree 0 of ligand 0 (about an hour)
python scripts/regenerate.py --id 0 --tree 0 --out out
```

A trajectory takes a little over a minute on one core, after a few seconds
enumerating the ligand's conformations.

### Public data

The part of v2 analyzed in the Pinion paper is public, readable without
credentials, under
`https://holotypebio-pinion.s3.us-east-2.amazonaws.com/trellis/upstream/`
(`s3://holotypebio-pinion/trellis/upstream/`), and its trees can be browsed at
[nextstrain.org/groups/holotypebio](https://nextstrain.org/groups/holotypebio?filter=trellis-v2).
[DATA-V2.md](DATA-V2.md#public-release) describes what is there;
`v2/release.sha256` lists every object's checksum.

```bash
d=trellis-18aa-CSQK-FF-ne45-q0
aws s3 cp --no-sign-request --recursive s3://holotypebio-pinion/trellis/upstream/$d-indep/ $d-indep/
grep "$d-indep/" v2/release.sha256 | shasum -a 256 -c
```

## Evaluation interface

`trellis.sswm.compute_sswm_probabilities` exposes the ground-truth SSWM
fixation-probability distribution over all single-nucleotide neighbors of
a reference DNA sequence. Downstream evaluation code uses this as the
oracle when scoring how well a learned model has recovered the fitness
landscape.

Because the oracle *is* the sampler, it takes the same optional
`mutation_spectrum` (per-base-change weights `q`, keyed by `ref+alt`) and
`fixation_fn` arguments the generator uses. Omitting them gives the v1
uniform-spectrum, diploid-neutral-branch behavior; to score v2 data,
pass the ligand's spectrum and `fixation_probability_haploid` so `P_true`
reflects how those trajectories were sampled.

```python
from trellis.cache import FitnessCache
from trellis.energy import load_mj_matrix
from trellis.fitness import compute_fitness_aa
from trellis.fold_enum import enumerate_conformations
from trellis.genetic_code import translate
from trellis.ligand import create_ligand
from trellis.sswm import compute_sswm_probabilities, pfix_for_target

# One-time setup per ligand
mj = load_mj_matrix()
ligand = create_ligand("KEMN", anchor=(0, -1))
db = enumerate_conformations(18, ligand)
cache = FitnessCache()

# Per-reference evaluation
ref_aa = translate(ref_dna)
if ref_aa not in cache:
    cache.put(ref_aa, compute_fitness_aa(ref_aa, ligand, mj, 1.0, db=db))
ref_fitness = cache.get(ref_aa).fitness

mutant_dnas, ground_truth = compute_sswm_probabilities(
    ref_dna, ref_fitness, ligand, mj, Ne=50.0, temperature=1.0,
    fitness_cache=cache, db=db,
)
# ground_truth sums to 1 (or is all zeros if every neighbor is lethal)

# Single mutation lookup
p = pfix_for_target(ref_dna, target_dna, ligand, mj,
                    Ne=50.0, temperature=1.0,
                    fitness_cache=cache, db=db)
```

Share the `FitnessCache` across all evaluations for a given ligand —
folding is the dominant cost, and the cache amortizes it.

The CLI `scripts/pfix_distribution.py` exercises the same API for
exploration:

```bash
# Full distribution for a reference sequence
python scripts/pfix_distribution.py \
    --reference CTCTGCAACACAACACGGCTCGATGTTCTCTATGGAGAATGTGACTGCGCGCTG \
    --ligand KEMN --Ne 50

# Single-mutation P_fix as JSON
python scripts/pfix_distribution.py \
    --reference <ref-dna> --target <neighbor-dna> \
    --ligand KEMN --Ne 50 --json
```

## Run tests

```bash
pytest
```

Or a single module:

```bash
pytest tests/test_lattice.py -v
pytest tests/test_energy.py -v
```

## Repository layout

```
trellis/
├── trellis/
│   ├── __init__.py
│   ├── lattice.py           # 2D lattice, SAW enumeration
│   ├── energy.py            # MJ matrix, conformation energy
│   ├── fold_bb.py           # branch-and-bound folding (reference)
│   ├── fold_enum.py         # pre-enumeration folding (production)
│   ├── ligand.py            # ligand placement, binding energy
│   ├── fitness.py           # fitness function
│   ├── genetic_code.py      # codon table, translation, mutations
│   ├── sswm.py              # SSWM trajectory generation
│   ├── phylogeny.py         # phylogenetic tree generation
│   ├── parameters.py        # v2 per-ligand draws (q, Ne), salts, splits
│   ├── auspice_io.py        # Auspice v2 JSON serialization
│   ├── trajectory_io.py     # FASTA / tar.zst output
│   ├── cache.py             # fitness cache
│   └── mj_matrix.csv        # MJ 1985 contact potential
├── tests/
├── scripts/
│   ├── fold_sequence.py             # fold a single sequence
│   ├── pfix_distribution.py         # SSWM fixation-probability distribution
│   ├── generate_trajectories.py     # bulk parallel trajectory generation
│   ├── generate_phylogeny.py        # single phylogenetic tree generation
│   ├── stitch_phylogenies.py        # join trees at a shared root
│   ├── inspect_shard.py             # inspect / extract tar.zst shards
│   ├── benchmark.py                 # single-worker pipeline benchmark
│   ├── benchmark_bb_vs_enum.py      # B&B vs pre-enumeration comparison
│   ├── generate_viz_trajectory.py   # data for the lattice-trajectory viz
│   ├── generate_lattice_schematic.py  # data for the lattice-schematic viz
│   │   # --- the v2 corpus ---
│   ├── generate_ligand_list.py      # v2/simple-ligands.json
│   ├── gen_complex_ligands_family.py  # v2/complex-ligands-family.json
│   ├── gen_complex_ligands_extend.py  # v2/complex-ligands.json
│   ├── ligand_shapes.py             # shape pool + placement (shared helper)
│   ├── build_parameters.py          # v2/parameters.json
│   ├── v2_indep_submit.py           # submit indep-trajectory Batch jobs (+ v2_indep_worker.py)
│   ├── v2_phylo_submit.py           # submit phylogeny Batch jobs (+ v2_phylo_worker.py)
│   ├── aggregate_v2_indep.py        # pack trajectories into train/test shards
│   ├── shards.py                    # shard reading and writing (shared helper)
│   ├── upload_phylogenies_nextstrain_v2.py  # publish trees to Nextstrain
│   ├── gen_trellis_v2_yaml.py       # config for the trajectories workflow
│   ├── regenerate.py                # rebuild any trajectory or tree locally
│   ├── release_public.py            # cut the public release from a full corpus
│   └── _env.py                      # $S3_BUCKET, $NEXTSTRAIN_GROUP
├── viz/
│   ├── lattice-schematic/   # folding-ensemble / fitness figure component
│   ├── lattice-trajectory/  # SSWM-trajectory figure component
│   └── README.md
├── notes/                   # dated design records
├── v2/                      # v2 manifests and release checksums
├── FOLDING.md               # folding technical reference
├── EVOLUTION.md             # evolutionary model technical reference
├── BENCHMARK.md             # performance benchmarks
├── DATA-V2.md               # v2 corpus catalog
├── GENERATE-V2.md           # v2 generation playbook (Batch, Nextstrain, pipeline)
├── pyproject.toml
├── LICENSE.md
└── README.md
```
