Metadata-Version: 2.4
Name: phip-seq-library-generator
Version: 1.0.0
Summary: Config-driven CLI pipeline that turns viral proteomes into synthesis-ready PhIP-seq oligonucleotide libraries.
Author-email: Izabella Zamora <izabella.zamora@arcinstitute.org>
Maintainer-email: Izabella Zamora <izabella.zamora@arcinstitute.org>
License: MIT License
        
        Copyright (c) 2026 Izabella Zamora, Arc Institute
        
        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.
        
Project-URL: Homepage, https://github.com/izabellaleahz/phip_seq_oligo_generator
Project-URL: Repository, https://github.com/izabellaleahz/phip_seq_oligo_generator
Project-URL: Visualizer, https://izabellaleahz.github.io/phip-seq-tile-visualizer
Keywords: PhIP-seq,phage display,oligo library,peptide tiling,virome,immunology,bioinformatics,codon optimization
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: biopython>=1.79
Requires-Dist: numpy>=1.21.0
Requires-Dist: pandas>=1.3.0
Requires-Dist: scipy>=1.9.0
Requires-Dist: matplotlib>=3.4.0
Requires-Dist: seaborn>=0.11.0
Requires-Dist: xxhash>=3.0.0
Requires-Dist: dnachisel>=3.0.0
Requires-Dist: requests>=2.28.0
Requires-Dist: tqdm>=4.64.0
Requires-Dist: typer>=0.9.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pyyaml>=6.0.0
Requires-Dist: tomli>=2.0.0; python_version < "3.11"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Provides-Extra: notebook
Requires-Dist: jupyter>=1.0.0; extra == "notebook"
Requires-Dist: ipykernel>=6.0.0; extra == "notebook"
Dynamic: license-file

# PhIP-seq Virome Library Generator

A Python CLI pipeline that transforms viral proteomes into synthesis-ready DNA oligonucleotide libraries for PhIP-seq (Phage Immunoprecipitation Sequencing). Fetches viral proteins from UniProt/RefSeq, tiles them into overlapping peptides, and generates codon-optimized DNA with restriction enzyme site avoidance.

## Overview

The pipeline takes a host taxonomy ID (e.g., 9606 for human), downloads all known viral proteins infecting that host, and produces a library of ~195 bp DNA oligos ready for oligo synthesis. Each oligo encodes a 49-amino-acid peptide tile with E. coli-optimized codons, flanked by cloning adapters.

**Current library (human + bat + bird):** ~492,000 unique oligos covering ~73,000 proteins from ~2,200 viruses.

```
Oligo structure (195 bp):
[5' adapter 24bp][codon-optimized coding 147bp][3' adapter 24bp]
```

---

## Installation

### Prerequisites

- Python 3.9+
- [CD-HIT](https://github.com/weizhongli/cdhit) — protein clustering
- [MAFFT](https://mafft.cbrc.jp/alignment/software/) — multiple sequence alignment

```bash
# 1. External tools (must be on PATH before running the pipeline)
conda install -c bioconda cd-hit mafft

# 2. The package itself (installs all Python dependencies + the `phiplib` command)
pip install .

# ...or, for development (editable install with test/lint tools):
pip install -e ".[dev]"
```

Installing the package puts a `phiplib` command on your PATH (equivalent to
`python -m phiplib`). Both forms work interchangeably throughout this README.

### Verify

```bash
phiplib --version
phiplib --help
phiplib validate --config config.yaml
```

> **New to PhIP-seq?** Start with the [**Primer for wet-lab biologists**](docs/PRIMER.md) —
> it explains what this tool makes, why, and walks through a first run on toy data.

---

## Quick Start: Jupyter Notebooks

**Want to create a library in one notebook?** Check out our interactive examples:

- **[quickstart_any_pathogen.ipynb](examples/quickstart_any_pathogen.ipynb)** - Create any library in 3 blocks (10-20 min)
- **[create_library_monkeypox.ipynb](examples/create_library_monkeypox.ipynb)** - Detailed step-by-step tutorial

Just edit the organism name and TaxID, run the notebook, and get synthesis-ready oligos!

See [examples/README.md](examples/README.md) for more details.

---

## Quick Start

```bash
# Generate default config
python -m phiplib init --output config.yaml

# Edit config.yaml with your parameters...

# Run full pipeline
python -m phiplib run --config config.yaml

# Add controls (peptide + stop codon phages)
PYTHONPATH=src python scripts/add_controls.py \
    --output-dir outputs/ --prefix virome_library

# Validate final library before synthesis
PYTHONPATH=src python scripts/validate_final_library.py \
    --fasta outputs/final_library/virome_library.fasta \
    --metadata outputs/final_library/virome_library_metadata.tsv
```

---

## Pipeline

Eight sequential steps, each resumable and independently skippable:

```
┌──────────────┐   ┌──────────────┐   ┌──────────────────┐   ┌──────────────┐
│ 1. Fetch     │──▶│ 2. Filter    │──▶│ 3. Collapse      │──▶│ 4. Tile      │
│ Proteins     │   │ Proteins     │   │ Proteins (CD-HIT)│   │ Proteins     │
│              │   │              │   │ 99% identity     │   │ MSA-aligned  │
│ UniProt +    │   │ Length, AA   │   │                  │   │ 49aa / 25aa  │
│ RefSeq       │   │ quality      │   │                  │   │ overlap      │
└──────────────┘   └──────────────┘   └──────────────────┘   └──────────────┘
                                                                    │
┌──────────────┐   ┌──────────────┐   ┌──────────────────┐   ┌─────▼────────┐
│ 8. Generate  │◀──│ 7. Codon     │◀──│ 6. Add           │◀──│ 5. Collapse  │
│ Output       │   │ Optimize     │   │ Adapters         │   │ Tiles        │
│              │   │              │   │                  │   │              │
│ FASTA +      │   │ E. coli      │   │ 5' + 3' linkers │   │ Exact-match  │
│ metadata     │   │ RE avoidance │   │ RE site check    │   │ dedup        │
└──────────────┘   └──────────────┘   └──────────────────┘   └──────────────┘
```

### Step Details

| # | Step | What it does | Key parameters |
|---|------|-------------|----------------|
| 1 | **fetch_proteins** | Download from UniProt (host-based query) + RefSeq (gap-fill for missing taxa) | `host_taxid` |
| 2 | **filter_proteins** | Remove short proteins (<49 AA), ambiguous residues (X/B/Z), optional Swiss-Prot-only filtering for overrepresented viruses | `min_protein_length`, `target_viruses`, `target_virus_mode` |
| 3 | **collapse_proteins** | CD-HIT clustering at 99% identity to remove near-duplicates; prefers Swiss-Prot as cluster representatives | `similarity_threshold` |
| 4 | **tile_proteins** | MSA-aligned tiling: MAFFT aligns each 80%-identity cluster, tiles placed on reference grid and projected to members. Falls back to naive grid tiling for singletons or large clusters (>500). Tiles with ANY X residue are rejected. | `tile_length`, `overlap`, `similarity_threshold` |
| 5 | **collapse_tiles** | Deduplicate identical tile sequences; track all source proteins per unique tile | `identity_threshold` (1.0 = exact match) |
| 6 | **add_adapters** | Attach cloning adapter sequences to tile metadata; check adapters for RE sites | `adapter_5prime`, `adapter_3prime` |
| 7 | **codon_optimize** | E. coli codon optimization with iterative RE site avoidance (up to 100 attempts), GC content control (30–70%), Shine-Dalgarno avoidance | `gc_min`, `gc_max`, `avoid_patterns` |
| 8 | **generate_output** | Assemble final oligos, write FASTA + metadata TSV + protein coverage CSV + RE scan report | `prefix`, `generate_metadata` |

### Resume & Partial Runs

The manifest system (`.phiplib_manifest.json`) tracks step completion, artifact checksums, and config hash. If config changes between runs, all steps re-execute.

```bash
# Resume from a specific step
python -m phiplib run --config config.yaml --start-at tile_proteins

# Stop after a step
python -m phiplib run --config config.yaml --stop-after collapse_tiles

# Skip specific steps
python -m phiplib run --config config.yaml --skip filter_proteins,add_adapters

# Force full re-run (ignore cache)
python -m phiplib run --config config.yaml --force

# Dry-run preview
python -m phiplib run --config config.yaml --dry-run

# Check status
python -m phiplib status --config config.yaml
```

---

## Controls

The library includes two types of controls appended after the main pipeline:

### Peptide Controls (3 tiles)

Known human protein fragments as specificity controls:

| ID | Gene | Source | Sequence (49 AA) |
|----|------|--------|-------------------|
| CONTROL_GFAP_F5 | GFAP | NP_001229305.1 | RELRLRLDQLTANSARLEVERDNLAQDLATVRQKLQDETNLRLEAENNL |
| CONTROL_GFAP_F11 | GFAP | NP_001229305.1 | TDAAARNAELLRQAKHEANDYRRQLQSLTCDLESLRGTNESLERQMREQ |
| CONTROL_MYC_F17 | MYC | NP_002458.2 | PKVVILKKATAYILSVQAEEQKLISEEDLLRKRREQLKHKLEQLRNSCA |

### Stop Codon Phages (50 oligos)

Negative controls with a stop codon at position 1 + random filler DNA. No peptide is displayed on the phage surface — establishes background signal distribution.

- Mixed stop codons: TAA, TAG, TGA (rotating)
- 144 bp unique filler per phage (seeded, deterministic)
- GC 30–70%, no RE sites, no homopolymer runs ≥7 bp, no Shine-Dalgarno

```bash
# Add controls to pipeline output
PYTHONPATH=src python scripts/add_controls.py \
    --output-dir outputs/combined_library_2026 \
    --prefix combined_virome_library
```

---

## Configuration

All parameters in YAML. See `config.yaml` for the human-only template or `config_combined_library.yaml` for the combined human+bat+bird library.

### Key Sections

```yaml
output_dir: "outputs"
log_level: "INFO"

inputs:
  virushostdb_path: "inputs/virushostdb.tsv"
  protein_fasta: null        # null = auto-fetch; or path to pre-combined FASTA
  protein_metadata: null

fetch:
  host_taxid: 9606           # NCBI taxonomy ID of host organism
  skip: false

filter:
  target_viruses: []         # empty = all viruses; or list of names
  target_virus_mode: "all"   # "all" | "swissprot_only" | "prefer_swissprot"
  min_protein_length: 49
  allow_ambiguous_aa: false

collapse_proteins:
  similarity_threshold: 0.99
  prefer_swissprot: true

tile:
  tile_length: 49
  overlap: 25
  similarity_threshold: 0.8  # CD-HIT threshold for MSA clustering
  max_cluster_size: 500      # Clusters larger than this use naive tiling

collapse_tiles:
  identity_threshold: 1.0    # 1.0 = exact match only

adapters:
  adapter_5prime: "TGGAGCCATCCGCAGTTCGAGAAA"
  adapter_3prime: "GACTACAAGGACGACGATGATAAG"   # FLAG tag

restriction_enzymes:
  enzymes: ["HindIII", "EcoRI", "XhoI"]
  fail_on_sites: false

codon_optimization:
  host_organism: "ecoli"
  gc_min: 0.30
  gc_max: 0.70
  avoid_patterns: ["AGGAGG"]  # Shine-Dalgarno
  n_jobs: -1

output:
  prefix: "virome_library"
  generate_metadata: true
  generate_coverage: true
```

### Multi-Host Libraries

To build a combined library (e.g., human + bat + bird viruses), fetch each host's proteins separately, combine into a single FASTA, and point the config at it:

```yaml
inputs:
  protein_fasta: "outputs/inputs/human_bat_bird_combined.fasta"
  protein_metadata: "outputs/inputs/human_bat_bird_combined_metadata.tsv"
fetch:
  skip: true
```

---

## Output Files

```
outputs/combined_library_2026/
├── inputs/                          # Fetched/provided proteins
├── protein_clusters/                # CD-HIT clustering output
│   ├── proteins_collapsed_99.fasta
│   └── proteins_collapsed_99.fasta.clstr
├── tiles/                           # Raw tiles (before dedup)
├── tile_clusters/                   # Deduplicated tiles
│   └── collapsed_tiles.json         # 492K tiles with metadata
├── adapted/                         # Tiles with adapter metadata
├── optimized/                       # Codon-optimized tiles
│   ├── optimized_tiles.json         # Tiles + DNA sequences
│   └── dna_validation_report.txt
└── final_library/                   # ← SYNTHESIS OUTPUT
    ├── combined_virome_library.fasta           # Full oligos (195 bp each)
    ├── combined_virome_library_metadata.tsv    # Complete metadata
    ├── combined_virome_library_protein_coverage.csv
    ├── combined_virome_library_re_scan_report.txt
    └── combined_virome_library_qc_report.txt   # Pre-synthesis QC
```

### Final FASTA Format

```
>CONTROL_GFAP_F5 protein=GFAP pos=0-49 control_type=peptide_control
TGGAGCCATCCGCAGTTCGAGAAACGTGAACTGCGTCTGCGT...GACTACAAGGACGACGATGATAAG
```

Each record is a complete 195 bp oligo: `24bp adapter + 147bp coding + 24bp adapter`.

### Metadata Columns

| Column | Description |
|--------|-------------|
| `id` | Unique tile identifier |
| `sequence_aa` | Amino acid sequence (49 AA) |
| `sequence_dna` | Codon-optimized DNA (147 bp) |
| `full_oligo` | Complete oligo with adapters (195 bp) |
| `protein_id` | Representative source protein |
| `start_pos` / `end_pos` | Position in source protein |
| `source_proteins` | All proteins sharing this tile |
| `num_proteins` | Count of source proteins |
| `is_merged` | Whether tile represents multiple proteins |
| `is_control` | Control flag (True for controls) |
| `control_type` | `peptide_control` or `stop_codon_phage` |

---

## Pre-Synthesis QC

The `add_controls.py` script runs automated QC after appending controls:

- **Oligo length uniformity** — all should be 195 bp
- **GC content** — mean, range, count outside 30–70%
- **Homopolymer runs** — flags oligos with ≥7 bp same-base runs
- **Duplicate detection** — flags identical oligo sequences
- **RE site scan** — HindIII, EcoRI, XhoI in coding regions

Additional standalone validation:

```bash
PYTHONPATH=src python scripts/validate_final_library.py \
    --fasta outputs/final_library/library.fasta \
    --metadata outputs/final_library/library_metadata.tsv
```

Checks: back-translation accuracy, adapter presence, internal stop codons, valid bases (ATGC only), FASTA↔metadata consistency.

---

## Tile Visualizer

An interactive web app for browsing the library is hosted separately:

**Repository:** [phip-seq-tile-visualizer](https://github.com/izabellaleahz/phip-seq-tile-visualizer)

**Live site:** https://izabellaleahz.github.io/phip-seq-tile-visualizer

Features:
- Browse viruses by host species (human / bat / bird / controls)
- View protein coverage tracks with tile positions
- Click tiles to see peptide + DNA sequences and cross-virus sharing
- Library statistics and host species breakdown

To regenerate visualizer data after a pipeline run:

```bash
bash run_update_visualizer.sh
```

---

## Project Structure

```
phip_seq_oligo_generator/
├── src/phiplib/
│   ├── cli.py                   # Typer CLI (run, validate, status, init, steps)
│   ├── config.py                # Pydantic v2 config schemas
│   ├── dna_generator.py         # Codon optimization engine
│   ├── utils.py                 # Helpers (hashing, FASTA validation, CD-HIT)
│   ├── exceptions.py            # Custom exception hierarchy
│   ├── pipeline/
│   │   ├── runner.py            # Step orchestrator with resume logic
│   │   ├── manifest.py          # JSON state persistence
│   │   └── steps/
│   │       ├── base.py          # Abstract PipelineStep base class
│   │       ├── fetch_proteins.py
│   │       ├── filter_proteins.py
│   │       ├── collapse_proteins.py
│   │       ├── tile_proteins.py # MSA-aligned tiling (MAFFT)
│   │       ├── collapse_tiles.py
│   │       ├── add_adapters.py
│   │       ├── codon_optimize.py
│   │       └── generate_output.py
│   └── qc/
│       ├── tiling.py            # Coverage gap / RE site checks
│       ├── composition.py       # Library statistics
│       └── visualization.py     # Plotting utilities
├── scripts/
│   ├── add_controls.py          # Append controls + pre-synthesis QC
│   └── validate_final_library.py # Comprehensive final validation
├── tests/
│   ├── test_dna_generator.py
│   ├── test_toy_run.py          # End-to-end on GFP/BFP/RFP
│   ├── test_runner_and_config.py
│   ├── test_tiling_unit.py
│   └── test_case_toy_example/   # Toy proteins for testing
├── docs/
│   └── PRIMER.md                # Wet-lab biologist's primer + walkthrough
├── config.yaml                  # Human-only template
├── config_combined_library.yaml # Human + bat + bird config
├── pyproject.toml               # Package metadata, dependencies, entry point
├── requirements.txt             # (mirror of pyproject deps, for `pip install -r`)
└── LICENSE                      # MIT
```

---

## Testing

```bash
pytest tests/ -v
pytest tests/test_dna_generator.py -v     # DNA generation tests
pytest tests/ --cov=src/phiplib --cov-report=html
```

---

## SLURM / HPC

```bash
sbatch run_combined_library.slurm
```

The SLURM script runs the pipeline followed by control addition. Typical resource requirements: 8 CPUs, 64 GB RAM, 1–4 hours depending on library size.

---

## Data Sources

- **Virus-Host DB:** https://www.genome.jp/virushostdb/ — maps viral taxa to host organisms
- **UniProt:** REST API — primary source for viral protein sequences
- **NCBI RefSeq:** Entrez API — gap-fill for taxa missing from UniProt
- **E. coli codon usage:** Kazusa database — frequency-weighted codon table

---

## Dependencies

**Python:** biopython, numpy, pandas, pydantic, typer, pyyaml, requests, tqdm, dnachisel, xxhash

**External:** CD-HIT (clustering), MAFFT (MSA)

**Full list:** see `requirements.txt`
