Mosaic integration¶
In a mosaic design the batches do not all measure the same modalities. M3 still puts every cell in one embedding.
Here two batches of the demo have RNA and ADT and the third has RNA only. The
tutorial uses the full demo (30,534 cells), like the patient-prediction and
attribution tutorials; training takes about 20 minutes on a laptop CPU. For a
quick look, m3.datasets.liu_demo(n_cells=3000) in step 0 brings that down to
about 3 minutes.
import pandas as pd
import anndata as ad
import scanpy as sc
import matplotlib.pyplot as plt
import m3
sc.settings.verbosity = 1
0. Example files¶
This cell writes the demo as one .h5ad per modality: rna.h5ad with all
three batches and adt.h5ad with B1 and B2 only, as batch B3 has no ADT.
Skip it when you have your own files.
demo = m3.datasets.liu_demo()
obs = demo.obs.copy()
obs.index = [f"cell{i:05d}" for i in range(demo.n_cells)] # cell barcodes
has_adt = (obs["batch"] != "B3").to_numpy()
ad.AnnData(demo.modalities["rna"], obs=obs,
var=pd.DataFrame(index=demo.var["rna"])).write_h5ad("rna.h5ad")
ad.AnnData(demo.modalities["adt"][has_adt], obs=obs[has_adt],
var=pd.DataFrame(index=demo.var["adt"])).write_h5ad("adt.h5ad")
1. Read the files¶
Give m3.read_h5ad one file per modality. It matches the cells by name and
marks the cells a file does not have as not measured for that modality: here
the cells of B3 have no ADT. It prints the number of cells per batch and
modality.
Each file's obs needs the batch column. Within a batch, every modality must
have the same cells, or none of them; otherwise read_h5ad stops before
loading any counts and names the batch and example cells. If your batch column
has another name, pass it as batch_key= here and when building the model. If
.X holds normalised values and the counts are in a layer, pass
layer="counts".
data = m3.read_h5ad({"rna": "rna.h5ad", "adt": "adt.h5ad"})
print(data)
cells per batch ('batch') and modality:
rna adt
B1 7163 7163
B2 10789 10789
B3 12582 0
Dataset(n_cells=30534, batches=['B1', 'B2', 'B3'], modalities=[rna:1000, adt:192])
data.present records, per cell, which modalities were measured. A batch can
lack any modality, RNA included. For files already in memory, pass the AnnData
objects to m3.from_anndata in the same way.
Files per batch¶
When each batch comes as its own files, combine them per modality with
anndata first. label="batch" adds the batch column, and index_unique="-"
appends the batch to the cell names, so barcodes that repeat across batches
stay distinct and match between the modalities. The first cell writes example
files; the second reads them.
rna, adt = ad.read_h5ad("rna.h5ad"), ad.read_h5ad("adt.h5ad")
for b in ["B1", "B2", "B3"]:
for mod, adata in [("rna", rna), ("adt", adt)]:
part = adata[adata.obs["batch"] == b].copy()
if part.n_obs:
del part.obs["batch"] # the batch is only in the file name
part.write_h5ad(f"{b}_{mod}.h5ad")
rna = ad.concat([ad.read_h5ad(f"{b}_rna.h5ad") for b in ["B1", "B2", "B3"]],
label="batch", keys=["B1", "B2", "B3"], index_unique="-")
adt = ad.concat([ad.read_h5ad(f"{b}_adt.h5ad") for b in ["B1", "B2"]],
label="batch", keys=["B1", "B2"], index_unique="-")
print(m3.from_anndata({"rna": rna, "adt": adt}))
cells per batch ('batch') and modality:
rna adt
B1 7163 7163
B2 10789 10789
B3 12582 0
Dataset(n_cells=30534, batches=['B1', 'B2', 'B3'], modalities=[rna:1000, adt:192])
2. Train¶
Training is the same call as for fully measured data.
model = m3.M3(data, condition_keys="cond_group")
model.train()
print("capabilities:", model.capabilities)
Using 'matrix/data'
torch.Size([1000, 7163])
Using 'matrix/data'
torch.Size([1000, 10789])
Using 'matrix/data'
torch.Size([1000, 12582])
Using 'matrix/data'
torch.Size([192, 7163])
Using 'matrix/data'
torch.Size([192, 10789])
Batch counts: {np.int64(0): np.int64(7163), np.int64(1): np.int64(10789), np.int64(2): np.int64(12582)}
Minimum batch size: 7163
Epoch 1, Validation Loss: 4.1653
Epoch 2, Validation Loss: 4.1027
Epoch 3, Validation Loss: 4.0379
... (294 epochs omitted) ...
Epoch 298, Validation Loss: 0.5341
Epoch 299, Validation Loss: 0.5353
Epoch 300, Validation Loss: 0.5359
Using 'matrix/data'
torch.Size([1000, 7163])
Using 'matrix/data'
torch.Size([1000, 10789])
Using 'matrix/data'
torch.Size([1000, 12582])
Using 'matrix/data'
torch.Size([192, 7163])
Using 'matrix/data'
torch.Size([192, 10789])
capabilities: {'embedding': True, 'reconstruct': True, 'predict_donors': False}
3. One embedding for all cells¶
The embedding covers every cell, including the RNA-only batch. As in
Use your own data, it
goes back into an AnnData by the obs_names column of model.cell_metadata;
here that AnnData is rna.h5ad, which holds every cell.
part="bio" includes the condition factors, so cells also separate by
condition. part="intrinsic" leaves them out.
rna = ad.read_h5ad("rna.h5ad")
emb = pd.DataFrame(model.embedding(part="bio"),
index=model.cell_metadata["obs_names"])
rna.obsm["X_m3"] = emb.loc[rna.obs_names].to_numpy()
print(rna)
AnnData object with n_obs Ć n_vars = 30534 Ć 1000
obs: 'sample_id', 'Donor', 'cond_group', 'Age_interval', 'mergedcelltype', 'batch'
obsm: 'X_m3'
sc.pp.neighbors(rna, use_rep="X_m3", transformer="sklearn")
sc.tl.umap(rna)
sc.pl.umap(rna, color=["mergedcelltype", "batch", "cond_group"], wspace=0.5, show=False)
plt.savefig("umap_mosaic.png", dpi=130, bbox_inches="tight")
plt.show()
rna.write_h5ad("mosaic_m3.h5ad")