Metadata-Version: 2.4
Name: rammappy
Version: 0.3.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Typing :: Typed
License-File: LICENSE
Summary: A Python interface to rammap, the Rust implementation of minimap2
Keywords: bioinformatics,sequence-alignment,spliced-alignment,genomics
Author-email: Tom Stanton <tomdstanton@gmail.com>
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Project-URL: Bug Tracker, https://github.com/tomdstanton/rammappy/issues
Project-URL: Builds, https://github.com/tomdstanton/rammappy/actions
Project-URL: Coverage, https://codecov.io/gh/tomdstanton/rammappy/
Project-URL: Documentation, https://tomdstanton.github.io/rammappy/
Project-URL: Homepage, https://tomdstanton.github.io/rammappy/
Project-URL: PyPI, https://pypi.org/project/rammappy
Project-URL: Repository, https://github.com/tomdstanton/rammappy

# 🔗🐍🧬 rammappy [![Stars](https://img.shields.io/github/stars/tomdstanton/rammappy.svg?style=social&maxAge=3600&label=Star)](https://github.com/tomdstanton/rammappy/stargazers)

*[PyO3](https://pyo3.rs/) bindings and zero-copy Python interface to [`rammap`](https://github.com/jwanglab/rammap), the Rust implementation of [`minimap2`](https://lh3.github.io/minimap2).*

[![Release](https://img.shields.io/github/v/release/tomdstanton/rammappy)](https://img.shields.io/github/v/release/tomdstanton/rammappy)
[![PyPI](https://img.shields.io/pypi/v/rammappy.svg?logo=PyPI)](https://pypi.org/project/rammappy)
[![ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![ty](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ty/main/assets/badge/v0.json)](https://github.com/astral-sh/ty)

<div class="markdown-alert markdown-alert-warning" style="padding: 1rem; margin-bottom: 1rem; border-left: 0.25rem solid #e3b341; background-color: rgba(227, 179, 65, 0.1); border-radius: 6px;">
  <p style="font-weight: 600; margin-top: 0; margin-bottom: 0.5rem; display: flex; align-items: center; color: #e3b341;">
    ⚠️ Warning
  </p>
  <p style="margin-bottom: 0; color: inherit;">
    This library is still in active development, with API refinements possible between minor versions.
  </p>
</div>

---

## 🗺️ Overview

`rammappy` provides a zero-dependency, immutable, thread-safe Python OOP interface over [`rammap-core`](https://crates.io/crates/rammap-core) (`Python >=3.12`, `abi3-py312` + free-threaded Python `3.14t`):

- **Zero third-party dependencies**: Pure Rust extension + Python standard library (`collections.abc.Buffer` & `memoryview`).
- **PEP 3118 zero-copy FFI in both directions**:
  - **Inputs**: Accept `bytes`, `bytearray`, `memoryview` slices, `mmap.mmap`, or `Record` instances directly without copying (strictly rejecting `str`).
  - **Outputs**: `MappingBatch`, `PairedMappingBatch`, `DpAlignmentBatch`, and `Sketch` expose contiguous Struct-of-Arrays `memoryview` columns (`offsets`, `scores`, `target_ids`, `cigar_data`, `cigar_offsets`, etc.) that work natively in Python stdlib *and* wrap in $O(1)$ zero-copy via `numpy.asarray(...)` or `pyarrow`.
- **Immutable & thread-safe (`#[pyclass(frozen)]`)**: `Index` and `Aligner` share `Arc<Index>` in $O(1)$ without serialization. Single-thread (`threads=1`, the default) runs sequentially on the GIL-detached calling thread without spawning OS threads, `threads=0` shares Rayon's global pool, and `threads>1` lazily allocates an isolated worker pool with per-worker DP/chaining scratch reuse.

## 🔧 Installing

```bash
uv add rammappy
```

For local development:

```bash
just install
```

## 💡 Examples

### 🧬 Parsing FASTA/FASTQ Files & Zero-Copy `mmap`

All file readers, memory parsers, and chunk streamers yield immutable `Record` objects:

```python
import mmap
import rammappy

# Optional context manager deterministically closes the OS file descriptor
with rammappy.FastxReader("sequences.fq.gz") as reader:
    for record in reader:
        mv = memoryview(record)  # zero-copy PEP 3118 byte view of record.sequence
        assert len(mv) == len(record)

# Parse directly from an mmap or memoryview slice without copying
with open("reference.fa", "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm:
    records = rammappy.parse_fasta_bytes(mm)

# Chunk-fed streaming (subclasses SequenceStreamer)
streamer = rammappy.FastaStreamer(rna_to_dna=False)
streamer.push(b">seq1\nACGT\n>seq2\nGGGG\n")
streamer.finalize()
for record in streamer:
    assert isinstance(record, rammappy.Record)
```

### 🧠 Building an In-Memory or Streaming `Index` & `Aligner`

`Index.build`, `IndexBuilder`, and `Index.load_bytes` / `Index.to_bytes` support in-memory, low-RSS streaming, and serialized buffer workflows, while `Aligner.from_reference` auto-detects `.mmi` / `RMMI` index files vs FASTA/FASTQ references via magic-byte sniffing:

```python
import rammappy

# Stream contigs one-by-one without holding all raw FASTA bytes in memory at once
builder = rammappy.IndexBuilder(k=15, w=10, threads=4)
builder.add(b"chr1", b"ACGT" * 1000)
builder.add(b"chr2", b"TGCA" * 1000)
index = builder.finish()
assert b"chr1" in index

# In-memory index round-trip (also supports minimap2 .mmi files via Index.load / load_bytes)
raw_rmmi = index.to_bytes()
reloaded = rammappy.Index.load_bytes(memoryview(raw_rmmi))

# Share Arc<Index> in O(1) across one or more immutable Aligners
aligner = rammappy.Aligner(reloaded, preset=rammappy.Preset.Sr, threads=4)
```

### ⚙️ Immutable Configuration (`MapOptions` & `AlignFlags`)

Configuration objects are immutable (`frozen`) value objects supporting `.replace(...)` (and Python 3.13+ `copy.replace`), making accidental lost-mutation bugs impossible:

```python
from rammappy import AlignFlags, MapOptions, Preset, ScoringParams

opts = MapOptions.from_preset(Preset.Sr).replace(
    scoring=ScoringParams(match_score=3, mismatch_penalty=6),
    flags=AlignFlags.SHORT_READ | AlignFlags.ALL_CHAINS | AlignFlags.OUT_CIGAR,
)

custom_aligner = aligner.with_options(opts)
```

### 🔬 Parallel Batch Alignment (`MappingBatch`)

`Aligner.map_batch` returns a CSR `MappingBatch` supporting both lazy Python `Sequence` iteration (`batch[query_idx] -> QueryMappings -> Mapping`) and zero-copy PEP 3118 `memoryview` columns:

```python
queries = [
    (b"q1", b"ACGT" * 20),
    (b"q2", b"TGCA" * 20),
]

batch = aligner.map_batch(queries)

# 1. Idiomatic OOP Sequence access (preserves CIGAR, cs, md, target_name)
for q_idx, hits in enumerate(batch):
    if hits:
        top = hits[0]
        assert top.cigar is not None

# 2. Zero-copy stdlib memoryview column slicing (CSR offsets in record indices)
offsets = batch.offsets
scores = batch.scores
cigar_offsets = batch.cigar_offsets
cigar_data = batch.cigar_data  # BAM uint32 words: (op_len << 4) | op_code

q0_scores = scores[offsets[0] : offsets[1]]
```

### 👯 Paired-End Mapping (`map_pair` & `PairedMappingBatch`)

`Aligner.map_pair` and `Aligner.map_pairs_batch` run native structured paired-end rescue and proper-pair scoring (`is_proper_pair`), preserving full CIGAR (`full_cigar`), chimeric `sa_tag`, and mate-separated zero-copy `MappingBatch` views:

```python
pairs = [
    (b"frag1", r1_seq, r2_seq),
]

pe_batch = aligner.map_pairs_batch(pairs)
r1_hits, r2_hits = pe_batch[0]
if r1_hits and r2_hits:
    assert r1_hits[0].is_proper_pair
    full = r1_hits[0].full_cigar  # FullCigar with leading/trailing S/H clips & seq_range
```

### ⚡ SIMD Pairwise Dynamic Programming (`rammappy.dp`)

`PairwiseAligner` exposes `rammap`'s SIMD Needleman-Wunsch (`Global`), Smith-Waterman (`Local`), banded single/dual-affine `SemiGlobal`, and Z-drop seed `Extension` kernels directly without building an index:

```python
from rammappy.dp import DpMode, DpScoring, PairwiseAligner

dp_aligner = PairwiseAligner(
    DpMode.Global,
    scoring=DpScoring(match_score=2, mismatch_penalty=4, gap_open=4, gap_extend=2),
)
aln = dp_aligner.align(b"ACGTACGT", b"ACGTTCGT")
assert aln.cigar == b"8M"

dp_batch = dp_aligner.align_batch([(b"ACGTACGT", b"ACGTTCGT"), (b"AAAA", b"AAAT")])
assert len(dp_batch.scores) == 2
```

### 📊 Polymorphic Sequence Sketchers (`Sketcher` -> `Sketch`)

`MinimizerSketcher`, `SyncmerSketcher`, and `RandstrobeSketcher` inherit from `Sketcher` and return a `Sketch` container with both `Minimizer` indexing and zero-copy `memoryview` columns:

```python
sketcher: rammappy.Sketcher = rammappy.MinimizerSketcher(k=15, w=10)
sketch = sketcher.sketch(b"ACTG" * 50)

first = sketch[0]
assert first.hash == sketch.hashes[0]
assert first.position == sketch.positions[0]
```

---

## 🔄 Upgrading from `0.1.x` (Breaking Changes)

The `0.2.0` architecture redesign introduces an immutable OOP model, strict zero-copy PEP 3118 byte buffers, and zero runtime dependencies. See [CHANGELOG.md](CHANGELOG.md) for full release notes.

| Area | `0.1.x` | `0.2.0` |
| :--- | :--- | :--- |
| **Python version** | `>=3.10` | `>=3.12` (`abi3-py312`, PEP 3118 `Buffer`) |
| **Sequence / name FFI** | Accepted `str` or `bytes` | Contiguous byte buffers (`bytes`, `bytearray`, `memoryview`, `mmap`) or `Record` (`str` raises `TypeError`) |
| **`Record` signature** | `Record(name, desc, seq, qual)` | `Record(name, seq, *, description=None, quality=None)` |
| **FASTA/FASTQ readers** | Returned `(name, seq)` tuples | All readers & streamers yield `Record` objects |
| **Options & mutability** | In-place mutation (`opts.scoring.match_score = 3`, `index.strip_sequences()`, `aligner.load_junctions_bed(...)`) | Immutable `frozen` types (`opts.replace(...)`, `index.without_sequences()`, `aligner.with_options(...)`, `aligner.with_junctions_bed(...)`) |
| **Batch alignment** | `list[MappingIterator]` / NumPy `map_batch_numpy` | Zero-dependency CSR `MappingBatch` (`Sequence[QueryMappings]` + zero-copy `memoryview` columns, `numpy.asarray`-ready) |
| **Sketchers** | `MinimizerSketcher(w, k)` -> `list[Minimizer]` | `MinimizerSketcher(k, w, *, is_hpc=False)` (subclass of `Sketcher`) -> `Sketch` (`Sequence[Minimizer]` + `memoryview` columns) |
| **Exceptions & `Strand`** | `ValueError` on missing contig; `FastxReader` swallowed I/O errors | Dual-inheritance `SequenceNotFoundError` (`KeyError`), `FormatError` (`ValueError`), `IndexIOError` (`OSError`); `Strand` `IntEnum` (`+1` / `-1`) |

---

## 👏 Acknowledgments

We thank the original authors of `rammap`, Jeremy R. Wang and Heng Li, for their high-performance Rust implementation of minimap2[^1].

## 📚 References

[^1]: Jeremy R. Wang and Heng Li. Memory-safe high-performance sequence mapping with rammap (2026). bioRxiv. [10.64898/2026.05.26.726289](https://doi.org/10.64898/2026.05.26.726289).

