Metadata-Version: 2.4
Name: edge-rs
Version: 0.2.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Dist: numpy>=1.23
Requires-Dist: beartype>=0.19
Requires-Dist: polars>=1.0
Requires-Dist: anndata>=0.10 ; extra == 'anndata'
Requires-Dist: formulaic>=1.2.2 ; extra == 'anndata'
Provides-Extra: anndata
Summary: edgeR and limma-voom differential expression for Python, in Rust.
Author-email: Gregor Lueg <gregorlueg@me.com>
License: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://gregorlueg.github.io/edge-rs/
Project-URL: Repository, https://github.com/GregorLueg/edge-rs

[![PyPI](https://img.shields.io/pypi/v/edge-rs.svg)](https://pypi.org/project/edge-rs/)
[![Docs](https://img.shields.io/badge/docs-latest-blue.svg)](https://gregorlueg.github.io/edge-rs/)
[![CI](https://github.com/GregorLueg/edge-rs/actions/workflows/python-test.yml/badge.svg)](https://github.com/GregorLueg/edge-rs/actions/workflows/python-test.yml)

# edge-rs

edgeR's quasi-likelihood pipeline, limma-voom and NEBULA for Python, with the
numerics in the [`edge-rs`](https://github.com/GregorLueg/edge-rs) Rust crate.
No R, no rpy2, and every function named after the R function it reproduces.

Two ways in, each speaking the dialect of its crowd:

- **Bulk and pseudobulk**: NumPy counts in, polars frames out.
- **Single cell**: an `AnnData` in, a pandas frame out. NEBULA runs straight on
  the counts layer, optionally on the GPU.

Docs, API reference and vignettes: <https://gregorlueg.github.io/edge-rs/>

## Install

```bash
uv pip install edge-rs              # bulk: NumPy, polars and beartype
uv pip install 'edge-rs[anndata]'   # plus NEBULA on AnnData
```

The GPU path is compiled into every wheel. It goes through wgpu (Metal, Vulkan
or DX12), so there is no CUDA toolkit to install; `edge_rs.gpu_available()`
says whether this machine has a usable adapter.

## Bulk and pseudobulk

```python
import edge_rs

# counts: (n_genes, n_samples), as in edgeR
res = edge_rs.run_edger_ql(counts, design, feature_ids=genes, coef="treated")
res = edge_rs.run_limma_voom(counts, design, feature_ids=genes, coef="treated")
```

Or step by step, as in edgeR and limma:

```python
keep = edge_rs.filter_by_expr(counts, design=design)
lib_size = counts.sum(axis=0)
nf = edge_rs.calc_norm_factors(counts[keep], lib_size=lib_size)

fit = edge_rs.glm_ql_fit(counts[keep], design, lib_size=lib_size, norm_factors=nf)
edge_rs.top_tags(edge_rs.glm_ql_ftest(fit, coef="treated"))

vfit = edge_rs.voom_lm_fit(counts[keep], design, lib_size=lib_size, norm_factors=nf)
edge_rs.top_table(edge_rs.ebayes(vfit), coef="treated")
```

Would rather not carry `lib_size` around? `make_dgelist` bundles counts,
library sizes, normalisation factors and annotation. Subsetting it keeps the
library sizes of the full matrix, as edgeR's `keep.lib.sizes = TRUE` does, and
every function above takes it in place of the counts:

```python
dge = edge_rs.make_dgelist(counts, genes=pl.DataFrame({"gene_id": genes}))
dge = edge_rs.calc_norm_factors(dge[edge_rs.filter_by_expr(dge, design=design)])
fit = edge_rs.glm_ql_fit(dge, design)
edge_rs.top_tags(
    edge_rs.glm_ql_ftest(fit, coef="treated"), feature_ids=dge.genes["gene_id"]
)
```

Counts are genes x samples. Pseudobulk from
[bixverse](https://gregorlueg.github.io/bixverse-rs/) is the other way round,
so it goes in as `pb.counts.T`. A design is a NumPy matrix or a polars frame;
with a frame, the column names become coefficient names and `coef="treated"`
works. Everything is 0-based. Results are polars frames with snake_case columns
(`log_fc`, `p_value`, `fdr`, `adj_p_value`).

## Single cell: NEBULA on AnnData

Donors in a single cell experiment are the replicates, not the cells. NEBULA
models that with a subject-level random effect, and `edge_rs.nebula` runs it
straight on an `AnnData`:

```python
fit = edge_rs.nebula(adata, "donor", "~ condition + age", genes=hvgs)
fit.test(coef="condition[T.treated]").sort_values("p_value").head()
```

Cells x genes, as scanpy keeps them. Counts come from `layers["counts"]` by
default (`layer=None` for `X`, `"raw"` for `adata.raw.X`) and have to be raw
integers. Cells need not be sorted by donor. Offsets default to the library
sizes. Only want the B cells? `mask_obs=adata.obs["cell_type"] == "B"` fits
those without subsetting the `AnnData`.

The design is a [Formulaic](https://matthewwardrop.github.io/formulaic) formula
over `obs`, so interactions, transforms and other contrast codings all work.
Formulaic names the columns its own way: `condition[T.treated]`, not R's
`conditiontreated`. Already have a design matrix? Pass a DataFrame indexed by
`obs_names`, or an array in `obs` order.

`nebula()` returns a `NebulaFit`: the coefficients, their covariance per gene
and the overdispersions. The fit doesn't care what you test, so test as many
coefficients or contrasts as you like off one fit:

```python
fit.test(coef="age")
fit.test(contrast="condition[T.drug_b] - condition[T.drug_a]")
```

Yes, `test()` returns pandas, indexed by gene: it's what the scverse crowd
expects. Columns are `log_fc` (natural log, as NEBULA reports it), `se`, `z`,
`p_value`, `fdr`, both overdispersions and the convergence flags.

The layer's CSR is read in place and transposed one block of genes at a time,
so memory on top of the counts stays at one block. A fit is milliseconds to
seconds per gene, so pass the HVGs or a candidate set rather than all 30k
genes. Need data larger than memory? bixverse runs the same Rust out of core.

### On the GPU

```python
if edge_rs.gpu_available():
    fit = edge_rs.nebula(adata, "donor", "~ condition", genes=hvgs, device="gpu")
```

`device="gpu"` moves NEBULA's stage two, the penalised fits behind the variance
components, onto the device. wgpu has no `float64`, so those fits run in
`float32` and the results land close to the CPU's, not on them. Designs up to
eight columns. A design of categoricals only, `"~ condition"` say, runs on the
CPU regardless: cells share design rows within each donor, the zero counts sum
from tables, and that beats the device. Under the default NEBULA-LN most genes
never reach stage two either, so `method="hl"` with a continuous covariate is
where the device has work to do. Measure on your data before you switch.

## What's in it

| Python | R |
| --- | --- |
| `make_dgelist`, `DgeList` | `edgeR::DGEList` |
| `filter_by_expr` | `edgeR::filterByExpr` |
| `calc_norm_factors` | `edgeR::calcNormFactors` |
| `cpm`, `ave_log_cpm` | `edgeR::cpm`, `edgeR::aveLogCPM` |
| `remove_batch_effect` | `limma::removeBatchEffect` |
| `glm_ql_fit`, `glm_ql_ftest`, `top_tags` | `edgeR::glmQLFit`, `edgeR::glmQLFTest`, `edgeR::topTags` |
| `voom`, `voom_lm_fit`, `lm_fit` | `limma::voom`, `edgeR::voomLmFit`, `limma::lmFit` |
| `make_contrasts`, `contrasts_fit` | `limma::makeContrasts`, `limma::contrasts.fit` |
| `ebayes`, `top_table` | `limma::eBayes`, `limma::topTable` |
| `run_edger_ql`, `run_limma_voom` | the above, chained |
| `nebula` (on `AnnData`) | `nebula::nebula` |

Not exposed yet: the exact test, `glmFit`/`glmLRT`/`glmTreat` and
`diffSpliceDGE`. The crate has all of them.

## How close to R?

The crate is gated against edgeR 4.10.7, limma 3.68.5 and nebula 1.5.9 on
committed fixtures, and the Python tests run the same fixtures through the
bindings. The bulk vignette reruns the edgeR QL F1000 workflow on GSE60450 and
matches R on every number it shows. The GPU path is checked against the CPU
path on the same fixture.

## Vignettes

Three notebooks: bulk DGE on GSE60450, pseudobulk DGE on the Kang PBMCs with
bixverse, and NEBULA on the same PBMCs as an `AnnData`. Each is a jupytext `.py`
in `docs/vignettes/` with its executed `.ipynb` next to it, and the data
download on first use.

```bash
uv sync --group dev --group vignettes
uv run maturin develop --release
uv run python dev/vignettes.py execute             # all of them
uv run python dev/vignettes.py execute pseudobulk  # or by name
```

## Development

```bash
uv sync --group dev
uv run maturin develop --release
uv run pytest tests -q
```

The wheel builds against the crate in the parent directory, so it always tracks
this checkout. `maturin develop --no-default-features` builds without the GPU
path.

