Metadata-Version: 2.4
Name: crispex
Version: 0.1.0
Summary: SpCas9 sgRNA design: Ensembl lookup, PAM scanning, heuristic on-target scoring, ranked CSV
Author: Siavash Ghaffari
License-Expression: MIT
Project-URL: Homepage, https://github.com/Siavashghaffari/Crispex
Project-URL: Repository, https://github.com/Siavashghaffari/Crispex
Project-URL: Documentation, https://github.com/Siavashghaffari/Crispex#readme
Project-URL: Bug Tracker, https://github.com/Siavashghaffari/Crispex/issues
Keywords: crispr,sgrna,guide-design,gene-editing,machine-learning
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
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: pandas>=1.3.0
Requires-Dist: numpy>=1.21.0
Requires-Dist: scikit-learn>=1.0.0
Requires-Dist: requests>=2.26.0
Requires-Dist: click>=8.0.0
Requires-Dist: pyfaidx>=0.7.0
Requires-Dist: tqdm>=4.62.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=3.0.0; extra == "dev"
Requires-Dist: black>=22.0.0; extra == "dev"
Requires-Dist: flake8>=4.0.0; extra == "dev"
Requires-Dist: mypy>=0.950; extra == "dev"
Dynamic: license-file

# Crispex

**CRISPR sgRNA Design for SpCas9**

Crispex is a Python package and CLI for designing CRISPR single guide RNAs (sgRNAs) for SpCas9. It looks up a gene or region in Ensembl, scans for NGG PAM sites, applies quality filters, scores on-target efficiency with Azimuth-style heuristics, and exports ranked guides as CSV.

> **Genome-wide off-target search is not implemented in 0.1.0.** See [Off-target caveat](#off-target-caveat) before using any guide at the bench.

## Features

- **Simple Interface**: Single command from gene name to ranked guides
- **On-Target Scoring**: Efficiency scoring using Azimuth-style sequence heuristics (rule-based; no trained model ships in 0.1.0)
- **Off-Target Risk Estimate**: Rough per-guide risk score — *not* a genome search (see [Off-target caveat](#off-target-caveat))
- **Quality Filters**: Automatic filtering by GC content, homopolymers, and sequence complexity
- **Multiple Input Modes**: Gene symbols or genomic coordinates
- **Ready-to-Order Output**: CSV export with sequences formatted for oligo synthesis

## Installation

### From Source (MVP)

```bash
git clone https://github.com/Siavashghaffari/Crispex.git
cd Crispex
pip install -e .
```

### Dependencies

Crispex requires Python 3.9 or later and the following packages:
- biopython
- pandas
- numpy
- scikit-learn
- requests
- click
- pyfaidx
- tqdm

These will be automatically installed when you install Crispex.

## Quick Start

### Command Line Interface

Design guides for a gene:

```bash
crispex design --gene TP53 --species human
```

Design guides for a genomic region:

```bash
crispex design --region chr17:7675000-7676000 --species human
```

Get top 10 guides:

```bash
crispex design --gene BRCA1 --top-n 10
```

### Python API

```python
from crispex import design_guides

# Design guides for a gene
guides = design_guides(gene="TP53", species="human", top_n=5)

# View results
print(guides.head())

# Access specific guide information
top_guide = guides.iloc[0]
print(f"Best guide: {top_guide['guide_sequence']}")
print(f"Efficiency: {top_guide['efficiency_score']:.1f}")
print(f"1MM off-target risk estimate (NOT measured): {top_guide['offtarget_risk_estimate_1mm']}")
```

## Usage Examples

### Example 1: Basic Gene Targeting

```bash
$ crispex design --gene TP53 --species human

╔══════════════════════════════════════════════════════════════════════╗
║                    Crispex v0.1.0                                    ║
║                 CRISPR sgRNA Design for SpCas9                       ║
╚══════════════════════════════════════════════════════════════════════╝

[1/5] Fetching gene information for TP53...
      → Querying Ensembl REST API...
      ✓ Found TP53 on chr17

[2/5] Extracting guide candidates...
      ✓ Found 247 potential guides

[3/5] Predicting on-target efficiency...
      ✓ Scored 247 guides (heuristic Azimuth-style rules)

[4/5] Estimating off-targets...
      ✓ Heuristic estimate complete (no genome search -- see note below)

[5/5] Ranking guides...
      ✓ Top 5 guides selected

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

                          🎯 TOP GUIDE

  Guide Sequence:  GGAAGACTCCAGTGGTAATC
  PAM:             TGG
  Full Oligo:      GGAAGACTCCAGTGGTAATCTGG

  Genomic Location:
    Chromosome:    chr17
    Position:      7,675,088-7,675,110 (+)

  Performance Scores:
    Efficiency:    81.2 / 100  ████████████████░░░░

  Off-Target Risk Estimate:
    ⚠  NOT measured. No genome was searched. These are heuristic
       scores from the guide sequence alone, and they change
       between runs. Do not read them as off-target counts.
    1 mismatch:        ~2  (estimate)
    2 mismatches:      ~8  (estimate)
    3 mismatches:      ~34  (estimate)
    Perfect match:      1  (assumed, not verified)

  Quality Metrics:
    GC content:    50.0%  ✓

💾 Results saved to: tp53_guides.csv

🧬 Ready to order!
   Use the 'full_sequence' column from the CSV for oligo synthesis.

⚠  Off-target caveat
   The offtarget_risk_estimate_* columns are heuristic estimates derived
   from each guide's own sequence composition. Crispex 0.1.0 does NOT
   align guides against a reference genome, so these numbers are not real
   off-target sites and will vary between runs. perfect_match_assumed is
   always 1 by assumption; guide uniqueness is not verified. Validate with
   a genome-wide tool (Cas-OFFinder, CRISPOR, CHOPCHOP) before ordering.
```

### Example 2: Programmatic Filtering

```python
from crispex import design_guides

# Design guides
guides = design_guides(gene="MYC", species="human", top_n=20)

# Filter for high-efficiency guides with a low off-target risk estimate
high_quality = guides[
    (guides['efficiency_score'] > 70) &
    (guides['offtarget_risk_estimate_1mm'] <= 2) &
    (guides['offtarget_risk_estimate_2mm'] <= 5)
]

print(f"Found {len(high_quality)} high-quality guides")

# Export filtered results
high_quality.to_csv('myc_high_quality_guides.csv', index=False)
```

### Example 3: Genomic Region Targeting

```python
from crispex import design_guides

# Target specific region
guides = design_guides(
    region="chr17:7675000-7676000",
    species="human",
    top_n=5,
    output="region_guides.csv"
)

# Iterate through guides
for idx, guide in guides.iterrows():
    print(f"Guide {guide['rank']}: {guide['guide_sequence']} "
          f"(Efficiency: {guide['efficiency_score']:.1f})")
```

## Output Format

Crispex generates a CSV file with the following columns:

| Column | Description |
|--------|-------------|
| `rank` | Guide ranking (1 = best) |
| `guide_sequence` | 20bp guide sequence (5'→3', without PAM) |
| `pam_sequence` | PAM sequence (e.g., NGG for SpCas9) |
| `full_sequence` | Guide + PAM for ordering |
| `chromosome` | Chromosome name |
| `start` | Genomic start coordinate (1-based) |
| `end` | Genomic end coordinate (1-based, inclusive) |
| `strand` | + or - strand |
| `efficiency_score` | On-target efficiency (0-100, Azimuth) |
| `perfect_match_assumed` | Always `1`. An **assumption** that the guide hits its own target site — Crispex does not verify uniqueness. Carries no measured information. See [caveat](#off-target-caveat) |
| `offtarget_risk_estimate_1mm` | **Heuristic risk estimate** at 1 mismatch — not a site count, varies between runs. See [caveat](#off-target-caveat) |
| `offtarget_risk_estimate_2mm` | **Heuristic risk estimate** at 2 mismatches — not a site count, varies between runs. See [caveat](#off-target-caveat) |
| `offtarget_risk_estimate_3mm` | **Heuristic risk estimate** at 3 mismatches — not a site count, varies between runs. See [caveat](#off-target-caveat) |
| `gc_content` | GC percentage (0-100) |
| `gene_name` | Gene symbol (if applicable) |
| `exon` | Exon number (if applicable) |

## CLI Commands

### `crispex design`

Design sgRNA guides for a gene or genomic region.

**Options:**
- `--gene TEXT`: Gene symbol (e.g., TP53, BRCA1)
- `--region TEXT`: Genomic coordinates (e.g., chr17:7661779-7687550)
- `--species TEXT`: Species [human|mouse] (default: human)
- `--output PATH`: Output CSV file path (auto-generated if not specified)
- `--top-n INTEGER`: Number of guides to return (default: 5, max: 100)

**Examples:**
```bash
crispex design --gene TP53 --species human
crispex design --gene BRCA1 --top-n 10
crispex design --region chr17:7675000-7676000 --species human
crispex design --gene MYC --output my_guides.csv
```

### `crispex install-genome`

Prints step-by-step instructions for installing a reference genome. Crispex
0.1.0 does **not** download the genome for you — see
[Reference genomes](#reference-genomes).

```bash
crispex install-genome --species human
```

If the genome is already present, this reports its path, size and whether it
has been indexed, instead of repeating the instructions.

### `crispex list-genomes`

Show installed genomes.

```bash
crispex list-genomes
```

## How It Works

Crispex follows a 5-step workflow:

1. **Gene/Region Lookup**: Fetches sequence from Ensembl REST API
2. **Guide Extraction**: Scans for PAM sites (NGG for SpCas9) and extracts 20bp guides
3. **Quality Filtering**: Filters by GC content (40-60%), homopolymers, polyT runs
4. **Efficiency Prediction**: Scores guides using Azimuth algorithm (0-100)
5. **Off-Target Estimate**: Estimates off-target load at 0-3 mismatches from guide sequence composition (no genome alignment — see [caveat](#off-target-caveat))
6. **Ranking**: Sorts by efficiency and specificity, returns top N guides

## Supported Species

- **Human**: GRCh38 assembly
- **Mouse**: GRCm39 assembly

## Reference genomes

Crispex looks for reference genomes in `~/.crispex/genomes/`:

| Species | Assembly | Expected filename |
|---------|----------|-------------------|
| human   | GRCh38   | `GRCh38.fa` (+ `GRCh38.fa.fai`) |
| mouse   | GRCm39   | `GRCm39.fa` (+ `GRCm39.fa.fai`) |

**Genome installation in 0.1.0 is manual.** `crispex install-genome` does not
download anything; it prints the exact URL, target path and indexing command
so you can copy-paste the one-time setup:

```bash
crispex install-genome --species human
```

The human download is ~0.8 GB compressed and ~3.1 GB on disk once
decompressed; mouse is ~0.75 GB and ~2.7 GB. Sources are pinned to Ensembl
release 116, and Crispex expects Ensembl-style chromosome names (`1`, `2`,
`X`) rather than UCSC-style (`chr1`, `chr2`, `chrX`).

Check what is installed with:

```bash
crispex list-genomes
```

**You do not need a genome to run `crispex design`.** Nothing in the 0.1.0
design pipeline reads the reference genome — sequence comes from the Ensembl
REST API, and off-target numbers are estimated from the guide sequence itself.
The genome is only used by the `GenomeManager` API, and is groundwork for the
genome-wide off-target search planned for a later release.

## Off-target caveat

**The `offtarget_risk_estimate_*` columns are heuristic estimates, not measured
off-target sites, and `perfect_match_assumed` is a constant, not a measurement.**

Crispex 0.1.0 does not align guides against a reference genome. Those counts
are derived from each guide's own sequence composition (k-mer diversity, GC
balance, homopolymer content) and are randomised within a band, so **they
differ between runs for the same guide** and do not correspond to real loci in
the genome.

`perfect_match_assumed` is hardcoded to `1` for every guide. It records the
assumption that a guide matches its own target site; Crispex never checks
whether the guide occurs elsewhere in the genome, so this column is not
evidence of uniqueness.

Use these columns, at most, as a rough relative penalty inside Crispex's own
ranking.
Before ordering oligos, validate candidate guides with a tool that performs a
real genome-wide search:

- [Cas-OFFinder](http://www.rgenome.net/cas-offinder/)
- [CRISPOR](http://crispor.tefor.net/)
- [CHOPCHOP](https://chopchop.cbu.uib.no/)

Genome-wide off-target search is the top priority for a future release.

## Quality Filters

Guides are automatically filtered by:

- **GC Content**: 40-60% (optimal for SpCas9)
- **Homopolymer Runs**: No runs of ≥4 identical bases
- **PolyT Stretches**: No TTTT sequences (causes pol III termination)

## Limitations (MVP)

This is a Minimum Viable Product with the following limitations:

- **Off-target search**: Not implemented. Counts are heuristic estimates that are not genome-derived and vary between runs — see [Off-target caveat](#off-target-caveat). A real FM-index/Bowtie2 search is planned
- **Efficiency model**: Simplified Azimuth implementation (production will use full gradient boosting model)
- **Genome download**: Manual, one-time install; `crispex install-genome` prints instructions rather than downloading — see [Reference genomes](#reference-genomes)
- **Cas variants**: SpCas9 only (SaCas9, Cas12a support planned)
- **No SNP checking**: Variant-aware design not yet implemented
- **No chromatin analysis**: Accessibility scoring planned for future release

## Development

### Running Tests

```bash
pytest tests/ -v
```

### Code Style

```bash
black crispex/
flake8 crispex/
```

## Troubleshooting

### Gene Not Found

If you receive a "Gene not found" error:
- Check spelling (gene symbols are case-sensitive in some databases)
- Try synonyms (e.g., TP53 vs P53)
- Use Ensembl gene ID (e.g., ENSG00000141510)
- Verify species (human vs mouse)

### No Guides Found

If no guides pass quality filters:
- Region may be too GC-rich or GC-poor
- Try a different exon or region
- Check sequence composition

### API Timeout

If Ensembl API times out:
- Check internet connection
- Try again (automatic retry logic included)
- Ensembl may be experiencing high load

### Genome Not Installed

If you hit a "genome is not installed" error from the `GenomeManager` API, the
error message contains the full install procedure. You can also print it with:

```bash
crispex install-genome --species human
```

See [Reference genomes](#reference-genomes). Note that `crispex design` does
not need a genome — if a plain design run fails, the cause is something else.


## License

Crispex is released under the [MIT License](LICENSE).

Copyright (c) 2025 Siavash Ghaffari

## Authors

This work was developed by Siavash Ghaffari. For any questions, feedback, or additional information, please feel free to reach out. Your input is highly valued and will help improve and refine this pipeline further.



## Acknowledgments

Crispex builds upon:
- Azimuth algorithm (Doench et al. 2016)
- Ensembl genome database
- BioPython library

## Roadmap

Future features planned:
- Full Azimuth gradient boosting model integration
- Genome-wide off-target search using FM-index
- SNP-aware design with dbSNP integration
- Chromatin accessibility scoring
- SaCas9 and Cas12a support
- Batch processing for multiple genes
- Base editor and prime editor support

---

**Version**: 0.1.0 (MVP)

**Status**: Alpha - Suitable for research use, not validated for therapeutic applications

**Last Updated**: 2025-01-24
