Python API¶
The package is installed from PyPI with pip installm3-sc and imported as import m3.
It has a one-to-one counterpart in the R API — both drive the same
engine and produce identical results.
The public API has two pieces:
- an input facade (
m3.read_h5,m3.read_h5ad,m3.from_anndata,m3.read_matrix,m3.concat, andm3.datasets.*) that turns common single-cell formats into one canonicalDataset; and - the
m3.M3model object, whose methods cover representation learning, donor-level disease prediction, integrated-gradients attribution, and generative augmentation.
A typical run is three lines:
import m3
data = m3.datasets.liu_demo() # 1. load a Dataset
model = m3.M3(data, condition_keys=["cond_group"], # 2. declare column roles
celltype_key="mergedcelltype",
donor_key="sample_id").train() # 3. train
emb = model.embedding(part="bio") # read out
What each read-out needs¶
Every trained model gives the cell-level read-outs. The others need more, set when the model is built:
| Read-out | Needs |
|---|---|
embedding, reconstruct, generate |
a trained model; a condition and a batch column are enough |
augment |
also donor_key and celltype_key |
predict_donors, donor_embedding, attribute |
also the donor predictor |
The donor predictor is the second training stage. train() runs it when
both donor_key and celltype_key were passed to m3.M3, and skips it with
donor_prediction=False. By default predict_donors reports the held-out
donors only, so with nothing held out it returns no rows; pass
include_reference=True for the donors the model trained on.
A read-out called without what it needs raises
m3.M3CapabilityError, and the message says what is missing.
model.capabilities shows whether the model is trained (embedding,
reconstruct) and whether it has the donor predictor (predict_donors):
Input facade¶
All readers return a Dataset holding raw counts.
m3 normalises internally, so do not pre–log-normalise the input.
The model uses the modalities named rna, adt and atac; a modality with any
other name is left out. For a walk-through from files on disk, see
Use your own data.
Batches. The model reads the batches from the obs column named by
batch_key in m3.M3 (default "batch"). The readers do not make up a
batch: when obs has no batch column, the printed Dataset shows
batches=not set, and m3.M3 raises an error unless batch_key names the
column to use. batch="name" on a reader is for input that is one batch: it
writes that label to obs["batch"], and raises an error if obs already has a
batch column with other values.
m3.read_h5¶
m3.read_h5(*, rna: str | None = None, adt: str | None = None,
atac: str | None = None, metadata: str,
batch: str | None = None) -> Dataset
Read paper-format HDF5 count matrices plus a metadata CSV. Pass
the path to each modality you have (at least one of rna / adt / atac) and
the per-cell metadata CSV. Matrix orientation (cells×features vs.
features×cells) is resolved automatically against the feature count.
m3.read_h5ad¶
m3.read_h5ad(path: str | dict[str, str], *, batch: str | None = None,
modality: str = "rna", batch_key: str = "batch",
layer: str | dict[str, str] | None = None,
join: str = "exact") -> Dataset
Read AnnData .h5ad file(s): one file, or one file per modality as a dict,
e.g. {"rna": "rna.h5ad", "adt": "adt.h5ad"}.
One file per modality. The cells are matched by name, and a cell missing
from a file is marked as not measured for that modality (a mosaic design, see
Mosaic integration). Before any
counts are loaded, the files are checked from their obs alone:
- every file's
obshas the batch column,batch_key; - cell names are unique within each file, and the files agree on the batch of each cell;
- within a batch, every modality has the same cells, or none of them. With
join="inner", the cells that not every modality of their batch has are left out instead, and their number is printed.
Then the counts must be whole numbers (an error otherwise), no modality may be
all zero for a whole batch, and obs columns that several files share must
agree. The other obs columns of every file are kept. The number of cells per
batch and modality is printed.
One file. If adata.var has a feature_types column (Gene Expression /
Antibody Capture / Peaks), the matrix is split into modalities; otherwise
the whole matrix is taken as modality. Non-integer counts give a warning.
In both cases the cell names are kept, unchanged, in an obs_names column.
batch— when all cells are one batch, its label, written toobs["batch"]batch_key— with one file per modality, theobscolumn that identifies the batcheslayer— where the raw counts are, if not in.X: a layer name, or{modality: layer name}for some modalities onlyjoin—"exact"or"inner", see above
m3.from_anndata¶
m3.from_anndata(adata: AnnData | dict[str, AnnData], *, batch: str | None = None,
modality: str = "rna", batch_key: str = "batch",
layer: str | dict[str, str] | None = None,
join: str = "exact") -> Dataset
Build a Dataset from in-memory AnnData: one object, or one per modality as a
dict such as {"rna": rna, "adt": adt}. Behaves as
read_h5ad. Per-batch files are combined per modality with
anndata first, e.g.
ad.concat(pieces, label="batch", keys=batch_names, index_unique="-"), which
adds the batch column and keeps barcodes that repeat across batches distinct. A
MuData can be passed as m3.from_anndata(mdata.mod); the joint mdata.obs is
not read.
m3.read_matrix¶
m3.read_matrix(*, counts: dict, obs: 'pd.DataFrame', var: dict,
batch: str | None = None) -> Dataset
Build a Dataset from in-memory per-modality count arrays that are already in
one cell order. The rows of the matrices and of obs are matched by position,
not by name; for files or AnnData objects,
read_h5ad / from_anndata match the cells
by name and check them.
counts—{modality -> array | sparse}of raw counts, shape[n_cells, n_features]obs— per-cellDataFrame,n_cellsrows, in the same cell order as the matrices. Its index is not kept, so store the cell names in a column.var—{modality -> list/Index}of feature names, aligned to each matrix's columnsbatch— when all cells are one batch, its label, written toobs["batch"]; leave it out whenobshas a column that identifies the batches
m3.concat¶
Stack Datasets that were built separately into one multi-batch Dataset
(one file or AnnData per modality, read with read_h5ad, needs no
concat). Features per
modality are harmonised by name intersection (the first batch's order is
kept); a batch missing a whole modality is zero-filled and flagged in
present (mosaic design, see
Mosaic integration). The inputs
either all have a batch column, with labels unique across inputs, or none has
one; in the second case batch_key in m3.M3 names the column that
identifies the batches.
m3.datasets.liu_demo¶
Load the built-in Liu et al. COVID-19 demo — a ~30 k-cell (30,534) stratified subsample of the full ~135 k-cell dataset, shipped inside the wheel so every tutorial runs with no downloads.
>>> data = m3.datasets.liu_demo()
>>> print(data)
Dataset(n_cells=30534, batches=['B1', 'B2', 'B3'], modalities=[rna:1000, adt:192])
obs carries the columns batch (B1 / B2 / B3), sample_id, Donor,
cond_group (HC / Severe), Age_interval, and mergedcelltype.
Pass n_cells (900 to 13,077) to load a smaller, fixed subsample instead of
all 30,534 cells. Training time is proportional to the number of cells, so this
is the quickest way to try cell-level integration on a CPU:
>>> m3.datasets.liu_demo(n_cells=6000)
Dataset(n_cells=6000, batches=['B1', 'B2', 'B3'], modalities=[rna:1000, adt:192])
The same cells are returned on every call. They come from six major cell types that every batch has: B_Mem, CD4_Mem, Mono_Classical, Mono_Nonclassical, NK and Plasmablast. Each batch contributes equally, and each of these types keeps at least 50 cells in every batch. Donor-level prediction and attribution need enough cells per donor, so use the full demo there.
m3.datasets.liu_demo_model¶
Path of a model trained in advance on the full demo, shipped inside the wheel.
Read it with M3.load and the full demo data (not a
liu_demo(n_cells=...) subsample) to go straight to the read-outs without
training:
>>> data = m3.datasets.liu_demo()
>>> model = m3.M3.load(m3.datasets.liu_demo_model("patient_prediction"), data)
name is "patient_prediction" (batch B3 held out, the model of the
patient prediction tutorial) or
"attribution" (trained on all three batches, the model of the
feature attribution tutorial).
The Dataset container¶
The readers return an immutable, multimodal, multi-batch raw-count container. You normally obtain one from a reader rather than constructing it by hand. Useful read-only members:
| Member | Meaning |
|---|---|
data.modalities |
{name -> scipy.sparse.csr_matrix} of raw counts |
data.obs |
per-cell DataFrame (always contains a batch column) |
data.var |
{name -> pd.Index} of feature names per modality |
data.present |
{name -> bool ndarray} per-cell modality presence (mosaic) |
data.n_cells |
number of cells |
data.modality_names |
list of modality names, e.g. ['rna', 'adt'] |
data.batches |
list of batch labels |
m3.M3¶
m3.M3(
dataset,
*,
condition_keys, # str | list[str] (required)
target_condition: str | None = None,
donor_key: str | None = None,
celltype_key: str | None = None,
batch_key: str = "batch",
held_out: list | None = None,
held_out_samples: list | None = None,
hvg: dict | None = None,
embedding_dim: int = 30,
)
Construct a model and freeze the column-role contract against dataset.obs.
Nothing is trained yet — call train.
| Argument | Role |
|---|---|
condition_keys |
one or more obs columns the model is made aware of; each gets its own latent factor. m3 is condition-aware, so this is required. |
target_condition |
the single condition used for prediction / attribution (defaults to the first of condition_keys). |
donor_key |
obs column identifying a donor/sample. Required for donor-level prediction, attribution, and augment. |
celltype_key |
obs column with cell-type labels. Needed for the donor predictor, attribution and augment. The cell-level model does not use it, so an embedding needs only condition_keys and the batch column. |
batch_key |
obs column with the batch label (default "batch"). An error is raised when obs has no such column. It is the integration / held-out unit, the site the donor adversary removes, and the stratifier for augment(batch=...). After training, cell_metadata["batch"] holds this column's values. A single-batch dataset trains without batch correction and warns. The cells of one batch must all have the same modalities, so in a mosaic dataset a batch either has a modality for all its cells or for none. |
held_out |
batch label(s) to hold out as an unlabelled query set — their target_condition labels are masked during training and recovered by predict_donors. |
held_out_samples |
donor/sample ID(s) to hold out as the query set instead of a whole batch — may span batches; requires donor_key and is mutually exclusive with held_out. Their target_condition labels are masked during training and recovered by predict_donors. |
hvg |
{modality -> n_top} highly-variable-feature selection, e.g. {"rna": 1000}. Omit to use all features as given. |
embedding_dim |
size of the whole latent (default 30): the intrinsic factor, then two dimensions per condition, then two for batch. The "bio" embedding leaves out the batch factor and so has embedding_dim - 2 columns. |
After construction, model.contract records the frozen roles, including
model.contract["reference_vocab"] (the condition values observed in the
reference batches).
M3.train¶
M3.train(
*,
max_epochs: int = 300,
lr: float = 1e-5,
batch_size: int = 256,
early_stop_patience: int = 300,
min_delta: float = 0.0,
val_percentage: float = 0.1,
weight_batch_ae: float = 1.0,
weight_modality: dict | list | None = None,
balance_batches: bool = True,
donor_prediction: bool | None = None,
donor_predictor: dict | None = None,
seed: int | None = 0,
) -> M3
Train the integration VAE and, when applicable, the donor predictor on top.
Returns the model (so you can chain .train()). Uses CUDA automatically when
available; otherwise CPU.
max_epochs,lr,batch_size— training epochs (default300), learning rate (default1e-5) and batch size (default256) of the integration VAE.early_stop_patience,min_delta— early-stopping patience in epochs (default300) and minimum improvement of the validation loss (default0). With the defaults the patience equalsmax_epochs, so training runs all epochs.val_percentage— fraction of cells held for validation (default0.1).weight_batch_ae— weight of the batch-autoencoder loss (default1.0).donor_prediction—None(default) auto-enables the donor predictor whendonor_keyandcelltype_keyare set. PassFalsefor pure representation learning,Trueto require it.balance_batches— whenTrue(default), the VAE trains on a batch-balanced subset; with no held-out query, downstream steps are automatically rebuilt on the full reference so sparse cell types are not biased out.weight_modality— per-modality weights of the reconstruction loss, as a dict keyed by modality name, e.g.{"rna": 1.0, "atac": 0.2}.None(default) weights every modality equally.seed— seeds the integration VAE so a run is reproducible (default0): the same data in the same cell order, with the same settings and seed, gives an identical result.Noneleaves it unseeded.donor_predictor— a dict tuning the Stage-2 adversarial corrector. Recognised keys (defaults):enc_lr(1e-5),glr(5e-3),n_epochs(30),patient_w(3.0),adv_max(1.0),adv_warmup(10),n_disc(1),hidden(64),min_cells(5).
M3.save¶
Write the trained model to path, to be read back with load.
The file holds the trained weights and the model's settings, not the data, so it
is small. It is a zip of arrays and contains no pickled objects. An existing file
is replaced; the folder must exist. Returns path.
M3.load¶
Read a model written by save, without training again. dataset
must be the Dataset the model was trained on: the same cells in the same
order, with the same counts, feature names and the obs columns named in
m3.M3(...) (other obs columns may differ). load returns a new model, so no
m3.M3(...) call is needed first. It gives the read-outs of the model that was
saved: identical in the environment that saved it, and equal up to floating-point
rounding in another. The exception is generate and augment, which draw random
numbers: a GPU and a CPU give different draws for the same seed. Calling train()
on it trains again from scratch.
data = m3.read_h5ad("my_data.h5ad")
model = m3.M3.load("model.m3", data)
emb = model.embedding("bio")
load raises a ValueError instead of returning a model that could give
different numbers: when dataset is not the one the model was trained on (the
message names what differs), when the file is damaged or was not written by
save, and when the loaded weights do not reproduce the outputs recorded in the
file.
Read-outs¶
m3.embedding¶
Cell-level latent, row-aligned to cell_metadata — not
necessarily to the input. Rows are grouped by batch; with held_out /
held_out_samples they are reference cells then query cells. Align on the obs_names column
that from_anndata / read_h5ad carry through, never by
position:
emb = pd.DataFrame(model.embedding("intrinsic"),
index=model.cell_metadata["obs_names"])
adata.obsm["X_m3"] = emb.loc[adata.obs_names].to_numpy()
part selects which factor(s):
"bio"— the intrinsic biological latent plus every condition factor (the integration embedding for clustering / UMAP; cells also separate by condition)"intrinsic"— the intrinsic biological latent only (cell types across batches, without the condition differences)"batch"— the 2-d batch factor (should carry batch signal, not biology)- any name in
condition_keys— that condition's 2-d factor
part |
columns | with embedding_dim=30, one condition |
|---|---|---|
"intrinsic" |
embedding_dim - 2 - 2 × n_conditions |
26 |
| a condition key | 2 | 2 |
"batch" |
2 | 2 |
"bio" |
intrinsic, then each condition: embedding_dim - 2 |
28 |
m3.reconstruct¶
Posterior-mean decode of every cell, returned as {modality -> ndarray}
([n_cells, n_features]). With remove_batch=True (default) the batch factor is
zeroed before decoding, yielding a batch-corrected matrix suitable for
cross-batch differential expression.
Rows follow cell_metadata and columns follow
dataset.var[modality] (with hvg=, only the selected features are returned).
Values are on the scale the model trains on, not counts:
log2(count / size + 1), where size is the cell's total count in that modality
divided by the mean total over all cells.
m3.predict_donors¶
Donor-level prediction of target_condition. Requires the donor predictor.
Returns one row per donor with columns donor, is_reference,
predicted_label, and a prob_<label> column per class. By default only the
held-out query donors are returned; pass include_reference=True to include
the reference donors too.
m3.donor_embedding¶
The corrector-corrected per-donor vector used for prediction — a DataFrame
indexed by donor, with an is_reference column followed by embedding dimensions
(m3_0, m3_1, …). Join with predict_donors(include_reference=True) for
labels, or feed straight into UMAP for a patient-level map. Requires the donor
predictor.
m3.generate¶
Posterior-resampled synthetic cells (one per reference cell, 1:1), returned as
{modality -> ndarray}. tau scales the sampling temperature. Handy for
noise-augmenting a training set.
m3.augment¶
M3.augment(*, conditions: list, n_donors: list, tau: float = 0.8,
batch: str | None = None, seed: int = 42) -> dict
Synthesise new donors per condition by posterior-resampling real donor
templates. conditions lists the target_condition values to generate and
n_donors how many synthetic donors for each (same length). Returns
{"expression": {modality -> ndarray}, "obs": DataFrame}. When batch is given
(a value of batch_key), templates are drawn only from that batch — useful for
reproducing batch-stratified figures. Requires donor_key + celltype_key.
m3.cell_metadata¶
Row-aligned metadata for embedding /
reconstruct (reference cells first, then query cells). Data read
with from_anndata / read_h5ad carries the input barcodes in an obs_names
column; for read_matrix / read_h5, put an identifier column in obs yourself.
Attribution¶
m3.attribute¶
M3.attribute(*, reference_labels: list, target_class: int | None = None,
n_steps: int = 50) -> Attribution
End-to-end integrated-gradients attribution of target_condition, returning an
Attribution. Requires the donor predictor.
reference_labels— the healthy/baseline label(s) oftarget_condition(e.g.["HC"]). These set the IG baseline at two levels: the mean expression of reference cells (cell-level IG) and the mean patient vector over reference donors (donor-level IG). Supplying them is what keeps housekeeping / pan–cell-type genes from dominating the ranking.target_class— which non-reference class to attribute toward; defaults to the first class not inreference_labels.n_steps— IG interpolation steps (default50; lower is faster but biased).
The Attribution object¶
Returned by attribute. Holds several views of importance:
| Member | Type | Meaning |
|---|---|---|
attr.genes |
DataFrame(feature, importance) |
raw mean(\|IG\|) over all cells — quick, unfiltered |
attr.celltypes |
DataFrame(celltype, importance) |
per–cell-type importance |
attr.donors |
DataFrame(donor, attribution) or None |
per-donor attribution |
attr.cells |
ndarray |
signed per-cell importance |
attr.attribution |
ndarray [n_cells, n_features] |
full cell × feature IG matrix |
attr.gene_celltype_matrix |
ndarray [n_celltypes, n_features] |
signed per–(cell-type, feature) attribution |
attr.target_label |
str |
the attributed (non-reference) condition |
Attribution.top_genes¶
Attribution.top_genes(n: int = 100, *, min_cells_per_condition: int = 200,
exclude_regex: str | None = <housekeeping>,
modality: str | None = None) -> pd.DataFrame
The publication ranking recipe. Drops cell types where either the reference or
the target condition has fewer than min_cells_per_condition cells, scores each
feature as mean(|gene_celltype_matrix|) across the kept cell types, removes
housekeeping / ribosomal genes by name (exclude_regex, default matches
^MT-, ^RPL, ^RPS, …; pass None to skip), optionally restricts to one
modality ("rna" / "adt" / "atac"), and returns the top-n ranked
DataFrame with columns feature, modality, score, n_celltypes_used.
Attribution.top_celltypes¶
Cell-type importance ranking, filtered to types with at least
min_cells_per_condition cells in both the reference and the target
condition (default 200; set 0 for the raw celltypes table).
Exceptions¶
m3.M3CapabilityError— a read-out was called on a model that lacks what it needs, see What each read-out needs (subclassesRuntimeError). The message names what is missing and how to obtain it.
Versioning¶
The installed version is available as m3.__version__.
R ⇄ Python correspondence¶
Every verb has a 1:1 counterpart in the R API. The R package wraps the same engine, so a script translated line-for-line produces identical numbers.
| Python | R |
|---|---|
m3.datasets.liu_demo() |
m3_demo() |
m3.read_h5() / m3.read_h5ad() |
m3_read_h5() / m3_read_h5ad() |
m3.from_anndata() / m3.read_matrix() |
m3_dataset() |
m3.concat() |
m3_concat() |
m3.M3(...).train() |
m3_train(...) |
M3.save() / M3.load() |
m3_save() / m3_load() |
m3.datasets.liu_demo_model() |
m3_demo_model() |
M3.capabilities |
m3_capabilities() |
M3.embedding() |
m3_embedding() |
M3.cell_metadata |
m3_cell_metadata() |
M3.reconstruct() |
m3_reconstruct() |
M3.predict_donors() |
m3_predict_donors() |
M3.donor_embedding() |
m3_donor_embedding() |
M3.generate() |
m3_generate() |
M3.augment() |
m3_augment() |
M3.attribute() |
m3_attribute() |
Attribution.top_genes() / .top_celltypes() |
m3_top_genes() / m3_top_celltypes() |
| — | m3_shutdown() (R only — releases the engine session) |
See also¶
- R API — the same surface for R (
library(m3)). - Tutorials — Representation learning, Patient prediction, Feature attribution, Data augmentation, Use your own data, Mosaic integration.