Skip to content

Tools

Embeddings

From manifolds-rs, extra manifolds. scbix.tl.umap and scbix.tl.tsne are these functions. Its docs cover the estimators and every keyword argument passed through.

umap

umap(
    adata: AnnData,
    *,
    n_components: int = 2,
    min_dist: int | float = 0.5,
    spread: int | float = 1.0,
    neighbors_key: str = "neighbors",
    key_added: str | None = None,
    device: str = "cpu",
    seed: int = 42,
    verbose: int = 0,
    copy: bool = False,
    **kwargs: Any,
) -> AnnData | None

UMAP on the sc.pp.neighbors graph, stored the way sc.tl.umap does.

The neighbour graph is taken from obsp rather than searched again, so n_neighbors and the metric are whatever sc.pp.neighbors used. The representation (use_rep / n_pcs) is read from the same uns[neighbors_key]["params"]; it feeds the initialisation.

Parameters:

Name Type Description Default
adata AnnData

Annotated data matrix, after sc.pp.neighbors.

required
n_components int

Output dimensionality.

2
min_dist int | float

How tightly points may pack. Fits the repulsion curve with spread.

0.5
spread int | float

Scale of the embedding relative to min_dist.

1.0
neighbors_key str

Where sc.pp.neighbors stored its results in uns.

'neighbors'
key_added str | None

Store under obsm[key_added] and uns[key_added] instead of obsm["X_umap"] and uns["umap"].

None
device str

"cpu" for manifolds_rs.UMAP, "gpu" for manifolds_rs.UMAPGpu.

'cpu'
seed int

Fixes the initialisation and the negative sampling.

42
verbose int

0 quiet, 1 normal, 2 detailed.

0
copy bool

Return a modified copy instead of writing into adata.

False
**kwargs Any

Any other constructor argument of the chosen estimator, e.g. n_epochs, init, optim_params. Unknown names raise.

{}

Returns:

Type Description
AnnData | None

The copy if copy, else None. Sets obsm["X_umap" | key_added]

AnnData | None

and uns["umap" | key_added]["params"].

Raises:

Type Description
ValueError

If sc.pp.neighbors has not run, its graph is ragged, or the representation is missing or sparse.

tsne

tsne(
    adata: AnnData,
    n_pcs: int | None = None,
    *,
    use_rep: str | None = None,
    perplexity: int | float = 30.0,
    approx: str = "barnes_hut",
    key_added: str | None = None,
    device: str = "cpu",
    seed: int = 42,
    verbose: int = 0,
    copy: bool = False,
    **kwargs: Any,
) -> AnnData | None

t-SNE on a representation, stored the way sc.tl.tsne does.

Searches its own 3 * perplexity neighbours; sc.pp.neighbors is not used.

Parameters:

Name Type Description Default
adata AnnData

Annotated data matrix.

required
n_pcs int | None

Leading columns of the representation to use. None uses all.

None
use_rep str | None

None for obsm["X_pca"], "X" for adata.X, or any other obsm key. Must be dense.

None
perplexity int | float

Effective neighbourhood size.

30.0
approx str

"barnes_hut", "qd", "fft", "fft_3k", or "fft_3k_gpu" with device="gpu".

'barnes_hut'
key_added str | None

Store under obsm[key_added] and uns[key_added] instead of obsm["X_tsne"] and uns["tsne"].

None
device str

"cpu" for manifolds_rs.TSNE, "gpu" for manifolds_rs.TSNEGpu.

'cpu'
seed int

Fixes the initialisation.

42
verbose int

0 quiet, 1 normal, 2 detailed.

0
copy bool

Return a modified copy instead of writing into adata.

False
**kwargs Any

Any other constructor argument of the chosen estimator, e.g. n_epochs, learning_rate, ann, metric. Unknown names raise.

{}

Returns:

Type Description
AnnData | None

The copy if copy, else None. Sets obsm["X_tsne" | key_added]

AnnData | None

and uns["tsne" | key_added]["params"].

Raises:

Type Description
ValueError

If the representation is missing or sparse, or approx is not available on device.

NEBULA

From edge-rs, extra nebula. scbix.tl.nebula is this function. edge-rs needs Python 3.11 or later, so on 3.10 the extra installs nothing.

nebula

nebula(
    adata: AnnData,
    subject_key: str,
    design: str | ndarray | DataFrame,
    *,
    layer: str | None = "counts",
    genes: Sequence[str] | ndarray | Index | None = None,
    mask_obs: str | ndarray | Series | None = None,
    offset: ndarray
    | Series
    | Sequence[float]
    | None = None,
    method: Literal["ln", "hl"] = "ln",
    cpc: float = 0.005,
    mincp: int = 5,
    min_subjects: int = 0,
    shrink_dispersion: bool = True,
    gene_block_size: int = 1000,
    device: Literal["cpu", "gpu"] = "cpu",
) -> NebulaFit

NEBULA's negative binomial gamma mixed model, per gene.

The variance splits into a subject-level random effect and a cell-level overdispersion, so donors are modelled rather than pseudoreplicated. A fit takes milliseconds to seconds per gene, so pass the HVGs or a candidate set as genes rather than all of them. Cells need not be sorted by subject.

Parameters:

Name Type Description Default
adata AnnData

Annotated data matrix with raw counts.

required
subject_key str

obs column with the subject (donor), the random effect.

required
design str | ndarray | DataFrame

A Formulaic formula over obs, e.g. "~ condition * age", or a precomputed design with one row per obs. A DataFrame is matched to obs_names by its index and its columns name the coefficients; an array goes by position and its coefficients by number. Formulaic treatment codes against the first level (category order, else sorted) and names the columns condition[T.treated].

required
layer str | None

Where the counts are. None reads X, "raw" reads adata.raw.X unless a layer of that name exists.

'counts'
genes Sequence[str] | ndarray | Index | None

Gene names or a boolean mask over var. None fits every gene.

None
mask_obs str | ndarray | Series | None

Fit only these cells, e.g. one cell type, without subsetting the AnnData. A boolean array over obs, a boolean Series matched to obs_names by its index, or the name of a boolean obs column. None fits every cell. The default offset is still each cell's library size over every gene.

None
offset ndarray | Series | Sequence[float] | None

Strictly positive scaling per cell, one per obs. A Series is matched to obs_names by its index, anything else by position. None uses the library size over every gene of the layer.

None
method Literal['ln', 'hl']

"ln" for NEBULA-LN, "hl" for NEBULA-HL. LN falls back to HL below 30 cells per subject, as in R.

'ln'
cpc float

Drop a gene whose mean count per cell is at most this.

0.005
mincp int

Drop a gene expressed in fewer cells than this.

5
min_subjects int

Drop a gene fewer subjects than this express. 0 is off.

0
shrink_dispersion bool

Also shrink the cell-level overdispersions towards an empirical Bayes prior. Does not change the test.

True
gene_block_size int

Genes transposed and fitted at a time. Bounds the memory on top of the counts.

1000
device Literal['cpu', 'gpu']

"gpu" runs the penalised fits on the wgpu device (Metal, Vulkan or DX12) in float32, so results land close to the CPU path but not on it. A design of categoricals only runs the CPU path anyway, which is faster there. Check edge_rs.gpu_available() first.

'cpu'

Returns:

Type Description
NebulaFit

The NebulaFit over the genes that passed the expression filter, in

NebulaFit

input order. Its test runs the Wald test.

Raises:

Type Description
ValueError

On a missing layer or column, non-integral counts, a two-sided formula, a design of the wrong shape or not of full rank, a bad offset, or no gene passing the filter.

RuntimeError

With device="gpu" and no usable GPU.

References

He et al., Communications Biology 4, 629, 2021.

Examples:

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

Sanity and Bonsai

From bonsai-rs, extra bonsai. scbix.tl.sanity and scbix.tl.bonsai are bonsai_rs.anndata.sanity and bonsai_rs.anndata.bonsai. Both leave adata untouched and return a result carrying cell and gene names.

sanity

sanity(
    adata: AnnData,
    *,
    layer: str | None = "counts",
    genes: Sequence[str]
    | ndarray
    | Index
    | Series
    | None = None,
    cell_totals: ndarray | Series | None = None,
    variance_rule: VarianceRule = "marginalise",
    fixed_variance: float | None = None,
    dtype: type[float32] | type[float64] = float32,
    gpu: bool = False,
    min_signal_to_noise: float | None = None,
    max_amplification: float | None = None,
    verbose: int = 0,
) -> AnnDataSanity

Sanity posteriors from an AnnData, over the genes Bonsai would keep.

The first half of bonsai: genes failing the S5 amplification cap or the signal-to-noise floor are never stored. For every gene, run bonsai_rs.sanity on the matrix instead. adata is not modified.

Parameters:

Name Type Description Default
adata AnnData

As bonsai.

required
layer str | None

As bonsai.

'counts'
genes Sequence[str] | ndarray | Index | Series | None

As bonsai.

None
cell_totals ndarray | Series | None

As bonsai.

None
variance_rule VarianceRule

As bonsai_rs.sanity.

'marginalise'
fixed_variance float | None

As bonsai_rs.sanity.

None
dtype type[float32] | type[float64]

As bonsai_rs.sanity.

float32
gpu bool

As bonsai.

False
min_signal_to_noise float | None

As bonsai_rs.bonsai.

None
max_amplification float | None

As from_sanity.

None
verbose int

As bonsai_rs.sanity.

0

Returns:

Type Description
AnnDataSanity

The posteriors, cells x kept genes, with their names.

Raises:

Type Description
ValueError

On a missing layer, non-integral counts, or an unknown gene.

BonsaiError

If no gene survives, or gpu=True and no GPU can be reached.

bonsai

bonsai(
    adata: AnnData,
    *,
    layer: str | None = "counts",
    genes: Sequence[str]
    | ndarray
    | Index
    | Series
    | None = None,
    cell_totals: ndarray | Series | None = None,
    variance_rule: VarianceRule = "marginalise",
    fixed_variance: float | None = None,
    dtype: type[float32] | type[float64] = float32,
    gpu: bool = False,
    start: Start = "linkage",
    search: Search = "approximate",
    min_signal_to_noise: float | None = None,
    max_amplification: float | None = None,
    reroot: bool = False,
    verbose: int = 0,
) -> AnnDataBonsai

Raw counts in an AnnData to a Bonsai tree over its cells.

bonsai_from_counts on a layer: Sanity, the S5 conversion and the tree search, all in Rust. Sanity stores only the genes that would survive Bonsai's ingest (the S5 amplification cap and the signal-to-noise floor), so no HVG selection is needed and the dense posteriors never exceed kept genes x cells. Same tree and loglikelihood as bonsai_from_counts on the same counts. adata is not modified.

Parameters:

Name Type Description Default
adata AnnData

Annotated data matrix with raw UMI counts.

required
layer str | None

Where the counts are. None reads X, "raw" reads adata.raw.X unless a layer of that name exists.

'counts'
genes Sequence[str] | ndarray | Index | Series | None

Candidate genes: names, a boolean mask over var, or a boolean Series matched to var_names by its index, such as adata.var["highly_variable"]. None considers every gene; only those passing the filters are used.

None
cell_totals ndarray | Series | None

Total UMIs per cell. A Series is matched to obs_names by its index. None sums each cell over every gene of the layer, also when genes is a subset. Pass this if the layer itself is a gene subset.

None
variance_rule VarianceRule

As sanity.

'marginalise'
fixed_variance float | None

As sanity.

None
dtype type[float32] | type[float64]

As sanity.

float32
gpu bool

As sanity. Only Sanity runs on the GPU. The keep test then sees float32 posteriors, so a gene sitting on a threshold can go the other way from the CPU run.

False
start Start

As bonsai.

'linkage'
search Search

As bonsai.

'approximate'
min_signal_to_noise float | None

As bonsai.

None
max_amplification float | None

As from_sanity.

None
reroot bool

As bonsai.

False
verbose int

As bonsai_from_counts.

0

Returns:

Type Description
AnnDataBonsai

The tree with cell and gene names attached, and a node table.

Raises:

Type Description
ValueError

On a missing layer, non-integral counts, or an unknown gene.

BonsaiError

If no gene survives, or gpu=True and no GPU can be reached.

Examples:

>>> res = bs.anndata.bonsai(adata, layer="counts")
>>> res.nodes.query("is_leaf").head()

scDblFinder

scbix.tl.scdblfinder is available in the base install and reads raw counts from adata.layers["counts"] by default. Use layer=None for adata.X, a layer name for another layer. With AnnData 0.13 or later, pass A.X or A.layers["counts"] from anndata.acc through the same argument. Counts can be dense, CSR or CSC, in any integer or float dtype, as long as every value is a finite, non-negative integer that fits in uint32. Bixverse reads the matrix in its own layout, borrowing the buffers: canonical uint32 CSR or CSC is not copied, anything else is cast once. Don't mutate the input during the call. Grouped runs slice the matrix once per group.

import scbix
from scbix.tl import ScdblfinderParams

scbix.tl.scdblfinder(
    adata,
    layer="counts",
    group_by="capture_id",
    scdblfinder_params=ScdblfinderParams(
        expected_doublet_rate=0.08,
        gbm_n_trees=150,
    ),
    seed=42,
)

Calls go to adata.obs["scDblFinder"]; the classifier score, CXDS score, weighted score, and cluster label go to scDblFinder_score, scDblFinder_cxds, scDblFinder_weighted, and scDblFinder_cluster. Parameters and run metadata go to adata.uns["scDblFinder"]. With return_features=True, classifier features go to adata.obsm["scDblFinder_features"]. copy=True returns a modified copy; otherwise the function mutates adata and returns None.

Set algorithm options through ScdblfinderParams. It uses Bixverse defaults and takes a KnnParams object through knn. KnnParams(k=None), the default, keeps scDblFinder's automatic neighbour count, also when you only change the search method. When fast_cluster=True and n_centroids=None, scbix resolves the centroid count to int(sqrt(n_cells) * 4).

Set group_by to a column in adata.obs to score each sample or capture independently. Groups under 50 cells are rejected and groups under 500 cells warn. Results retain the original observation order, cluster labels are prefixed with the group name, and uns stores per-group thresholds, rates, selected genes, and resolved parameters.

SEACells

SEACells uses the selected dense embedding in adata.obsm. Expression data is unnecessary, including when adata.X is None. A C-contiguous float32 embedding is borrowed, anything else is cast once. Don't mutate it during the call.

By default, the call returns None and writes categorical assignments to adata.obs["seacells"] and fit metadata to adata.uns["seacells"]. Each entry in labels corresponds to the observation name at the same position in archetype_obs_names. The RSS history includes the initial objective, and iteration-limited fits retain their assignments with converged=False if they did not meet the tolerance.

Pass SeacellsParams(n_sea_cells=500) to set the target. The other fields mirror bixverse.params.SeacellsParams, and all of them land in uns[key_added]["params"]. KnnParams(k=None), the default, means 25 neighbours. use_rep accepts a string or, on AnnData 0.13 or later, an A.obsm[...] accessor. Use key_added to store another fit or rerun to replace the existing output. Use copy=True to annotate a copy, including when the input is a view.

Bixverse's greedy initialisation can fail for some embeddings and metacell targets. A failed fit raises PyO3's PanicException and writes no outputs. A smaller target may succeed.

tl

Tools, scanpy style: fn(adata, *, ..., key_added=..., copy=False).

umap and tsne (manifolds-rs), nebula (edge-rs), sanity and bonsai (bonsai-rs) are the sibling wheels' own AnnData functions, imported on first access so their extras stay optional.

KnnParams dataclass

KnnParams(
    *,
    k: int | None = None,
    knn_method: Literal[
        "kmknn",
        "hnsw",
        "annoy",
        "nndescent",
        "ivf",
        "exhaustive",
    ] = "kmknn",
    ann_dist: Literal["euclidean", "cosine"] = "euclidean",
    n_trees: int = 50,
    search_budget: int | None = None,
    delta: float = 0.001,
    diversify_prob: float = 0.0,
    ef_budget: int | None = None,
    m: int = 16,
    ef_construction: int = 200,
    ef_search: int = 100,
    n_list: int | None = None,
    n_probe: int | None = None,
)

Nearest-neighbour settings, shared by scDblFinder and SEACells.

Field names and defaults match the kNN fields of the bixverse params.

Attributes:

Name Type Description
k int | None

Number of neighbours. None takes the method's default: automatic (0) for scDblFinder, 25 for SEACells.

knn_method Literal['kmknn', 'hnsw', 'annoy', 'nndescent', 'ivf', 'exhaustive']

Nearest-neighbour search.

ann_dist Literal['euclidean', 'cosine']

Distance metric.

n_trees int

Annoy: number of trees.

search_budget int | None

Annoy: search budget per tree. None is n_trees * k * 20.

delta float

NN-Descent: early termination criterion.

diversify_prob float

NN-Descent: diversification probability.

ef_budget int | None

NN-Descent: query budget.

m int

HNSW: connections per layer.

ef_construction int

HNSW: candidate list size during construction.

ef_search int

HNSW: candidate list size at query time.

n_list int | None

IVF and kmknn: number of lists. None is sqrt(n).

n_probe int | None

IVF: number of lists to probe. None is sqrt(n_list).

ScdblfinderParams dataclass

ScdblfinderParams(
    *,
    n_genes: int = 1352,
    doublet_ratio: float = 1.0,
    heterotypic_bias: float = 1.0,
    cluster_resolution: float = 1.0,
    cluster_iters: int = 10,
    fast_cluster: bool = False,
    n_iterations: int = 3,
    gbm_n_trees: int = 200,
    max_depth: int = 4,
    learning_rate: float = 0.3,
    min_samples_leaf: int = 20,
    subsample_rate: float = 0.75,
    cv_folds: int = 5,
    cv_early_stop: int = 2,
    se_fraction: float = 1.0,
    include_pcs: int = 19,
    expected_doublet_rate: float | None = None,
    cxds_genes: int | None = None,
    manual_threshold: float | None = None,
    log_transform: bool = True,
    mean_center: bool = True,
    normalise_variance: bool = False,
    target_size: float = 1000000.0,
    no_pcs: int = 30,
    svd_solver: Literal[
        "randomised", "auto", "covariance", "exact"
    ] = "randomised",
    knn: KnnParams = KnnParams(),
    km_type: Literal[
        "emeans", "standard", "minibatch"
    ] = "emeans",
    e_means_epochs: float | None = None,
    n_centroids: int | None = None,
    k_means_iter: int = 100,
    batch_size: int = 4098,
)

scDblFinder parameters with Bixverse Python defaults.

Defaults match bixverse.params.ScdblfinderParams. Configure neighbours through knn; its k=None keeps scDblFinder's automatic choice.

to_rust

to_rust(*, n_cells: int | None = None) -> dict[str, Any]

Return the flat parameter mapping accepted by the Rust engine.

SeacellsParams dataclass

SeacellsParams(
    *,
    n_sea_cells: int,
    max_fw_iters: int = 50,
    convergence_epsilon: float = 0.001,
    max_iter: int = 100,
    min_iter: int = 10,
    greedy_threshold: int = 20000,
    graph_building: str = "union",
    pruning: bool = True,
    pruning_threshold: float = 1e-07,
    n_landmarks: int | None = None,
    knn: KnnParams = KnnParams(),
)

SEACells parameters with bixverse defaults.

Defaults match bixverse.params.SeacellsParams. Configure neighbours through knn; its k=None means 25 neighbours.

Attributes:

Name Type Description
n_sea_cells int

Number of metacells to fit.

max_fw_iters int

Frank-Wolfe iterations per matrix update.

convergence_epsilon float

Stop once the RSS change falls below convergence_epsilon * RSS(0).

max_iter int

Maximum outer iterations.

min_iter int

Minimum outer iterations.

greedy_threshold int

Above this many cells, archetypes start from a random selection instead of the greedy search.

graph_building str

kNN graph symmetrisation.

pruning bool

Prune tiny weights during the Frank-Wolfe updates.

pruning_threshold float

Weights below this are pruned.

n_landmarks int | None

Use the Nystroem extension with this many landmarks to find archetypes. Useful for larger data.

knn KnnParams

Nearest-neighbour settings.

to_rust

to_rust() -> dict[str, Any]

Return the flat parameter mapping accepted by the Rust engine.

scdblfinder

scdblfinder(
    adata: AnnData,
    *,
    layer: LayerRef = "counts",
    key_added: str = "scDblFinder",
    copy: bool = False,
    scdblfinder_params: ScdblfinderParams | None = None,
    return_features: bool = False,
    group_by: str | None = None,
    seed: int = 42,
    verbose: bool | int = True,
) -> AnnData | None

Call doublets on an AnnData count matrix using Bixverse scDblFinder.

The count buffers are borrowed, not copied: do not mutate adata during the call.

Parameters:

Name Type Description Default
adata AnnData

In-memory AnnData with raw integer counts.

required
layer LayerRef

Layer name or AnnData accessor. Use None or A.X for X.

'counts'
key_added str

Prefix for the observation columns and uns entry.

'scDblFinder'
copy bool

Return a modified copy instead of mutating adata.

False
scdblfinder_params ScdblfinderParams | None

Parameters matching bixverse.params.ScdblfinderParams. None uses its defaults.

None
return_features bool

Store classifier features in obsm.

False
group_by str | None

Observation column defining independent sample runs.

None
seed int

Random seed.

42
verbose bool | int

False/0 for silent, True/1 for progress, or 2 for detailed progress.

True

Returns:

Type Description
AnnData | None

None when copy=False; otherwise the modified AnnData copy.

Raises:

Type Description
TypeError

If inputs or parameters have the wrong types.

ValueError

If the selected matrix does not contain raw integer counts.

On completion, obs[key_added] stores calls; score, CXDS, weighted score, and cluster labels use _score, _cxds, _weighted, and _cluster suffixes. uns[key_added] stores parameters and run metadata. Requested features are stored in obsm[f"{key_added}_features"].

seacells

seacells(
    adata: AnnData,
    *,
    seacells_params: SeacellsParams,
    use_rep: RepRef = "X_pca",
    seed: int = 42,
    key_added: str = "seacells",
    copy: bool = False,
) -> AnnData | None

Fit CPU SEACells on an embedding in adata.obsm.

The embedding is borrowed when it is already C-contiguous float32: do not mutate it during the call.

Parameters:

Name Type Description Default
adata AnnData

AnnData containing a dense embedding.

required
seacells_params SeacellsParams

Target metacell count and fit settings.

required
use_rep RepRef

Embedding name or an AnnData A.obsm[...] accessor.

'X_pca'
seed int

Seed for the neighbour search and fit.

42
key_added str

Output key in obs and uns. Existing outputs are replaced.

'seacells'
copy bool

Return an annotated copy.

False

Returns:

Type Description
AnnData | None

The annotated copy when requested, otherwise None.

Raises:

Type Description
ValueError

If the embedding or fit settings are invalid.

bonsai

bonsai(
    adata: AnnData,
    *,
    layer: str | None = "counts",
    genes: Sequence[str]
    | ndarray
    | Index
    | Series
    | None = None,
    cell_totals: ndarray | Series | None = None,
    variance_rule: VarianceRule = "marginalise",
    fixed_variance: float | None = None,
    dtype: type[float32] | type[float64] = float32,
    gpu: bool = False,
    start: Start = "linkage",
    search: Search = "approximate",
    min_signal_to_noise: float | None = None,
    max_amplification: float | None = None,
    reroot: bool = False,
    verbose: int = 0,
) -> AnnDataBonsai

Raw counts in an AnnData to a Bonsai tree over its cells.

bonsai_from_counts on a layer: Sanity, the S5 conversion and the tree search, all in Rust. Sanity stores only the genes that would survive Bonsai's ingest (the S5 amplification cap and the signal-to-noise floor), so no HVG selection is needed and the dense posteriors never exceed kept genes x cells. Same tree and loglikelihood as bonsai_from_counts on the same counts. adata is not modified.

Parameters:

Name Type Description Default
adata AnnData

Annotated data matrix with raw UMI counts.

required
layer str | None

Where the counts are. None reads X, "raw" reads adata.raw.X unless a layer of that name exists.

'counts'
genes Sequence[str] | ndarray | Index | Series | None

Candidate genes: names, a boolean mask over var, or a boolean Series matched to var_names by its index, such as adata.var["highly_variable"]. None considers every gene; only those passing the filters are used.

None
cell_totals ndarray | Series | None

Total UMIs per cell. A Series is matched to obs_names by its index. None sums each cell over every gene of the layer, also when genes is a subset. Pass this if the layer itself is a gene subset.

None
variance_rule VarianceRule

As sanity.

'marginalise'
fixed_variance float | None

As sanity.

None
dtype type[float32] | type[float64]

As sanity.

float32
gpu bool

As sanity. Only Sanity runs on the GPU. The keep test then sees float32 posteriors, so a gene sitting on a threshold can go the other way from the CPU run.

False
start Start

As bonsai.

'linkage'
search Search

As bonsai.

'approximate'
min_signal_to_noise float | None

As bonsai.

None
max_amplification float | None

As from_sanity.

None
reroot bool

As bonsai.

False
verbose int

As bonsai_from_counts.

0

Returns:

Type Description
AnnDataBonsai

The tree with cell and gene names attached, and a node table.

Raises:

Type Description
ValueError

On a missing layer, non-integral counts, or an unknown gene.

BonsaiError

If no gene survives, or gpu=True and no GPU can be reached.

Examples:

>>> res = bs.anndata.bonsai(adata, layer="counts")
>>> res.nodes.query("is_leaf").head()

sanity

sanity(
    adata: AnnData,
    *,
    layer: str | None = "counts",
    genes: Sequence[str]
    | ndarray
    | Index
    | Series
    | None = None,
    cell_totals: ndarray | Series | None = None,
    variance_rule: VarianceRule = "marginalise",
    fixed_variance: float | None = None,
    dtype: type[float32] | type[float64] = float32,
    gpu: bool = False,
    min_signal_to_noise: float | None = None,
    max_amplification: float | None = None,
    verbose: int = 0,
) -> AnnDataSanity

Sanity posteriors from an AnnData, over the genes Bonsai would keep.

The first half of bonsai: genes failing the S5 amplification cap or the signal-to-noise floor are never stored. For every gene, run bonsai_rs.sanity on the matrix instead. adata is not modified.

Parameters:

Name Type Description Default
adata AnnData

As bonsai.

required
layer str | None

As bonsai.

'counts'
genes Sequence[str] | ndarray | Index | Series | None

As bonsai.

None
cell_totals ndarray | Series | None

As bonsai.

None
variance_rule VarianceRule

As bonsai_rs.sanity.

'marginalise'
fixed_variance float | None

As bonsai_rs.sanity.

None
dtype type[float32] | type[float64]

As bonsai_rs.sanity.

float32
gpu bool

As bonsai.

False
min_signal_to_noise float | None

As bonsai_rs.bonsai.

None
max_amplification float | None

As from_sanity.

None
verbose int

As bonsai_rs.sanity.

0

Returns:

Type Description
AnnDataSanity

The posteriors, cells x kept genes, with their names.

Raises:

Type Description
ValueError

On a missing layer, non-integral counts, or an unknown gene.

BonsaiError

If no gene survives, or gpu=True and no GPU can be reached.

nebula

nebula(
    adata: AnnData,
    subject_key: str,
    design: str | ndarray | DataFrame,
    *,
    layer: str | None = "counts",
    genes: Sequence[str] | ndarray | Index | None = None,
    mask_obs: str | ndarray | Series | None = None,
    offset: ndarray
    | Series
    | Sequence[float]
    | None = None,
    method: Literal["ln", "hl"] = "ln",
    cpc: float = 0.005,
    mincp: int = 5,
    min_subjects: int = 0,
    shrink_dispersion: bool = True,
    gene_block_size: int = 1000,
    device: Literal["cpu", "gpu"] = "cpu",
) -> NebulaFit

NEBULA's negative binomial gamma mixed model, per gene.

The variance splits into a subject-level random effect and a cell-level overdispersion, so donors are modelled rather than pseudoreplicated. A fit takes milliseconds to seconds per gene, so pass the HVGs or a candidate set as genes rather than all of them. Cells need not be sorted by subject.

Parameters:

Name Type Description Default
adata AnnData

Annotated data matrix with raw counts.

required
subject_key str

obs column with the subject (donor), the random effect.

required
design str | ndarray | DataFrame

A Formulaic formula over obs, e.g. "~ condition * age", or a precomputed design with one row per obs. A DataFrame is matched to obs_names by its index and its columns name the coefficients; an array goes by position and its coefficients by number. Formulaic treatment codes against the first level (category order, else sorted) and names the columns condition[T.treated].

required
layer str | None

Where the counts are. None reads X, "raw" reads adata.raw.X unless a layer of that name exists.

'counts'
genes Sequence[str] | ndarray | Index | None

Gene names or a boolean mask over var. None fits every gene.

None
mask_obs str | ndarray | Series | None

Fit only these cells, e.g. one cell type, without subsetting the AnnData. A boolean array over obs, a boolean Series matched to obs_names by its index, or the name of a boolean obs column. None fits every cell. The default offset is still each cell's library size over every gene.

None
offset ndarray | Series | Sequence[float] | None

Strictly positive scaling per cell, one per obs. A Series is matched to obs_names by its index, anything else by position. None uses the library size over every gene of the layer.

None
method Literal['ln', 'hl']

"ln" for NEBULA-LN, "hl" for NEBULA-HL. LN falls back to HL below 30 cells per subject, as in R.

'ln'
cpc float

Drop a gene whose mean count per cell is at most this.

0.005
mincp int

Drop a gene expressed in fewer cells than this.

5
min_subjects int

Drop a gene fewer subjects than this express. 0 is off.

0
shrink_dispersion bool

Also shrink the cell-level overdispersions towards an empirical Bayes prior. Does not change the test.

True
gene_block_size int

Genes transposed and fitted at a time. Bounds the memory on top of the counts.

1000
device Literal['cpu', 'gpu']

"gpu" runs the penalised fits on the wgpu device (Metal, Vulkan or DX12) in float32, so results land close to the CPU path but not on it. A design of categoricals only runs the CPU path anyway, which is faster there. Check edge_rs.gpu_available() first.

'cpu'

Returns:

Type Description
NebulaFit

The NebulaFit over the genes that passed the expression filter, in

NebulaFit

input order. Its test runs the Wald test.

Raises:

Type Description
ValueError

On a missing layer or column, non-integral counts, a two-sided formula, a design of the wrong shape or not of full rank, a bad offset, or no gene passing the filter.

RuntimeError

With device="gpu" and no usable GPU.

References

He et al., Communications Biology 4, 629, 2021.

Examples:

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

tsne

tsne(
    adata: AnnData,
    n_pcs: int | None = None,
    *,
    use_rep: str | None = None,
    perplexity: int | float = 30.0,
    approx: str = "barnes_hut",
    key_added: str | None = None,
    device: str = "cpu",
    seed: int = 42,
    verbose: int = 0,
    copy: bool = False,
    **kwargs: Any,
) -> AnnData | None

t-SNE on a representation, stored the way sc.tl.tsne does.

Searches its own 3 * perplexity neighbours; sc.pp.neighbors is not used.

Parameters:

Name Type Description Default
adata AnnData

Annotated data matrix.

required
n_pcs int | None

Leading columns of the representation to use. None uses all.

None
use_rep str | None

None for obsm["X_pca"], "X" for adata.X, or any other obsm key. Must be dense.

None
perplexity int | float

Effective neighbourhood size.

30.0
approx str

"barnes_hut", "qd", "fft", "fft_3k", or "fft_3k_gpu" with device="gpu".

'barnes_hut'
key_added str | None

Store under obsm[key_added] and uns[key_added] instead of obsm["X_tsne"] and uns["tsne"].

None
device str

"cpu" for manifolds_rs.TSNE, "gpu" for manifolds_rs.TSNEGpu.

'cpu'
seed int

Fixes the initialisation.

42
verbose int

0 quiet, 1 normal, 2 detailed.

0
copy bool

Return a modified copy instead of writing into adata.

False
**kwargs Any

Any other constructor argument of the chosen estimator, e.g. n_epochs, learning_rate, ann, metric. Unknown names raise.

{}

Returns:

Type Description
AnnData | None

The copy if copy, else None. Sets obsm["X_tsne" | key_added]

AnnData | None

and uns["tsne" | key_added]["params"].

Raises:

Type Description
ValueError

If the representation is missing or sparse, or approx is not available on device.

umap

umap(
    adata: AnnData,
    *,
    n_components: int = 2,
    min_dist: int | float = 0.5,
    spread: int | float = 1.0,
    neighbors_key: str = "neighbors",
    key_added: str | None = None,
    device: str = "cpu",
    seed: int = 42,
    verbose: int = 0,
    copy: bool = False,
    **kwargs: Any,
) -> AnnData | None

UMAP on the sc.pp.neighbors graph, stored the way sc.tl.umap does.

The neighbour graph is taken from obsp rather than searched again, so n_neighbors and the metric are whatever sc.pp.neighbors used. The representation (use_rep / n_pcs) is read from the same uns[neighbors_key]["params"]; it feeds the initialisation.

Parameters:

Name Type Description Default
adata AnnData

Annotated data matrix, after sc.pp.neighbors.

required
n_components int

Output dimensionality.

2
min_dist int | float

How tightly points may pack. Fits the repulsion curve with spread.

0.5
spread int | float

Scale of the embedding relative to min_dist.

1.0
neighbors_key str

Where sc.pp.neighbors stored its results in uns.

'neighbors'
key_added str | None

Store under obsm[key_added] and uns[key_added] instead of obsm["X_umap"] and uns["umap"].

None
device str

"cpu" for manifolds_rs.UMAP, "gpu" for manifolds_rs.UMAPGpu.

'cpu'
seed int

Fixes the initialisation and the negative sampling.

42
verbose int

0 quiet, 1 normal, 2 detailed.

0
copy bool

Return a modified copy instead of writing into adata.

False
**kwargs Any

Any other constructor argument of the chosen estimator, e.g. n_epochs, init, optim_params. Unknown names raise.

{}

Returns:

Type Description
AnnData | None

The copy if copy, else None. Sets obsm["X_umap" | key_added]

AnnData | None

and uns["umap" | key_added]["params"].

Raises:

Type Description
ValueError

If sc.pp.neighbors has not run, its graph is ragged, or the representation is missing or sparse.