Metadata-Version: 2.4
Name: denspatial
Version: 0.3.0
Summary: Density-aware spatial gene-set association with detection-matched null models for spot-resolution spatial transcriptomics
Author: Chen Lihua
License-Expression: MIT
Keywords: spatial transcriptomics,Visium,gene set,Moran,null model,density
Classifier: Programming Language :: Python :: 3
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Requires-Dist: scipy>=1.7
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Provides-Extra: io
Requires-Dist: anndata>=0.9; extra == "io"
Requires-Dist: h5py>=3.6; extra == "io"
Provides-Extra: plot
Requires-Dist: matplotlib; extra == "plot"
Dynamic: license-file

# denspatial

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.23601594.svg)](https://doi.org/10.5281/zenodo.23601594)

**Density-aware spatial gene-set association with detection-matched null models.**

At spot resolution (e.g. 10x Visium), a gene-set score is strongly coupled to
per-spot sequencing depth / cell density. As a result, the correlation between
*two* gene-set scores is often dominated by this shared density component, and
naive spatial-coupling claims are inflated.

`denspatial` provides a small, dependency-light toolkit to test whether a
gene-set association is **specific** or merely a **density artifact**:

1. `signature_score` — per-gene z-scored mean gene-set score (recommended);
2. `morans_i` — spatial autocorrelation with a permutation null;
3. `partial_spearman` — rank-based partial correlation controlling for density;
4. `matched_null_sets` — **random gene sets matched on cross-gene detection rate**
   (the key control that existing spatial tools do not implement);
5. `gene_set_coupling` — one call returning raw & partial coupling plus
   matched-null p-values and Moran's I;
6. `density_audit` — three-outcome verdict per gene-set pair
   (`true_signal` / `density_driven` / `not_beyond_chance`) with BH-FDR;
7. `audit_single` — single-set check of spatial structure against
   detection-matched nulls;
8. `from_h5ad` — load `.h5ad` files (anndata, or a dependency-light h5py fallback).

## Install

```bash
pip install -e .
# with the h5ad reader:  pip install -e ".[io]"
```

## Quick start

```python
import numpy as np
from denspatial import gene_set_coupling, density_audit

res = gene_set_coupling(X, coords, HYPOXIA_GENES, VESSEL_GENES, gene_names,
                        n_null=100)
print(res["raw_rho"], res["partial_rho"], res["p_partial_null"])

# three-outcome audit over several gene-set pairs
audit = density_audit(X, coords,
                      {"hypoxia": HYPOXIA_GENES, "vessel": VESSEL_GENES},
                      gene_names, n_null=100)
for row in audit["pairs"]:
    print(row["pair"], row["verdict"])
```

`X` = locations × genes (ideally `log1p(CPM)`); `coords` = locations × 2.

A runnable synthetic example: `python examples/quickstart.py`.

## Multiple density sources

Capture depth correlates with several measured confounds at once. The `density`
argument accepts a single vector, an `(n, k)` array, a list of vectors, or a dict
of named sources; all sources are residualised jointly:

```python
from denspatial import density_sources_from, gene_set_coupling

# bundle of UMI-derived covariates (log depth, detected genes, neighbourhood depth)
src = density_sources_from(X, coords)
res = gene_set_coupling(X, coords, A, B, gene_names, density=src, n_null=100)
print(res["density_sources"])
# ['log1p_library', 'n_genes', 'neighbour_library', 'neighbour_library_sq']

# add image- or cross-modality confounds as named sources
density = {"umi": lib_z, "he_cellity": he_z, "imc_cd45": imc_z}
res = gene_set_coupling(X, coords, A, B, gene_names, density=density, n_null=100)
```

Backward compatible: passing a single vector (or nothing) behaves exactly as in
v0.1–v0.2. See `examples/multisource_demo.py`.

## Verdicts

| verdict | meaning |
|---|---|
| `true_signal` | density-partial coupling exceeds detection-matched nulls (BH q ≤ α) |
| `density_driven` | raw coupling exceeds nulls, but density-partial coupling does not |
| `not_beyond_chance` | raw coupling itself does not exceed detection-matched nulls |

## Why it matters

> In Visium, gene-set scores covary with cell density; **any "program coupling"
> conclusion must be density-residualised and tested against a
> detection-matched null** — otherwise it is largely spurious.

## Reproducing the figures

Every panel of the accompanying Application Note can be regenerated
from this checkout; see [`REPRODUCE.md`](REPRODUCE.md). Figure 2 uses
the public Visium section GSM9226169 from GSE307534, and the bundled
toy dataset under `testdata/` reproduces the qualitative behaviour in
under a minute with no download.

## Testing

```bash
pytest -q
```

## Citation

If you use denspatial in your work, please cite:

> Chen Lihua (2026). denspatial: density-aware spatial gene-set association with
> detection-matched null models. Zenodo.
> https://doi.org/10.5281/zenodo.23601594 (all versions)
> v0.3.0: https://doi.org/10.5281/zenodo.23880399
> v0.1.0: https://doi.org/10.5281/zenodo.23601595

A machine-readable entry is provided in `CITATION.cff`.

## License

MIT
