|
| 1 | +"""Shared data loaders for gallery examples.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import warnings |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import scanpy as sc |
| 9 | +import spatialdata as sd |
| 10 | +from spatialdata.models import Image2DModel, ShapesModel, TableModel |
| 11 | + |
| 12 | + |
| 13 | +def load_visium_breast_cancer() -> sd.SpatialData: |
| 14 | + """Load Visium breast cancer tissue as a SpatialData object. |
| 15 | +
|
| 16 | + Uses ``scanpy.datasets.visium_sge`` which caches the download |
| 17 | + via :mod:`pooch`, so the data is only fetched once. |
| 18 | + """ |
| 19 | + with warnings.catch_warnings(): |
| 20 | + warnings.simplefilter("ignore") |
| 21 | + adata = sc.datasets.visium_sge( |
| 22 | + sample_id="V1_Breast_Cancer_Block_A_Section_1", |
| 23 | + ) |
| 24 | + |
| 25 | + sample = list(adata.uns["spatial"].keys())[0] |
| 26 | + meta = adata.uns["spatial"][sample] |
| 27 | + sf = meta["scalefactors"]["tissue_hires_scalef"] |
| 28 | + |
| 29 | + image = Image2DModel.parse( |
| 30 | + np.moveaxis(meta["images"]["hires"], -1, 0), |
| 31 | + dims=("c", "y", "x"), |
| 32 | + ) |
| 33 | + |
| 34 | + radius = meta["scalefactors"]["spot_diameter_fullres"] * sf / 2 |
| 35 | + circles = ShapesModel.parse( |
| 36 | + adata.obsm["spatial"] * sf, |
| 37 | + geometry=0, |
| 38 | + radius=radius, |
| 39 | + index=adata.obs_names, |
| 40 | + ) |
| 41 | + |
| 42 | + adata.obs["region"] = "spots" |
| 43 | + adata.obs["region"] = adata.obs["region"].astype("category") |
| 44 | + adata.obs["instance_key"] = adata.obs_names |
| 45 | + table = TableModel.parse( |
| 46 | + adata, |
| 47 | + region="spots", |
| 48 | + region_key="region", |
| 49 | + instance_key="instance_key", |
| 50 | + ) |
| 51 | + |
| 52 | + table.var_names_make_unique() |
| 53 | + sc.pp.normalize_total(table) |
| 54 | + sc.pp.log1p(table) |
| 55 | + |
| 56 | + return sd.SpatialData( |
| 57 | + images={"tissue": image}, |
| 58 | + shapes={"spots": circles}, |
| 59 | + tables={"table": table}, |
| 60 | + ) |
0 commit comments