From 3cd3675e42f5892b3c48176e62cdfbd56992627d Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:56:09 -0500 Subject: [PATCH 1/9] Update data URLs. Remove demo workflows whose data is no longer accessible --- demos/README.md | 6 +- demos/Snakefile | 26 +- demos/codeluppi-2018-via-zarr/Snakefile | 34 --- demos/codeluppi-2018-via-zarr/config.yml | 4 - .../vitessce.template.json | 241 --------------- demos/codeluppi-2018/Snakefile | 132 --------- demos/codeluppi-2018/config.yml | 6 - .../src/convert_to_cells_csv.py | 73 ----- .../src/convert_to_cells_h5ad_zarr.py | 190 ------------ .../src/convert_to_molecules_csv.py | 32 -- .../src/convert_to_molecules_h5ad_zarr.py | 54 ---- .../codeluppi-2018/src/convert_to_ome_zarr.py | 41 --- demos/codeluppi-2018/vitessce.template.json | 279 ------------------ demos/eng-2019/Snakefile | 36 --- demos/eng-2019/config.yml | 3 - demos/eng-2019/src/convert_to_csv.py | 57 ---- demos/eng-2019/vitessce.template.json | 194 ------------ demos/kuppe-2022/Snakefile | 9 +- demos/marshall-2022/Snakefile | 4 +- demos/meta-2022-azimuth/Snakefile | 2 +- demos/satija-2020/Snakefile | 105 ------- demos/satija-2020/config.yml | 3 - demos/satija-2020/src/constants.py | 11 - demos/satija-2020/src/convert_to_zarr.py | 125 -------- demos/satija-2020/src/generate_cell_sets.py | 152 ---------- demos/satija-2020/src/split_annotation_csv.py | 46 --- demos/satija-2020/src/utils.py | 224 -------------- demos/satija-2020/vitessce.template.json | 135 --------- demos/sn-atac-seq-hubmap-2020/Snakefile | 35 --- demos/sn-atac-seq-hubmap-2020/config.yml | 2 - .../src/convert_to_csv.py | 54 ---- .../vitessce.template.json | 87 ------ demos/wang-2018/Snakefile | 44 --- demos/wang-2018/config.yml | 5 - demos/wang-2018/src/convert_to_csv.py | 107 ------- demos/wang-2018/vitessce.template.json | 100 ------- 36 files changed, 11 insertions(+), 2647 deletions(-) delete mode 100644 demos/codeluppi-2018-via-zarr/Snakefile delete mode 100644 demos/codeluppi-2018-via-zarr/config.yml delete mode 100644 demos/codeluppi-2018-via-zarr/vitessce.template.json delete mode 100644 demos/codeluppi-2018/Snakefile delete mode 100644 demos/codeluppi-2018/config.yml delete mode 100644 demos/codeluppi-2018/src/convert_to_cells_csv.py delete mode 100644 demos/codeluppi-2018/src/convert_to_cells_h5ad_zarr.py delete mode 100644 demos/codeluppi-2018/src/convert_to_molecules_csv.py delete mode 100644 demos/codeluppi-2018/src/convert_to_molecules_h5ad_zarr.py delete mode 100644 demos/codeluppi-2018/src/convert_to_ome_zarr.py delete mode 100644 demos/codeluppi-2018/vitessce.template.json delete mode 100644 demos/eng-2019/Snakefile delete mode 100644 demos/eng-2019/config.yml delete mode 100644 demos/eng-2019/src/convert_to_csv.py delete mode 100644 demos/eng-2019/vitessce.template.json delete mode 100644 demos/satija-2020/Snakefile delete mode 100644 demos/satija-2020/config.yml delete mode 100644 demos/satija-2020/src/constants.py delete mode 100644 demos/satija-2020/src/convert_to_zarr.py delete mode 100644 demos/satija-2020/src/generate_cell_sets.py delete mode 100644 demos/satija-2020/src/split_annotation_csv.py delete mode 100644 demos/satija-2020/src/utils.py delete mode 100644 demos/satija-2020/vitessce.template.json delete mode 100644 demos/sn-atac-seq-hubmap-2020/Snakefile delete mode 100644 demos/sn-atac-seq-hubmap-2020/config.yml delete mode 100644 demos/sn-atac-seq-hubmap-2020/src/convert_to_csv.py delete mode 100644 demos/sn-atac-seq-hubmap-2020/vitessce.template.json delete mode 100644 demos/wang-2018/Snakefile delete mode 100644 demos/wang-2018/config.yml delete mode 100644 demos/wang-2018/src/convert_to_csv.py delete mode 100644 demos/wang-2018/vitessce.template.json diff --git a/demos/README.md b/demos/README.md index d9fc32fb..b473afc6 100644 --- a/demos/README.md +++ b/demos/README.md @@ -21,8 +21,6 @@ pip install -e "..[dev]" snakemake --cores all --rerun-triggers mtime ``` -> NOTE: You will need to refresh the cellxgene urls as they are valid only for a week - please see snakemake files for instructions. - ### Serve data locally ```sh @@ -68,13 +66,13 @@ Be sure to re-run after making changes to `vitessce.template.json`. Local: ```sh -python fill_template.py -d codeluppi-2018 -t local > ./codeluppi-2018/vitessce.local.json +python fill_template.py -d habib-2017 -t local > ./habib-2017/vitessce.local.json ``` Remote: ```sh -python fill_template.py -d codeluppi-2018 -t remote -v 0.0.33 > ./codeluppi-2018/vitessce.remote.json +python fill_template.py -d habib-2017 -t remote -v 0.0.33 > ./habib-2017/vitessce.remote.json ``` ### Configure AWS and Google Cloud CLIs diff --git a/demos/Snakefile b/demos/Snakefile index f41382be..bb5d5489 100644 --- a/demos/Snakefile +++ b/demos/Snakefile @@ -19,22 +19,10 @@ include: "./common.smk" # All subworkflows listed here will be # executed as part of the 'all' rule # in this snakefile. -subworkflow codeluppi_2018: - workdir: - "codeluppi-2018" - -subworkflow codeluppi_2018_via_zarr: - workdir: - "codeluppi-2018-via-zarr" - subworkflow combat_2022: workdir: "combat-2022" -subworkflow eng_2019: - workdir: - "eng-2019" - subworkflow habib_2017: workdir: "habib-2017" @@ -55,18 +43,6 @@ subworkflow meta_2022_azimuth: workdir: "meta-2022-azimuth" -subworkflow satija_2020: - workdir: - "satija-2020" - -subworkflow sn_atac_seq_hubmap_2020: - workdir: - "sn-atac-seq-hubmap-2020" - -subworkflow wang_2018: - workdir: - "wang-2018" - # End subworkflow list. # Only access workflow._subworkflows after all @@ -131,4 +107,4 @@ rule fill_templates: for subworkflow_dir in params.subworkflow_dirs: if os.path.exists(os.path.join(subworkflow_dir, 'vitessce.template.json')): shell(f"python fill_template.py -d {subworkflow_dir} -t local > {os.path.join(subworkflow_dir, 'vitessce.local.json')}") - shell(f"python fill_template.py -d {subworkflow_dir} -t remote -v {BUCKET_VERSION} > {os.path.join(subworkflow_dir, 'vitessce.remote.json')}") \ No newline at end of file + shell(f"python fill_template.py -d {subworkflow_dir} -t remote -v {BUCKET_VERSION} > {os.path.join(subworkflow_dir, 'vitessce.remote.json')}") diff --git a/demos/codeluppi-2018-via-zarr/Snakefile b/demos/codeluppi-2018-via-zarr/Snakefile deleted file mode 100644 index 076065e4..00000000 --- a/demos/codeluppi-2018-via-zarr/Snakefile +++ /dev/null @@ -1,34 +0,0 @@ -include: "../common.smk" -configfile: "config.yml" - -from pathlib import Path - -BASE_SRC_DIR = Path("../codeluppi-2018/src") - -module base_workflow: - snakefile: "../codeluppi-2018/Snakefile" - config: config - -rule all: - input: - [ (PROCESSED_DIR / f) for f in config['output'] ] - -use rule * from base_workflow as base_* - -use rule convert_to_ome_zarr from base_workflow as base_convert_to_ome_zarr with: - output: - directory(PROCESSED_DIR / "codeluppi_2018_nature_methods.image.ome.zarr") - params: - script=(BASE_SRC_DIR / "convert_to_ome_zarr.py") - -use rule convert_to_cells_zarr from base_workflow as base_convert_to_cells_zarr with: - output: - directory(PROCESSED_DIR / "codeluppi_2018_nature_methods.cells.h5ad.zarr") - params: - script=(BASE_SRC_DIR / "convert_to_cells_h5ad_zarr.py") - -use rule convert_to_molecules_zarr from base_workflow as base_convert_to_molecules_zarr with: - output: - directory(PROCESSED_DIR / "codeluppi_2018_nature_methods.molecules.h5ad.zarr") - params: - script=(BASE_SRC_DIR / "convert_to_molecules_h5ad_zarr.py") diff --git a/demos/codeluppi-2018-via-zarr/config.yml b/demos/codeluppi-2018-via-zarr/config.yml deleted file mode 100644 index ec89cf72..00000000 --- a/demos/codeluppi-2018-via-zarr/config.yml +++ /dev/null @@ -1,4 +0,0 @@ -output: -- codeluppi_2018_nature_methods.image.ome.zarr -- codeluppi_2018_nature_methods.molecules.h5ad.zarr -- codeluppi_2018_nature_methods.cells.h5ad.zarr diff --git a/demos/codeluppi-2018-via-zarr/vitessce.template.json b/demos/codeluppi-2018-via-zarr/vitessce.template.json deleted file mode 100644 index 8df96cef..00000000 --- a/demos/codeluppi-2018-via-zarr/vitessce.template.json +++ /dev/null @@ -1,241 +0,0 @@ -{ - "name": "Codeluppi et al., Nature Methods 2018", - "description": "Spatial organization of the somatosensory cortex revealed by osmFISH", - "version": "1.0.15", - "initStrategy": "auto", - "datasets": [ - { - "uid": "codeluppi", - "name": "Codeluppi", - "files": [ - { - "fileType": "anndata.zarr", - "url": "{{ base_url }}/codeluppi_2018_nature_methods.cells.h5ad.zarr", - "options": { - "obsFeatureMatrix": { - "path": "layers/X_uint8" - }, - "obsSegmentations": { - "path": "obsm/X_segmentations" - }, - "obsLocations": { - "path": "obsm/X_spatial" - }, - "obsEmbedding": [ - { - "path": "obsm/X_pca", - "embeddingType": "PCA" - }, - { - "path": "obsm/X_tsne", - "embeddingType": "t-SNE" - } - ], - "obsSets": [ - { - "name": "Cell Type", - "path": ["obs/Cluster", "obs/Subcluster"] - } - ] - }, - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression" - } - }, - { - "fileType": "anndata.zarr", - "url": "{{ base_url }}/codeluppi_2018_nature_methods.molecules.h5ad.zarr", - "options": { - "obsLocations": { - "path": "obsm/X_spatial" - }, - "obsLabels": { - "path": "obs/Gene" - } - }, - "coordinationValues": { - "obsType": "molecule" - } - }, - { - "fileType": "image.ome-zarr", - "url": "{{ base_url_gcp }}/codeluppi_2018_nature_methods.image.ome.zarr" - } - ] - } - ], - "coordinationSpace": { - "embeddingZoom": { - "PCA": 0, - "TSNE": 0.75 - }, - "embeddingType": { - "PCA": "PCA", - "TSNE": "t-SNE" - }, - "spatialZoom": { - "A": -5.5 - }, - "spatialTargetX": { - "A": 16000 - }, - "spatialTargetY": { - "A": 20000 - }, - "spatialImageLayer": { - "A": [ - { - "type": "raster", - "index": 0, - "visible": true, - "colormap": null, - "opacity": 1, - "domainType": "Min/Max", - "transparentColor": null, - "renderingMode": "Additive", - "use3d": false, - "channels": [ - { - "selection": { - "c": 1 - }, - "color": [ - 0, - 0, - 255 - ], - "visible": true, - "slider": [ - 1, - 1473 - ] - }, - { - "selection": { - "c": 0 - }, - "color": [ - 0, - 255, - 0 - ], - "visible": true, - "slider": [ - 1, - 447 - ] - } - ] - } - ] - }, - "spatialSegmentationLayer": { - "A": { - "opacity": 1, "radius": 0, "visible": true, "stroked": false - } - }, - "spatialPointLayer": { - "A": { - "opacity": 1, "radius": 20, "visible": true - } - } - }, - "layout": [ - { - "component": "description", - "x": 0, - "y": 0, - "w": 2, - "h": 1 - }, - { - "component": "layerController", - "coordinationScopes": { - "spatialImageLayer": "A", - "spatialSegmentationLayer": "A", - "spatialPointLayer": "A" - }, - "x": 0, - "y": 1, - "w": 2, - "h": 4 - }, - { - "component": "status", - "x": 0, - "y": 5, - "w": 2, - "h": 1 - }, - { - "component": "spatial", - "coordinationScopes": { - "spatialZoom": "A", - "spatialTargetX": "A", - "spatialTargetY": "A", - "spatialImageLayer": "A", - "spatialSegmentationLayer": "A", - "spatialPointLayer": "A" - }, - "x": 2, - "y": 0, - "w": 4, - "h": 4 - }, - { - "component": "featureList", - "x": 9, - "y": 0, - "w": 3, - "h": 2 - }, - { - "component": "obsSets", - "x": 9, - "y": 3, - "w": 3, - "h": 2 - }, - { - "component": "heatmap", - "props": { - "transpose": true - }, - "x": 2, - "y": 4, - "w": 5, - "h": 2 - }, - { - "component": "obsSetFeatureValueDistribution", - "x": 7, - "y": 4, - "w": 5, - "h": 2 - }, - { - "component": "scatterplot", - "coordinationScopes": { - "embeddingType": "PCA", - "embeddingZoom": "PCA" - }, - "x": 6, - "y": 0, - "w": 3, - "h": 2 - }, - { - "component": "scatterplot", - "coordinationScopes": { - "embeddingType": "TSNE", - "embeddingZoom": "TSNE" - }, - "x": 6, - "y": 2, - "w": 3, - "h": 2 - } - ] -} \ No newline at end of file diff --git a/demos/codeluppi-2018/Snakefile b/demos/codeluppi-2018/Snakefile deleted file mode 100644 index 9a0dd78a..00000000 --- a/demos/codeluppi-2018/Snakefile +++ /dev/null @@ -1,132 +0,0 @@ -include: "../common.smk" -configfile: "config.yml" - -# HDF5 image URL -PKLAB_URL = "http://pklab.med.harvard.edu/viktor/data/spatial/linnarson/Nuclei_polyT.int16.sf.hdf5" - -# http://linnarssonlab.org/osmFISH/availability/ -CELLS_LOOM_URL = "http://linnarssonlab.org/osmFISH/osmFISH_SScortex_mouse_all_cells.loom" -CELLS_PKL_URL = "https://storage.googleapis.com/linnarsson-lab-www-blobs/blobs/osmFISH/data/polyT_seg.pkl" -MOLECULES_HDF5_URL = "https://storage.googleapis.com/linnarsson-lab-www-blobs/blobs/osmFISH/data/mRNA_coords_raw_counting.hdf5" - -rule all: - input: - [ (PROCESSED_DIR / f) for f in config['output'] ] - -# The following rules are also imported by ../codeluppi-2018-via-zarr/Snakefile. -rule convert_to_ome_zarr: - input: - (RAW_DIR / "Nuclei_polyT.int16.sf.hdf5") - output: - directory(PROCESSED_DIR / "codeluppi_2018_nature_methods.image.ome.zarr") - params: - script=(SRC_DIR / "convert_to_ome_zarr.py") - shell: - ''' - python {params.script} \ - -i {input} \ - -o {output} - ''' - -rule convert_to_cells_csv: - input: - directory(PROCESSED_DIR / "codeluppi_2018_nature_methods.cells.h5ad.zarr") - output: - cells=(PROCESSED_DIR / "codeluppi_2018_nature_methods.cells.csv"), - segmentations=(PROCESSED_DIR / "codeluppi_2018_nature_methods.cells.segmentations.json"), - matrix=(PROCESSED_DIR / "codeluppi_2018_nature_methods.cells.matrix.csv") - params: - script=(SRC_DIR / "convert_to_cells_csv.py") - shell: - ''' - python {params.script} \ - -i {input} \ - -oc {output.cells} \ - -os {output.segmentations} \ - -om {output.matrix} - ''' - -rule convert_to_molecules_csv: - input: - directory(PROCESSED_DIR / "codeluppi_2018_nature_methods.molecules.h5ad.zarr") - output: - (PROCESSED_DIR / "codeluppi_2018_nature_methods.molecules.csv") - params: - script=(SRC_DIR / "convert_to_molecules_csv.py") - shell: - ''' - python {params.script} \ - -i {input} \ - -o {output} - ''' - -rule convert_to_cells_zarr: - input: - loom=(RAW_DIR / "osmFISH_SScortex_mouse_all_cells.loom"), - pkl=(RAW_DIR / "polyT_seg.pkl") - output: - directory(PROCESSED_DIR / "codeluppi_2018_nature_methods.cells.h5ad.zarr") - params: - script=(SRC_DIR / "convert_to_cells_h5ad_zarr.py") - shell: - ''' - python {params.script} \ - -il {input.loom} \ - -ip {input.pkl} \ - -o {output} - ''' - -rule convert_to_molecules_zarr: - input: - (RAW_DIR / "mRNA_coords_raw_counting.hdf5") - output: - directory(PROCESSED_DIR / "codeluppi_2018_nature_methods.molecules.h5ad.zarr") - params: - script=(SRC_DIR / "convert_to_molecules_h5ad_zarr.py") - shell: - ''' - python {params.script} \ - -i {input} \ - -o {output} - ''' - -# Download raw data. -rule download_image_hdf5: - output: - (RAW_DIR / "Nuclei_polyT.int16.sf.hdf5") - params: - file_url=PKLAB_URL - shell: - ''' - curl -L --retry 999 --retry-delay 3 -C - -o {output} {params.file_url} - ''' - -rule download_cells_loom: - output: - (RAW_DIR / "osmFISH_SScortex_mouse_all_cells.loom") - params: - file_url=CELLS_LOOM_URL - shell: - ''' - curl -L --retry 999 --retry-delay 3 -C - -o {output} {params.file_url} - ''' - -rule download_cells_pkl: - output: - (RAW_DIR / "polyT_seg.pkl") - params: - file_url=CELLS_PKL_URL - shell: - ''' - curl -L --retry 999 --retry-delay 3 -C - -o {output} {params.file_url} - ''' - -rule download_molecules_hdf5: - output: - (RAW_DIR / "mRNA_coords_raw_counting.hdf5") - params: - file_url=MOLECULES_HDF5_URL - shell: - ''' - curl -L --retry 999 --retry-delay 3 -C - -o {output} {params.file_url} - ''' \ No newline at end of file diff --git a/demos/codeluppi-2018/config.yml b/demos/codeluppi-2018/config.yml deleted file mode 100644 index 5d4c07db..00000000 --- a/demos/codeluppi-2018/config.yml +++ /dev/null @@ -1,6 +0,0 @@ -output: -- codeluppi_2018_nature_methods.image.ome.zarr -- codeluppi_2018_nature_methods.cells.csv -- codeluppi_2018_nature_methods.cells.segmentations.json -- codeluppi_2018_nature_methods.cells.matrix.csv -- codeluppi_2018_nature_methods.molecules.csv diff --git a/demos/codeluppi-2018/src/convert_to_cells_csv.py b/demos/codeluppi-2018/src/convert_to_cells_csv.py deleted file mode 100644 index 19387aa8..00000000 --- a/demos/codeluppi-2018/src/convert_to_cells_csv.py +++ /dev/null @@ -1,73 +0,0 @@ -import argparse -from anndata import read_zarr -import json -import pandas as pd - - -def convert_to_csv(args): - adata = read_zarr(args.input) - - cells_df = adata.obs - cells_df['TSNE_1'] = adata.obsm['X_tsne'][:, 0] - cells_df['TSNE_2'] = adata.obsm['X_tsne'][:, 1] - cells_df['PCA_1'] = adata.obsm['X_pca'][:, 0] - cells_df['PCA_2'] = adata.obsm['X_pca'][:, 1] - cells_df['UMAP_1'] = adata.obsm['X_umap'][:, 0] - cells_df['UMAP_2'] = adata.obsm['X_umap'][:, 1] - cells_df['X'] = adata.obsm['X_centroid'][:, 0] - cells_df['Y'] = adata.obsm['X_centroid'][:, 1] - cells_df.index = cells_df.index.rename("cell_id") - - segmentations = {} - for i, cell_id in enumerate(adata.obs.index.values.tolist()): - segmentations[cell_id] = [ - [int(coord) for coord in xy] - for xy in adata.obsm["X_segmentations"][i, :, :] - ] - - matrix_df = pd.DataFrame( - index=adata.obs.index.values.tolist(), - columns=adata.var.index.values.tolist(), - data=adata.X - ) - matrix_df.index = matrix_df.index.rename("cell_id") - - cells_df.to_csv(args.output_cells, index=True) - matrix_df.to_csv(args.output_matrix, index=True) - - with open(args.output_segmentations, "w") as f: - json.dump(segmentations, f) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "-i", - "--input", - type=str, - required=True, - help="Input AnnData-Zarr store", - ) - parser.add_argument( - "-oc", - "--output_cells", - type=str, - required=True, - help="Output cells.csv file" - ) - parser.add_argument( - "-os", - "--output_segmentations", - type=str, - required=True, - help="Output obsSegmentations.json file", - ) - parser.add_argument( - "-om", - "--output_matrix", - type=str, - required=True, - help="Output obsFeatureMatrix.csv file", - ) - args = parser.parse_args() - convert_to_csv(args) diff --git a/demos/codeluppi-2018/src/convert_to_cells_h5ad_zarr.py b/demos/codeluppi-2018/src/convert_to_cells_h5ad_zarr.py deleted file mode 100644 index 09bff9d5..00000000 --- a/demos/codeluppi-2018/src/convert_to_cells_h5ad_zarr.py +++ /dev/null @@ -1,190 +0,0 @@ -import argparse -from anndata import read_loom -import pickle -import numpy as np -import scanpy as sc -import geopandas as gpd -from shapely.geometry import Polygon -from vitessce.data_utils import ( - to_uint8, - sort_var_axis, - optimize_adata, -) - -# Taken from http://linnarssonlab.org/osmFISH/clusters/ -LOOKUP = { - "Astrocyte Gfap": "Astrocyte", - "Astrocyte Mfge8": "Astrocyte", - "C. Plexus": "Ventricle", - "Endothelial 1": "Vasculature", - "Endothelial": "Vasculature", - "Ependymal": "Ventricle", - "Hippocampus": "Excitatory neurons", - "Inhibitory CP": "Inhibitory neurons", - "Inhibitory Cnr1": "Inhibitory neurons", - "Inhibitory Crhbp": "Inhibitory neurons", - "Inhibitory IC": "Inhibitory neurons", - "Inhibitory Kcnip2": "Inhibitory neurons", - "Inhibitory Pthlh": "Inhibitory neurons", - "Inhibitory Vip": "Inhibitory neurons", - "Microglia": "Brain immune", - "Oligodendrocyte COP": "Oligodendrocytes", - "Oligodendrocyte MF": "Oligodendrocytes", - "Oligodendrocyte Mature": "Oligodendrocytes", - "Oligodendrocyte NF": "Oligodendrocytes", - "Oligodendrocyte Precursor cells": "Oligodendrocytes", - "Pericytes": "Vasculature", - "Perivascular Macrophages": "Brain immune", - "Pyramidal Cpne5": "Excitatory neurons", - "Pyramidal Kcnip2": "Excitatory neurons", - "Pyramidal L2-3 L5": "Excitatory neurons", - "Pyramidal L2-3": "Excitatory neurons", - "Pyramidal L3-4": "Excitatory neurons", - "Pyramidal L5": "Excitatory neurons", - "Pyramidal L6": "Excitatory neurons", - "Vascular Smooth Muscle": "Vasculature", - "pyramidal L4": "Excitatory neurons", -} - -# Copied from https://github.com/vitessce/vitessce-data/blob/6726dae/python/cell_reader.py#L17 - - -def octagon(poly): - """ - Returns a bounding octagon. - >>> square = np.array([[0,0], [0,1], [1,1], [1,0]]) - >>> octagon(square) - [[0, 0], [0, 1], [0, 1], [1, 1], [1, 1], [1, 0], [1, 0], [0, 0]] - >>> triangle = np.array([[1,0], [0,2], [2,3]]) - >>> octagon(triangle) - [[0, 1], [0, 2], [1, 3], [2, 3], [2, 3], [2, 1], [1, 0], [1, 0]] - >>> type(octagon(triangle)[0][0]) - - """ - # SciPy has ConvexHull, but it segfaulted on me: perhaps - # https://github.com/scipy/scipy/issues/9751 - # ... and even if I fixed it locally, - # not sure we want that fragility. - # - # Also: The goal is really just to get a simplified shape... - # A convex hull is too precise in some ways, - # while in others it falls short, ie, concavities. - # - # I kind-of like the obvious artificiality of an octagon. - - # Was unsigned, and substraction causes underflow. - poly_as_int = poly - min_x = np.min(poly_as_int[:, [0]]) - max_x = np.max(poly_as_int[:, [0]]) - min_y = np.min(poly_as_int[:, [1]]) - max_y = np.max(poly_as_int[:, [1]]) - - summed = np.sum(poly_as_int, axis=1) - diffed = np.diff(poly_as_int, axis=1) - - min_sum = np.min(summed) - max_sum = np.max(summed) - min_diff = np.min(diffed) - max_diff = np.max(diffed) - - return Polygon( - [ - [min_x, min_sum - min_x], - [min_x, max_diff + min_x], # ^ Left - [max_y - max_diff, max_y], - [max_sum - max_y, max_y], # ^ Botton - [max_x, max_sum - max_x], - [max_x, min_diff + max_x], # ^ Right - [min_y - min_diff, min_y], - [min_sum - min_y, min_y], # ^ Top - ] - ) - - -def convert_to_cells_h5ad_zarr(args): - adata = read_loom( - args.input_loom, - obsm_mapping={ - "X_tsne": ["_tSNE_1", "_tSNE_2"], - "X_spatial": ["X", "Y"], - }, - ) - - adata.obs["is_excluded"] = adata.obs["ClusterName"] == "Excluded" - adata = adata[~adata.obs["is_excluded"], :].copy() - - # Reorder the genes axis after hierarchical clustering. - leaf_list = sort_var_axis(adata.X, adata.var.index.values) - adata = adata[:, leaf_list].copy() - - # Store expression matrix as uint8 - adata.layers["X_uint8"] = to_uint8(adata.X, norm_along="var") - - sc.pp.pca(adata) - sc.pp.neighbors(adata) - sc.tl.umap(adata) - - adata.obs = adata.obs.rename(columns={"ClusterName": "Subcluster"}) - adata.obs["Cluster"] = adata.obs["Subcluster"].apply(lambda val: LOOKUP[val]) - - adata.obsm["X_centroid"] = np.zeros((adata.shape[0], 2)) - adata.obsm["X_segmentations"] = np.zeros((adata.shape[0], 8, 2)) - - with open(args.input_pkl, "rb") as f_in: - segmentation = pickle.load(f_in) - - cell_ids = adata.obs.index.values.tolist() - - geoseries = gpd.GeoSeries( - index=cell_ids, - data=[Polygon(segmentation[cell_id]) for cell_id in cell_ids], - ) - geoseries_simple = geoseries.apply( - lambda p: octagon(np.array(p.exterior.coords)) - ) - centroids = geoseries_simple.centroid - - adata.obsm["X_centroid"][:, 0] = centroids.x - adata.obsm["X_centroid"][:, 1] = centroids.y - - for cell_id in cell_ids: - i = cell_ids.index(cell_id) - adata.obsm["X_segmentations"][i, :, :] = np.array( - geoseries_simple.loc[cell_id].exterior.coords - )[:8, :] - - adata = optimize_adata( - adata, - obs_cols=["Cluster", "Subcluster", "Region"], - var_cols=["Fluorophore", "Hybridization"], - obsm_keys=[ - "X_tsne", - "X_umap", - "X_pca", - "X_spatial", - "X_centroid", - "X_segmentations", - ], - layer_keys=["X_uint8"], - ) - - adata.write_zarr(args.output) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "-il", "--input_loom", type=str, required=True, help="Input Loom file" - ) - parser.add_argument( - "-ip", "--input_pkl", type=str, required=True, help="Input pickle file" - ) - parser.add_argument( - "-o", - "--output", - type=str, - required=True, - help="Output AnnData Zarr store", - ) - args = parser.parse_args() - convert_to_cells_h5ad_zarr(args) diff --git a/demos/codeluppi-2018/src/convert_to_molecules_csv.py b/demos/codeluppi-2018/src/convert_to_molecules_csv.py deleted file mode 100644 index 93e0ea77..00000000 --- a/demos/codeluppi-2018/src/convert_to_molecules_csv.py +++ /dev/null @@ -1,32 +0,0 @@ -import argparse -from anndata import read_zarr - - -def convert_to_csv(args): - adata = read_zarr(args.input) - - molecules_df = adata.obs - molecules_df['X'] = adata.obsm['X_spatial'][:, 0] - molecules_df['Y'] = adata.obsm['X_spatial'][:, 1] - molecules_df.index = molecules_df.index.rename("molecule_id") - molecules_df.to_csv(args.output) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "-i", - "--input", - type=str, - required=True, - help="Input AnnData-Zarr store", - ) - parser.add_argument( - "-o", - "--output", - type=str, - required=True, - help="Output molecules.csv file" - ) - args = parser.parse_args() - convert_to_csv(args) diff --git a/demos/codeluppi-2018/src/convert_to_molecules_h5ad_zarr.py b/demos/codeluppi-2018/src/convert_to_molecules_h5ad_zarr.py deleted file mode 100644 index 761a5950..00000000 --- a/demos/codeluppi-2018/src/convert_to_molecules_h5ad_zarr.py +++ /dev/null @@ -1,54 +0,0 @@ -import argparse -import pandas as pd -import h5py -from anndata import AnnData -from vitessce.data_utils import ( - optimize_adata, -) - - -def convert_to_csv(args): - with h5py.File(args.input, "r") as f: - molecule_types = list(f.keys()) - - molecules_df = pd.DataFrame(index=[], columns=["X", "Y", "Gene"]) - start_at = 0 - for molecule_type in molecule_types: - molecule_arr = f[molecule_type][()] - molecule_type_ids = [ - str(i) for i in range(start_at, start_at + len(molecule_arr)) - ] - start_at += len(molecule_arr) - molecule_type_df = pd.DataFrame( - index=molecule_type_ids, columns=molecules_df.columns.values.tolist() - ) - molecule_type_df["Gene"] = molecule_type - molecule_type_df["X"] = [m[0] for m in molecule_arr] - molecule_type_df["Y"] = [m[1] for m in molecule_arr] - - molecules_df = pd.concat([molecules_df, molecule_type_df]) - - molecules_df.index = molecules_df.index.rename("molecule_id") - - # Molecules zarr - m_obs_df = molecules_df[["Gene"]] - m_var_df = pd.DataFrame(index=[], columns=[], data=[]) - - m_adata = AnnData(X=None, obs=m_obs_df, var=m_var_df) - m_adata.obsm["X_spatial"] = molecules_df[["X", "Y"]].values - m_adata = optimize_adata(m_adata) - - # Write outputs - m_adata.write_zarr(args.output) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - "-i", "--input", type=str, required=True, help="Input hdf5 file" - ) - parser.add_argument( - "-o", "--output", type=str, required=True, help="Output AnnData Zarr store" - ) - args = parser.parse_args() - convert_to_csv(args) diff --git a/demos/codeluppi-2018/src/convert_to_ome_zarr.py b/demos/codeluppi-2018/src/convert_to_ome_zarr.py deleted file mode 100644 index 4ef9fa0d..00000000 --- a/demos/codeluppi-2018/src/convert_to_ome_zarr.py +++ /dev/null @@ -1,41 +0,0 @@ -import argparse -import h5py -import numpy as np -from vitessce.data_utils import ( - multiplex_img_to_ome_zarr, -) - - -def convert_to_ome_zarr(args): - with h5py.File(args.input, "r") as f: - channel_names = list(f.keys()) - first_channel = channel_names[0] - img_shape = (len(channel_names), *f[first_channel].shape) - img_dtype = f[first_channel].dtype - img_arr = np.zeros(img_shape, dtype=img_dtype) - for channel_i, channel_name in enumerate(channel_names): - img_arr[channel_i, :, :] = f[channel_name] - - img_arr = img_arr.astype(np.dtype("= 1 - for level in range(min_ancestor_list_len - 1): - unique_level_cell_types = set() - for ancestors, cell_set in ancestors_and_sets: - unique_level_cell_types.add(ancestors[0]) - - if len(unique_level_cell_types) == 1: - for ancestors, cell_set in ancestors_and_sets: - ancestors.pop(0) - else: - break - - # Create the hierarchy as a dict. - h = dict() - for ancestors, cell_set in ancestors_and_sets: - fill_in_dict_from_path(h, ancestors, cell_set) - - # Try removing all of the single-child "any" levels - # now that the hierarchy has been created as a dict. - h = remove_any_from_dict_levels(h) - - # Transform the dict into an object matching the JSON schema. - tree["tree"] = [ - dict_to_tree("Cell Type Annotations", h) - ] - return tree diff --git a/demos/satija-2020/src/split_annotation_csv.py b/demos/satija-2020/src/split_annotation_csv.py deleted file mode 100644 index 671ea552..00000000 --- a/demos/satija-2020/src/split_annotation_csv.py +++ /dev/null @@ -1,46 +0,0 @@ -import argparse -import pandas as pd - -from constants import COLUMNS - - -def split_annotation_csv(input_file, output_file, globus_id): - df = pd.read_csv(input_file) - df = df.loc[df[COLUMNS.GLOBUS_ID.value] == globus_id] - df = df[[ - COLUMNS.CELL_ID.value, - COLUMNS.ANNOTATION.value, - COLUMNS.PREDICTION_SCORE.value - ]] - df.to_csv(output_file, index=False) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument( - '-i', - '--input_file', - type=str, - required=True, - help='Input CSV file' - ) - parser.add_argument( - '-o', - '--output_file', - type=str, - required=True, - help='Output CSV file' - ) - parser.add_argument( - '-gid', - '--globus_id', - type=str, - required=True, - help='Globus ID to use for filtering' - ) - args = parser.parse_args() - split_annotation_csv( - args.input_file, - args.output_file, - args.globus_id - ) diff --git a/demos/satija-2020/src/utils.py b/demos/satija-2020/src/utils.py deleted file mode 100644 index 1f3492df..00000000 --- a/demos/satija-2020/src/utils.py +++ /dev/null @@ -1,224 +0,0 @@ -import networkx -import obonet - -from constants import CL_ROOT_ID - - -def load_cl_obo_graph(cl_obo_file): - graph = obonet.read_obo(cl_obo_file) - - # Make sure there are no cycles. - assert networkx.is_directed_acyclic_graph(graph) - - id_to_name = { - id_: data.get('name') - for id_, data in graph.nodes(data=True) - } - name_to_id = { - data['name']: id_ - for id_, data in graph.nodes(data=True) if 'name' in data - } - - return graph, id_to_name, name_to_id - - -# Construct the tree, according to the following schema: -# https://github.com/hubmapconsortium/vitessce/blob/d5f63aa1d08aa61f6b20f6ad6bbfba5fceb6b5ef/src/schemas/cell_sets.schema.json -def init_cell_sets_tree(): - return { - "datatype": "obs", - "version": "0.1.3", - "tree": [] - } - - -# Merge multiple cell sets trees. -def merge_cell_sets_trees(*args): - ''' - >>> tree_a = init_cell_sets_tree() - >>> tree_b = init_cell_sets_tree() - >>> tree_a["tree"].append({ - ... "name": "a", - ... "set": [1, 2, 3] - ... }) - >>> tree_b["tree"].append({ - ... "name": "b", - ... "set": [4, 5, 6] - ... }) - >>> tree_merged = merge_cell_sets_trees(tree_a, tree_b) - >>> len(tree_merged["tree"]) - 2 - >>> [x["name"] for x in tree_merged["tree"]] - ['a', 'b'] - ''' - assert len(args) > 1 - - result = args[0] - for arg in args[1:]: - for level_zero_node in arg["tree"]: - result["tree"].append(level_zero_node) - return result - - -# Recursively convert a nested dict to a level zero node -# of the cell-set hierarchy schema. -def dict_to_tree(name, value): - ''' - >>> h_dict = { - ... "hematopoietic cell": { - ... "leukocyte": [4, 5, 6], - ... "hematopoietic precursor cell": [7, 8, 9] - ... }, - ... "epithelial cell": [1, 2, 3] - ... } - >>> h_tree = dict_to_tree("test", h_dict) - >>> h_tree["name"] - 'test' - >>> [x["name"] for x in h_tree["children"]] - ['hematopoietic cell', 'epithelial cell'] - ''' - if isinstance(value, dict): - return { - "name": name, - "children": [ - dict_to_tree(child_name, child_value) - for child_name, child_value in value.items() - ] - } - else: - return { - "name": name, - "set": value, - } - - -# Given a list of multiple paths up the DAG, -# sort the list according to a heuristic. -def sort_paths_up_cell_ontology(paths_up): - ''' - >>> ex_paths_up = [ - ... ['b', 'motile cell', 'native cell', 'cell'], - ... ['a', 'b', 'c', 'somatic cell', 'native cell', 'cell'], - ... ['a', 'somatic cell', 'native cell', 'cell'] - ... ] - >>> sorted_paths_up = sort_paths_up_cell_ontology(ex_paths_up) - >>> sorted_paths_up[0] - ['a', 'somatic cell', 'native cell', 'cell'] - >>> sorted_paths_up[1] - ['a', 'b', 'c', 'somatic cell', 'native cell', 'cell'] - ''' - PREFERENCES = [ - ['animal cell', 'eukaryotic cell', 'native cell', 'cell'], - ['somatic cell', 'native cell', 'cell'], - ['nucleate cell', 'native cell', 'cell'], - ['precursor cell', 'native cell', 'cell'], - ] - # Prefer all of the above before "functional" categories like - # [..., 'motile cell', 'native cell', 'cell'] - WORST_PREFERENCE_INDEX = len(PREFERENCES) - - def get_first_preference_index_and_path_length(path_up): - path_preference_match_index = WORST_PREFERENCE_INDEX - for preference_index, preference in enumerate(PREFERENCES): - if path_up[-len(preference):] == preference: - path_preference_match_index = preference_index - break - # Return a tuple of the first matching preference "path ending" - # and the path length (to use shorter paths if multiple paths - # match the same top path ending). - return (path_preference_match_index, len(path_up)) - return sorted(paths_up, key=get_first_preference_index_and_path_length) - - -# Using the cell ontology DAG, -# get all possible paths up to the root from -# a given node_id value. -def get_paths_up_cell_ontology(graph, node_id): - if node_id == CL_ROOT_ID: - return [ - [node_id] - ] - - # Get ancestors of the cell type - # (counterintuitive that the function is called descendants). - ancestor_term_set = networkx.descendants(graph, node_id) - - # Make sure the cell type has an ancestor - # with the 'cell' root ID. - assert CL_ROOT_ID in ancestor_term_set - - # Get the parents of the current node. - node_parents = graph.out_edges(node_id, keys=True) - - up_dag_paths = [] - for node_parent in node_parents: - _, curr_parent_id, relationship = node_parent - if relationship == "is_a": - parent_paths = get_paths_up_cell_ontology(graph, curr_parent_id) - for parent_path in parent_paths: - up_dag_paths.append([node_id] + parent_path) - return up_dag_paths - - -# Using a path through the DAG for a particular cell set, -# recursively fill in a nested dict. -def fill_in_dict_from_path(d, keys, child): - ''' - >>> h = dict() - >>> path_set_tuple = ( - ... ["type a", "type b", "type c"], - ... ["cell 1", "cell 2", "cell 3"] - ... ) - >>> fill_in_dict_from_path(h, path_set_tuple[0], path_set_tuple[1]) - {'any': ['cell 1', 'cell 2', 'cell 3']} - >>> h - {'type a': {'type b': {'type c': {'any': ['cell 1', 'cell 2', 'cell 3']}}}} - ''' - """ - d : dict The resulting dictionary so far. - keys : A list of keys representing the path down the cell ontology DAG. - child : A set value. - """ - key = keys[0] - - if key in d and isinstance(d[key], dict): - result = d[key] - else: - result = d[key] = dict() - - if len(keys) == 1: - result["any"] = child - return result - else: - new_keys = keys.copy() - new_keys.pop(0) - return fill_in_dict_from_path(result, new_keys, child) - - -# Try removing the extra hierarchy level for the "any" set, -# if it is an "only-child" -def remove_any_from_dict_levels(v): - ''' - >>> h = {'type b': {'type c': {'any': ['cell 1', 'cell 2', 'cell 3']}}} - >>> new_h = remove_any_from_dict_levels(h) - >>> new_h - {'type b': {'type c': ['cell 1', 'cell 2', 'cell 3']}} - ''' - if isinstance(v, dict): - keys = list(v.keys()) - if len(keys) == 1 and keys[0] == "any": - # Return the value associated with the "any" property, - # since "any" has no siblings. - return v["any"] - else: - # This is a dict with multiple values, so recursively - # try this function on all of its values. - return dict( - zip( - keys, - list(map(remove_any_from_dict_levels, v.values())) - ) - ) - else: - # This is not a dict, so just return as-is. - return v diff --git a/demos/satija-2020/vitessce.template.json b/demos/satija-2020/vitessce.template.json deleted file mode 100644 index 7cfff396..00000000 --- a/demos/satija-2020/vitessce.template.json +++ /dev/null @@ -1,135 +0,0 @@ -{ - "version": "1.0.15", - "name": "HBM336.FWTN.636", - "description": "Spleen scRNA-seq HuBMAP dataset with cell type annotations generated by the Satija lab and the Seurat v3.1 Label Transfer workflow", - "public": true, - "datasets": [ - { - "uid": "2dca1bf5832a4102ba780e9e54f6c350", - "name": "HBM336.FWTN.636", - "files": [ - { - "fileType": "anndata.zarr", - "url": "{{ base_url }}/satija_2020.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression", - "embeddingType": "UMAP" - }, - "options": { - "obsEmbedding": { - "path": "obsm/X_umap" - }, - "obsFeatureMatrix": { - "path": "layers/X_uint8" - }, - "obsLabels": [ - { - "path": "obs/prediction_score", - "obsLabelsType": "Cell Type Annotation Prediction Score" - } - ] - } - }, - { - "fileType": "obsSets.json", - "url": "{{ base_url }}/satija_2020.cell-sets.json", - "coordinationValues": { - "obsType": "cell" - } - } - ] - } - ], - "initStrategy": "auto", - "coordinationSpace": { - "embeddingType": { - "UMAP": "UMAP" - }, - "obsLabelsType": { - "A": "Cell Type Annotation Prediction Score" - }, - "embeddingZoom": { - "A": 3 - }, - "embeddingTargetX": { - "A": 0 - }, - "embeddingTargetY": { - "A": 0 - }, - "spatialZoom": { - "A": 3 - }, - "spatialTargetX": { - "A": 0 - }, - "spatialTargetY": { - "A": 0 - }, - "featureValueColormapRange": { - "A": [ - 0, - 0.25 - ] - } - }, - "layout": [ - { - "component": "obsSets", - "h": 4, - "w": 4, - "x": 4, - "y": 0, - "coordinationScopes": {} - }, - { - "component": "obsSetSizes", - "h": 4, - "w": 4, - "x": 8, - "y": 0, - "coordinationScopes": {} - }, - { - "component": "scatterplot", - "h": 4, - "w": 4, - "x": 0, - "y": 0, - "coordinationScopes": { - "embeddingType": "UMAP", - "embeddingZoom": "A", - "embeddingTargetX": "A", - "embeddingTargetY": "A", - "obsLabelsType": [ - "A" - ] - } - }, - { - "component": "heatmap", - "h": 4, - "w": 10, - "x": 0, - "y": 4, - "coordinationScopes": { - "featureValueColormapRange": "A", - "obsLabelsType": [ - "A" - ] - }, - "props": { - "transpose": false - } - }, - { - "component": "description", - "h": 4, - "w": 2, - "x": 10, - "y": 4 - } - ] -} \ No newline at end of file diff --git a/demos/sn-atac-seq-hubmap-2020/Snakefile b/demos/sn-atac-seq-hubmap-2020/Snakefile deleted file mode 100644 index bfa4094a..00000000 --- a/demos/sn-atac-seq-hubmap-2020/Snakefile +++ /dev/null @@ -1,35 +0,0 @@ -include: "../common.smk" -configfile: "config.yml" - -BASE_URL = "https://vitessce-data.s3.amazonaws.com/0.0.32/master_release/human_intestine_2020_hubmap/human_intestine_2020_hubmap" - - -rule all: - input: - [ (PROCESSED_DIR / f) for f in config['output'] ] - -# Convert the old JSON files to simpler CSV formats. -rule convert_to_csv: - input: - cells=(RAW_DIR / "cells.json"), - cell_sets=(RAW_DIR / "cell-sets.json") - output: - cells=(PROCESSED_DIR / "human_intestine_2020_hubmap.cells.csv") - params: - script=(SRC_DIR / "convert_to_csv.py") - shell: - ''' - python {params.script} \ - -ic {input.cells} \ - -ics {input.cell_sets} \ - -oc {output.cells} - ''' - -# Download original JSON files. -rule download_file: - output: - (RAW_DIR / "{prefix}.json") - shell: - ''' - curl -L -o {output} {BASE_URL}.{wildcards.prefix}.json - ''' \ No newline at end of file diff --git a/demos/sn-atac-seq-hubmap-2020/config.yml b/demos/sn-atac-seq-hubmap-2020/config.yml deleted file mode 100644 index 4793de16..00000000 --- a/demos/sn-atac-seq-hubmap-2020/config.yml +++ /dev/null @@ -1,2 +0,0 @@ -output: -- human_intestine_2020_hubmap.cells.csv diff --git a/demos/sn-atac-seq-hubmap-2020/src/convert_to_csv.py b/demos/sn-atac-seq-hubmap-2020/src/convert_to_csv.py deleted file mode 100644 index f696c90f..00000000 --- a/demos/sn-atac-seq-hubmap-2020/src/convert_to_csv.py +++ /dev/null @@ -1,54 +0,0 @@ -import argparse -import json -import pandas as pd - - -def convert_to_csv(args): - with open(args.input_cells) as f: - cells_json = json.load(f) - with open(args.input_cell_sets) as f: - cell_sets_json = json.load(f) - - cell_ids = cells_json.keys() - cells_df = pd.DataFrame(index=cell_ids, columns=["UMAP_1", "UMAP_2", "cluster"]) - cells_df['UMAP_1'] = cells_df.apply(lambda row: cells_json[str(row.name)]['mappings']['UMAP'][0], axis='columns') - cells_df['UMAP_2'] = cells_df.apply(lambda row: cells_json[str(row.name)]['mappings']['UMAP'][1], axis='columns') - cells_df.index = cells_df.index.rename('cell_id') - - for cluster in cell_sets_json['tree'][0]['children']: - cluster_name = cluster['name'] - cluster_cell_ids = cluster['set'] - - for cell_id in cluster_cell_ids: - cells_df.at[cell_id, 'cluster'] = cluster_name - - cells_df['cluster'] = cells_df['cluster'].astype(str) - - cells_df.to_csv(args.output_cells, index=True) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument( - '-ic', - '--input_cells', - type=str, - required=True, - help='Input cells.json file' - ) - parser.add_argument( - '-ics', - '--input_cell_sets', - type=str, - required=True, - help='Input molecules.json file' - ) - parser.add_argument( - '-oc', - '--output_cells', - type=str, - required=True, - help='Output cells.csv file' - ) - args = parser.parse_args() - convert_to_csv(args) diff --git a/demos/sn-atac-seq-hubmap-2020/vitessce.template.json b/demos/sn-atac-seq-hubmap-2020/vitessce.template.json deleted file mode 100644 index e5aa4478..00000000 --- a/demos/sn-atac-seq-hubmap-2020/vitessce.template.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "version": "1.0.15", - "name": "HBM485.TBWH.322", - "description": "Large intestine snATAC-seq HuBMAP dataset with genomic data visualization powered by HiGlass", - "datasets": [ - { - "uid": "A", - "name": "HBM485.TBWH.322", - "files": [ - { - "fileType": "obsEmbedding.csv", - "url": "{{ base_url }}/human_intestine_2020_hubmap.cells.csv", - "coordinationValues": { - "obsType": "cell", - "embeddingType": "UMAP" - }, - "options": { - "obsIndex": "cell_id", - "obsEmbedding": ["UMAP_1", "UMAP_2"] - } - }, - { - "fileType": "obsSets.csv", - "url": "{{ base_url }}/human_intestine_2020_hubmap.cells.csv", - "coordinationValues": { - "obsType": "cell" - }, - "options": { - "obsIndex": "cell_id", - "obsSets": [ - { - "name": "Clusters", - "column": "cluster" - } - ] - } - }, - { - "fileType": "genomic-profiles.zarr", - "url": "https://vitessce-data.s3.amazonaws.com/0.0.32/master_release/human_intestine_2020_hubmap/human_intestine_2020_hubmap.genomic-profiles.zarr" - } - ] - } - ], - "coordinationSpace": { - "dataset": { - "A": "A" - }, - "embeddingType": { - "A": "UMAP" - } - }, - "layout": [ - { - "component": "scatterplot", - "coordinationScopes": { - "dataset": "A", - "embeddingType": "A" - }, - "x": 0, - "y": 6, - "w": 6, - "h": 6 - }, - { - "component": "obsSets", - "coordinationScopes": { - "dataset": "A" - }, - "x": 6, - "y": 6, - "w": 6, - "h": 6 - }, - { - "component": "genomicProfiles", - "coordinationScopes": { - "dataset": "A" - }, - "x": 0, - "y": 0, - "w": 12, - "h": 6 - } - ], - "initStrategy": "auto" -} \ No newline at end of file diff --git a/demos/wang-2018/Snakefile b/demos/wang-2018/Snakefile deleted file mode 100644 index 71dda5b9..00000000 --- a/demos/wang-2018/Snakefile +++ /dev/null @@ -1,44 +0,0 @@ -include: "../common.smk" -configfile: "config.yml" - -# TODO: start from the real raw files -BASE_URL = "https://s3.amazonaws.com/vitessce-data/0.0.31/master_release/wang/wang" - - -rule all: - input: - [ (PROCESSED_DIR / f) for f in config['output'] ] - -# Convert the old JSON files to simpler CSV and JSON formats. -rule convert_to_csv: - input: - cells=(RAW_DIR / "cells.json"), - molecules=(RAW_DIR / "molecules.json"), - expression_matrix=(RAW_DIR / "genes.json") - output: - cells=(PROCESSED_DIR / "wang_2018_scientific_reports.cells.csv"), - segmentations=(PROCESSED_DIR / "wang_2018_scientific_reports.cells.segmentations.json"), - matrix=(PROCESSED_DIR / "wang_2018_scientific_reports.cells.matrix.csv"), - molecules=(PROCESSED_DIR / "wang_2018_scientific_reports.molecules.csv") - params: - script=(SRC_DIR / "convert_to_csv.py") - shell: - ''' - python {params.script} \ - -ic {input.cells} \ - -im {input.molecules} \ - -iem {input.expression_matrix} \ - -oc {output.cells} \ - -ocs {output.segmentations} \ - -ocm {output.matrix} \ - -om {output.molecules} - ''' - -# Download original JSON files. -rule download_file: - output: - (RAW_DIR / "{prefix}.json") - shell: - ''' - curl -L -o {output} {BASE_URL}.{wildcards.prefix}.json - ''' \ No newline at end of file diff --git a/demos/wang-2018/config.yml b/demos/wang-2018/config.yml deleted file mode 100644 index 998e228a..00000000 --- a/demos/wang-2018/config.yml +++ /dev/null @@ -1,5 +0,0 @@ -output: -- wang_2018_scientific_reports.cells.csv -- wang_2018_scientific_reports.cells.segmentations.json -- wang_2018_scientific_reports.cells.matrix.csv -- wang_2018_scientific_reports.molecules.csv diff --git a/demos/wang-2018/src/convert_to_csv.py b/demos/wang-2018/src/convert_to_csv.py deleted file mode 100644 index 76479124..00000000 --- a/demos/wang-2018/src/convert_to_csv.py +++ /dev/null @@ -1,107 +0,0 @@ -import argparse -import json -import pandas as pd - - -def convert_to_csv(args): - with open(args.input_cells) as f: - cells_json = json.load(f) - with open(args.input_molecules) as f: - molecules_json = json.load(f) - with open(args.input_expression_matrix) as f: - expression_matrix = json.load(f) - - molecules_df = pd.DataFrame(index=[], columns=["X", "Y", "Gene"]) - start_at = 0 - for molecule_type, molecule_arr in molecules_json.items(): - molecule_type_ids = [str(i) for i in range(start_at, start_at + len(molecule_arr))] - start_at += len(molecule_arr) - molecule_type_df = pd.DataFrame(index=molecule_type_ids, columns=molecules_df.columns.values.tolist()) - molecule_type_df['Gene'] = molecule_type - molecule_type_df['X'] = [m[0] for m in molecule_arr] - molecule_type_df['Y'] = [m[1] for m in molecule_arr] - - molecules_df = pd.concat([molecules_df, molecule_type_df]) - molecules_df.index = molecules_df.index.rename('molecule_id') - - cell_ids = cells_json.keys() - cells_df = pd.DataFrame(index=cell_ids, columns=["X", "Y"]) - cells_df['X'] = cells_df.apply(lambda row: cells_json[str(row.name)]['xy'][0], axis='columns') - cells_df['Y'] = cells_df.apply(lambda row: cells_json[str(row.name)]['xy'][1], axis='columns') - cells_df.index = cells_df.index.rename('cell_id') - - segmentations = dict() - for cell_id, cell_obj in cells_json.items(): - segmentations[cell_id] = cell_obj['poly'] - - matrix_df = pd.DataFrame(index=cell_ids, columns=list(expression_matrix.keys())) - matrix_df.index = matrix_df.index.astype(str) - for gene_id in matrix_df.columns.values.tolist(): - for cell_id in matrix_df.index.values.tolist(): - try: - matrix_df.at[cell_id, gene_id] = expression_matrix[gene_id]['cells'][cell_id] / expression_matrix[gene_id]['max'] - except KeyError: - matrix_df.at[cell_id, gene_id] = 0 - matrix_df.index = matrix_df.index.rename('cell_id') - - cells_df.to_csv(args.output_cells, index=True) - matrix_df.to_csv(args.output_cells_matrix, index=True) - molecules_df.to_csv(args.output_molecules, index=True) - - with open(args.output_cells_segmentations, 'w') as f: - json.dump(segmentations, f) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument( - '-ic', - '--input_cells', - type=str, - required=True, - help='Input cells.json file' - ) - parser.add_argument( - '-im', - '--input_molecules', - type=str, - required=True, - help='Input molecules.json file' - ) - parser.add_argument( - '-iem', - '--input_expression_matrix', - type=str, - required=True, - help='Input clusters.json file' - ) - parser.add_argument( - '-oc', - '--output_cells', - type=str, - required=True, - help='Output cells.csv file' - ) - parser.add_argument( - '-ocs', - '--output_cells_segmentations', - type=str, - required=True, - help='Output obsSegmentations.json file' - ) - parser.add_argument( - '-ocm', - '--output_cells_matrix', - type=str, - required=True, - help='Output obsFeatureMatrix.csv file' - ) - parser.add_argument( - '-om', - '--output_molecules', - type=str, - required=True, - help='Output molecules.csv file' - ) - args = parser.parse_args() - convert_to_csv(args) diff --git a/demos/wang-2018/vitessce.template.json b/demos/wang-2018/vitessce.template.json deleted file mode 100644 index 728c9a70..00000000 --- a/demos/wang-2018/vitessce.template.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "name": "Wang et al., Scientific Reports 2018", - "version": "1.0.15", - "description": "Multiplexed imaging of high-density libraries of RNAs with MERFISH and expansion microscopy", - "public": true, - "datasets": [ - { - "uid": "wang-2018", - "name": "Wang 2018", - "files": [ - { - "fileType": "obsSegmentations.json", - "url": "{{ base_url }}/wang_2018_scientific_reports.cells.segmentations.json", - "coordinationValues": { - "obsType": "cell" - } - }, - { - "fileType": "obsLocations.csv", - "url": "{{ base_url }}/wang_2018_scientific_reports.cells.csv", - "options": { - "obsIndex": "cell_id", - "obsLocations": ["X", "Y"] - }, - "coordinationValues": { - "obsType": "cell" - } - }, - { - "fileType": "obsLocations.csv", - "url": "{{ base_url }}/wang_2018_scientific_reports.molecules.csv", - "options": { - "obsIndex": "molecule_id", - "obsLocations": ["X", "Y"] - }, - "coordinationValues": { - "obsType": "molecule" - } - }, - { - "fileType": "obsLabels.csv", - "url": "{{ base_url }}/wang_2018_scientific_reports.molecules.csv", - "options": { - "obsIndex": "molecule_id", - "obsLabels": "Gene" - }, - "coordinationValues": { - "obsType": "molecule" - } - }, - { - "fileType": "obsFeatureMatrix.csv", - "url": "{{ base_url }}/wang_2018_scientific_reports.cells.matrix.csv", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression" - } - } - ] - } - ], - "initStrategy": "auto", - "coordinationSpace": { - "spatialZoom": { - "A": -1 - }, - "spatialSegmentationLayer": { - "A": { - "opacity": 1, "radius": 0, "visible": true, "stroked": false - } - }, - "spatialPointLayer": { - "A": { - "opacity": 1, "radius": 2, "visible": true - } - } - }, - "layout": [ - { - "component": "spatial", - "coordinationScopes": { - "spatialZoom": "A", - "spatialSegmentationLayer": "A", - "spatialPointLayer": "A" - }, - "x": 0, - "y": 0, - "w": 10, - "h": 2 - }, - { - "component": "featureList", - "x": 10, - "y": 0, - "w": 2, - "h": 2 - } - ] -} \ No newline at end of file From 017215c8b7fdbc53ce319d1714a8538a56be3a46 Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:27:06 -0500 Subject: [PATCH 2/9] Modernize demo workflows --- .github/workflows/test_demos.yml | 5 +- AGENTS.md | 2 +- demos/.envrc | 1 - demos/README.md | 41 ++-- demos/Snakefile | 151 ++++++++------- demos/combat-2022/Snakefile | 11 +- demos/combat-2022/src/convert_to_zarr.py | 13 ++ demos/common.smk | 23 ++- demos/create_demo.sh | 77 +++++--- demos/environment.yml | 31 ---- demos/fill_template.py | 6 + demos/habib-2017/Snakefile | 11 +- demos/habib-2017/src/convert_to_zarr.py | 11 ++ demos/human-lymph-node-10x-visium/Snakefile | 11 +- .../src/create_zarr.py | 18 ++ demos/kuppe-2022/Snakefile | 17 +- demos/kuppe-2022/src/convert_to_zarr.py | 14 ++ demos/marshall-2022/Snakefile | 11 +- demos/marshall-2022/src/convert_to_zarr.py | 13 ++ demos/meta-2022-azimuth/Snakefile | 11 +- .../meta-2022-azimuth/src/convert_to_zarr.py | 12 ++ pyproject.toml | 11 +- uv.lock | 175 ++++++++++++++---- 23 files changed, 473 insertions(+), 203 deletions(-) delete mode 100644 demos/.envrc delete mode 100644 demos/environment.yml diff --git a/.github/workflows/test_demos.yml b/.github/workflows/test_demos.yml index 5aa2f676..acd080ee 100644 --- a/.github/workflows/test_demos.yml +++ b/.github/workflows/test_demos.yml @@ -4,15 +4,14 @@ on: [push, pull_request] jobs: test_demos: - # Pinned: the datrie sdist (via snakemake 7) does not compile with the GCC on ubuntu-26.04. - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: astral-sh/setup-uv@v3 with: version: "latest" - name: Install vitessce - run: uv sync --extra dev --extra all --extra demos + run: uv sync --extra demos - name: Run tests working-directory: ./demos run: uv run snakemake -j 1 --dry-run diff --git a/AGENTS.md b/AGENTS.md index 862452c7..120ef2c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,7 +29,7 @@ uv run marimo export html docs/notebooks/marimo.py -o docs/notebooks/marimo.html cd tests-widget && pnpm install && pnpm exec playwright test ``` -Demo pipelines: `cd demos && uv run snakemake -j 1 --dry-run` (needs `--extra demos`). +Demo pipelines: `cd demos && uv run snakemake -j 1 --dry-run` (needs `--extra demos`). Each demo is a Snakemake module of `demos/Snakefile`; its `src/` scripts declare dependencies with PEP 723 inline metadata and run via `uv run --script`. ## Architecture diff --git a/demos/.envrc b/demos/.envrc deleted file mode 100644 index 1f3424c5..00000000 --- a/demos/.envrc +++ /dev/null @@ -1 +0,0 @@ -use conda vitessce-python-demos \ No newline at end of file diff --git a/demos/README.md b/demos/README.md index b473afc6..87108aac 100644 --- a/demos/README.md +++ b/demos/README.md @@ -6,19 +6,37 @@ However, now that there are consensus single-cell file formats (e.g., h5ad) and ### Setup -Set up the `vitessce-python-demos` environment using conda. +The demos use [uv](https://docs.astral.sh/uv/) for environment management, and must have `uv` on the `PATH`. + +The outer Snakemake environment is defined by the `demos` extra in the root `pyproject.toml`: + +```sh +uv sync --extra demos +``` + +Each processing script in `./{demo_dir}/src/` declares its own dependencies using [PEP 723 inline script metadata](https://peps.python.org/pep-0723/) and is run by the Snakemake rules with `uv run --script`, so uv creates an isolated (cached) environment per script. The scripts depend on the local (repository) version of `vitessce` via `[tool.uv.sources]`. + +To run a script manually: ```sh -cd demos -conda env create -f environment.yml -conda activate vitessce-python-demos -pip install -e "..[dev]" +uv run --script ./habib-2017/src/convert_to_zarr.py -i input.h5ad -o output.h5ad.zarr ``` ### Run +From within the `demos` directory: + +```sh +uv run snakemake --cores all --rerun-triggers mtime +``` + +Use `--dry-run` to list the jobs without running them. + +Each demo is a Snakemake [module](https://snakemake.readthedocs.io/en/stable/snakefiles/modularization.html#modules) of the main `./Snakefile`, with rule names prefixed by the demo key (e.g., `habib_2017_convert_to_zarr`). Each demo can also be run on its own: + ```sh -snakemake --cores all --rerun-triggers mtime +cd habib-2017 +uv run snakemake --cores all ``` ### Serve data locally @@ -36,9 +54,10 @@ To add a new demo, run ``` Then, -- Add a subworkflow entry to the main demos workflow in `./Snakefile` +- Add the demo directory name to `DEMO_DIRS` and add a `module` and `use rule` entry to the main demos workflow in `./Snakefile` (the script prints these) - Specify the output filenames in the `output` list in `./{new_demo_dir}/config.yml` - Fill in the Snakefile in `./{new_demo_dir}/Snakefile` +- Write the processing script(s) in `./{new_demo_dir}/src/`, declaring their dependencies in the PEP 723 `# /// script` block, and call them from rules via `uv run --script {params.script}` - Write a test Vitessce configuration in `./{new_demo_dir}/vitessce.template.json` - Test the demo by running the Vitessce frontend locally and navigating to `http://localhost:3000/?url=http://localhost:8000/{new_demo_dir}/vitessce.json` @@ -56,7 +75,7 @@ To use the same configuration for both development (with localhost file URLs) an We can render the template to `vitessce.local.json` and `vitessce.remote.json` using the following commands: ```sh -snakemake fill_templates -j 1 +uv run snakemake fill_templates -j 1 ``` Be sure to re-run after making changes to `vitessce.template.json`. @@ -66,13 +85,13 @@ Be sure to re-run after making changes to `vitessce.template.json`. Local: ```sh -python fill_template.py -d habib-2017 -t local > ./habib-2017/vitessce.local.json +uv run --script fill_template.py -d habib-2017 -t local > ./habib-2017/vitessce.local.json ``` Remote: ```sh -python fill_template.py -d habib-2017 -t remote -v 0.0.33 > ./habib-2017/vitessce.remote.json +uv run --script fill_template.py -d habib-2017 -t remote -v 0.0.33 > ./habib-2017/vitessce.remote.json ``` ### Configure AWS and Google Cloud CLIs @@ -88,5 +107,5 @@ Configure the Google Cloud CLI by running `gcloud auth login` ([reference](https ### Run and deploy ```sh -snakemake --cores all --rerun-triggers mtime --config upload=true +uv run snakemake --cores all --rerun-triggers mtime --config upload=true ``` \ No newline at end of file diff --git a/demos/Snakefile b/demos/Snakefile index bb5d5489..704755ae 100644 --- a/demos/Snakefile +++ b/demos/Snakefile @@ -1,86 +1,93 @@ from pathlib import Path, PosixPath -import yaml import os -from pprint import pprint -# Remote providers should be used, but cloud files are -# not working as outputs: https://github.com/snakemake/snakemake/issues/870 -# from snakemake.remote.S3 import RemoteProvider as S3RemoteProvider -# from snakemake.remote.GS import RemoteProvider as GSRemoteProvider -# S3 = S3RemoteProvider() -# GS = GSRemoteProvider() +include: "./common.smk" BUCKET_VERSION = "0.0.34" BUCKET_NAME = "vitessce-data" BUCKET = PosixPath(BUCKET_NAME) / BUCKET_VERSION / "main" -include: "./common.smk" +# Each demo lives in its own subdirectory with its own Snakefile. +# Demos are imported as modules (Snakemake >= 8 removed the `subworkflow` directive). +# The `prefix` makes all of a module's input/output paths relative to its +# subdirectory, so each demo can also be run standalone from within its directory. +# To add a demo, append its directory name here and add +# a corresponding `module` + `use rule` block below. +DEMO_DIRS = [ + "combat-2022", + "habib-2017", + "human-lymph-node-10x-visium", + "kuppe-2022", + "marshall-2022", + "meta-2022-azimuth", +] + +module combat_2022: + snakefile: "combat-2022/Snakefile" + prefix: "combat-2022" + +use rule * from combat_2022 as combat_2022_* + +module habib_2017: + snakefile: "habib-2017/Snakefile" + prefix: "habib-2017" + +use rule * from habib_2017 as habib_2017_* + +module human_lymph_node_10x_visium: + snakefile: "human-lymph-node-10x-visium/Snakefile" + prefix: "human-lymph-node-10x-visium" -# All subworkflows listed here will be -# executed as part of the 'all' rule -# in this snakefile. -subworkflow combat_2022: - workdir: - "combat-2022" +use rule * from human_lymph_node_10x_visium as human_lymph_node_10x_visium_* -subworkflow habib_2017: - workdir: - "habib-2017" +module kuppe_2022: + snakefile: "kuppe-2022/Snakefile" + prefix: "kuppe-2022" -subworkflow human_lymph_node_10x_visium: - workdir: - "human-lymph-node-10x-visium" +use rule * from kuppe_2022 as kuppe_2022_* -subworkflow kuppe_2022: - workdir: - "kuppe-2022" +module marshall_2022: + snakefile: "marshall-2022/Snakefile" + prefix: "marshall-2022" -subworkflow marshall_2022: - workdir: - "marshall-2022" +use rule * from marshall_2022 as marshall_2022_* -subworkflow meta_2022_azimuth: - workdir: - "meta-2022-azimuth" +module meta_2022_azimuth: + snakefile: "meta-2022-azimuth/Snakefile" + prefix: "meta-2022-azimuth" -# End subworkflow list. +use rule * from meta_2022_azimuth as meta_2022_azimuth_* -# Only access workflow._subworkflows after all -# subworkflows have been defined above. -SUBWORKFLOW_KEYS = workflow._subworkflows.keys() -SUBWORKFLOW_DIRS = dict(zip(SUBWORKFLOW_KEYS, [ v._workdir for v in workflow._subworkflows.values() ])) +# End demo module list. + + +def get_demo_outputs(demo_dir): + return load_demo_outputs(Path(workflow.basedir) / demo_dir) + + +IN_FILES = [ + str(Path(demo_dir) / PROCESSED_DIR / demo_output) + for demo_dir in DEMO_DIRS + for demo_output in get_demo_outputs(demo_dir) +] +OUT_FILES = [ + str(BUCKET / demo_dir / demo_output) + for demo_dir in DEMO_DIRS + for demo_output in get_demo_outputs(demo_dir) +] -def get_subworkflow_outputs(subworkflow_key): - with open(Path(SUBWORKFLOW_DIRS[subworkflow_key]) / "config.yml") as f: - subworkflow_config = yaml.load(f, Loader=yaml.SafeLoader) - return subworkflow_config['output'] rule all: + default_target: True input: - in_files=[ - [ - globals()[subworkflow_key](str(PROCESSED_DIR / subworkflow_output)) - for subworkflow_output - in get_subworkflow_outputs(subworkflow_key) - ] - for subworkflow_key - in SUBWORKFLOW_KEYS - ] + in_files=IN_FILES params: should_upload=config.get("upload"), - out_files=[ - [ - str(BUCKET / SUBWORKFLOW_DIRS[subworkflow_key] / subworkflow_output) - for subworkflow_output - in get_subworkflow_outputs(subworkflow_key) - ] - for subworkflow_key - in SUBWORKFLOW_KEYS - ] + out_files=OUT_FILES run: - if str2bool(params.should_upload): + if str2bool(str(params.should_upload)): print("Uploading") - for in_file, out_file in zip(input.in_files, flatten(params.out_files)): + for in_file, out_file in zip(input.in_files, params.out_files): if os.path.isdir(in_file): if is_aws(out_file): shell(f"aws s3 sync {in_file} s3://{out_file}") @@ -90,21 +97,25 @@ rule all: shell(f"aws s3 cp {in_file} s3://{out_file}") else: print("Not uploading. To upload, use snakemake --config upload=true") - for in_file, out_file in zip(input.in_files, flatten(params.out_files)): + for in_file, out_file in zip(input.in_files, params.out_files): if is_aws(out_file): shell(f"echo \"{in_file} s3://{out_file}\"") else: shell(f"echo \"{in_file} gs://{out_file}\"") + rule fill_templates: params: - subworkflow_dirs=[ - SUBWORKFLOW_DIRS[subworkflow_key] - for subworkflow_key - in SUBWORKFLOW_KEYS - ] - run: - for subworkflow_dir in params.subworkflow_dirs: - if os.path.exists(os.path.join(subworkflow_dir, 'vitessce.template.json')): - shell(f"python fill_template.py -d {subworkflow_dir} -t local > {os.path.join(subworkflow_dir, 'vitessce.local.json')}") - shell(f"python fill_template.py -d {subworkflow_dir} -t remote -v {BUCKET_VERSION} > {os.path.join(subworkflow_dir, 'vitessce.remote.json')}") + demo_dirs=[ + demo_dir + for demo_dir in DEMO_DIRS + if os.path.exists(os.path.join(demo_dir, "vitessce.template.json")) + ], + version=BUCKET_VERSION + shell: + ''' + for demo_dir in {params.demo_dirs}; do + uv run --script fill_template.py -d "$demo_dir" -t local > "$demo_dir/vitessce.local.json" + uv run --script fill_template.py -d "$demo_dir" -t remote -v {params.version} > "$demo_dir/vitessce.remote.json" + done + ''' diff --git a/demos/combat-2022/Snakefile b/demos/combat-2022/Snakefile index a305702f..d55be363 100644 --- a/demos/combat-2022/Snakefile +++ b/demos/combat-2022/Snakefile @@ -1,5 +1,10 @@ include: "../common.smk" -configfile: "config.yml" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) # https://doi.org/10.1016/j.cell.2022.01.012 # https://zenodo.org/record/6120249 @@ -8,7 +13,7 @@ H5AD_URL = "https://zenodo.org/record/6120249/files/COMBAT-CITESeq-EXPRESSION-AT rule all: input: - [ (PROCESSED_DIR / f) for f in config['output'] ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ] # Convert the raw AnnData .h5ad file to a processed AnnData .zarr store. rule convert_to_zarr: @@ -20,7 +25,7 @@ rule convert_to_zarr: script=(SRC_DIR / "convert_to_zarr.py") shell: ''' - python {params.script} \ + uv run --script {params.script} \ -i {input} \ -o {output} ''' diff --git a/demos/combat-2022/src/convert_to_zarr.py b/demos/combat-2022/src/convert_to_zarr.py index e90f097b..c9568701 100644 --- a/demos/combat-2022/src/convert_to_zarr.py +++ b/demos/combat-2022/src/convert_to_zarr.py @@ -1,3 +1,16 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata", +# "numpy", +# "scipy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// import argparse from anndata import read_h5ad import numpy as np diff --git a/demos/common.smk b/demos/common.smk index 5929ad96..8208502e 100644 --- a/demos/common.smk +++ b/demos/common.smk @@ -1,17 +1,30 @@ from pathlib import Path +import yaml -# Directory / file constants -SRC_DIR = Path("src") +# Directory / file constants. +# These are relative to the working directory of a demo. +# When a demo Snakefile is used as a module of the top-level Snakefile, +# the module `prefix` is prepended to input/output paths automatically. DATA_DIR = Path("data") RAW_DIR = DATA_DIR / "raw" PROCESSED_DIR = DATA_DIR / "processed" + # Helper functions def str2bool(v): - return v is not None and v.lower() in ("yes", "true", "t", "1") + return v is not None and v.lower() in ("yes", "true", "t", "1") + def flatten(l): - return [item for sublist in l for item in sublist] + return [item for sublist in l for item in sublist] + def is_aws(output_path): - return not output_path.endswith('.ome.zarr') \ No newline at end of file + return not output_path.endswith('.ome.zarr') + + +def load_demo_outputs(demo_dir): + """Return the list of output filenames from a demo's config.yml.""" + with open(Path(demo_dir) / "config.yml") as f: + return yaml.safe_load(f)["output"] + diff --git a/demos/create_demo.sh b/demos/create_demo.sh index 66adcf2b..1cc69234 100755 --- a/demos/create_demo.sh +++ b/demos/create_demo.sh @@ -2,37 +2,72 @@ set -o errexit set -o pipefail -(( $# == 1 )) || die "Requires one argument, the demo name; Instead got $#." +if (( $# != 1 )); then + echo "Requires one argument, the demo name; Instead got $#." >&2 + exit 1 +fi -SUBWORKFLOW_DIR=$1 -SUBWORKFLOW_KEY=${SUBWORKFLOW_DIR//-/_} +DEMO_DIR=$1 +DEMO_KEY=${DEMO_DIR//-/_} -mkdir "./$SUBWORKFLOW_DIR" -mkdir "./$SUBWORKFLOW_DIR/src" -touch "./$SUBWORKFLOW_DIR/Snakefile" -touch "./$SUBWORKFLOW_DIR/config.yml" -touch "./$SUBWORKFLOW_DIR/vitessce.template.json" +mkdir "./$DEMO_DIR" +mkdir "./$DEMO_DIR/src" +touch "./$DEMO_DIR/vitessce.template.json" -cat << EOF > "./$SUBWORKFLOW_DIR/Snakefile" +cat << 'EOF2' > "./$DEMO_DIR/Snakefile" include: "../common.smk" -configfile: "config.yml" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) rule all: input: - [ (PROCESSED_DIR / f) for f in config['output'] ] -EOF + [ (PROCESSED_DIR / f) for f in OUTPUTS ] +EOF2 -cat << EOF > "./$SUBWORKFLOW_DIR/config.yml" +cat << EOF2 > "./$DEMO_DIR/config.yml" output: -- $1.h5ad.zarr -EOF +- $DEMO_DIR.h5ad.zarr +EOF2 + +cat << 'EOF2' > "./$DEMO_DIR/src/convert_to_zarr.py" +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse +from anndata import read_h5ad + + +def convert_h5ad_to_zarr(input_path, output_path): + adata = read_h5ad(input_path) + adata.write_zarr(output_path) + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input', type=str, required=True, help='Input H5AD file') + parser.add_argument('-o', '--output', type=str, required=True, help='Output Zarr store') + args = parser.parse_args() + convert_h5ad_to_zarr(args.input, args.output) +EOF2 +cat << EOF2 +Add "$DEMO_DIR" to DEMO_DIRS in the main demos Snakefile, along with: -cat << EOF -Add the following to the main demos Snakefile: +module $DEMO_KEY: + snakefile: "$DEMO_DIR/Snakefile" + prefix: "$DEMO_DIR" -subworkflow $SUBWORKFLOW_KEY: - workdir: - "$SUBWORKFLOW_DIR" -EOF \ No newline at end of file +use rule * from $DEMO_KEY as ${DEMO_KEY}_* +EOF2 diff --git a/demos/environment.yml b/demos/environment.yml deleted file mode 100644 index cbeb9d20..00000000 --- a/demos/environment.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: vitessce-python-demos -channels: - - bioconda - - conda-forge -dependencies: - - python==3.9 - - numpy - - pandas - - anndata>=0.7.8 - - numba - - scanpy - - jupyterlab - - zarr - - h5py - - boto3 - - numcodecs - - scipy - - snakemake>=6.0 - - pyyaml - - imageio - - networkx - - shapely - - geopandas - - dask-geopandas - - pip - - pip: - - loompy - - generate-tiff-offsets>=0.1.7 - - obonet==0.2.5 - - leidenalg - - ome-zarr==0.2.1 \ No newline at end of file diff --git a/demos/fill_template.py b/demos/fill_template.py index c2296e76..f2b79e55 100644 --- a/demos/fill_template.py +++ b/demos/fill_template.py @@ -1,3 +1,9 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "jinja2", +# ] +# /// import os from os.path import join from jinja2 import Environment, FileSystemLoader diff --git a/demos/habib-2017/Snakefile b/demos/habib-2017/Snakefile index 7a0b3c20..1e6ae6d4 100644 --- a/demos/habib-2017/Snakefile +++ b/demos/habib-2017/Snakefile @@ -1,5 +1,10 @@ include: "../common.smk" -configfile: "config.yml" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) # https://www.covid19cellatlas.org/index.healthy.html#habib17 @@ -8,7 +13,7 @@ H5AD_URL = "https://covid19.cog.sanger.ac.uk/habib17.processed.h5ad" # Rules rule all: input: - [ (PROCESSED_DIR / f) for f in config['output'] ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ] # Convert the raw AnnData .h5ad file to a processed AnnData .zarr store. rule convert_to_zarr: @@ -20,7 +25,7 @@ rule convert_to_zarr: script=(SRC_DIR / "convert_to_zarr.py") shell: ''' - python {params.script} \ + uv run --script {params.script} \ -i {input} \ -o {output} ''' diff --git a/demos/habib-2017/src/convert_to_zarr.py b/demos/habib-2017/src/convert_to_zarr.py index e08bda31..2ba1b027 100644 --- a/demos/habib-2017/src/convert_to_zarr.py +++ b/demos/habib-2017/src/convert_to_zarr.py @@ -1,3 +1,14 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// import argparse from anndata import read_h5ad from vitessce.data_utils import ( diff --git a/demos/human-lymph-node-10x-visium/Snakefile b/demos/human-lymph-node-10x-visium/Snakefile index ec961d19..935f8537 100644 --- a/demos/human-lymph-node-10x-visium/Snakefile +++ b/demos/human-lymph-node-10x-visium/Snakefile @@ -1,10 +1,15 @@ include: "../common.smk" -configfile: "config.yml" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) # Rules rule all: input: - [ (PROCESSED_DIR / f) for f in config['output'] ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ] #(PROCESSED_DIR / "human_lymph_node_10x_visium.ome.zarr"), # Convert the raw AnnData .h5ad file to a processed AnnData .zarr store. @@ -16,7 +21,7 @@ rule create_zarr: script=(SRC_DIR / "create_zarr.py") shell: ''' - python {params.script} \ + uv run --script {params.script} \ -oa {output.adata} \ -oi {output.img} ''' diff --git a/demos/human-lymph-node-10x-visium/src/create_zarr.py b/demos/human-lymph-node-10x-visium/src/create_zarr.py index 5c7b44da..e0d070c9 100644 --- a/demos/human-lymph-node-10x-visium/src/create_zarr.py +++ b/demos/human-lymph-node-10x-visium/src/create_zarr.py @@ -1,4 +1,20 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "scanpy", +# "numpy", +# "scipy", +# "igraph", +# "leidenalg", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// import argparse +from pathlib import Path import scanpy as sc import numpy as np import scipy.cluster @@ -10,6 +26,8 @@ def create_zarr(output_adata, output_img): + # Download raw data to data/raw, next to data/processed, regardless of the working directory. + sc.settings.datasetdir = Path(output_adata).parent.parent / "raw" adata = sc.datasets.visium_sge(sample_id="V1_Human_Lymph_Node", include_hires_tiff=True) # Reference: https://scanpy-tutorials.readthedocs.io/en/latest/spatial/basic-analysis.html diff --git a/demos/kuppe-2022/Snakefile b/demos/kuppe-2022/Snakefile index 9b944d0e..2e2ff38f 100644 --- a/demos/kuppe-2022/Snakefile +++ b/demos/kuppe-2022/Snakefile @@ -1,5 +1,10 @@ include: "../common.smk" -configfile: "config.yml" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) # https://zenodo.org/record/6578047 @@ -22,7 +27,7 @@ IMG_DIR = (RAW_DIR / "ACH0012" / "outs" / "Volumes" / "RicoData2" / "MI_project" rule all: input: - [ (PROCESSED_DIR / f) for f in config['output'] ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ] rule convert_to_zarr: @@ -43,7 +48,7 @@ rule convert_to_zarr: script=(SRC_DIR / "convert_to_zarr.py") shell: ''' - python {params.script} \ + uv run --script {params.script} \ -ir {input.rna} \ -ia {input.atac} \ -iva {input.visium_adata} \ @@ -61,15 +66,13 @@ rule convert_to_zarr: rule unzip: input: (RAW_DIR / "ACH0012" / "outs" / "spatial_ACH0012_spatial.zip") - params: - out_dir=(RAW_DIR / "ACH0012" / "outs") output: (IMG_DIR / "tissue_hires_image.png"), (IMG_DIR / "tissue_positions_list.csv"), (IMG_DIR / "scalefactors_json.json") shell: ''' - unzip -o {input} -d {params.out_dir} + unzip -o {input} -d "$(dirname {input})" ''' # Untar directory containing image @@ -80,7 +83,7 @@ rule untar: (RAW_DIR / "ACH0012" / "outs" / "spatial_ACH0012_spatial.zip") shell: ''' - tar -xvzf {input} -C {RAW_DIR} + tar -xvzf {input} -C "$(dirname {input})" ''' # Download image diff --git a/demos/kuppe-2022/src/convert_to_zarr.py b/demos/kuppe-2022/src/convert_to_zarr.py index 21e5968c..6f8ab7dc 100644 --- a/demos/kuppe-2022/src/convert_to_zarr.py +++ b/demos/kuppe-2022/src/convert_to_zarr.py @@ -1,3 +1,17 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata", +# "numpy", +# "pandas", +# "imageio", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// import argparse import numpy as np import pandas as pd diff --git a/demos/marshall-2022/Snakefile b/demos/marshall-2022/Snakefile index e405c708..4da84f41 100644 --- a/demos/marshall-2022/Snakefile +++ b/demos/marshall-2022/Snakefile @@ -1,5 +1,10 @@ include: "../common.smk" -configfile: "config.yml" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) # https://doi.org/10.1016/j.isci.2022.104097 @@ -13,7 +18,7 @@ H5AD_URL = "https://datasets.cellxgene.cziscience.com/69ecc4ce-5bb2-4f2c-9ce7-15 rule all: input: - [ (PROCESSED_DIR / f) for f in config['output'] ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ] rule convert_to_zarr: input: @@ -24,7 +29,7 @@ rule convert_to_zarr: script=(SRC_DIR / "convert_to_zarr.py") shell: ''' - python {params.script} \ + uv run --script {params.script} \ -i {input} \ -o {output} ''' diff --git a/demos/marshall-2022/src/convert_to_zarr.py b/demos/marshall-2022/src/convert_to_zarr.py index b99aa324..aecb8ade 100644 --- a/demos/marshall-2022/src/convert_to_zarr.py +++ b/demos/marshall-2022/src/convert_to_zarr.py @@ -1,3 +1,16 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata", +# "numpy", +# "scanpy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// import argparse from anndata import read_h5ad import numpy as np diff --git a/demos/meta-2022-azimuth/Snakefile b/demos/meta-2022-azimuth/Snakefile index bde0d5e7..d06c2a04 100644 --- a/demos/meta-2022-azimuth/Snakefile +++ b/demos/meta-2022-azimuth/Snakefile @@ -1,5 +1,10 @@ include: "../common.smk" -configfile: "config.yml" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) # https://twitter.com/satijalab/status/1404822000464433158 @@ -11,7 +16,7 @@ H5AD_URL = "https://datasets.cellxgene.cziscience.com/2c01a563-73dd-47a1-8fc4-d1 rule all: input: - [ (PROCESSED_DIR / f) for f in config['output'] ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ] rule convert_to_zarr: input: @@ -22,7 +27,7 @@ rule convert_to_zarr: script=(SRC_DIR / "convert_to_zarr.py") shell: ''' - python {params.script} \ + uv run --script {params.script} \ -i {input} \ -o {output} ''' diff --git a/demos/meta-2022-azimuth/src/convert_to_zarr.py b/demos/meta-2022-azimuth/src/convert_to_zarr.py index 10c82425..274d284a 100644 --- a/demos/meta-2022-azimuth/src/convert_to_zarr.py +++ b/demos/meta-2022-azimuth/src/convert_to_zarr.py @@ -1,3 +1,15 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata", +# "scipy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// import argparse from anndata import read_h5ad from scipy import sparse diff --git a/pyproject.toml b/pyproject.toml index 0927920f..a266deeb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -90,11 +90,13 @@ notebook = [ 'starlette>=0.42.0', 'tqdm>=4.1.0', ] +# Outer environment for the Snakemake workflows in demos/. +# The processing scripts in demos/*/src/ declare their own dependencies +# via PEP 723 inline metadata and are run with `uv run --script`. demos = [ - "pulp==2.7.0", - # snakemake>=8 removed the `subworkflow` directive used by demos/Snakefile. - "snakemake<8", + "snakemake>=9.0.0", "pyyaml", + "jinja2", ] # SpatialQuery sq = [ @@ -124,9 +126,6 @@ dev = [ [tool.uv] default-groups = ["dev"] override-dependencies = [] -# datrie (a dependency of snakemake<8) 0.8.2 ships pre-generated C code -# that fails to compile with GCC 14; 0.8.3 regenerates it via Cython. -constraint-dependencies = ["datrie>=0.8.3"] [tool.hatch.build] exclude = [".github", ".claude", "docs", "demos", "binder"] diff --git a/uv.lock b/uv.lock index 560d5678..7e38b279 100644 --- a/uv.lock +++ b/uv.lock @@ -2,9 +2,6 @@ version = 1 revision = 5 requires-python = ">=3.12" -[manifest] -constraints = [{ name = "datrie", specifier = ">=0.8.3" }] - [[package]] name = "aiobotocore" version = "2.23.1" @@ -537,6 +534,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e6/75/49e5bfe642f71f272236b5b2d2691cf915a7283cc0ceda56357b61daa538/comm-0.2.2-py3-none-any.whl", hash = "sha256:e6fb86cb70ff661ee8c9c14e7d36d6de3b4066f1441be4063df9c5009f0a64d3", size = 7180, upload-time = "2024-03-12T16:53:39.226Z" }, ] +[[package]] +name = "conda-inject" +version = "1.3.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/a8/8dc86113c65c949cc72d651461d6e4c544b3302a85ed14a5298829e6a419/conda_inject-1.3.2.tar.gz", hash = "sha256:0b8cde8c47998c118d8ff285a04977a3abcf734caf579c520fca469df1cd0aac", size = 3635, upload-time = "2024-05-27T12:20:58.873Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/4c/fc30b69fb4062aee57e3ab7ff493647c4220144908f0839c619f912045bf/conda_inject-1.3.2-py3-none-any.whl", hash = "sha256:6e641b408980c2814e3e527008c30749117909a21ff47392f07ef807da93a564", size = 4133, upload-time = "2024-05-27T12:20:57.332Z" }, +] + [[package]] name = "configargparse" version = "1.7" @@ -712,12 +721,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/05/3d/f783a19cedbd5e146543775404d6976ca2162fec53ccbba5ffd8da68bd9a/datashader-0.18.1-py3-none-any.whl", hash = "sha256:5585af146e83af51c61d49168a741a6280a482072572e16573af1e5c6b600f8a", size = 18329111, upload-time = "2025-05-08T07:16:07.429Z" }, ] -[[package]] -name = "datrie" -version = "0.8.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/51/0b/c0f53a14317b304e2e93b29a831b0c83306caae9af7f0e2e037d17c4f63f/datrie-0.8.3.tar.gz", hash = "sha256:ea021ad4c8a8bf14e08a71c7872a622aa399a510f981296825091c7ca0436e80", size = 499040, upload-time = "2025-08-28T12:37:23.227Z" } - [[package]] name = "debugpy" version = "1.8.8" @@ -1092,6 +1095,30 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ff/62/85c4c919272577931d407be5ba5d71c20f0b616d31a0befe0ae45bb79abd/imagesize-1.4.1-py2.py3-none-any.whl", hash = "sha256:0d8d18d08f840c19d0ee7ca1fd82490fdc3729b7ac93f49870406ddde8ef8d8b", size = 8769, upload-time = "2022-07-01T12:21:02.467Z" }, ] +[[package]] +name = "immutables" +version = "0.21" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/69/41/0ccaa6ef9943c0609ec5aa663a3b3e681c1712c1007147b84590cec706a0/immutables-0.21.tar.gz", hash = "sha256:b55ffaf0449790242feb4c56ab799ea7af92801a0a43f9e2f4f8af2ab24dfc4a", size = 89008, upload-time = "2024-10-10T00:55:01.434Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/f9/0c46f600702b815182212453f5514c0070ee168b817cdf7c3767554c8489/immutables-0.21-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ef1ed262094b755903122c3c3a83ad0e0d5c3ab7887cda12b2fe878769d1ee0d", size = 31885, upload-time = "2024-10-10T00:54:19.406Z" }, + { url = "https://files.pythonhosted.org/packages/29/34/7608d2eab6179aa47e8f59ab0fbd5b3eeb2333d78c9dc2da0de8de4ed322/immutables-0.21-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce604f81d9d8f26e60b52ebcb56bb5c0462c8ea50fb17868487d15f048a2f13e", size = 31537, upload-time = "2024-10-10T00:54:20.998Z" }, + { url = "https://files.pythonhosted.org/packages/f7/52/cb9e2bb7a69338155ffabbd2f993c968c750dd2d5c6c6eaa6ebb7bfcbdfa/immutables-0.21-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b48b116aaca4500398058b5a87814857a60c4cb09417fecc12d7da0f5639b73d", size = 104270, upload-time = "2024-10-10T00:54:21.912Z" }, + { url = "https://files.pythonhosted.org/packages/0f/a4/25df835a9b9b372a4a869a8a1ac30a32199f2b3f581ad0e249f7e3d19eed/immutables-0.21-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dad7c0c74b285cc0e555ec0e97acbdc6f1862fcd16b99abd612df3243732e741", size = 104864, upload-time = "2024-10-10T00:54:22.956Z" }, + { url = "https://files.pythonhosted.org/packages/4a/51/b548fbc657134d658e179ee8d201ae82d9049aba5c3cb2d858ed2ecb7e3f/immutables-0.21-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e44346e2221a5a676c880ca8e0e6429fa24d1a4ae562573f5c04d7f2e759b030", size = 99733, upload-time = "2024-10-10T00:54:23.99Z" }, + { url = "https://files.pythonhosted.org/packages/47/db/d7b1e0e88faf07fe9a88579a86f58078a9a37fff871f4b3dbcf28cad9a12/immutables-0.21-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8b10139b529a460e53fe8be699ebd848c54c8a33ebe67763bcfcc809a475a26f", size = 101698, upload-time = "2024-10-10T00:54:25.734Z" }, + { url = "https://files.pythonhosted.org/packages/69/2d/6fe42a1a053dd8cfb9f45e91d5246522637c7287dc6bd347f67aedf7aedb/immutables-0.21-cp312-cp312-win32.whl", hash = "sha256:fc512d808662614feb17d2d92e98f611d69669a98c7af15910acf1dc72737038", size = 30977, upload-time = "2024-10-10T00:54:27.436Z" }, + { url = "https://files.pythonhosted.org/packages/63/45/d062aca6971e99454ce3ae42a7430037227fee961644ed1f8b6c9b99e0a5/immutables-0.21-cp312-cp312-win_amd64.whl", hash = "sha256:461dcb0f58a131045155e52a2c43de6ec2fe5ba19bdced6858a3abb63cee5111", size = 35088, upload-time = "2024-10-10T00:54:28.388Z" }, + { url = "https://files.pythonhosted.org/packages/5e/db/60da6f5a3c3f64e0b3940c4ad86e1971d9d2eb8b13a179c26eda5ec6a298/immutables-0.21-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:79674b51aa8dd983f9ac55f7f67b433b1df84a6b4f28ab860588389a5659485b", size = 31922, upload-time = "2024-10-10T00:54:29.305Z" }, + { url = "https://files.pythonhosted.org/packages/9b/89/5420f1d16a652024fcccc9c07d46d4157fcaf33ff37c82412c83fc16ef36/immutables-0.21-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:93c8350f8f7d0d9693f708229d9d0578e6f3b785ce6da4bced1da97137aacfad", size = 31552, upload-time = "2024-10-10T00:54:30.282Z" }, + { url = "https://files.pythonhosted.org/packages/d2/d0/a5fb7c164ddb298ec37537e618b70dfa30c7cae9fac01de374c36489cbc9/immutables-0.21-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:583d2a63e444ce1538cc2bda56ae1f4a1a11473dbc0377c82b516bc7eec3b81e", size = 104334, upload-time = "2024-10-10T00:54:31.284Z" }, + { url = "https://files.pythonhosted.org/packages/f3/a5/5fda0ee4a261a85124011ac0750fec678f00e1b2d4a5502b149a3b4d86d9/immutables-0.21-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b274a52da9b106db55eceb93fc1aea858c4e6f4740189e3548e38613eafc2021", size = 104898, upload-time = "2024-10-10T00:54:32.295Z" }, + { url = "https://files.pythonhosted.org/packages/93/fa/d46bfe92f2c66d35916344176ff87fa839aac9c16849652947e722b7a15f/immutables-0.21-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:338bede057250b33716a3e4892e15df0bf5a5ddbf1d67ead996b3e680b49ef9e", size = 99966, upload-time = "2024-10-10T00:54:34.046Z" }, + { url = "https://files.pythonhosted.org/packages/d7/f5/2a19e2e095f7a39d8d77dcc10669734d2d99773ce00c99bdcfeeb7d714e6/immutables-0.21-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8781c89583b68f604cf30f0978b722165824c3075888639fde771bf1a3e12dc0", size = 101773, upload-time = "2024-10-10T00:54:35.851Z" }, + { url = "https://files.pythonhosted.org/packages/86/80/5b6ee53f836cf2067ced997efbf2ce20890627f150c3089ea50cf607e783/immutables-0.21-cp313-cp313-win32.whl", hash = "sha256:e97ea83befad873712f283c0cccd630f70cba753e207b4868af28d5b85e9dc54", size = 30988, upload-time = "2024-10-10T00:54:37.618Z" }, + { url = "https://files.pythonhosted.org/packages/ff/07/f623e6da78368fc0b1772f4877afbf60f34c4cc93f1a8f1006507afa21ec/immutables-0.21-cp313-cp313-win_amd64.whl", hash = "sha256:cfcb23bd898f5a4ef88692b42c51f52ca7373a35ba4dcc215060a668639eb5da", size = 35147, upload-time = "2024-10-10T00:54:38.558Z" }, +] + [[package]] name = "iniconfig" version = "2.1.0" @@ -3332,16 +3359,18 @@ wheels = [ [[package]] name = "snakemake" -version = "7.32.4" +version = "9.16.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "appdirs" }, + { name = "conda-inject" }, { name = "configargparse" }, { name = "connection-pool" }, - { name = "datrie" }, { name = "docutils" }, + { name = "dpath" }, { name = "gitpython" }, { name = "humanfriendly" }, + { name = "immutables" }, { name = "jinja2" }, { name = "jsonschema" }, { name = "nbformat" }, @@ -3349,17 +3378,105 @@ dependencies = [ { name = "psutil" }, { name = "pulp" }, { name = "pyyaml" }, + { name = "referencing" }, { name = "requests" }, { name = "reretry" }, { name = "smart-open" }, - { name = "stopit" }, + { name = "snakemake-interface-common" }, + { name = "snakemake-interface-executor-plugins" }, + { name = "snakemake-interface-logger-plugins" }, + { name = "snakemake-interface-report-plugins" }, + { name = "snakemake-interface-scheduler-plugins" }, + { name = "snakemake-interface-storage-plugins" }, { name = "tabulate" }, { name = "throttler" }, - { name = "toposort" }, { name = "wrapt" }, { name = "yte" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f4/94/884160dab89886cef7802df0a8c8217bfb2d795427dee01ad0e0dc15964a/snakemake-7.32.4.tar.gz", hash = "sha256:fdc3f15dd7b06fabb7da30d460e0a3b1fba08e4ea91f9c32c47a83705cdc7b6e", size = 371171, upload-time = "2023-09-18T14:47:18.704Z" } +sdist = { url = "https://files.pythonhosted.org/packages/20/5e/715560f7010fab1db390d738006bc4183f5dc48356583d6d5cc59d0fd25d/snakemake-9.16.3.tar.gz", hash = "sha256:a7b2b76d8f7dc61e7860e0f3351d7356cef65ce41f1a5e99dae537dae5afa659", size = 6759310, upload-time = "2026-02-05T16:16:50.347Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2b/0c/adf4310b15ebcbbbe36d316808d48142424f904422fef1fecca3d6e76c8a/snakemake-9.16.3-py3-none-any.whl", hash = "sha256:42f9b74446794750a333fbaeb977fddf561ec7b3abd00839c44ab97c630781e3", size = 1143158, upload-time = "2026-02-05T16:16:47.417Z" }, +] + +[[package]] +name = "snakemake-interface-common" +version = "1.23.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "argparse-dataclass" }, + { name = "configargparse" }, + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/89/c3/592f832f6e5d2d31f749392e48e8401b7625dec668d3d365d8d28f2b6c30/snakemake_interface_common-1.23.0.tar.gz", hash = "sha256:6ed14531a461417659364a0dd0acc51b786af4e26fc15cc5e00ff3d9fcaffacc", size = 13960, upload-time = "2026-03-08T21:54:29.251Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/90/a4a3652e832667917383f8d34112bdb37b78a6d14efc049e22a2c8192524/snakemake_interface_common-1.23.0-py3-none-any.whl", hash = "sha256:43bb10102d07149f27787dfc65a7342b86ff772973e7f9ca4940c89cb412a11e", size = 17162, upload-time = "2026-03-08T21:54:28.074Z" }, +] + +[[package]] +name = "snakemake-interface-executor-plugins" +version = "9.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "argparse-dataclass" }, + { name = "snakemake-interface-common" }, + { name = "throttler" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/54/50/de06b284c45a8e94fb8e4a12d5235065e78b49b8f84329dc10fe39f4b7dd/snakemake_interface_executor_plugins-9.4.0.tar.gz", hash = "sha256:9d4138897beacbaadaedad94b63f948eaeb604b7fc78f9cf65ac57f090f2c066", size = 16549, upload-time = "2026-03-08T17:04:02.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5c/2c/4422eb14884bb4955ce65819799ff6452dcd3aa5f8e158540a287877bbcf/snakemake_interface_executor_plugins-9.4.0-py3-none-any.whl", hash = "sha256:d335c093185897e4e3654a39bab3a6f1c57dc1a54f998c92bd2d88640ab4a05e", size = 22567, upload-time = "2026-03-08T17:04:01.296Z" }, +] + +[[package]] +name = "snakemake-interface-logger-plugins" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "snakemake-interface-common" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a7/0c/3fa5d592663c65669a867526604aadc6fbc235fb9284e94b49c0ef59aa41/snakemake_interface_logger_plugins-2.1.0.tar.gz", hash = "sha256:c89a00d2a398490cecd91b6dc6db8049cba93712d82e1d8f3000f3040bf3791c", size = 15917, upload-time = "2026-05-20T15:12:35.259Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/aa/43/cfdaf562303012024c8f48efebdfe258eef3d895665bd7e0000fdeb2411d/snakemake_interface_logger_plugins-2.1.0-py3-none-any.whl", hash = "sha256:601e3e0770dd1b460c1dcb7bd33f4fc2eb8af5016634b80d985cb993f674ef46", size = 14313, upload-time = "2026-05-20T15:12:34.186Z" }, +] + +[[package]] +name = "snakemake-interface-report-plugins" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "snakemake-interface-common" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/d6/6160ed98de665d6871dd356597dbf726688cc786e88668359ca37b7d9f54/snakemake_interface_report_plugins-1.3.0.tar.gz", hash = "sha256:fc9495298bec4e69721ab8afe6d6d88a86966fda2eeb003db56b9a88b86d5934", size = 4283, upload-time = "2025-10-31T10:52:36.55Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f0/f0/df73f6abc9b5910e43612ae28c7b6f666af80c4edd46a216ef47599ab6cb/snakemake_interface_report_plugins-1.3.0-py3-none-any.whl", hash = "sha256:78da3931f70e79eef51e5645a40b172929e555fe4d86ff45d6b856e521a379db", size = 7251, upload-time = "2025-10-31T10:52:35.474Z" }, +] + +[[package]] +name = "snakemake-interface-scheduler-plugins" +version = "2.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "snakemake-interface-common" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/88/d9/d480807d2cfc2d132bc760d877d45ec8fbe620a24200ec4d2697c4a26031/snakemake_interface_scheduler_plugins-2.0.2.tar.gz", hash = "sha256:2797e8fa9019d983132c2b403f14d6fcd3c5ad4c8d8a66b984b4740a71cacc46", size = 8642, upload-time = "2025-10-20T13:58:12.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0e/d0/f4e9894c8aaf37efe3bf1afe15ee3cf0546d82b2713a589e266ee47bf2ef/snakemake_interface_scheduler_plugins-2.0.2-py3-none-any.whl", hash = "sha256:b9ddfa508bd480711de1770dfb24f3b813cfa3cd0f862f0127ef721ae5346915", size = 10766, upload-time = "2025-10-20T13:58:11.898Z" }, +] + +[[package]] +name = "snakemake-interface-storage-plugins" +version = "4.4.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "humanfriendly" }, + { name = "snakemake-interface-common" }, + { name = "tenacity" }, + { name = "throttler" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/93/6e/f3c5b2d621fd6a6b78d8cfc01fef6b926fe2c277f5ed77c5e4deeacb94eb/snakemake_interface_storage_plugins-4.4.1.tar.gz", hash = "sha256:b2b5bf05318af36955ebf2ce76c921c0fb06904ca98fb30e1657d88b7b7b6945", size = 14924, upload-time = "2026-03-16T11:16:01.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/49/1f72d8c05d8588f06a61f1af3deb125a4ff8169d2a41f1b839d62c824d1c/snakemake_interface_storage_plugins-4.4.1-py3-none-any.whl", hash = "sha256:6e075f448543cc3d0cb1ee5e6e5a83af9761e7085f3ce0922011685d098f231e", size = 18256, upload-time = "2026-03-16T11:15:59.582Z" }, +] [[package]] name = "sniffio" @@ -3638,12 +3755,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/16/fe/e07300c027a868d32d8ed7a425503401e91a03ff90e7ca525c115c634ffb/stdlib_list-0.11.0-py3-none-any.whl", hash = "sha256:8bf8decfffaaf273d4cfeb5bd852b910a00dec1037dcf163576803622bccf597", size = 83617, upload-time = "2024-10-15T18:49:56.057Z" }, ] -[[package]] -name = "stopit" -version = "1.1.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/35/58/e8bb0b0fb05baf07bbac1450c447d753da65f9701f551dca79823ce15d50/stopit-1.1.2.tar.gz", hash = "sha256:f7f39c583fd92027bd9d06127b259aee7a5b7945c1f1fa56263811e1e766996d", size = 18281, upload-time = "2018-02-09T00:32:14.204Z" } - [[package]] name = "tabulate" version = "0.9.0" @@ -3662,6 +3773,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9b/87/ce70db7cae60e67851eb94e1a2127d4abb573d3866d2efd302ceb0d4d2a5/tblib-3.0.0-py3-none-any.whl", hash = "sha256:80a6c77e59b55e83911e1e607c649836a69c103963c5f28a46cbeef44acf8129", size = 12478, upload-time = "2023-10-22T00:35:46.515Z" }, ] +[[package]] +name = "tenacity" +version = "9.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/9e/497c1c8ebe5a5b5d1d4a7511aea22c0bb1a97e3170d98abdef0e1b34265a/tenacity-9.2.1.tar.gz", hash = "sha256:a606b5c808d0cded4a359d5b9932d867ff2a6a6b64d37350260fd01bbdf83839", size = 58261, upload-time = "2026-10-07T12:13:01.633Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/26/1ff2b0721ac66a3ec5b1402b333110b352ab0a8724052ac279a7b82d40c4/tenacity-9.2.1-py3-none-any.whl", hash = "sha256:9e56f17539296baab7beabb08b92f6ee3d7be92d8be72d763360677c2ad6580e", size = 32310, upload-time = "2026-10-07T12:13:00.102Z" }, +] + [[package]] name = "terminado" version = "0.18.1" @@ -3745,15 +3865,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/03/98/eb27cc78ad3af8e302c9d8ff4977f5026676e130d28dd7578132a457170c/toolz-1.0.0-py3-none-any.whl", hash = "sha256:292c8f1c4e7516bf9086f8850935c799a874039c8bcf959d47b600e4c44a6236", size = 56383, upload-time = "2024-10-04T16:17:01.533Z" }, ] -[[package]] -name = "toposort" -version = "1.10" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/69/19/8e955d90985ecbd3b9adb2a759753a6840da2dff3c569d412b2c9217678b/toposort-1.10.tar.gz", hash = "sha256:bfbb479c53d0a696ea7402601f4e693c97b0367837c8898bc6471adfca37a6bd", size = 11132, upload-time = "2023-02-27T13:59:51.834Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f6/17/57b444fd314d5e1593350b9a31d000e7411ba8e17ce12dc7ad54ca76b810/toposort-1.10-py3-none-any.whl", hash = "sha256:cbdbc0d0bee4d2695ab2ceec97fe0679e9c10eab4b2a87a9372b929e70563a87", size = 8500, upload-time = "2023-02-25T20:07:06.538Z" }, -] - [[package]] name = "tornado" version = "6.4.1" @@ -3923,7 +4034,7 @@ all = [ { name = "uvicorn" }, ] demos = [ - { name = "pulp" }, + { name = "jinja2" }, { name = "pyyaml" }, { name = "snakemake" }, ] @@ -3975,6 +4086,7 @@ requires-dist = [ { name = "anywidget", marker = "extra == 'all'", specifier = ">=0.11.0" }, { name = "black", specifier = ">=21.11b1" }, { name = "generate-tiff-offsets", marker = "extra == 'all'", specifier = ">=0.1.9" }, + { name = "jinja2", marker = "extra == 'demos'" }, { name = "jinja2", marker = "extra == 'docs'" }, { name = "jsonschema", specifier = ">=4.0.0" }, { name = "jupyter-server-proxy", marker = "extra == 'all'", specifier = ">=1.5.2" }, @@ -3989,12 +4101,11 @@ requires-dist = [ { name = "ome-zarr", marker = "extra == 'all'", specifier = "==0.15.0" }, { name = "oxc-py", marker = "extra == 'all'", specifier = ">=0.1.1" }, { name = "pandas", specifier = ">=1.1.2" }, - { name = "pulp", marker = "extra == 'demos'", specifier = "==2.7.0" }, { name = "pybind11", marker = "extra == 'sq'" }, { name = "pyyaml", marker = "extra == 'demos'" }, { name = "scanpy", marker = "extra == 'all'", specifier = ">=1.10.2" }, { name = "scipy", specifier = ">=1.2.1" }, - { name = "snakemake", marker = "extra == 'demos'", specifier = "<8" }, + { name = "snakemake", marker = "extra == 'demos'", specifier = ">=9.0.0" }, { name = "spatialdata", marker = "extra == 'notebook'", specifier = "==0.7.3" }, { name = "spatialquery", marker = "extra == 'sq'", specifier = "==0.0.4" }, { name = "sphinx", marker = "extra == 'docs'", specifier = "==4.2.0" }, From 85c57b179abfc6a7b1044ed78c288a06cd1c420f Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:27:09 -0500 Subject: [PATCH 3/9] WIP: add per-tech example pipelines --- .gitignore | 4 +- demos/Snakefile | 186 +++++++- demos/anndata-chromium-pbmc/Snakefile | 48 ++ demos/anndata-chromium-pbmc/config.yml | 2 + .../src/process_chromium.py | 93 ++++ .../vitessce.template.json | 111 +++++ demos/anndata-parse-pbmc/Snakefile | 56 +++ demos/anndata-parse-pbmc/config.yml | 2 + demos/anndata-parse-pbmc/src/process_parse.py | 116 +++++ .../anndata-parse-pbmc/vitessce.template.json | 117 +++++ demos/common.smk | 4 + demos/mudata-cite-seq-pbmc/Snakefile | 52 ++ demos/mudata-cite-seq-pbmc/config.yml | 2 + .../src/process_cite_seq.py | 172 +++++++ .../vitessce.template.json | 185 ++++++++ demos/mudata-pbmc-multiome-10x/Snakefile | 62 +++ demos/mudata-pbmc-multiome-10x/config.yml | 3 + .../src/process_multiome.py | 237 ++++++++++ .../vitessce.template.json | 199 ++++++++ demos/mudata-snareseq2-lung-hubmap/Snakefile | 56 +++ demos/mudata-snareseq2-lung-hubmap/config.yml | 3 + .../src/process_snareseq2.py | 171 +++++++ .../vitessce.template.json | 234 +++++++++ .../Snakefile | 62 +++ .../config.yml | 2 + .../src/ome_tiff_to_ome_zarr_3d.py | 125 +++++ .../vitessce.template.json | 126 +++++ demos/spatialdata-atera-kidney/Snakefile | 74 +++ demos/spatialdata-atera-kidney/config.yml | 2 + .../src/to_spatialdata.py | 176 +++++++ .../vitessce.template.json | 392 ++++++++++++++++ .../Snakefile | 56 +++ .../config.yml | 2 + .../src/convert_to_spatialdata.py | 175 +++++++ .../src/download_zip_member.py | 93 ++++ .../vitessce.template.json | 180 +++++++ .../Snakefile | 72 +++ .../config.yml | 2 + .../src/sprm_to_spatialdata.py | 189 ++++++++ .../vitessce.template.json | 364 ++++++++++++++ demos/spatialdata-cosmx-nsclc/Snakefile | 65 +++ demos/spatialdata-cosmx-nsclc/config.yml | 2 + .../src/convert_to_spatialdata.py | 265 +++++++++++ .../vitessce.template.json | 238 ++++++++++ .../Snakefile | 66 +++ .../config.yml | 2 + .../src/convert_to_spatialdata.py | 130 +++++ .../vitessce.template.json | 416 ++++++++++++++++ .../spatialdata-geomx-mouse-embryo/Snakefile | 79 ++++ .../spatialdata-geomx-mouse-embryo/config.yml | 2 + .../src/convert_to_spatialdata.py | 196 ++++++++ .../vitessce.template.json | 301 ++++++++++++ .../Snakefile | 56 +++ .../config.yml | 2 + .../src/convert_to_spatialdata.py | 244 ++++++++++ .../vitessce.template.json | 180 +++++++ .../Snakefile | 94 ++++ .../config.yml | 2 + .../src/convert_with_thyra.py | 43 ++ .../src/make_vitessce_store.py | 225 +++++++++ .../vitessce.template.json | 188 ++++++++ .../Snakefile | 69 +++ .../config.yml | 2 + .../src/to_spatialdata.py | 139 ++++++ .../vitessce.template.json | 144 ++++++ .../Snakefile | 128 +++++ .../config.yml | 2 + .../src/hdf5_boundaries_to_parquet.py | 85 ++++ .../src/to_spatialdata.py | 138 ++++++ .../vitessce.template.json | 352 ++++++++++++++ .../spatialdata-mibi-hubmap-uterus/Snakefile | 70 +++ .../spatialdata-mibi-hubmap-uterus/config.yml | 2 + .../src/sprm_to_spatialdata.py | 189 ++++++++ .../vitessce.template.json | 364 ++++++++++++++ .../Snakefile | 54 +++ .../config.yml | 2 + .../src/convert_to_spatialdata.py | 92 ++++ .../vitessce.template.json | 165 +++++++ .../Snakefile | 77 +++ .../config.yml | 3 + .../src/process_spatial_atac_rna.py | 282 +++++++++++ .../vitessce.template.json | 284 +++++++++++ .../Snakefile | 105 +++++ .../config.yml | 2 + .../src/convert_to_spatialdata.py | 158 +++++++ .../src/fragments_to_gene_scores.py | 71 +++ .../vitessce.template.json | 443 ++++++++++++++++++ .../Snakefile | 62 +++ .../config.yml | 2 + .../src/convert_to_spatialdata.py | 100 ++++ .../vitessce.template.json | 230 +++++++++ demos/spatialdata-visium-hd-3.0.0/Snakefile | 44 ++ demos/spatialdata-visium-hd-3.0.0/config.yml | 2 + .../src/rasterize_bins.py | 63 +++ .../vitessce.template.json | 179 +++++++ demos/spatialdata-visium-hd-4.0.1/Snakefile | 41 ++ demos/spatialdata-visium-hd-4.0.1/config.yml | 2 + .../vitessce.template.json | 150 ++++++ demos/spatialdata-visium/Snakefile | 40 ++ demos/spatialdata-visium/config.yml | 2 + .../spatialdata-visium/vitessce.template.json | 136 ++++++ demos/spatialdata-xenium-rep1/Snakefile | 44 ++ demos/spatialdata-xenium-rep1/config.yml | 2 + .../src/morton_sort_points.py | 58 +++ .../vitessce.template.json | 169 +++++++ 105 files changed, 11749 insertions(+), 2 deletions(-) create mode 100644 demos/anndata-chromium-pbmc/Snakefile create mode 100644 demos/anndata-chromium-pbmc/config.yml create mode 100644 demos/anndata-chromium-pbmc/src/process_chromium.py create mode 100644 demos/anndata-chromium-pbmc/vitessce.template.json create mode 100644 demos/anndata-parse-pbmc/Snakefile create mode 100644 demos/anndata-parse-pbmc/config.yml create mode 100644 demos/anndata-parse-pbmc/src/process_parse.py create mode 100644 demos/anndata-parse-pbmc/vitessce.template.json create mode 100644 demos/mudata-cite-seq-pbmc/Snakefile create mode 100644 demos/mudata-cite-seq-pbmc/config.yml create mode 100644 demos/mudata-cite-seq-pbmc/src/process_cite_seq.py create mode 100644 demos/mudata-cite-seq-pbmc/vitessce.template.json create mode 100644 demos/mudata-pbmc-multiome-10x/Snakefile create mode 100644 demos/mudata-pbmc-multiome-10x/config.yml create mode 100644 demos/mudata-pbmc-multiome-10x/src/process_multiome.py create mode 100644 demos/mudata-pbmc-multiome-10x/vitessce.template.json create mode 100644 demos/mudata-snareseq2-lung-hubmap/Snakefile create mode 100644 demos/mudata-snareseq2-lung-hubmap/config.yml create mode 100644 demos/mudata-snareseq2-lung-hubmap/src/process_snareseq2.py create mode 100644 demos/mudata-snareseq2-lung-hubmap/vitessce.template.json create mode 100644 demos/ome-zarr-lightsheet-hubmap-spleen/Snakefile create mode 100644 demos/ome-zarr-lightsheet-hubmap-spleen/config.yml create mode 100644 demos/ome-zarr-lightsheet-hubmap-spleen/src/ome_tiff_to_ome_zarr_3d.py create mode 100644 demos/ome-zarr-lightsheet-hubmap-spleen/vitessce.template.json create mode 100644 demos/spatialdata-atera-kidney/Snakefile create mode 100644 demos/spatialdata-atera-kidney/config.yml create mode 100644 demos/spatialdata-atera-kidney/src/to_spatialdata.py create mode 100644 demos/spatialdata-atera-kidney/vitessce.template.json create mode 100644 demos/spatialdata-aviti24-teton-hela-tnfa/Snakefile create mode 100644 demos/spatialdata-aviti24-teton-hela-tnfa/config.yml create mode 100644 demos/spatialdata-aviti24-teton-hela-tnfa/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-aviti24-teton-hela-tnfa/src/download_zip_member.py create mode 100644 demos/spatialdata-aviti24-teton-hela-tnfa/vitessce.template.json create mode 100644 demos/spatialdata-codex-hubmap-large-intestine/Snakefile create mode 100644 demos/spatialdata-codex-hubmap-large-intestine/config.yml create mode 100644 demos/spatialdata-codex-hubmap-large-intestine/src/sprm_to_spatialdata.py create mode 100644 demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json create mode 100644 demos/spatialdata-cosmx-nsclc/Snakefile create mode 100644 demos/spatialdata-cosmx-nsclc/config.yml create mode 100644 demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-cosmx-nsclc/vitessce.template.json create mode 100644 demos/spatialdata-dbit-seq-mouse-embryo/Snakefile create mode 100644 demos/spatialdata-dbit-seq-mouse-embryo/config.yml create mode 100644 demos/spatialdata-dbit-seq-mouse-embryo/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json create mode 100644 demos/spatialdata-geomx-mouse-embryo/Snakefile create mode 100644 demos/spatialdata-geomx-mouse-embryo/config.yml create mode 100644 demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-geomx-mouse-embryo/vitessce.template.json create mode 100644 demos/spatialdata-illumina-stratamap-mouse-kidney/Snakefile create mode 100644 demos/spatialdata-illumina-stratamap-mouse-kidney/config.yml create mode 100644 demos/spatialdata-illumina-stratamap-mouse-kidney/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-illumina-stratamap-mouse-kidney/vitessce.template.json create mode 100644 demos/spatialdata-maldi-msi-timstof-mouse-brain/Snakefile create mode 100644 demos/spatialdata-maldi-msi-timstof-mouse-brain/config.yml create mode 100644 demos/spatialdata-maldi-msi-timstof-mouse-brain/src/convert_with_thyra.py create mode 100644 demos/spatialdata-maldi-msi-timstof-mouse-brain/src/make_vitessce_store.py create mode 100644 demos/spatialdata-maldi-msi-timstof-mouse-brain/vitessce.template.json create mode 100644 demos/spatialdata-merfish-zhuang-abca-4/Snakefile create mode 100644 demos/spatialdata-merfish-zhuang-abca-4/config.yml create mode 100644 demos/spatialdata-merfish-zhuang-abca-4/src/to_spatialdata.py create mode 100644 demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json create mode 100644 demos/spatialdata-merscope-mouse-brain/Snakefile create mode 100644 demos/spatialdata-merscope-mouse-brain/config.yml create mode 100644 demos/spatialdata-merscope-mouse-brain/src/hdf5_boundaries_to_parquet.py create mode 100644 demos/spatialdata-merscope-mouse-brain/src/to_spatialdata.py create mode 100644 demos/spatialdata-merscope-mouse-brain/vitessce.template.json create mode 100644 demos/spatialdata-mibi-hubmap-uterus/Snakefile create mode 100644 demos/spatialdata-mibi-hubmap-uterus/config.yml create mode 100644 demos/spatialdata-mibi-hubmap-uterus/src/sprm_to_spatialdata.py create mode 100644 demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json create mode 100644 demos/spatialdata-slide-seq-hubmap-kidney/Snakefile create mode 100644 demos/spatialdata-slide-seq-hubmap-kidney/config.yml create mode 100644 demos/spatialdata-slide-seq-hubmap-kidney/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-slide-seq-hubmap-kidney/vitessce.template.json create mode 100644 demos/spatialdata-spatial-atac-rna-mouse-brain/Snakefile create mode 100644 demos/spatialdata-spatial-atac-rna-mouse-brain/config.yml create mode 100644 demos/spatialdata-spatial-atac-rna-mouse-brain/src/process_spatial_atac_rna.py create mode 100644 demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json create mode 100644 demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile create mode 100644 demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/config.yml create mode 100644 demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/fragments_to_gene_scores.py create mode 100644 demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json create mode 100644 demos/spatialdata-stellaromics-pyxa-small/Snakefile create mode 100644 demos/spatialdata-stellaromics-pyxa-small/config.yml create mode 100644 demos/spatialdata-stellaromics-pyxa-small/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json create mode 100644 demos/spatialdata-visium-hd-3.0.0/Snakefile create mode 100644 demos/spatialdata-visium-hd-3.0.0/config.yml create mode 100644 demos/spatialdata-visium-hd-3.0.0/src/rasterize_bins.py create mode 100644 demos/spatialdata-visium-hd-3.0.0/vitessce.template.json create mode 100644 demos/spatialdata-visium-hd-4.0.1/Snakefile create mode 100644 demos/spatialdata-visium-hd-4.0.1/config.yml create mode 100644 demos/spatialdata-visium-hd-4.0.1/vitessce.template.json create mode 100644 demos/spatialdata-visium/Snakefile create mode 100644 demos/spatialdata-visium/config.yml create mode 100644 demos/spatialdata-visium/vitessce.template.json create mode 100644 demos/spatialdata-xenium-rep1/Snakefile create mode 100644 demos/spatialdata-xenium-rep1/config.yml create mode 100644 demos/spatialdata-xenium-rep1/src/morton_sort_points.py create mode 100644 demos/spatialdata-xenium-rep1/vitessce.template.json diff --git a/.gitignore b/.gitignore index 4e008044..ba353e7f 100644 --- a/.gitignore +++ b/.gitignore @@ -43,4 +43,6 @@ vitessce/yarn.lock tests-widget/test-results/ tests-widget/playwright-report/ tests-widget/blob-report/ -tests-widget/playwright/.cache/ \ No newline at end of file +tests-widget/playwright/.cache/ + +TODO.md diff --git a/demos/Snakefile b/demos/Snakefile index 704755ae..9f67f9f1 100644 --- a/demos/Snakefile +++ b/demos/Snakefile @@ -14,12 +14,46 @@ BUCKET = PosixPath(BUCKET_NAME) / BUCKET_VERSION / "main" # To add a demo, append its directory name here and add # a corresponding `module` + `use rule` block below. DEMO_DIRS = [ + "anndata-chromium-pbmc", + "anndata-parse-pbmc", "combat-2022", "habib-2017", "human-lymph-node-10x-visium", "kuppe-2022", "marshall-2022", "meta-2022-azimuth", + "mudata-cite-seq-pbmc", + "mudata-pbmc-multiome-10x", + "mudata-snareseq2-lung-hubmap", + "ome-zarr-lightsheet-hubmap-spleen", + "spatialdata-atera-kidney", + "spatialdata-aviti24-teton-hela-tnfa", + "spatialdata-codex-hubmap-large-intestine", + "spatialdata-cosmx-nsclc", + "spatialdata-dbit-seq-mouse-embryo", + "spatialdata-geomx-mouse-embryo", + "spatialdata-merfish-zhuang-abca-4", + "spatialdata-merscope-mouse-brain", + "spatialdata-mibi-hubmap-uterus", + "spatialdata-slide-seq-hubmap-kidney", + "spatialdata-spatial-atac-rna-mouse-brain", + "spatialdata-spatial-cut-and-tag-rna-mouse-brain", + "spatialdata-stellaromics-pyxa-small", + "spatialdata-visium", + "spatialdata-visium-hd-3.0.0", + "spatialdata-visium-hd-4.0.1", + "spatialdata-xenium-rep1", +] + +# Demos that are registered as modules (so their rules can be run explicitly, +# e.g. `snakemake _all`) but are excluded from the default `all` target: +# - spatialdata-illumina-stratamap-mouse-kidney: the raw data must be downloaded manually +# (the Illumina demo dataset is behind a registration form). +# - spatialdata-maldi-msi-timstof-mouse-brain: Thyra can only read Bruker timsTOF .d data +# on Linux/Windows, and the raw download is ~19 GB. +MANUAL_DEMO_DIRS = [ + "spatialdata-illumina-stratamap-mouse-kidney", + "spatialdata-maldi-msi-timstof-mouse-brain", ] module combat_2022: @@ -58,6 +92,156 @@ module meta_2022_azimuth: use rule * from meta_2022_azimuth as meta_2022_azimuth_* +module spatialdata_visium: + snakefile: "spatialdata-visium/Snakefile" + prefix: "spatialdata-visium" + +use rule * from spatialdata_visium as spatialdata_visium_* + +module spatialdata_visium_hd_3_0_0: + snakefile: "spatialdata-visium-hd-3.0.0/Snakefile" + prefix: "spatialdata-visium-hd-3.0.0" + +use rule * from spatialdata_visium_hd_3_0_0 as spatialdata_visium_hd_3_0_0_* + +module spatialdata_visium_hd_4_0_1: + snakefile: "spatialdata-visium-hd-4.0.1/Snakefile" + prefix: "spatialdata-visium-hd-4.0.1" + +use rule * from spatialdata_visium_hd_4_0_1 as spatialdata_visium_hd_4_0_1_* + +module spatialdata_xenium_rep1: + snakefile: "spatialdata-xenium-rep1/Snakefile" + prefix: "spatialdata-xenium-rep1" + +use rule * from spatialdata_xenium_rep1 as spatialdata_xenium_rep1_* + +module anndata_chromium_pbmc: + snakefile: "anndata-chromium-pbmc/Snakefile" + prefix: "anndata-chromium-pbmc" + +use rule * from anndata_chromium_pbmc as anndata_chromium_pbmc_* + +module anndata_parse_pbmc: + snakefile: "anndata-parse-pbmc/Snakefile" + prefix: "anndata-parse-pbmc" + +use rule * from anndata_parse_pbmc as anndata_parse_pbmc_* + +module mudata_cite_seq_pbmc: + snakefile: "mudata-cite-seq-pbmc/Snakefile" + prefix: "mudata-cite-seq-pbmc" + +use rule * from mudata_cite_seq_pbmc as mudata_cite_seq_pbmc_* + +module mudata_pbmc_multiome_10x: + snakefile: "mudata-pbmc-multiome-10x/Snakefile" + prefix: "mudata-pbmc-multiome-10x" + +use rule * from mudata_pbmc_multiome_10x as mudata_pbmc_multiome_10x_* + +module mudata_snareseq2_lung_hubmap: + snakefile: "mudata-snareseq2-lung-hubmap/Snakefile" + prefix: "mudata-snareseq2-lung-hubmap" + +use rule * from mudata_snareseq2_lung_hubmap as mudata_snareseq2_lung_hubmap_* + +module ome_zarr_lightsheet_hubmap_spleen: + snakefile: "ome-zarr-lightsheet-hubmap-spleen/Snakefile" + prefix: "ome-zarr-lightsheet-hubmap-spleen" + +use rule * from ome_zarr_lightsheet_hubmap_spleen as ome_zarr_lightsheet_hubmap_spleen_* + +module spatialdata_atera_kidney: + snakefile: "spatialdata-atera-kidney/Snakefile" + prefix: "spatialdata-atera-kidney" + +use rule * from spatialdata_atera_kidney as spatialdata_atera_kidney_* + +module spatialdata_aviti24_teton_hela_tnfa: + snakefile: "spatialdata-aviti24-teton-hela-tnfa/Snakefile" + prefix: "spatialdata-aviti24-teton-hela-tnfa" + +use rule * from spatialdata_aviti24_teton_hela_tnfa as spatialdata_aviti24_teton_hela_tnfa_* + +module spatialdata_codex_hubmap_large_intestine: + snakefile: "spatialdata-codex-hubmap-large-intestine/Snakefile" + prefix: "spatialdata-codex-hubmap-large-intestine" + +use rule * from spatialdata_codex_hubmap_large_intestine as spatialdata_codex_hubmap_large_intestine_* + +module spatialdata_cosmx_nsclc: + snakefile: "spatialdata-cosmx-nsclc/Snakefile" + prefix: "spatialdata-cosmx-nsclc" + +use rule * from spatialdata_cosmx_nsclc as spatialdata_cosmx_nsclc_* + +module spatialdata_dbit_seq_mouse_embryo: + snakefile: "spatialdata-dbit-seq-mouse-embryo/Snakefile" + prefix: "spatialdata-dbit-seq-mouse-embryo" + +use rule * from spatialdata_dbit_seq_mouse_embryo as spatialdata_dbit_seq_mouse_embryo_* + +module spatialdata_geomx_mouse_embryo: + snakefile: "spatialdata-geomx-mouse-embryo/Snakefile" + prefix: "spatialdata-geomx-mouse-embryo" + +use rule * from spatialdata_geomx_mouse_embryo as spatialdata_geomx_mouse_embryo_* + +module spatialdata_illumina_stratamap_mouse_kidney: + snakefile: "spatialdata-illumina-stratamap-mouse-kidney/Snakefile" + prefix: "spatialdata-illumina-stratamap-mouse-kidney" + +use rule * from spatialdata_illumina_stratamap_mouse_kidney as spatialdata_illumina_stratamap_mouse_kidney_* + +module spatialdata_maldi_msi_timstof_mouse_brain: + snakefile: "spatialdata-maldi-msi-timstof-mouse-brain/Snakefile" + prefix: "spatialdata-maldi-msi-timstof-mouse-brain" + +use rule * from spatialdata_maldi_msi_timstof_mouse_brain as spatialdata_maldi_msi_timstof_mouse_brain_* + +module spatialdata_merfish_zhuang_abca_4: + snakefile: "spatialdata-merfish-zhuang-abca-4/Snakefile" + prefix: "spatialdata-merfish-zhuang-abca-4" + +use rule * from spatialdata_merfish_zhuang_abca_4 as spatialdata_merfish_zhuang_abca_4_* + +module spatialdata_merscope_mouse_brain: + snakefile: "spatialdata-merscope-mouse-brain/Snakefile" + prefix: "spatialdata-merscope-mouse-brain" + +use rule * from spatialdata_merscope_mouse_brain as spatialdata_merscope_mouse_brain_* + +module spatialdata_mibi_hubmap_uterus: + snakefile: "spatialdata-mibi-hubmap-uterus/Snakefile" + prefix: "spatialdata-mibi-hubmap-uterus" + +use rule * from spatialdata_mibi_hubmap_uterus as spatialdata_mibi_hubmap_uterus_* + +module spatialdata_slide_seq_hubmap_kidney: + snakefile: "spatialdata-slide-seq-hubmap-kidney/Snakefile" + prefix: "spatialdata-slide-seq-hubmap-kidney" + +use rule * from spatialdata_slide_seq_hubmap_kidney as spatialdata_slide_seq_hubmap_kidney_* + +module spatialdata_spatial_atac_rna_mouse_brain: + snakefile: "spatialdata-spatial-atac-rna-mouse-brain/Snakefile" + prefix: "spatialdata-spatial-atac-rna-mouse-brain" + +use rule * from spatialdata_spatial_atac_rna_mouse_brain as spatialdata_spatial_atac_rna_mouse_brain_* + +module spatialdata_spatial_cut_and_tag_rna_mouse_brain: + snakefile: "spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile" + prefix: "spatialdata-spatial-cut-and-tag-rna-mouse-brain" + +use rule * from spatialdata_spatial_cut_and_tag_rna_mouse_brain as spatialdata_spatial_cut_and_tag_rna_mouse_brain_* + +module spatialdata_stellaromics_pyxa_small: + snakefile: "spatialdata-stellaromics-pyxa-small/Snakefile" + prefix: "spatialdata-stellaromics-pyxa-small" + +use rule * from spatialdata_stellaromics_pyxa_small as spatialdata_stellaromics_pyxa_small_* + # End demo module list. @@ -108,7 +292,7 @@ rule fill_templates: params: demo_dirs=[ demo_dir - for demo_dir in DEMO_DIRS + for demo_dir in DEMO_DIRS + MANUAL_DEMO_DIRS if os.path.exists(os.path.join(demo_dir, "vitessce.template.json")) ], version=BUCKET_VERSION diff --git a/demos/anndata-chromium-pbmc/Snakefile b/demos/anndata-chromium-pbmc/Snakefile new file mode 100644 index 00000000..f12090f3 --- /dev/null +++ b/demos/anndata-chromium-pbmc/Snakefile @@ -0,0 +1,48 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# 10x Chromium single-cell gene expression (3' v3.1) of human PBMCs. +# Dataset: "PBMCs from a Healthy Donor: Whole Transcriptome Analysis" +# (Cell Ranger 4.0.0; the parent whole-transcriptome library of the +# 10x Targeted Gene Expression demo datasets), published by 10x Genomics. +# https://www.10xgenomics.com/datasets/pbm-cs-from-a-healthy-donor-whole-transcriptome-analysis-1-1-standard-4-0-0 +# License: 10x Genomics public datasets are released under CC BY 4.0. +# This is the same dataset used by the celldega Chromium tutorial: +# https://github.com/broadinstitute/celldega/blob/main/notebooks/Chromium_pre-process.ipynb +# The file below is the original 10x Genomics download (no mirror). +H5_URL = "https://cf.10xgenomics.com/samples/cell-exp/4.0.0/Parent_NGSC3_DI_PBMC/Parent_NGSC3_DI_PBMC_filtered_feature_bc_matrix.h5" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# QC, normalize, HVG, PCA, UMAP, Leiden, marker genes, then write AnnData-Zarr. +rule process: + input: + (RAW_DIR / "Parent_NGSC3_DI_PBMC_filtered_feature_bc_matrix.h5") + output: + directory(PROCESSED_DIR / "chromium_pbmc_healthy_donor.h5ad.zarr") + params: + script=(SRC_DIR / "process_chromium.py") + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + -o {output} + ''' + +# Download the Cell Ranger filtered feature-barcode matrix (HDF5, ~35 MB). +rule download_data: + output: + (RAW_DIR / "Parent_NGSC3_DI_PBMC_filtered_feature_bc_matrix.h5") + params: + file_url=H5_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/anndata-chromium-pbmc/config.yml b/demos/anndata-chromium-pbmc/config.yml new file mode 100644 index 00000000..fac38a2f --- /dev/null +++ b/demos/anndata-chromium-pbmc/config.yml @@ -0,0 +1,2 @@ +output: +- chromium_pbmc_healthy_donor.h5ad.zarr diff --git a/demos/anndata-chromium-pbmc/src/process_chromium.py b/demos/anndata-chromium-pbmc/src/process_chromium.py new file mode 100644 index 00000000..1ecc3b3b --- /dev/null +++ b/demos/anndata-chromium-pbmc/src/process_chromium.py @@ -0,0 +1,93 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata==0.13.4", +# "scanpy==1.12.6", +# "igraph==1.0.0", +# "leidenalg==0.12.0", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +""" +Basic Scanpy processing of a 10x Chromium filtered_feature_bc_matrix.h5 file, +following https://github.com/broadinstitute/celldega/blob/main/notebooks/Chromium_pre-process.ipynb +(QC, normalization, HVG selection, PCA, UMAP, Leiden clustering) +plus marker gene detection. The result is written as an AnnData-Zarr store +optimized for Vitessce. +""" +import argparse + +import numpy as np +import scanpy as sc +from vitessce.data_utils import ( + to_dense, + to_uint8, + sort_var_axis, + optimize_adata, +) + +N_MARKERS_PER_CLUSTER = 5 + + +def process(input_path, output_path): + adata = sc.read_10x_h5(input_path) + adata.var_names_make_unique() + + # QC metrics. Mitochondrial genes are "MT-" for human. + adata.var["mt"] = adata.var_names.str.startswith("MT-") + adata.var["ribo"] = adata.var_names.str.startswith(("RPS", "RPL")) + sc.pp.calculate_qc_metrics(adata, qc_vars=["mt", "ribo"], inplace=True, log1p=False) + sc.pp.filter_cells(adata, min_genes=200) + sc.pp.filter_genes(adata, min_cells=3) + adata = adata[adata.obs["pct_counts_mt"] < 20].copy() + + # Normalize to median total counts and log-transform. + sc.pp.normalize_total(adata) + sc.pp.log1p(adata) + sc.pp.highly_variable_genes(adata, n_top_genes=2000) + + sc.tl.pca(adata, mask_var="highly_variable") + sc.pp.neighbors(adata) + sc.tl.umap(adata) + sc.tl.leiden(adata, flavor="igraph", n_iterations=2, resolution=0.5, key_added="leiden") + adata.obs["leiden"] = adata.obs["leiden"].astype(str).map(lambda c: f"Cluster {c}").astype("category") + + # Marker genes per cluster. + sc.tl.rank_genes_groups(adata, groupby="leiden", method="wilcoxon") + markers = sc.get.rank_genes_groups_df(adata, group=None) + markers = markers.sort_values(["group", "scores"], ascending=[True, False]) + top_markers = markers.groupby("group", observed=True).head(N_MARKERS_PER_CLUSTER)["names"].unique() + adata.var["is_marker"] = adata.var_names.isin(top_markers) + + # Store an expression matrix with only the highly variable and marker genes. + adata = adata[:, adata.var["highly_variable"] | adata.var["is_marker"]].copy() + adata.X = np.asarray(to_dense(adata.X), dtype=np.float32) + + # Reorder the genes axis after hierarchical clustering. + leaf_list = sort_var_axis(adata.X, adata.var.index.values) + adata = adata[:, leaf_list].copy() + + # Store expression matrix as uint8 (scaled per gene) for the heatmap. + adata.layers["X_uint8"] = to_uint8(adata.X, norm_along="var") + + adata = optimize_adata( + adata, + obs_cols=["leiden", "n_genes_by_counts", "total_counts", "pct_counts_mt"], + obsm_keys=["X_umap", "X_pca"], + var_cols=["gene_ids", "highly_variable", "is_marker"], + layer_keys=["X_uint8"], + ) + # Chunk X by gene so that Vitessce can load one gene column at a time. + adata.write_zarr(output_path, chunks=(adata.n_obs, 10)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-i", "--input", type=str, required=True, help="Input 10x filtered_feature_bc_matrix.h5 file") + parser.add_argument("-o", "--output", type=str, required=True, help="Output AnnData-Zarr store") + args = parser.parse_args() + process(args.input, args.output) diff --git a/demos/anndata-chromium-pbmc/vitessce.template.json b/demos/anndata-chromium-pbmc/vitessce.template.json new file mode 100644 index 00000000..cf8755c0 --- /dev/null +++ b/demos/anndata-chromium-pbmc/vitessce.template.json @@ -0,0 +1,111 @@ +{ + "version": "1.0.15", + "name": "10x Chromium PBMCs from a Healthy Donor", + "description": "10x Genomics Chromium single-cell gene expression (3' v3.1) of ~10k PBMCs from a healthy donor. Processed with Scanpy (QC, normalization, HVG, PCA, UMAP, Leiden clustering, marker genes).", + "datasets": [{ + "uid": "chromium-pbmc", + "name": "Chromium PBMC", + "files": [{ + "fileType": "anndata.zarr", + "url": "{{ base_url }}/chromium_pbmc_healthy_donor.h5ad.zarr", + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression", + "embeddingType": "UMAP" + }, + "options": { + "obsFeatureMatrix": { + "path": "X" + }, + "obsEmbedding": { + "path": "obsm/X_umap" + }, + "obsSets": [{ + "name": "Leiden Cluster", + "path": "obs/leiden" + }] + } + }] + }], + "initStrategy": "auto", + "coordinationSpace": { + "embeddingType": { + "UMAP": "UMAP" + }, + "obsType": { + "A": "cell" + }, + "featureType": { + "A": "gene" + }, + "featureValueType": { + "A": "expression" + } + }, + "layout": [ + { + "component": "scatterplot", + "h": 6, "w": 5, "x": 0, "y": 0, + "coordinationScopes": { + "embeddingType": "UMAP", + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "uid": "A" + }, + { + "component": "obsSets", + "h": 3, "w": 3, "x": 5, "y": 0, + "coordinationScopes": { + "obsType": "A" + }, + "uid": "B" + }, + { + "component": "obsSetSizes", + "h": 3, "w": 4, "x": 8, "y": 0, + "coordinationScopes": { + "obsType": "A" + }, + "uid": "C" + }, + { + "component": "featureList", + "h": 3, "w": 3, "x": 5, "y": 3, + "coordinationScopes": { + "featureType": "A" + }, + "uid": "D" + }, + { + "component": "obsSetFeatureValueDistribution", + "h": 3, "w": 4, "x": 8, "y": 3, + "coordinationScopes": { + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "uid": "E" + }, + { + "component": "heatmap", + "h": 4, "w": 9, "x": 0, "y": 6, + "coordinationScopes": { + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "props": { + "transpose": true + }, + "uid": "F" + }, + { + "component": "description", + "h": 4, "w": 3, "x": 9, "y": 6, + "uid": "G" + } + ] +} diff --git a/demos/anndata-parse-pbmc/Snakefile b/demos/anndata-parse-pbmc/Snakefile new file mode 100644 index 00000000..2c75c685 --- /dev/null +++ b/demos/anndata-parse-pbmc/Snakefile @@ -0,0 +1,56 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Parse Biosciences Evercode Whole Transcriptome (split-pool combinatorial +# barcoding) of human PBMCs from four healthy donors (D1-D4), ~10k cells. +# Dataset: "Performance of Evercode WT in human immune cells (PBMCs)", WT v1 files +# (output of the Parse split-pipe: DGE.mtx, all_genes.csv, cell_metadata.csv). +# https://www.parsebiosciences.com/datasets/pbmc/performance-of-evercode-wt-in-human-immune-cells-pbmcs/ +# Related preprint: https://doi.org/10.1101/2022.08.27.505512 +# License: CC BY 4.0 (per the Parse dataset page). +# The files below are the original Parse Biosciences CDN downloads (no mirror, +# no form/login required). Newer Parse PBMC datasets (WT v3/v4, 1M PBMC, 10M PBMC) +# are only available via the Trailmaker platform (free account) or a contact form. +PARSE_BASE_URL = "https://cdn.parsebiosciences.com/pbmc/v1" +RAW_FILES = ["DGE.mtx", "all_genes.csv", "cell_metadata.csv"] + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# QC, normalize, HVG, PCA, UMAP, Leiden, marker genes, then write AnnData-Zarr. +rule process: + input: + mtx=(RAW_DIR / "DGE.mtx"), + genes=(RAW_DIR / "all_genes.csv"), + cells=(RAW_DIR / "cell_metadata.csv") + output: + directory(PROCESSED_DIR / "parse_pbmc_wt_v1.h5ad.zarr") + params: + script=(SRC_DIR / "process_parse.py") + shell: + ''' + uv run --script {params.script} \ + -m {input.mtx} \ + -g {input.genes} \ + -c {input.cells} \ + -o {output} + ''' + +# Download the split-pipe output files (DGE.mtx is ~200 MB). +rule download_data: + output: + (RAW_DIR / "{filename}") + wildcard_constraints: + filename="|".join(RAW_FILES).replace(".", r"\.") + params: + file_url=lambda w: f"{PARSE_BASE_URL}/{w.filename}" + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/anndata-parse-pbmc/config.yml b/demos/anndata-parse-pbmc/config.yml new file mode 100644 index 00000000..b0c71c9e --- /dev/null +++ b/demos/anndata-parse-pbmc/config.yml @@ -0,0 +1,2 @@ +output: +- parse_pbmc_wt_v1.h5ad.zarr diff --git a/demos/anndata-parse-pbmc/src/process_parse.py b/demos/anndata-parse-pbmc/src/process_parse.py new file mode 100644 index 00000000..e74140f3 --- /dev/null +++ b/demos/anndata-parse-pbmc/src/process_parse.py @@ -0,0 +1,116 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata==0.13.4", +# "scanpy==1.12.6", +# "igraph==1.0.0", +# "leidenalg==0.12.0", +# "pandas", +# "scipy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +""" +Load the output of the Parse Biosciences split-pipe (DGE.mtx, all_genes.csv, +cell_metadata.csv), following the Parse Scanpy tutorial +(https://support.parsebiosciences.com/hc/en-us/articles/360052794312-Scanpy-Tutorial-65k-PBMCs), +then run basic Scanpy processing (QC, normalization, HVG selection, PCA, UMAP, +Leiden clustering, marker genes). The result is written as an AnnData-Zarr store +optimized for Vitessce. +""" +import argparse + +import anndata as ad +import numpy as np +import pandas as pd +import scanpy as sc +from scipy.io import mmread +from vitessce.data_utils import ( + to_dense, + to_uint8, + sort_var_axis, + optimize_adata, +) + +N_MARKERS_PER_CLUSTER = 5 + + +def read_parse(mtx_path, genes_path, cells_path): + # In split-pipe output, the DGE.mtx matrix is cells x genes. + X = mmread(mtx_path).tocsr().astype(np.float32) + obs = pd.read_csv(cells_path, index_col="bc_wells") + obs.index = obs.index.astype(str) + obs.index.name = None + var = pd.read_csv(genes_path) + var = var.set_index("gene_name") + var.index = var.index.astype(str) + var.index.name = None + adata = ad.AnnData(X=X, obs=obs, var=var) + adata.var_names_make_unique() + return adata + + +def process(mtx_path, genes_path, cells_path, output_path): + adata = read_parse(mtx_path, genes_path, cells_path) + adata.obs["sample"] = adata.obs["sample"].astype("category") + + # QC metrics. Mitochondrial genes are "MT-" for human. + adata.var["mt"] = adata.var_names.str.startswith("MT-") + adata.var["ribo"] = adata.var_names.str.startswith(("RPS", "RPL")) + sc.pp.calculate_qc_metrics(adata, qc_vars=["mt", "ribo"], inplace=True, log1p=False) + sc.pp.filter_cells(adata, min_genes=200) + sc.pp.filter_genes(adata, min_cells=3) + adata = adata[adata.obs["pct_counts_mt"] < 20].copy() + + # Normalize to median total counts and log-transform. + sc.pp.normalize_total(adata) + sc.pp.log1p(adata) + sc.pp.highly_variable_genes(adata, n_top_genes=2000) + + sc.tl.pca(adata, mask_var="highly_variable") + sc.pp.neighbors(adata) + sc.tl.umap(adata) + sc.tl.leiden(adata, flavor="igraph", n_iterations=2, resolution=0.5, key_added="leiden") + adata.obs["leiden"] = adata.obs["leiden"].astype(str).map(lambda c: f"Cluster {c}").astype("category") + + # Marker genes per cluster. + sc.tl.rank_genes_groups(adata, groupby="leiden", method="wilcoxon") + markers = sc.get.rank_genes_groups_df(adata, group=None) + markers = markers.sort_values(["group", "scores"], ascending=[True, False]) + top_markers = markers.groupby("group", observed=True).head(N_MARKERS_PER_CLUSTER)["names"].unique() + adata.var["is_marker"] = adata.var_names.isin(top_markers) + + # Store an expression matrix with only the highly variable and marker genes. + adata = adata[:, adata.var["highly_variable"] | adata.var["is_marker"]].copy() + adata.X = np.asarray(to_dense(adata.X), dtype=np.float32) + + # Reorder the genes axis after hierarchical clustering. + leaf_list = sort_var_axis(adata.X, adata.var.index.values) + adata = adata[:, leaf_list].copy() + + # Store expression matrix as uint8 (scaled per gene) for the heatmap. + adata.layers["X_uint8"] = to_uint8(adata.X, norm_along="var") + + adata = optimize_adata( + adata, + obs_cols=["leiden", "sample", "n_genes_by_counts", "total_counts", "pct_counts_mt"], + obsm_keys=["X_umap", "X_pca"], + var_cols=["gene_id", "highly_variable", "is_marker"], + layer_keys=["X_uint8"], + ) + # Chunk X by gene so that Vitessce can load one gene column at a time. + adata.write_zarr(output_path, chunks=(adata.n_obs, 10)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-m", "--mtx", type=str, required=True, help="Input DGE.mtx file (cells x genes)") + parser.add_argument("-g", "--genes", type=str, required=True, help="Input all_genes.csv file") + parser.add_argument("-c", "--cells", type=str, required=True, help="Input cell_metadata.csv file") + parser.add_argument("-o", "--output", type=str, required=True, help="Output AnnData-Zarr store") + args = parser.parse_args() + process(args.mtx, args.genes, args.cells, args.output) diff --git a/demos/anndata-parse-pbmc/vitessce.template.json b/demos/anndata-parse-pbmc/vitessce.template.json new file mode 100644 index 00000000..91faae13 --- /dev/null +++ b/demos/anndata-parse-pbmc/vitessce.template.json @@ -0,0 +1,117 @@ +{ + "version": "1.0.15", + "name": "Parse Biosciences Evercode WT PBMCs", + "description": "Parse Biosciences Evercode Whole Transcriptome (WT v1, split-pool combinatorial barcoding) of ~10k PBMCs from four healthy donors. Processed with Scanpy (QC, normalization, HVG, PCA, UMAP, Leiden clustering, marker genes).", + "datasets": [{ + "uid": "parse-pbmc", + "name": "Parse PBMC", + "files": [{ + "fileType": "anndata.zarr", + "url": "{{ base_url }}/parse_pbmc_wt_v1.h5ad.zarr", + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression", + "embeddingType": "UMAP" + }, + "options": { + "obsFeatureMatrix": { + "path": "X" + }, + "obsEmbedding": { + "path": "obsm/X_umap" + }, + "obsSets": [ + { + "name": "Leiden Cluster", + "path": "obs/leiden" + }, + { + "name": "Donor", + "path": "obs/sample" + } + ] + } + }] + }], + "initStrategy": "auto", + "coordinationSpace": { + "embeddingType": { + "UMAP": "UMAP" + }, + "obsType": { + "A": "cell" + }, + "featureType": { + "A": "gene" + }, + "featureValueType": { + "A": "expression" + } + }, + "layout": [ + { + "component": "scatterplot", + "h": 6, "w": 5, "x": 0, "y": 0, + "coordinationScopes": { + "embeddingType": "UMAP", + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "uid": "A" + }, + { + "component": "obsSets", + "h": 3, "w": 3, "x": 5, "y": 0, + "coordinationScopes": { + "obsType": "A" + }, + "uid": "B" + }, + { + "component": "obsSetSizes", + "h": 3, "w": 4, "x": 8, "y": 0, + "coordinationScopes": { + "obsType": "A" + }, + "uid": "C" + }, + { + "component": "featureList", + "h": 3, "w": 3, "x": 5, "y": 3, + "coordinationScopes": { + "featureType": "A" + }, + "uid": "D" + }, + { + "component": "obsSetFeatureValueDistribution", + "h": 3, "w": 4, "x": 8, "y": 3, + "coordinationScopes": { + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "uid": "E" + }, + { + "component": "heatmap", + "h": 4, "w": 9, "x": 0, "y": 6, + "coordinationScopes": { + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "props": { + "transpose": true + }, + "uid": "F" + }, + { + "component": "description", + "h": 4, "w": 3, "x": 9, "y": 6, + "uid": "G" + } + ] +} diff --git a/demos/common.smk b/demos/common.smk index 8208502e..8ade0574 100644 --- a/demos/common.smk +++ b/demos/common.smk @@ -9,6 +9,10 @@ DATA_DIR = Path("data") RAW_DIR = DATA_DIR / "raw" PROCESSED_DIR = DATA_DIR / "processed" +# Base URL for the SpatialData example datasets. +# Reference: https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html +SPATIALDATA_SANDBOX_URL = "https://exampledata.scverse.org/spatialdata/spatialdata-sandbox" + # Helper functions def str2bool(v): diff --git a/demos/mudata-cite-seq-pbmc/Snakefile b/demos/mudata-cite-seq-pbmc/Snakefile new file mode 100644 index 00000000..a07fee18 --- /dev/null +++ b/demos/mudata-cite-seq-pbmc/Snakefile @@ -0,0 +1,52 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# CITE-seq-style paired RNA + surface protein (antibody-derived tag) profiling +# of human PBMCs: four probe-barcoded PBMC samples stained with the TotalSeq-C +# Human Universal Cocktail v2.0 and profiled with 10x GEM-X Flex v2 +# (Cell Ranger 10.0.0, 12,242 cells, 18,132 genes, 184 antibodies). +# Dataset: "16k Human PBMCs, TotalSeq-C 4-plex (Flex v2)", 10x Genomics. +# https://www.10xgenomics.com/datasets/Flexv2_16k_Human_PBMCs_TotalseqC_4plex +# License: CC BY 4.0. +# The file below is the original 10x Genomics download ("Multiplex" filtered +# feature-barcode matrix with the called cells of all four samples). +# This is the same source data as the Celldega mirror (pre-built MuData h5mu): +# https://huggingface.co/datasets/broadinstitute/Celldega_Supporting_Data/blob/main/Flex_16k_PBMC_CITE-seq/Flex_16k_PBMC_CITE-seq.h5mu +# whose pre-processing notebook is the basis for the RNA/protein split and +# probe-barcode-to-sample assignment in src/process_cite_seq.py. +H5_URL = "https://cf.10xgenomics.com/samples/cell-exp/10.0.0/16k_Human_PBMCs_TotalseqC_4plex_Multiplex/16k_Human_PBMCs_TotalseqC_4plex_Multiplex_filtered_feature_bc_matrix.h5" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Split into RNA and protein modalities, process each, and write MuData-Zarr. +rule process: + input: + (RAW_DIR / "16k_Human_PBMCs_TotalseqC_4plex_Multiplex_filtered_feature_bc_matrix.h5") + output: + directory(PROCESSED_DIR / "flex_pbmc_cite_seq.h5mu.zarr") + params: + script=(SRC_DIR / "process_cite_seq.py") + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + -o {output} + ''' + +# Download the Cell Ranger filtered feature-barcode matrix (HDF5, ~60 MB). +rule download_data: + output: + (RAW_DIR / "16k_Human_PBMCs_TotalseqC_4plex_Multiplex_filtered_feature_bc_matrix.h5") + params: + file_url=H5_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/mudata-cite-seq-pbmc/config.yml b/demos/mudata-cite-seq-pbmc/config.yml new file mode 100644 index 00000000..67668cd8 --- /dev/null +++ b/demos/mudata-cite-seq-pbmc/config.yml @@ -0,0 +1,2 @@ +output: +- flex_pbmc_cite_seq.h5mu.zarr diff --git a/demos/mudata-cite-seq-pbmc/src/process_cite_seq.py b/demos/mudata-cite-seq-pbmc/src/process_cite_seq.py new file mode 100644 index 00000000..dd1249be --- /dev/null +++ b/demos/mudata-cite-seq-pbmc/src/process_cite_seq.py @@ -0,0 +1,172 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata==0.13.4", +# "mudata==0.4.1", +# "scanpy==1.12.6", +# "igraph==1.0.0", +# "leidenalg==0.12.0", +# "pandas", +# "scipy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +""" +Build a MuData object (modalities "rna" and "prot") from a 10x Genomics +Cell Ranger filtered_feature_bc_matrix.h5 file containing both +"Gene Expression" and "Antibody Capture" features (CITE-seq-style +antibody-derived tags), following +https://huggingface.co/datasets/broadinstitute/Celldega_Supporting_Data/blob/main/Flex_16k_PBMC_CITE-seq/Flex_16k_PBMC_CITE-seq_Pre-process.ipynb + +Then run basic processing: +- RNA: QC, normalization, HVG selection, PCA, UMAP, Leiden clustering, marker genes. +- Protein: CLR normalization, PCA, UMAP (excluding isotype controls). + +The result is written as a MuData-Zarr store, so that Vitessce can load each +modality as an AnnData-Zarr store via the sub-paths mod/rna and mod/prot. +""" +import argparse +import warnings + +import mudata as md +import numpy as np +import pandas as pd +import scanpy as sc +from vitessce.data_utils import ( + to_dense, + to_uint8, + sort_var_axis, + optimize_adata, +) + +N_MARKERS_PER_CLUSTER = 5 + +# Flex barcodes are the 16-nt cell barcode + the 10-nt probe barcode of the sample. +# Probe barcode -> sample name, from the per-sample outputs of the same 10x run +# (as listed in the Celldega pre-processing notebook referenced above). +PROBE_BARCODES = { + "AGCCCGAACT": "C-A01", + "AGCCCTGCAT": "C-B01", + "ATGACACGCT": "C-C01", + "GATATCTGGA": "C-D01", +} + + +def clr(X): + """ + Centered log-ratio normalization of ADT counts, computed per protein across cells + (as in Seurat NormalizeData(normalization.method = "CLR", margin = 2)). + """ + X = np.asarray(to_dense(X), dtype=np.float64) + log_X = np.log1p(X) + geo_mean = np.exp(log_X.mean(axis=0, keepdims=True)) + return np.log1p(X / geo_mean).astype(np.float32) + + +def process_rna(rna): + rna.var["mt"] = rna.var_names.str.startswith("MT-") + sc.pp.calculate_qc_metrics(rna, qc_vars=["mt"], inplace=True, log1p=False) + sc.pp.filter_genes(rna, min_cells=3) + sc.pp.normalize_total(rna) + sc.pp.log1p(rna) + sc.pp.highly_variable_genes(rna, n_top_genes=2000) + sc.tl.pca(rna, mask_var="highly_variable") + sc.pp.neighbors(rna) + sc.tl.umap(rna) + sc.tl.leiden(rna, flavor="igraph", n_iterations=2, resolution=0.5, key_added="leiden") + rna.obs["leiden"] = rna.obs["leiden"].astype(str).map(lambda c: f"Cluster {c}").astype("category") + + # Marker genes per cluster. + sc.tl.rank_genes_groups(rna, groupby="leiden", method="wilcoxon") + markers = sc.get.rank_genes_groups_df(rna, group=None) + markers = markers.sort_values(["group", "scores"], ascending=[True, False]) + top_markers = markers.groupby("group", observed=True).head(N_MARKERS_PER_CLUSTER)["names"].unique() + rna.var["is_marker"] = rna.var_names.isin(top_markers) + + # Store an expression matrix with only the highly variable and marker genes. + rna = rna[:, rna.var["highly_variable"] | rna.var["is_marker"]].copy() + rna.X = np.asarray(to_dense(rna.X), dtype=np.float32) + leaf_list = sort_var_axis(rna.X, rna.var.index.values) + rna = rna[:, leaf_list].copy() + rna.layers["X_uint8"] = to_uint8(rna.X, norm_along="var") + return rna + + +def process_prot(prot): + prot.X = clr(prot.X) + prot.var["highly_variable"] = ~prot.var["isotype_control"] + sc.tl.pca(prot, mask_var="highly_variable", n_comps=30) + sc.pp.neighbors(prot) + sc.tl.umap(prot) + prot.layers["X_uint8"] = to_uint8(prot.X.copy(), norm_along="var") + return prot + + +def process(input_path, output_path): + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message="Variable names are not unique") + adata = sc.read_10x_h5(input_path, gex_only=False) + + adata.obs["sample"] = pd.Categorical(adata.obs_names.str[16:26].map(PROBE_BARCODES)) + + is_protein = (adata.var["feature_types"] == "Antibody Capture").to_numpy() + rna = adata[:, ~is_protein].copy() + prot = adata[:, is_protein].copy() + rna.var_names_make_unique() + + # Proteins keep their TotalSeq antibody name (unique) as the index, + # with the antibody target in var["target"]. + prot.var["target"] = prot.var["gene_ids"].astype(str) + prot.var["isotype_control"] = prot.var_names.str.contains("isotype", case=False) + + # Cell QC based on RNA; apply the same cell filter to both modalities. + sc.pp.calculate_qc_metrics(rna, inplace=True, log1p=False) + keep = rna.obs["n_genes_by_counts"].to_numpy() >= 200 + rna = rna[keep].copy() + prot = prot[keep].copy() + + rna = process_rna(rna) + prot = process_prot(prot) + + # Share the RNA-based clusters and UMAP with the protein modality, + # so that both modalities can be visualized on the same embedding. + prot.obs["leiden"] = rna.obs["leiden"] + prot.obsm["X_umap_rna"] = rna.obsm["X_umap"] + rna.obsm["X_umap_prot"] = prot.obsm["X_umap"] + + obs_cols = ["leiden", "sample"] + rna = optimize_adata( + rna, + obs_cols=obs_cols + ["n_genes_by_counts", "total_counts", "pct_counts_mt"], + obsm_keys=["X_umap", "X_umap_prot", "X_pca"], + var_cols=["gene_ids", "highly_variable", "is_marker"], + varm_keys=[], + layer_keys=["X_uint8"], + ) + prot = optimize_adata( + prot, + obs_cols=obs_cols, + obsm_keys=["X_umap", "X_umap_rna"], + var_cols=["target", "isotype_control"], + varm_keys=[], + layer_keys=["X_uint8"], + to_dense_X=True, + ) + prot.X = np.asarray(prot.X, dtype=np.float32) + + mdata = md.MuData({"rna": rna, "prot": prot}) + mdata.obs = rna.obs[obs_cols].copy() + # Chunk X by feature so that Vitessce can load one gene/protein column at a time. + mdata.write_zarr(output_path, chunks=(mdata.n_obs, 10)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-i", "--input", type=str, required=True, help="Input 10x filtered_feature_bc_matrix.h5 (GEX + Antibody Capture)") + parser.add_argument("-o", "--output", type=str, required=True, help="Output MuData-Zarr store") + args = parser.parse_args() + process(args.input, args.output) diff --git a/demos/mudata-cite-seq-pbmc/vitessce.template.json b/demos/mudata-cite-seq-pbmc/vitessce.template.json new file mode 100644 index 00000000..0e95e2cf --- /dev/null +++ b/demos/mudata-cite-seq-pbmc/vitessce.template.json @@ -0,0 +1,185 @@ +{ + "version": "1.0.15", + "name": "10x Flex v2 PBMC CITE-seq (TotalSeq-C)", + "description": "Paired gene expression and surface protein (184 TotalSeq-C antibodies) of ~12k human PBMCs from four samples, profiled with 10x GEM-X Flex v2. Stored as MuData-Zarr; each modality (mod/rna, mod/prot) is loaded as AnnData-Zarr. Leiden clusters and UMAP computed from RNA; protein values are CLR-normalized.", + "datasets": [{ + "uid": "flex-cite-seq-pbmc", + "name": "Flex CITE-seq PBMC", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/flex_pbmc_cite_seq.h5mu.zarr/mod/rna", + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression", + "embeddingType": "UMAP" + }, + "options": { + "obsFeatureMatrix": { + "path": "X" + }, + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "embeddingType": "UMAP" + }, + { + "path": "obsm/X_umap_prot", + "embeddingType": "UMAP (protein)" + } + ], + "obsSets": [ + { + "name": "Leiden Cluster (RNA)", + "path": "obs/leiden" + }, + { + "name": "Sample", + "path": "obs/sample" + } + ] + } + }, + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/flex_pbmc_cite_seq.h5mu.zarr/mod/prot", + "coordinationValues": { + "obsType": "cell", + "featureType": "protein", + "featureValueType": "abundance" + }, + "options": { + "obsFeatureMatrix": { + "path": "X" + }, + "featureLabels": { + "path": "var/target" + } + } + } + ] + }], + "initStrategy": "auto", + "coordinationSpace": { + "embeddingType": { + "RNA": "UMAP", + "PROT": "UMAP (protein)" + }, + "obsType": { + "A": "cell" + }, + "featureType": { + "RNA": "gene", + "PROT": "protein" + }, + "featureValueType": { + "RNA": "expression", + "PROT": "abundance" + }, + "featureSelection": { + "RNA": null, + "PROT": null + }, + "obsColorEncoding": { + "RNA": "cellSetSelection", + "PROT": "cellSetSelection" + } + }, + "layout": [ + { + "component": "scatterplot", + "h": 5, "w": 4, "x": 0, "y": 0, + "coordinationScopes": { + "embeddingType": "RNA", + "obsType": "A", + "featureType": "RNA", + "featureValueType": "RNA", + "featureSelection": "RNA", + "obsColorEncoding": "RNA" + }, + "props": { + "title": "UMAP (RNA), colored by gene" + }, + "uid": "A" + }, + { + "component": "scatterplot", + "h": 5, "w": 4, "x": 4, "y": 0, + "coordinationScopes": { + "embeddingType": "RNA", + "obsType": "A", + "featureType": "PROT", + "featureValueType": "PROT", + "featureSelection": "PROT", + "obsColorEncoding": "PROT" + }, + "props": { + "title": "UMAP (RNA), colored by protein" + }, + "uid": "B" + }, + { + "component": "obsSets", + "h": 5, "w": 4, "x": 8, "y": 0, + "coordinationScopes": { + "obsType": "A" + }, + "uid": "C" + }, + { + "component": "featureList", + "h": 4, "w": 2, "x": 0, "y": 5, + "coordinationScopes": { + "featureType": "RNA", + "featureSelection": "RNA", + "obsColorEncoding": "RNA" + }, + "props": { + "title": "Genes" + }, + "uid": "D" + }, + { + "component": "featureList", + "h": 4, "w": 2, "x": 2, "y": 5, + "coordinationScopes": { + "featureType": "PROT", + "featureSelection": "PROT", + "obsColorEncoding": "PROT" + }, + "props": { + "title": "Proteins" + }, + "uid": "E" + }, + { + "component": "heatmap", + "h": 4, "w": 8, "x": 4, "y": 5, + "coordinationScopes": { + "obsType": "A", + "featureType": "PROT", + "featureValueType": "PROT", + "featureSelection": "PROT", + "obsColorEncoding": "PROT" + }, + "props": { + "transpose": true + }, + "uid": "F" + }, + { + "component": "obsSetSizes", + "h": 3, "w": 6, "x": 0, "y": 9, + "coordinationScopes": { + "obsType": "A" + }, + "uid": "G" + }, + { + "component": "description", + "h": 3, "w": 6, "x": 6, "y": 9, + "uid": "H" + } + ] +} diff --git a/demos/mudata-pbmc-multiome-10x/Snakefile b/demos/mudata-pbmc-multiome-10x/Snakefile new file mode 100644 index 00000000..56c7db81 --- /dev/null +++ b/demos/mudata-pbmc-multiome-10x/Snakefile @@ -0,0 +1,62 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# 10x Genomics Single Cell Multiome ATAC + Gene Expression: +# "PBMC from a Healthy Donor - Granulocytes Removed Through Cell Sorting (10k)", +# processed with Cell Ranger ARC 2.0.0. +# - Dataset page: https://www.10xgenomics.com/datasets/pbmc-from-a-healthy-donor-granulocytes-removed-through-cell-sorting-10-k-1-standard-2-0-0 +# - Files are downloaded directly from the 10x Genomics CDN (no login required). +# - License: Creative Commons Attribution 4.0 (CC BY 4.0), per 10x Genomics' public datasets terms. +# - 10x does not publish cell type labels for this dataset, so clusters/cell types are computed here. +# Processing was inspired by https://github.com/MicTott/spatialscape-examples/tree/main/pbmc-multiome +# The ATAC fragments file (2.4 GB) is not used; the pseudobulk genomic profiles are +# computed from the cell-by-peak matrix instead. +BASE_URL = "https://cf.10xgenomics.com/samples/cell-arc/2.0.0/pbmc_granulocyte_sorted_10k/pbmc_granulocyte_sorted_10k" +PREFIX = "pbmc_granulocyte_sorted_10k" +RAW_FILES = [ + "filtered_feature_bc_matrix.h5", + "atac_peak_annotation.tsv", + "per_barcode_metrics.csv", +] + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# RNA + ATAC processing, to a MuData-Zarr store and a genomic-profiles (multivec) Zarr store. +rule process_multiome: + input: + h5=(RAW_DIR / f"{PREFIX}_filtered_feature_bc_matrix.h5"), + peak_annotation=(RAW_DIR / f"{PREFIX}_atac_peak_annotation.tsv"), + metrics=(RAW_DIR / f"{PREFIX}_per_barcode_metrics.csv"), + output: + mudata=directory(PROCESSED_DIR / "pbmc_multiome_10x.h5mu.zarr"), + profiles=directory(PROCESSED_DIR / "pbmc_multiome_10x.genomic-profiles.zarr"), + params: + script=(SRC_DIR / "process_multiome.py") + shell: + ''' + uv run --script {params.script} \ + --input_h5 {input.h5} \ + --input_peak_annotation {input.peak_annotation} \ + --input_metrics {input.metrics} \ + --output_mudata {output.mudata} \ + --output_profiles {output.profiles} + ''' + +rule download_data: + output: + (RAW_DIR / (PREFIX + "_{filename}")) + wildcard_constraints: + filename="|".join([f.replace(".", r"\.") for f in RAW_FILES]) + params: + file_url=lambda w: f"{BASE_URL}_{w.filename}" + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/mudata-pbmc-multiome-10x/config.yml b/demos/mudata-pbmc-multiome-10x/config.yml new file mode 100644 index 00000000..d56b0471 --- /dev/null +++ b/demos/mudata-pbmc-multiome-10x/config.yml @@ -0,0 +1,3 @@ +output: +- pbmc_multiome_10x.h5mu.zarr +- pbmc_multiome_10x.genomic-profiles.zarr diff --git a/demos/mudata-pbmc-multiome-10x/src/process_multiome.py b/demos/mudata-pbmc-multiome-10x/src/process_multiome.py new file mode 100644 index 00000000..d3bdb6dc --- /dev/null +++ b/demos/mudata-pbmc-multiome-10x/src/process_multiome.py @@ -0,0 +1,237 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "scanpy==1.12.6", +# "anndata==0.13.4", +# "mudata==0.4.1", +# "scikit-learn==1.9.1", +# "igraph", +# "leidenalg", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Process the 10x Genomics PBMC Multiome (RNA + ATAC) dataset. + +Inputs (Cell Ranger ARC 2.0.0 outputs): + - filtered_feature_bc_matrix.h5 (genes and peaks for the same nuclei) + - atac_peak_annotation.tsv (peak -> nearest gene) + - per_barcode_metrics.csv (ATAC QC metrics) + +Outputs: + - A MuData-Zarr store with two modalities (sharing the same obs index/order): + mod/rna: log-normalized gene expression (dense, chunked), RNA UMAP, Leiden clusters, cell types. + mod/atac: gene activity scores computed from the peak counts (dense, chunked), + ATAC UMAP (TF-IDF + LSI on peaks), ATAC Leiden clusters. + The top-level obs/obsm contain the cell type labels and both UMAPs. + - A genomic-profiles (multivec) Zarr store with one pseudobulk ATAC + accessibility track per cell type, computed from the peak counts. + +Processing loosely follows +https://github.com/MicTott/spatialscape-examples/blob/main/pbmc-multiome/prepare.py +""" +import argparse + +import anndata as ad +import mudata as md +import numpy as np +import pandas as pd +import scanpy as sc +import scipy.sparse as sp +from sklearn.decomposition import TruncatedSVD +from vitessce.data_utils import adata_to_multivec_zarr, optimize_adata + +# Marker gene sets used to name the RNA Leiden clusters. +MARKERS = { + "CD4 T": ["IL7R", "CD4", "CCR7", "LTB", "MAL", "TCF7"], + "CD8 T": ["CD8A", "CD8B", "GZMK", "CCL5", "GZMH"], + "NK": ["NKG7", "GNLY", "KLRD1", "KLRF1", "PRF1"], + "B": ["MS4A1", "CD79A", "BANK1", "CD19"], + "CD14 Mono": ["CD14", "LYZ", "S100A8", "S100A9", "VCAN"], + "CD16 Mono": ["FCGR3A", "MS4A7", "LST1", "CDKN1C"], + "DC": ["FCER1A", "CST3", "CLEC10A", "CD1C"], + "pDC": ["LILRA4", "IRF7", "CLEC4C", "TCF4"], + "Plasma": ["MZB1", "JCHAIN", "IGHG1", "XBP1"], + "Platelet": ["PPBP", "PF4", "GP9"], +} +GENOMIC_RESOLUTION = 5000 +VAR_CHUNK_SIZE = 10 + + +def tfidf_lsi(counts, n_components=50): + """TF-IDF + truncated SVD (LSI); drops the first component, which tracks sequencing depth.""" + X = counts.tocsr().astype(np.float32, copy=True) + X.data[:] = 1 + tf = sp.diags(1.0 / np.maximum(np.asarray(X.sum(axis=1)).ravel(), 1)) @ X + idf = np.log1p(X.shape[0] / np.maximum(np.asarray(X.sum(axis=0)).ravel(), 1)) + tfidf = (tf @ sp.diags(idf)).tocsr() + tfidf.data = np.log1p(tfidf.data * 1e4).astype(np.float32) + lsi = TruncatedSVD(n_components=n_components, random_state=0).fit_transform(tfidf)[:, 1:] + lsi /= np.linalg.norm(lsi, axis=1, keepdims=True) + 1e-9 + return lsi + + +def write_genomic_profiles(counts, chroms, starts, groups, output_path, assembly, obs_set_name): + """ + Aggregate a cell-by-region count matrix into pseudobulk profiles (one per group), + re-bin the regions to GENOMIC_RESOLUTION, normalize to counts per million, + and write a genomic-profiles (multivec) Zarr store. + """ + groups = pd.Categorical(groups) + group_names = [str(g) for g in groups.categories] + # (groups x cells) indicator matrix. + G = sp.csr_matrix( + (np.ones(len(groups), dtype=np.float32), (groups.codes, np.arange(len(groups)))), + shape=(len(group_names), len(groups)), + ) + pseudobulk = (G @ counts.tocsc().astype(np.float32)).tocsr() + + # Map each region to a fixed-size bin (by region start). + bins_df = pd.DataFrame({"chrom": np.asarray(chroms).astype(str), "bin": np.asarray(starts).astype(np.int64) // GENOMIC_RESOLUTION}) + bin_idx, _ = pd.factorize(bins_df["chrom"] + ":" + bins_df["bin"].astype(str)) + B = sp.csr_matrix( + (np.ones(len(bin_idx), dtype=np.float32), (np.arange(len(bin_idx)), bin_idx)), + shape=(len(bin_idx), bin_idx.max() + 1), + ) + binned = (pseudobulk @ B).toarray() + first_idx = pd.Series(np.arange(len(bin_idx))).groupby(bin_idx).first().values + new_bins = bins_df.iloc[first_idx].reset_index(drop=True) + + # Counts per million, per group. + totals = binned.sum(axis=1, keepdims=True) + binned = binned / np.maximum(totals, 1) * 1e6 + + # Sort bins by chromosome and position, as adata_to_multivec_zarr expects contiguous chromosomes. + order = new_bins.sort_values(["chrom", "bin"]).index.values + new_bins = new_bins.iloc[order].reset_index(drop=True) + binned = binned[:, order] + + start = new_bins["bin"] * GENOMIC_RESOLUTION + var = pd.DataFrame(index=[str(i) for i in range(len(new_bins))]) + var["interval"] = (new_bins["chrom"] + ":" + start.astype(str) + "-" + (start + GENOMIC_RESOLUTION - 1).astype(str)).values + obs = pd.DataFrame(index=group_names) + obs["group"] = group_names + profiles = ad.AnnData(X=binned.astype(np.float32), obs=obs, var=var) + adata_to_multivec_zarr( + profiles, output_path, + obs_set_col="group", obs_set_name=obs_set_name, obs_set_vals=group_names, + var_interval_col="interval", assembly=assembly, starting_resolution=GENOMIC_RESOLUTION, + ) + + +def main(args): + sc.settings.n_jobs = 4 + a = sc.read_10x_h5(args.input_h5, gex_only=False) + a.var_names_make_unique() + rna = a[:, a.var["feature_types"] == "Gene Expression"].copy() + atac = a[:, a.var["feature_types"] == "Peaks"].copy() + print(f"Read {a.n_obs} nuclei: {rna.n_vars} genes, {atac.n_vars} peaks") + + # RNA: QC, normalization, clustering, embedding. + rna.var["mt"] = rna.var_names.str.startswith("MT-") + sc.pp.calculate_qc_metrics(rna, qc_vars=["mt"], inplace=True, percent_top=None) + sc.pp.filter_cells(rna, min_genes=500) + rna = rna[rna.obs["pct_counts_mt"] < 20].copy() + sc.pp.filter_genes(rna, min_cells=10) + atac = atac[rna.obs_names].copy() + sc.pp.normalize_total(rna, target_sum=1e4) + sc.pp.log1p(rna) + sc.pp.highly_variable_genes(rna, n_top_genes=2000) + sc.pp.pca(rna, n_comps=50, mask_var="highly_variable") + sc.pp.neighbors(rna, n_pcs=30, n_neighbors=15) + sc.tl.leiden(rna, resolution=1.0, key_added="leiden", flavor="igraph", n_iterations=2, directed=False) + sc.tl.umap(rna, random_state=0) + + # Name each Leiden cluster by the marker set with the highest mean score. + score_cols = [] + for name, genes in MARKERS.items(): + present = [g for g in genes if g in rna.var_names] + if len(present) == 0: + print(f"Skipping marker set {name}: none of its genes passed filtering") + continue + col = f"score_{name}" + sc.tl.score_genes(rna, present, score_name=col) + score_cols.append(col) + cluster_means = rna.obs.groupby("leiden", observed=True)[score_cols].mean() + labels = cluster_means.idxmax(axis=1).str.replace("score_", "", regex=False) + rna.obs["cell_type"] = rna.obs["leiden"].map(labels).astype("category") + print(rna.obs["cell_type"].value_counts()) + + # ATAC: TF-IDF + LSI, neighbors, UMAP, Leiden. + peak_counts = atac.X.tocsr().astype(np.float32) + atac.obsm["X_lsi"] = tfidf_lsi(peak_counts) + sc.pp.neighbors(atac, use_rep="X_lsi", n_neighbors=20) + sc.tl.umap(atac, random_state=0) + sc.tl.leiden(atac, resolution=1.0, key_added="leiden", flavor="igraph", n_iterations=2, directed=False) + + # Gene activity: counts of peaks in gene promoters or within 2 kb of the gene (from Cell Ranger ARC's peak annotation). + ann = pd.read_csv(args.input_peak_annotation, sep="\t") + ann["peak"] = ann["chrom"] + ":" + ann["start"].astype(str) + "-" + ann["end"].astype(str) + ann = ann.dropna(subset=["gene"]) + ann = ann.assign(gene=ann["gene"].str.split(";")).explode("gene") + sel = ann[(ann["peak_type"] == "promoter") | (pd.to_numeric(ann["distance"], errors="coerce").abs() <= 2000)] + sel = sel[sel["peak"].isin(atac.var_names)].drop_duplicates(["peak", "gene"]) + peak_idx = pd.Index(atac.var_names).get_indexer(sel["peak"]) + gene_cat = pd.Categorical(sel["gene"]) + link = sp.csr_matrix( + (np.ones(len(sel), dtype=np.float32), (peak_idx, gene_cat.codes)), + shape=(atac.n_vars, len(gene_cat.categories)), + ) + act = ad.AnnData(X=(peak_counts @ link).tocsr(), obs=atac.obs[[]].copy(), var=pd.DataFrame(index=gene_cat.categories.astype(str))) + sc.pp.filter_genes(act, min_cells=10) + sc.pp.normalize_total(act, target_sum=1e4) + sc.pp.log1p(act) + print(f"Gene activity for {act.n_vars} genes") + + # Shared cell metadata. + metrics = pd.read_csv(args.input_metrics, index_col="barcode").reindex(rna.obs_names) + rna.obs["atac_fragments"] = metrics["atac_fragments"].to_numpy(dtype=float) + rna.obs["atac_tss_fraction"] = (metrics["atac_TSS_fragments"] / metrics["atac_fragments"].clip(lower=1)).to_numpy(dtype=float) + rna.obs["atac_frip"] = (metrics["atac_peak_region_fragments"] / metrics["atac_fragments"].clip(lower=1)).to_numpy(dtype=float) + + # Also store the ATAC clusters alongside the RNA cell metadata, so that all cell sets can be loaded from one table. + rna.obs["leiden_atac"] = atac.obs["leiden"].values + obs_cols = ["cell_type", "leiden", "leiden_atac", "total_counts", "n_genes_by_counts", "pct_counts_mt", "atac_fragments", "atac_tss_fraction", "atac_frip"] + rna_out = optimize_adata( + rna, obs_cols=obs_cols, var_cols=["highly_variable"], + obsm_keys=["X_umap", "X_pca"], varm_keys=[], layer_keys=[], + to_dense_X=True, + ) + atac.obs["cell_type"] = rna.obs["cell_type"].values + atac.obs["leiden_rna"] = rna.obs["leiden"].values + act.obs = atac.obs[["cell_type", "leiden", "leiden_rna"]].copy() + act.obsm["X_umap"] = atac.obsm["X_umap"] + act.obsm["X_lsi"] = atac.obsm["X_lsi"] + atac_out = optimize_adata( + act, obs_cols=["cell_type", "leiden", "leiden_rna"], var_cols=[], + obsm_keys=["X_umap", "X_lsi"], varm_keys=[], layer_keys=[], + to_dense_X=True, + ) + atac_out.uns["X_description"] = "Gene activity: log1p(CP10k) of ATAC peak counts in promoters or within 2 kb of each gene." + + mdata = md.MuData({"rna": rna_out, "atac": atac_out}) + mdata.obs["cell_type"] = rna.obs["cell_type"].values + mdata.obsm["X_umap_rna"] = rna_out.obsm["X_umap"] + mdata.obsm["X_umap_atac"] = atac_out.obsm["X_umap"] + # Chunk the feature axis so that Vitessce can load one (or a few) features at a time. + mdata.write_zarr(args.output_mudata, chunks=(mdata.n_obs, VAR_CHUNK_SIZE)) + + # Pseudobulk ATAC profiles per cell type, from the peak counts. + peak_coords = atac.var_names.str.extract(r"^(?P[^:]+):(?P\d+)-(?P\d+)$") + write_genomic_profiles( + peak_counts, peak_coords["chrom"].values, peak_coords["start"].astype(int).values, + rna.obs["cell_type"].astype(str).values, args.output_profiles, assembly="hg38", obs_set_name="Cell Type", + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--input_h5", type=str, required=True, help="Cell Ranger ARC filtered_feature_bc_matrix.h5") + parser.add_argument("--input_peak_annotation", type=str, required=True, help="Cell Ranger ARC atac_peak_annotation.tsv") + parser.add_argument("--input_metrics", type=str, required=True, help="Cell Ranger ARC per_barcode_metrics.csv") + parser.add_argument("--output_mudata", type=str, required=True, help="Output MuData-Zarr store") + parser.add_argument("--output_profiles", type=str, required=True, help="Output genomic-profiles Zarr store") + main(parser.parse_args()) diff --git a/demos/mudata-pbmc-multiome-10x/vitessce.template.json b/demos/mudata-pbmc-multiome-10x/vitessce.template.json new file mode 100644 index 00000000..c6f7bbce --- /dev/null +++ b/demos/mudata-pbmc-multiome-10x/vitessce.template.json @@ -0,0 +1,199 @@ +{ + "version": "1.0.18", + "name": "10x Multiome PBMC (granulocytes removed, 10k)", + "description": "10x Genomics Single Cell Multiome ATAC + Gene Expression of human PBMCs (Cell Ranger ARC 2.0.0); RNA expression, ATAC gene activity, and pseudobulk ATAC profiles per cell type", + "datasets": [ + { + "uid": "A", + "name": "10x Multiome", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/pbmc_multiome_10x.h5mu.zarr/mod/rna", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "embeddingType": "RNA UMAP" + } + ], + "obsSets": [ + { + "name": "Cell Type", + "path": "obs/cell_type" + }, + { + "name": "RNA Leiden", + "path": "obs/leiden" + }, + { + "name": "ATAC Leiden", + "path": "obs/leiden_atac" + } + ], + "obsFeatureMatrix": { + "path": "X" + } + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression" + } + }, + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/pbmc_multiome_10x.h5mu.zarr/mod/atac", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "embeddingType": "ATAC UMAP" + } + ], + "obsFeatureMatrix": { + "path": "X" + } + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene activity", + "featureValueType": "accessibility" + } + }, + { + "fileType": "genomic-profiles.zarr", + "url": "{{ base_url }}/pbmc_multiome_10x.genomic-profiles.zarr" + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "obsType": { + "A": "cell" + }, + "embeddingType": { + "RNA": "RNA UMAP", + "ATAC": "ATAC UMAP" + }, + "featureType": { + "RNA": "gene", + "ATAC": "gene activity" + }, + "featureValueType": { + "RNA": "expression", + "ATAC": "accessibility" + }, + "featureSelection": { + "RNA": null, + "ATAC": null + }, + "obsColorEncoding": { + "RNA": "cellSetSelection", + "ATAC": "cellSetSelection" + } + }, + "layout": [ + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "embeddingType": "RNA", + "featureType": "RNA", + "featureValueType": "RNA", + "featureSelection": "RNA", + "obsColorEncoding": "RNA" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 4 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "embeddingType": "ATAC", + "featureType": "ATAC", + "featureValueType": "ATAC", + "featureSelection": "ATAC", + "obsColorEncoding": "ATAC" + }, + "x": 6, + "y": 0, + "w": 6, + "h": 4 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 0, + "y": 4, + "w": 4, + "h": 4 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "RNA", + "featureValueType": "RNA", + "featureSelection": "RNA", + "obsColorEncoding": "RNA" + }, + "x": 4, + "y": 4, + "w": 4, + "h": 4 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "ATAC", + "featureValueType": "ATAC", + "featureSelection": "ATAC", + "obsColorEncoding": "ATAC" + }, + "x": 8, + "y": 4, + "w": 4, + "h": 4 + }, + { + "component": "genomicProfiles", + "coordinationScopes": { + "dataset": "A" + }, + "props": { + "assembly": "hg38" + }, + "x": 0, + "y": 8, + "w": 8, + "h": 4 + }, + { + "component": "obsSetSizes", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 8, + "y": 8, + "w": 4, + "h": 4 + } + ], + "initStrategy": "auto" +} \ No newline at end of file diff --git a/demos/mudata-snareseq2-lung-hubmap/Snakefile b/demos/mudata-snareseq2-lung-hubmap/Snakefile new file mode 100644 index 00000000..ff9ab24b --- /dev/null +++ b/demos/mudata-snareseq2-lung-hubmap/Snakefile @@ -0,0 +1,56 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# SNARE-seq2 (joint single-nucleus RNA + ATAC) from the HuBMAP Data Portal. +# Dataset: HBM582.RKVK.974, "SNARE-seq2 [Salmon + ArchR + Muon] data from the lung (left) +# of a 23.8-year-old white male" (540 nuclei), University of California San Diego TMC / LAPMAP. +# - Portal page: https://portal.hubmapconsortium.org/browse/dataset/cd0996bebdc726bd2a8bf418ba6ed845 +# - DOI of the raw dataset collection: see the portal page (HuBMAP registers DOIs as https://doi.org/10.35079/). +# - Other public SNARE-seq2 datasets: https://portal.hubmapconsortium.org/search/datasets?dataset_type=SNARE-seq2.SNARE-seq2,SNARE-seq2.SNARE-seq2+[Salmon+%2B+ArchR+%2B+Muon] +# (the others have more nuclei but their secondary_analysis.h5mu files are 3-19 GB). +# - Processed outputs are public on the HuBMAP assets server (no login needed). +# Data use: HuBMAP data sharing policy, https://hubmapconsortium.org/policies/ +# Note: assets.hubmapconsortium.org returns 403 to the default curl User-Agent, +# so we send a descriptive User-Agent instead. +HUBMAP_UUID = "cd0996bebdc726bd2a8bf418ba6ed845" +HUBMAP_ID = "HBM582.RKVK.974" +H5MU_URL = f"https://assets.hubmapconsortium.org/{HUBMAP_UUID}/secondary_analysis.h5mu" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Convert the HuBMAP secondary analysis MuData to a MuData-Zarr store and a genomic-profiles (multivec) Zarr store. +rule process_snareseq2: + input: + (RAW_DIR / f"{HUBMAP_ID}_secondary_analysis.h5mu") + output: + mudata=directory(PROCESSED_DIR / "snareseq2_lung.h5mu.zarr"), + profiles=directory(PROCESSED_DIR / "snareseq2_lung.genomic-profiles.zarr"), + params: + script=(SRC_DIR / "process_snareseq2.py"), + hubmap_id=HUBMAP_ID, + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + --hubmap_id {params.hubmap_id} \ + --output_mudata {output.mudata} \ + --output_profiles {output.profiles} + ''' + +# Download the HuBMAP secondary analysis MuData (2.8 GB). +rule download_data: + output: + (RAW_DIR / f"{HUBMAP_ID}_secondary_analysis.h5mu") + params: + file_url=H5MU_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -A "vitessce-demos" -o {output} "{params.file_url}" + ''' diff --git a/demos/mudata-snareseq2-lung-hubmap/config.yml b/demos/mudata-snareseq2-lung-hubmap/config.yml new file mode 100644 index 00000000..3c393fd9 --- /dev/null +++ b/demos/mudata-snareseq2-lung-hubmap/config.yml @@ -0,0 +1,3 @@ +output: +- snareseq2_lung.h5mu.zarr +- snareseq2_lung.genomic-profiles.zarr diff --git a/demos/mudata-snareseq2-lung-hubmap/src/process_snareseq2.py b/demos/mudata-snareseq2-lung-hubmap/src/process_snareseq2.py new file mode 100644 index 00000000..9714bd94 --- /dev/null +++ b/demos/mudata-snareseq2-lung-hubmap/src/process_snareseq2.py @@ -0,0 +1,171 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "anndata==0.13.4", +# "mudata==0.4.1", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Convert a HuBMAP SNARE-seq2 [Salmon + ArchR + Muon] secondary analysis MuData +(.h5mu) into Vitessce-friendly outputs. + +The HuBMAP secondary_analysis.h5mu has three modalities: + - rna: Salmon gene expression (scaled X; log-normalized values in raw.X), + Azimuth/CellTypist-style cell type predictions (obs/predicted_label), UMAP. + - atac_cbg: ArchR cell-by-gene (gene score) matrix, with its own UMAP and Leiden clusters. + - atac_cbb: ArchR cell-by-bin (500 bp tiles) binarized accessibility matrix. + plus a joint (MOFA + WNN) UMAP and Leiden clusters at the top level. + +Outputs: + - A MuData-Zarr store with modalities (sharing the same obs index/order): + mod/rna: log-normalized gene expression (dense, chunked), RNA UMAP, cell type labels. + mod/atac: log1p ArchR gene scores (dense, chunked), ATAC UMAP, ATAC clusters. + and a top-level obs (cell types, joint Leiden clusters) and obsm (joint UMAP). + - A genomic-profiles (multivec) Zarr store with one pseudobulk ATAC track per + predicted cell type, aggregated from the 500 bp tile matrix. +""" +import argparse + +import anndata as ad +import mudata as md +import numpy as np +import pandas as pd +import scipy.sparse as sp +from vitessce.data_utils import adata_to_multivec_zarr, optimize_adata + +GENOMIC_RESOLUTION = 5000 +VAR_CHUNK_SIZE = 10 +MIN_CELLS = 3 + + +def write_genomic_profiles(counts, chroms, starts, groups, output_path, assembly, obs_set_name): + """ + Aggregate a cell-by-region count matrix into pseudobulk profiles (one per group), + re-bin the regions to GENOMIC_RESOLUTION, normalize to counts per million, + and write a genomic-profiles (multivec) Zarr store. + """ + groups = pd.Categorical(groups) + group_names = [str(g) for g in groups.categories] + # (groups x cells) indicator matrix. + G = sp.csr_matrix( + (np.ones(len(groups), dtype=np.float32), (groups.codes, np.arange(len(groups)))), + shape=(len(group_names), len(groups)), + ) + pseudobulk = (G @ sp.csr_matrix(counts, dtype=np.float32)).tocsr() + + # Map each region to a fixed-size bin (by region start). + bins_df = pd.DataFrame({"chrom": np.asarray(chroms).astype(str), "bin": np.asarray(starts).astype(np.int64) // GENOMIC_RESOLUTION}) + bin_idx, _ = pd.factorize(bins_df["chrom"] + ":" + bins_df["bin"].astype(str)) + B = sp.csr_matrix( + (np.ones(len(bin_idx), dtype=np.float32), (np.arange(len(bin_idx)), bin_idx)), + shape=(len(bin_idx), bin_idx.max() + 1), + ) + binned = (pseudobulk @ B).toarray() + first_idx = pd.Series(np.arange(len(bin_idx))).groupby(bin_idx).first().values + new_bins = bins_df.iloc[first_idx].reset_index(drop=True) + + # Counts per million, per group. + totals = binned.sum(axis=1, keepdims=True) + binned = binned / np.maximum(totals, 1) * 1e6 + + # Sort bins by chromosome and position, as adata_to_multivec_zarr expects contiguous chromosomes. + order = new_bins.sort_values(["chrom", "bin"]).index.values + new_bins = new_bins.iloc[order].reset_index(drop=True) + binned = binned[:, order] + + start = new_bins["bin"] * GENOMIC_RESOLUTION + var = pd.DataFrame(index=[str(i) for i in range(len(new_bins))]) + var["interval"] = (new_bins["chrom"] + ":" + start.astype(str) + "-" + (start + GENOMIC_RESOLUTION - 1).astype(str)).values + obs = pd.DataFrame(index=group_names) + obs["group"] = group_names + profiles = ad.AnnData(X=binned.astype(np.float32), obs=obs, var=var) + adata_to_multivec_zarr( + profiles, output_path, + obs_set_col="group", obs_set_name=obs_set_name, obs_set_vals=group_names, + var_interval_col="interval", assembly=assembly, starting_resolution=GENOMIC_RESOLUTION, + ) + + +def main(args): + mdata = md.read_h5mu(args.input) + print(mdata) + rna = mdata["rna"] + cbg = mdata["atac_cbg"] + cbb = mdata["atac_cbb"] + + # Use one shared obs order (that of the top-level MuData object) for every modality. + obs_names = mdata.obs_names + for mod in (rna, cbg, cbb): + obs_names = obs_names.intersection(mod.obs_names, sort=False) + print(f"{len(obs_names)} nuclei shared across modalities") + + # RNA: log-normalized expression is stored in raw.X (X is scaled/clipped). + rna_raw = rna.raw.to_adata()[obs_names].copy() + rna_obs = rna.obs.loc[obs_names] + rna_raw.obs = rna_obs[["predicted_label", "predicted_CLID", "prediction_score", "azimuth_label", "leiden"]].copy() + rna_raw.obs = rna_raw.obs.rename(columns={"predicted_label": "cell_type", "leiden": "leiden_rna"}) + # Also store the ATAC and joint (WNN) clusters alongside the RNA cell metadata, + # so that all cell sets can be loaded from one table. + rna_raw.obs["leiden_atac"] = cbg.obs.loc[obs_names, "leiden"].values + rna_raw.obs["leiden_wnn"] = mdata.obs.loc[obs_names, "leiden_wnn"].values + rna_raw.obsm["X_umap"] = rna[obs_names].obsm["X_umap"] + n_cells = np.asarray((rna_raw.X > 0).sum(axis=0)).ravel() + rna_raw = rna_raw[:, n_cells >= MIN_CELLS].copy() + # Use gene symbols as feature labels where available. + rna_raw.var["hugo_symbol"] = rna_raw.var["hugo_symbol"].astype(str).where(rna_raw.var["hugo_symbol"].notna(), rna_raw.var_names.to_series()) + rna_out = optimize_adata( + rna_raw, + obs_cols=["cell_type", "predicted_CLID", "prediction_score", "azimuth_label", "leiden_rna", "leiden_atac", "leiden_wnn"], + var_cols=["hugo_symbol", "highly_variable"], + obsm_keys=["X_umap"], varm_keys=[], layer_keys=[], + to_dense_X=True, + ) + print(f"RNA: {rna_out.shape}") + + # ATAC: ArchR gene scores (cell x gene), log1p-transformed. + atac = cbg[obs_names].copy() + atac.X = sp.csr_matrix(atac.X) + n_cells = np.asarray((atac.X > 0).sum(axis=0)).ravel() + atac = atac[:, n_cells >= MIN_CELLS].copy() + atac.X = atac.X.log1p() + atac.obs = atac.obs.rename(columns={"leiden": "leiden_atac", "Clusters": "archr_clusters"}) + atac.obs["cell_type"] = rna_out.obs["cell_type"].values + atac_out = optimize_adata( + atac, + obs_cols=["cell_type", "leiden_atac", "archr_clusters", "TSSEnrichment", "nFrags"], + var_cols=["highly_variable"], + obsm_keys=["X_umap"], varm_keys=[], layer_keys=[], + to_dense_X=True, + ) + atac_out.uns["X_description"] = "log1p of ArchR gene scores." + print(f"ATAC gene scores: {atac_out.shape}") + + out = md.MuData({"rna": rna_out, "atac": atac_out}) + out.obs["cell_type"] = rna_out.obs["cell_type"].values + out.obs["leiden_wnn"] = mdata.obs.loc[obs_names, "leiden_wnn"].values + out.obsm["X_umap"] = np.asarray(mdata[obs_names].obsm["X_umap"], dtype=np.float32) + out.uns["hubmap_id"] = args.hubmap_id + # Chunk the feature axis so that Vitessce can load one (or a few) features at a time. + out.write_zarr(args.output_mudata, chunks=(out.n_obs, VAR_CHUNK_SIZE)) + + # Pseudobulk ATAC profiles per predicted cell type, from the 500 bp tile matrix. + tiles = cbb[obs_names] + chroms = "chr" + tiles.var["chrom"].astype(str).str.replace("^chr", "", regex=True) + starts = tiles.var["bin_start"].astype(str).astype(float).astype(np.int64) + write_genomic_profiles( + tiles.X, chroms.values, starts.values, rna_out.obs["cell_type"].astype(str).values, + args.output_profiles, assembly="hg38", obs_set_name="Cell Type", + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-i", "--input", type=str, required=True, help="HuBMAP secondary_analysis.h5mu") + parser.add_argument("--hubmap_id", type=str, required=True, help="HuBMAP ID of the dataset, stored in uns") + parser.add_argument("--output_mudata", type=str, required=True, help="Output MuData-Zarr store") + parser.add_argument("--output_profiles", type=str, required=True, help="Output genomic-profiles Zarr store") + main(parser.parse_args()) diff --git a/demos/mudata-snareseq2-lung-hubmap/vitessce.template.json b/demos/mudata-snareseq2-lung-hubmap/vitessce.template.json new file mode 100644 index 00000000..ab993606 --- /dev/null +++ b/demos/mudata-snareseq2-lung-hubmap/vitessce.template.json @@ -0,0 +1,234 @@ +{ + "version": "1.0.18", + "name": "SNARE-seq2 human lung (HuBMAP HBM582.RKVK.974)", + "description": "Joint single-nucleus RNA + ATAC (SNARE-seq2) of human lung, processed by the HuBMAP Salmon + ArchR + Muon pipeline", + "datasets": [ + { + "uid": "A", + "name": "SNARE-seq2", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/snareseq2_lung.h5mu.zarr/mod/rna", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "embeddingType": "RNA UMAP" + } + ], + "obsSets": [ + { + "name": "Cell Type", + "path": "obs/cell_type" + }, + { + "name": "Joint (WNN) Leiden", + "path": "obs/leiden_wnn" + }, + { + "name": "RNA Leiden", + "path": "obs/leiden_rna" + }, + { + "name": "ATAC Leiden", + "path": "obs/leiden_atac" + } + ], + "obsFeatureMatrix": { + "path": "X" + }, + "featureLabels": { + "path": "var/hugo_symbol" + } + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression" + } + }, + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/snareseq2_lung.h5mu.zarr/mod/atac", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "embeddingType": "ATAC UMAP" + } + ], + "obsFeatureMatrix": { + "path": "X" + } + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene score", + "featureValueType": "accessibility" + } + }, + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/snareseq2_lung.h5mu.zarr", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "embeddingType": "Joint (WNN) UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "cell" + } + }, + { + "fileType": "genomic-profiles.zarr", + "url": "{{ base_url }}/snareseq2_lung.genomic-profiles.zarr" + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "obsType": { + "A": "cell" + }, + "embeddingType": { + "RNA": "RNA UMAP", + "ATAC": "ATAC UMAP", + "WNN": "Joint (WNN) UMAP" + }, + "featureType": { + "RNA": "gene", + "ATAC": "gene score" + }, + "featureValueType": { + "RNA": "expression", + "ATAC": "accessibility" + }, + "featureSelection": { + "RNA": null, + "ATAC": null + }, + "obsColorEncoding": { + "RNA": "cellSetSelection", + "ATAC": "cellSetSelection" + } + }, + "layout": [ + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "embeddingType": "WNN" + }, + "x": 0, + "y": 0, + "w": 4, + "h": 4 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "embeddingType": "RNA", + "featureType": "RNA", + "featureValueType": "RNA", + "featureSelection": "RNA", + "obsColorEncoding": "RNA" + }, + "x": 4, + "y": 0, + "w": 4, + "h": 4 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "embeddingType": "ATAC", + "featureType": "ATAC", + "featureValueType": "ATAC", + "featureSelection": "ATAC", + "obsColorEncoding": "ATAC" + }, + "x": 8, + "y": 0, + "w": 4, + "h": 4 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 0, + "y": 4, + "w": 4, + "h": 4 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "RNA", + "featureValueType": "RNA", + "featureSelection": "RNA", + "obsColorEncoding": "RNA" + }, + "x": 4, + "y": 4, + "w": 4, + "h": 4 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "ATAC", + "featureValueType": "ATAC", + "featureSelection": "ATAC", + "obsColorEncoding": "ATAC" + }, + "x": 8, + "y": 4, + "w": 4, + "h": 4 + }, + { + "component": "genomicProfiles", + "coordinationScopes": { + "dataset": "A" + }, + "props": { + "assembly": "hg38" + }, + "x": 0, + "y": 8, + "w": 8, + "h": 4 + }, + { + "component": "obsSetSizes", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 8, + "y": 8, + "w": 4, + "h": 4 + } + ], + "initStrategy": "auto" +} diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/Snakefile b/demos/ome-zarr-lightsheet-hubmap-spleen/Snakefile new file mode 100644 index 00000000..f6f4e23f --- /dev/null +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/Snakefile @@ -0,0 +1,62 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# 3D light-sheet fluorescence microscopy (LSFM) of cleared human spleen from HuBMAP. +# +# Image pyramid dataset: HBM759.DQHR.327 (Light Sheet [Image Pyramid]), +# uuid 71b3fdd770de565e5d48a73060b72189 +# https://portal.hubmapconsortium.org/browse/dataset/71b3fdd770de565e5d48a73060b72189 +# "Light Sheet [Image Pyramid] data from the spleen of a 20-year-old white male" (University of Florida TMC). +# Raw (parent) dataset: HBM423.JZTB.864, uuid 073cad035ce246a0134e2214569adde9 +# https://doi.org/10.35079/HBM423.JZTB.864 +# Instrument: Zeiss LightSheet Z.1 (20x/1.0 clearing objective, 0.5x zoom), 1 channel (Iba1, 488 nm). +# Protocol: https://dx.doi.org/10.17504/protocols.io.bqaamsae +# Access: HuBMAP public (open, no login) data; see https://hubmapconsortium.org/policies/ +# +# The input is a single-channel ZYX OME-TIFF of 598 x 1920 x 1920 voxels +# (0.455 x 0.455 x 1.0 um), ~3.5 GB, with a 2x XY pyramid. +# To keep the output manageable, we use the 2x XY-downsampled level of the input pyramid +# (598 x 960 x 960, ~0.91 x 0.91 x 1.0 um voxels) as the output full resolution, +# then build 3 further levels by 2x2x2 mean downsampling (Z, Y, and X). +# +# Files are downloaded from the HuBMAP assets server (https://assets.hubmapconsortium.org//). +# Note: the assets server returns HTTP 403 for the default curl User-Agent, so we set a generic one. +HUBMAP_UUID = "71b3fdd770de565e5d48a73060b72189" +OME_TIFF_URL = f"https://assets.hubmapconsortium.org/{HUBMAP_UUID}/ometiff-pyramids/Level0/Channel1/UFL0007-SP-2-3-1.ome.tif" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Convert the OME-TIFF to a multiscale (Z, Y, X downsampled) OME-Zarr. +rule convert_to_ome_zarr: + input: + (RAW_DIR / "UFL0007-SP-2-3-1.ome.tif") + output: + directory(PROCESSED_DIR / "lightsheet_hubmap_spleen.ome.zarr") + params: + script=(SRC_DIR / "ome_tiff_to_ome_zarr_3d.py") + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + -o {output} \ + --source-level 1 \ + --num-levels 4 \ + --channel-name "Iba1" + ''' + +rule download_data: + output: + (RAW_DIR / "UFL0007-SP-2-3-1.ome.tif") + params: + file_url=OME_TIFF_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -A "vitessce-demos" -o {output} "{params.file_url}" + ''' diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/config.yml b/demos/ome-zarr-lightsheet-hubmap-spleen/config.yml new file mode 100644 index 00000000..3b1b600a --- /dev/null +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/config.yml @@ -0,0 +1,2 @@ +output: +- lightsheet_hubmap_spleen.ome.zarr diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/src/ome_tiff_to_ome_zarr_3d.py b/demos/ome-zarr-lightsheet-hubmap-spleen/src/ome_tiff_to_ome_zarr_3d.py new file mode 100644 index 00000000..75d55f48 --- /dev/null +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/src/ome_tiff_to_ome_zarr_3d.py @@ -0,0 +1,125 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "ome-zarr==0.15.0", +# "tifffile>=2025.5.10", +# "imagecodecs", +# "numpy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +""" +Convert a (pyramidal) 3D light-sheet OME-TIFF (single channel, ZYX) into a +multiscale 3D OME-Zarr (OME-NGFF v0.4, axes czyx), downsampling by 2 along +Z, Y, and X at each successive resolution level (suitable for volume rendering). + +To keep the output size manageable, the full-resolution level of the output +is read from a lower-resolution level of the input OME-TIFF pyramid +(--source-level, default 1 = 2x XY downsampling of the original acquisition). +""" +import argparse + +import numpy as np +import tifffile +import zarr +from ome_zarr.format import FormatV04 +from ome_zarr.writer import write_multiscale + + +def downsample_2x(arr): + """2x2x2 mean downsampling of a ZYX array (trailing odd planes/rows/cols are dropped).""" + z, y, x = (s // 2 * 2 for s in arr.shape) + arr = arr[:z, :y, :x].astype(np.float32) + out = arr.reshape(z // 2, 2, y // 2, 2, x // 2, 2).mean(axis=(1, 3, 5)) + return out + + +def get_physical_sizes(tif): + pixels = tifffile.xml2dict(tif.ome_metadata)["OME"]["Image"] + if isinstance(pixels, list): + pixels = pixels[0] + pixels = pixels["Pixels"] + return ( + float(pixels.get("PhysicalSizeZ", 1.0)), + float(pixels.get("PhysicalSizeY", 1.0)), + float(pixels.get("PhysicalSizeX", 1.0)), + ) + + +def main(input_path, output_path, source_level, num_levels, channel_name, chunk_size): + with tifffile.TiffFile(input_path) as tif: + series = tif.series[0] + assert series.axes == "ZYX", f"Expected ZYX axes, got {series.axes}" + print("Input pyramid levels:", [lvl.shape for lvl in series.levels]) + level0_shape = series.levels[0].shape + source = series.levels[source_level] + arr = source.asarray() + size_z, size_y, size_x = get_physical_sizes(tif) + + # Physical pixel size of the chosen source level (only Y and X are downsampled in the input pyramid). + size_y *= level0_shape[1] / arr.shape[1] + size_x *= level0_shape[2] / arr.shape[2] + print(f"Source level {source_level}: shape {arr.shape}, voxel size (um) z={size_z}, y={size_y:.4f}, x={size_x:.4f}") + + dtype = arr.dtype + pyramid = [arr] + for _ in range(1, num_levels): + pyramid.append(downsample_2x(pyramid[-1]).astype(dtype)) + # Add the channel axis. + pyramid = [level[np.newaxis, ...] for level in pyramid] + for i, level in enumerate(pyramid): + print(f"Output level {i}: {level.shape}") + + coordinate_transformations = [ + [{"type": "scale", "scale": [1.0, size_z * 2 ** i, size_y * 2 ** i, size_x * 2 ** i]}] + for i in range(num_levels) + ] + + # Contrast limits from a low-resolution level. + lo, hi = np.percentile(pyramid[-1], [0.5, 99.9]) + dtype_max = int(np.iinfo(dtype).max) + + group = zarr.open_group(output_path, mode="w", zarr_format=2) + write_multiscale( + pyramid, + group, + fmt=FormatV04(), + axes=[ + {"name": "c", "type": "channel"}, + {"name": "z", "type": "space", "unit": "micrometer"}, + {"name": "y", "type": "space", "unit": "micrometer"}, + {"name": "x", "type": "space", "unit": "micrometer"}, + ], + coordinate_transformations=coordinate_transformations, + storage_options=dict(chunks=(1, chunk_size, chunk_size, chunk_size)), + name=channel_name, + ) + # write_multiscale does not persist the "omero" metadata, so add it explicitly. + omero = { + "name": channel_name, + "rdefs": {"model": "greyscale"}, + "channels": [{ + "label": channel_name, + "color": "FFFFFF", + "active": True, + "window": {"min": 0, "max": dtype_max, "start": int(lo), "end": int(hi)}, + }], + } + group.attrs["omero"] = omero + print(f"Wrote {output_path}; suggested contrast window: [{int(lo)}, {int(hi)}]") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-i", "--input", required=True, help="Input pyramidal ZYX OME-TIFF") + parser.add_argument("-o", "--output", required=True, help="Output OME-Zarr store") + parser.add_argument("--source-level", type=int, default=1, help="Input pyramid level to use as the output full resolution") + parser.add_argument("--num-levels", type=int, default=4, help="Number of output resolution levels") + parser.add_argument("--channel-name", default="Channel 0", help="Channel label for the omero metadata") + parser.add_argument("--chunk-size", type=int, default=128, help="Chunk size along each of Z, Y, X") + args = parser.parse_args() + main(args.input, args.output, args.source_level, args.num_levels, args.channel_name, args.chunk_size) diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/vitessce.template.json b/demos/ome-zarr-lightsheet-hubmap-spleen/vitessce.template.json new file mode 100644 index 00000000..924d7c94 --- /dev/null +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/vitessce.template.json @@ -0,0 +1,126 @@ +{ + "version": "1.0.18", + "name": "Light-sheet human spleen (HuBMAP HBM759.DQHR.327)", + "description": "3D light-sheet fluorescence microscopy (Zeiss LightSheet Z.1) of cleared human spleen stained for Iba1, from HuBMAP (University of Florida TMC). Multiscale 3D OME-Zarr.", + "datasets": [ + { + "uid": "A", + "name": "Light-sheet human spleen (HuBMAP HBM759.DQHR.327)", + "files": [ + { + "fileType": "image.ome-zarr", + "url": "{{ base_url_gcp }}/lightsheet_hubmap_spleen.ome.zarr" + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "BlackIsZero" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0 + }, + "imageChannel": { + "init_A_image_0": "__dummy__" + }, + "spatialTargetC": { + "init_A_image_0": 0 + }, + "spatialChannelColor": { + "init_A_image_0": [ + 255, + 255, + 255 + ] + }, + "spatialChannelWindow": { + "init_A_image_0": [ + 292, + 1363 + ] + }, + "spatialChannelVisible": { + "init_A_image_0": true + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + }, + "imageChannel": { + "init_A_image_0": [ + "init_A_image_0" + ] + } + }, + "imageChannel": { + "spatialTargetC": { + "init_A_image_0": "init_A_image_0" + }, + "spatialChannelColor": { + "init_A_image_0": "init_A_image_0" + }, + "spatialChannelWindow": { + "init_A_image_0": "init_A_image_0" + }, + "spatialChannelVisible": { + "init_A_image_0": "init_A_image_0" + } + } + } + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0" + ] + }, + "x": 0, + "y": 0, + "w": 9, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0" + ] + }, + "x": 9, + "y": 0, + "w": 3, + "h": 12 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-atera-kidney/Snakefile b/demos/spatialdata-atera-kidney/Snakefile new file mode 100644 index 00000000..c4511ce2 --- /dev/null +++ b/demos/spatialdata-atera-kidney/Snakefile @@ -0,0 +1,74 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# 10x Genomics Atera: whole-transcriptome (WTA) in situ, non-diseased human kidney (FFPE). +# 399,120 cells, ~18,000 genes, ~1.08 billion high-quality transcripts; Atera Onboard Analysis v1.0.4. +# Source (10x Genomics dataset release; direct download, no login or form needed): +# https://www.10xgenomics.com/datasets/atera-wta-ffpe-human-nd-kidney +# License: CC BY 4.0. +# The output bundle includes Leiden clusters, Azimuth cell type annotations, and a UMAP. +# Also see https://github.com/broadinstitute/Celldega_Atera_v1_WTA_Kidney_non_diseased_FFPE +# (Celldega visualization of the same dataset) and +# https://github.com/MicTott/spatialscape-examples/tree/main/atera (the WTA preview datasets). +# +# Download size: 45.7 GB (zip), plus about the same again once unzipped. +# +# The Atera output bundle format is read with the (not yet released) spatialdata-io Atera reader; +# see the PEP 723 dependencies in src/to_spatialdata.py. +# +# The `tiny_atera_dataset` (a 3.6 MB synthetic bundle, 13 cells x 132 features, that 10x provides to +# demonstrate the Atera output format, CC BY 4.0, from +# https://www.10xgenomics.com/support/software/atera-onboard-analysis/latest/resources/example-data) +# can be used to test the pipeline quickly: +# snakemake -j 1 data/processed/tiny_atera_dataset.spatialdata.zarr +BUNDLE_URLS = { + "Atera_v1_WTA_Kidney_non_diseased_FFPE": "https://cf.10xgenomics.com/samples/atera/1.0.4/Atera_v1_WTA_Kidney_non_diseased_FFPE/Atera_v1_WTA_Kidney_non_diseased_FFPE_outs.zip", + "tiny_atera_dataset": "https://cf.10xgenomics.com/samples/atera/1.0.0/tiny_atera_dataset/tiny_atera_dataset_outs.zip", +} + +wildcard_constraints: + bundle="|".join(BUNDLE_URLS.keys()) + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Convert the output bundle to SpatialData, and add a morton-sorted copy of the +# transcripts (with quality value >= 20) for tiled access in Vitessce. +rule to_spatialdata: + input: + (RAW_DIR / "{bundle}_outs") + output: + directory(PROCESSED_DIR / "{bundle}.spatialdata.zarr") + params: + script=(SRC_DIR / "to_spatialdata.py") + shell: + ''' + uv run --script {params.script} -i {input} -o {output} + ''' + +rule unzip_bundle: + input: + (RAW_DIR / "{bundle}_outs.zip") + output: + directory(RAW_DIR / "{bundle}_outs") + shell: + ''' + rm -rf {output} + unzip -q {input} -d {output} + ''' + +rule download_bundle: + output: + (RAW_DIR / "{bundle}_outs.zip") + params: + file_url=lambda w: BUNDLE_URLS[w.bundle] + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-atera-kidney/config.yml b/demos/spatialdata-atera-kidney/config.yml new file mode 100644 index 00000000..a2b4b322 --- /dev/null +++ b/demos/spatialdata-atera-kidney/config.yml @@ -0,0 +1,2 @@ +output: +- Atera_v1_WTA_Kidney_non_diseased_FFPE.spatialdata.zarr diff --git a/demos/spatialdata-atera-kidney/src/to_spatialdata.py b/demos/spatialdata-atera-kidney/src/to_spatialdata.py new file mode 100644 index 00000000..b3cf9978 --- /dev/null +++ b/demos/spatialdata-atera-kidney/src/to_spatialdata.py @@ -0,0 +1,176 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# # The Atera reader is not yet in a spatialdata-io release. Pin to a commit of the scverse +# # `atera-reader` branch (https://github.com/scverse/spatialdata-io/pull/444, the review of #426). +# # TODO: switch to a spatialdata-io release once Atera support is merged. +# "spatialdata-io @ git+https://github.com/scverse/spatialdata-io@ec169cf6a75869707137e12cec8dd4781c9114f9", +# "anndata>=0.12,<0.13", # anndata 0.13 (X as a None-keyed layer) breaks spatialdata 0.7.3 table validation +# "numpy", +# "pandas", +# "scipy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse +import shutil +from os.path import isdir +from pathlib import Path + +import numpy as np +import pandas as pd +from scipy.sparse import csc_matrix +from spatialdata import read_zarr +from spatialdata.models import PointsModel, TableModel +from spatialdata.transformations import get_transformation +from spatialdata_io import atera +from vitessce.data_utils import ( + sdata_morton_sort_points, + sdata_points_modify_row_group_size, +) + +# Keep transcripts with a Phred-scaled quality value of at least 20 (as 10x does for Xenium Explorer). +MIN_QV = 20 + + +def fix_table(sdata): + table = sdata["table"] + attrs = table.uns["spatialdata_attrs"] + region = attrs["region"] + instance_key = attrs["instance_key"] + + # Use string cell IDs for both the table index and the shapes index, + # so that Vitessce can align the shapes with the table rows + # (and to avoid int64 arrays, which Zarr.js/JavaScript handles poorly). + cell_ids = table.obs[instance_key].astype(str).to_numpy() + table.obs[instance_key] = cell_ids + table.obs.index = pd.Index(cell_ids) + table.obs.index.name = None + for shapes_key in ["cell_boundaries", "nucleus_boundaries"]: + if shapes_key in sdata.shapes: + gdf = sdata.shapes[shapes_key] + gdf.index = gdf.index.astype(str) + gdf.index.name = None + + # Use gene symbols as the var index (for display in Vitessce, and for transcript gene codes). + table.var["feature_id"] = table.var.index.astype(str) + table.var.index = pd.Index(table.var["feature_name"].astype(str).to_numpy()) + table.var_names_make_unique() + + # The reader loads X lazily, as CSR chunks. Vitessce loads one gene (column) at a time, + # which is efficient for CSC (or dense, column-chunked) matrices but not for CSR. + X = table.X + if hasattr(X, "compute"): + X = X.compute() + table.X = csc_matrix(X, dtype=np.float32) + + # Categorical columns for Vitessce cell sets. + for col in table.obs.columns: + if col.startswith("leiden") or (col.startswith("azimuth_") and not col.endswith("_score")): + table.obs[col] = table.obs[col].astype(str).astype("category") + + del sdata["table"] + table.uns.pop("spatialdata_attrs", None) + sdata["table"] = TableModel.parse(table, region=region, region_key=attrs["region_key"], instance_key=instance_key) + + +def add_morton_sorted_points(sdata, points_key, morton_key): + transformations = get_transformation(sdata[points_key], get_all=True) + + ddf = sdata[points_key] + ddf = ddf[ddf["quality_score"] >= MIN_QV] + ddf.attrs.pop("transform", None) + sdata[points_key] = PointsModel.parse(ddf, feature_key="feature_name", transformations=transformations) + + sdata = sdata_morton_sort_points(sdata, points_key) + ddf = sdata[points_key] + + # Index of each transcript's gene into table.var.index (-1 if absent). + # Computed from the categorical codes (vectorized), rather than with + # vitessce.data_utils.sdata_points_process_columns, which does a Python-level + # lookup per row (too slow for the ~1 billion transcripts of a whole-transcriptome dataset). + var_index = sdata["table"].var["feature_name"].astype(str) + categories = pd.Index(ddf["feature_name"].cat.categories.astype(str)) + cat_to_var = np.append(pd.Index(var_index).get_indexer(categories), -1).astype(np.int32) + + def add_codes(pdf): + codes = pdf["feature_name"].cat.codes.to_numpy() + pdf = pdf.copy() + # Code -1 (missing category) maps to the last element (-1). + pdf["feature_name_codes"] = cat_to_var[codes] + return pdf + + meta = ddf._meta.copy() + meta["feature_name_codes"] = np.array([], dtype=np.int32) + ddf = ddf.map_partitions(add_codes, meta=meta) + + # Dictionary-encoded (categorical) columns must be the rightmost columns. + cols = [c for c in ddf.columns if c != "feature_name"] + ["feature_name"] + ddf = ddf[cols] + if "transform" in ddf.attrs: + del ddf.attrs["transform"] + + sdata[morton_key] = PointsModel.parse( + ddf, feature_key="feature_name", instance_key="cell_id", transformations=transformations + ) + sdata.write_element(morton_key) + sdata_points_modify_row_group_size(sdata, morton_key, row_group_size=25_000) + + +def find_bundle_dir(path): + # The output bundle files may be at the top level of the zip file, or within a single directory. + path = Path(path) + if (path / "experiment.spatial").exists(): + return path + subdirs = [d for d in path.iterdir() if d.is_dir() and (d / "experiment.spatial").exists()] + if len(subdirs) == 1: + return subdirs[0] + raise FileNotFoundError(f"Could not find an Atera output bundle (experiment.spatial) in {path}") + + +def process(bundle_path, output_path, include_transcripts): + sdata = atera( + find_bundle_dir(bundle_path), + cells_table=True, + cells_boundaries=True, + nucleus_boundaries=True, + # Vitessce uses the boundary polygons, so skip the full-resolution label rasters + # (as large as the morphology image). + cells_labels=False, + nucleus_labels=False, + transcripts=include_transcripts, + morphology_images=True, + morphology_3d_images=False, + # Write a multiscale image for Vitessce. + image_models_kwargs={"scale_factors": [2, 2, 2, 2, 2, 2], "chunks": (1, 4096, 4096)}, + ) + fix_table(sdata) + + # Write everything except the transcripts first. + points = dict(sdata.points) + for key in points: + del sdata.points[key] + if isdir(output_path): + shutil.rmtree(output_path) + sdata.write(output_path) + + if include_transcripts: + sdata = read_zarr(output_path) + sdata["transcripts"] = points["transcripts"] + add_morton_sorted_points(sdata, "transcripts", "transcripts_with_morton_codes") + + print(read_zarr(output_path)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input', type=str, required=True, help='Unzipped Atera output bundle directory') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + parser.add_argument('--no-transcripts', action='store_true', help='Do not include the transcripts Points element') + args = parser.parse_args() + process(args.input, args.output, not args.no_transcripts) diff --git a/demos/spatialdata-atera-kidney/vitessce.template.json b/demos/spatialdata-atera-kidney/vitessce.template.json new file mode 100644 index 00000000..6bff89df --- /dev/null +++ b/demos/spatialdata-atera-kidney/vitessce.template.json @@ -0,0 +1,392 @@ +{ + "version": "1.0.18", + "name": "Atera WTA non-diseased human kidney (FFPE)", + "description": "10x Genomics Atera whole-transcriptome in situ dataset, with Azimuth cell type annotations", + "datasets": [ + { + "uid": "A", + "name": "Atera WTA non-diseased human kidney (FFPE)", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/Atera_v1_WTA_Kidney_non_diseased_FFPE.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "obsSets": { + "obsSets": [ + { + "name": "Azimuth broad", + "path": "tables/table/obs/azimuth_broad" + }, + { + "name": "Azimuth coarse", + "path": "tables/table/obs/azimuth_coarse" + }, + { + "name": "Azimuth fine", + "path": "tables/table/obs/azimuth_fine" + }, + { + "name": "Leiden (resolution 1.0)", + "path": "tables/table/obs/leiden_res_1.0" + } + ], + "tablePath": "tables/table" + }, + "image": { + "path": "images/morphology", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/cell_boundaries", + "tablePath": "tables/table", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/table/obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "cell", + "fileUid": "cells" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/Atera_v1_WTA_Kidney_non_diseased_FFPE.spatialdata.zarr", + "options": { + "obsPoints": { + "path": "points/transcripts_with_morton_codes", + "tablePath": "tables/table", + "coordinateSystem": "global", + "featureIndexColumn": "feature_name_codes", + "mortonCodeColumn": "morton_code_2d" + } + }, + "coordinationValues": { + "obsType": "point", + "featureType": "gene", + "fileUid": "points" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "embeddingType": { + "A": "UMAP" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "fileUid": { + "init_A_image_0": "cells", + "init_A_obsSegmentations_0": "cells", + "init_A_obsPoints_0": "points" + }, + "photometricInterpretation": { + "init_A_image_0": "BlackIsZero" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0, + "init_A_obsSegmentations_0": 1.0, + "init_A_obsPoints_0": 1.0 + }, + "spatialLayerVisible": { + "init_A_image_0": true, + "init_A_obsSegmentations_0": true, + "init_A_obsPoints_0": false + }, + "imageChannel": { + "init_A_image_0": "__dummy__", + "init_A_image_1": "__dummy__", + "init_A_image_2": "__dummy__", + "init_A_image_3": "__dummy__" + }, + "spatialTargetC": { + "init_A_image_0": 0, + "init_A_image_1": 1, + "init_A_image_2": 2, + "init_A_image_3": 3 + }, + "spatialChannelColor": { + "init_A_image_0": [ + 0, + 0, + 255 + ], + "init_A_image_1": [ + 0, + 255, + 0 + ], + "init_A_image_2": [ + 255, + 255, + 0 + ], + "init_A_image_3": [ + 255, + 0, + 0 + ], + "init_A_obsSegmentations_0": [ + 255, + 255, + 255 + ] + }, + "spatialChannelVisible": { + "init_A_image_0": true, + "init_A_image_1": true, + "init_A_image_2": true, + "init_A_image_3": true, + "init_A_obsSegmentations_0": true + }, + "spatialChannelOpacity": { + "init_A_image_0": 1.0, + "init_A_image_1": 1.0, + "init_A_image_2": 1.0, + "init_A_image_3": 1.0, + "init_A_obsSegmentations_0": 0.75 + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + }, + "init_A_obsPoints_0": { + "pointLayer": [ + "init_A_obsPoints_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "fileUid": { + "init_A_image_0": "init_A_image_0" + }, + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerVisible": { + "init_A_image_0": "init_A_image_0" + }, + "imageChannel": { + "init_A_image_0": [ + "init_A_image_0", + "init_A_image_1", + "init_A_image_2", + "init_A_image_3" + ] + } + }, + "imageChannel": { + "spatialTargetC": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3" + }, + "spatialChannelColor": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3" + }, + "spatialChannelVisible": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3" + }, + "spatialChannelOpacity": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "fileUid": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialLayerOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialLayerVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialChannelVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialChannelColor": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + }, + "init_A_obsPoints_0": { + "pointLayer": { + "fileUid": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "obsType": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "spatialLayerOpacity": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "spatialLayerVisible": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "obsColorEncoding": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "init_A_obsPoints_0": "point", + "A": "cell" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "cellSetSelection", + "init_A_obsPoints_0": "geneSelection" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": true + }, + "pointLayer": { + "init_A_obsPoints_0": "__dummy__" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 6, + "y": 6, + "w": 3, + "h": 6 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "obsType": "A" + }, + "x": 9, + "y": 6, + "w": 3, + "h": 6 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/Snakefile b/demos/spatialdata-aviti24-teton-hela-tnfa/Snakefile new file mode 100644 index 00000000..98b37d89 --- /dev/null +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/Snakefile @@ -0,0 +1,56 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Element Biosciences AVITI24 (Teton CytoProfiling) of HeLa cells stimulated with TNF-alpha +# (and TNF receptor / pathway variants) over a 0-240 minute time course, in 48 wells. +# - Source: Zenodo record 17394327, +# "High-Throughput Multiomics Profiling of Model Systems Using the AVITI24 Platform (Lopez et al.)" +# https://zenodo.org/records/17394327 (DOI: 10.5281/zenodo.17394327), deposited by Element Biosciences. +# The record states that the data will also be mirrored to GEO. +# - License: CC-BY-4.0. +# - Element's own Teton datasets (e.g., https://www.elementbiosciences.com/resources) need registration, +# so we use this open deposit instead. +# The record is a single 10 GB zip (mostly bulk RNA-seq FASTQ files). We only download the +# AVITI24 RawCellStats parquet member (~520 MB) using HTTP range requests. +# The deposit has per-cell counts and morphology features, but no images or segmentations. +ZIP_URL = "https://zenodo.org/api/records/17394327/files/GEO_submission.zip/content" +ZIP_MEMBER = "GEO_submission/Teton/RawCellStats_ACE_3678.parquet" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Convert the RawCellStats table to SpatialData (cells as circles, counts and morphology tables). +rule convert_to_spatialdata: + input: + (RAW_DIR / "RawCellStats_ACE_3678.parquet") + output: + directory(PROCESSED_DIR / "aviti24_teton_hela_tnfa.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py") + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + -o {output} + ''' + +rule download_data: + output: + (RAW_DIR / "RawCellStats_ACE_3678.parquet") + params: + script=(SRC_DIR / "download_zip_member.py"), + zip_url=ZIP_URL, + zip_member=ZIP_MEMBER + shell: + ''' + uv run --script {params.script} \ + -u "{params.zip_url}" \ + -m "{params.zip_member}" \ + -o {output} + ''' diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/config.yml b/demos/spatialdata-aviti24-teton-hela-tnfa/config.yml new file mode 100644 index 00000000..8d5ce0a8 --- /dev/null +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/config.yml @@ -0,0 +1,2 @@ +output: +- aviti24_teton_hela_tnfa.spatialdata.zarr diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/src/convert_to_spatialdata.py b/demos/spatialdata-aviti24-teton-hela-tnfa/src/convert_to_spatialdata.py new file mode 100644 index 00000000..30127683 --- /dev/null +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/src/convert_to_spatialdata.py @@ -0,0 +1,175 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "spatialdata==0.7.3", +# # anndata 0.13 exposes X as a None-keyed layer, which spatialdata 0.7.3 table validation rejects. +# "anndata==0.12.19", +# "scanpy==1.12.6", +# "leidenalg", +# "igraph", +# "pyarrow", +# "geopandas", +# ] +# /// +"""Convert an Element Biosciences AVITI24 (Teton CytoProfiling) RawCellStats parquet file to SpatialData. + +RawCellStats has one row per cell, with: +- Cell, Well, WellLabel, Tile, X, Y (cell centroid in pixels, within its tile), Area (pixels) +- per-target counts for each batch of targets, as "{target}.{batch}" (whole cell) + and "{target}_Nuclear.{batch}" (nucleus), plus "Unassigned.{batch}" +- cell paint morphology features (AreaShape_*, Intensity_*, Texture_*, ... for the CP01 and CP02 stains) + +There are no images or segmentations in this deposit, so cells are represented as circles +(at their centroids, with the area of the cell). +The tiles are laid out on a grid by their row (R) and column (C) on the flow cell, +with a gap between tiles. Positions across tiles are therefore a layout, not stage coordinates. + +Output elements: +- shapes/cells: one circle per cell +- tables/counts: (cells x targets) whole-cell counts (CSC), with a "nuclear" layer, Leiden clusters and a UMAP +- tables/morphology: (cells x cell paint features) +""" +import argparse +import re +import shutil +from os.path import isdir + +import anndata as ad +import geopandas as gpd +import numpy as np +import pandas as pd +import pyarrow.parquet as pq +import scanpy as sc +from scipy import sparse +from shapely import points +from spatialdata import SpatialData +from spatialdata.models import ShapesModel, TableModel + +SHAPES_NAME = "cells" +META_COLS = ["Cell", "Well", "WellLabel", "Tile", "X", "Y", "Area"] +COUNT_COL = re.compile(r"^(?P.+)\.(?PB\d+)$") +TILE_NAME = re.compile(r"^L(?P\d+)R(?P\d+)C(?P\d+)S(?P\d+)$") +# Tile size in pixels (the maximum X/Y in the data is just below this) and the gap between tiles in the layout. +TILE_WIDTH, TILE_HEIGHT, TILE_GAP = 5472, 3648, 400 + + +def split_columns(columns): + counts, nuclear, unassigned, morphology = [], {}, [], [] + for col in columns: + if col in META_COLS: + continue + m = COUNT_COL.match(col) + if m is None: + morphology.append(col) + elif m["target"] == "Unassigned": + unassigned.append(col) + elif m["target"].endswith("_Nuclear"): + nuclear[f"{m['target'][:-len('_Nuclear')]}.{m['batch']}"] = col + else: + counts.append(col) + return counts, nuclear, unassigned, morphology + + +def add_clusters(adata): + tmp = adata.copy() + tmp.X = tmp.X.tocsr() + sc.pp.filter_cells(tmp, min_counts=1) + sc.pp.normalize_total(tmp) + sc.pp.log1p(tmp) + sc.pp.pca(tmp, n_comps=30) + sc.pp.neighbors(tmp) + sc.tl.leiden(tmp, flavor="igraph", n_iterations=2, resolution=0.5, random_state=0) + sc.tl.umap(tmp, random_state=0) + + adata.obs["leiden"] = tmp.obs["leiden"].reindex(adata.obs_names) + adata.obs["leiden"] = adata.obs["leiden"].cat.add_categories(["no counts"]).fillna("no counts") + umap = np.full((adata.n_obs, 2), np.nan, dtype=np.float32) + umap[adata.obs_names.get_indexer(tmp.obs_names)] = tmp.obsm["X_umap"] + adata.obsm["X_umap"] = umap + + +def process(input_path, output_path): + columns = pq.ParquetFile(input_path).schema_arrow.names + count_cols, nuclear_cols, unassigned_cols, morphology_cols = split_columns(columns) + print(f"{len(count_cols)} targets, {len(nuclear_cols)} with nuclear counts, {len(morphology_cols)} morphology features") + + meta = pq.read_table(input_path, columns=META_COLS).to_pandas() + cell_ids = meta["Cell"].astype(str).to_numpy() + + # Layout of tiles on the flow cell grid. + tiles = meta["Tile"].astype(str).str.extract(TILE_NAME).astype(int) + x = meta["X"].to_numpy() + (tiles["col"].to_numpy() - 1) * (TILE_WIDTH + TILE_GAP) + y = meta["Y"].to_numpy() + (tiles["row"].to_numpy() - 1) * (TILE_HEIGHT + TILE_GAP) + radius = np.sqrt(meta["Area"].to_numpy() / np.pi) + shapes = ShapesModel.parse( + gpd.GeoDataFrame({"radius": radius}, geometry=points(np.column_stack([x, y])), index=pd.Index(cell_ids, name=None)) + ) + + # Observation metadata. + obs = pd.DataFrame(index=pd.Index(cell_ids)) + obs["cell_id"] = cell_ids + obs["region"] = pd.Categorical([SHAPES_NAME] * len(obs)) + obs["well"] = pd.Categorical(meta["Well"].astype(str).to_numpy()) + obs["well_label"] = pd.Categorical(meta["WellLabel"].astype(str).to_numpy()) + # WellLabel is "{treatment} {minutes}", e.g., "TNF 45" or "DMEM 0". + label_parts = meta["WellLabel"].astype(str).str.rsplit(" ", n=1, expand=True) + obs["treatment"] = pd.Categorical(label_parts[0].to_numpy()) + minutes = label_parts[1].astype(int) + obs["time_min"] = pd.Categorical( + minutes.astype(str).to_numpy(), categories=[str(m) for m in sorted(minutes.unique())], ordered=True + ) + obs["tile"] = pd.Categorical(meta["Tile"].astype(str).to_numpy()) + obs["x_in_tile"] = meta["X"].to_numpy() + obs["y_in_tile"] = meta["Y"].to_numpy() + obs["area"] = meta["Area"].to_numpy() + unassigned = pq.read_table(input_path, columns=unassigned_cols).to_pandas() + for col in unassigned_cols: + obs[f"unassigned_{col.rsplit('.', 1)[1]}"] = unassigned[col].to_numpy(dtype=np.float32) + + # Counts table (whole cell), with nuclear counts as a layer. + counts = pq.read_table(input_path, columns=count_cols).to_pandas().to_numpy(dtype=np.float32) + nuclear = np.zeros_like(counts) + nuclear_present = [c for c in count_cols if c in nuclear_cols] + nuclear_df = pq.read_table(input_path, columns=[nuclear_cols[c] for c in nuclear_present]).to_pandas() + for c in nuclear_present: + nuclear[:, count_cols.index(c)] = nuclear_df[nuclear_cols[c]].to_numpy(dtype=np.float32) + var = pd.DataFrame( + { + "target": [COUNT_COL.match(c)["target"] for c in count_cols], + "batch": pd.Categorical([COUNT_COL.match(c)["batch"] for c in count_cols]), + }, + index=pd.Index(count_cols), + ) + counts_adata = ad.AnnData( + X=sparse.csc_matrix(counts), + obs=obs.copy(), + var=var, + layers={"nuclear": sparse.csc_matrix(nuclear)}, + ) + counts_adata.obsm["spatial"] = np.column_stack([x, y]) + add_clusters(counts_adata) + + # Morphology (cell paint) table. + morphology = pq.read_table(input_path, columns=morphology_cols).to_pandas().to_numpy(dtype=np.float32) + morphology_obs = obs[["cell_id", "region", "well", "well_label", "treatment", "time_min"]].copy() + morphology_obs["leiden"] = counts_adata.obs["leiden"] + morphology_adata = ad.AnnData(X=morphology, obs=morphology_obs, var=pd.DataFrame(index=pd.Index(morphology_cols))) + + tables = { + name: TableModel.parse(adata, region=SHAPES_NAME, region_key="region", instance_key="cell_id") + for name, adata in [("counts", counts_adata), ("morphology", morphology_adata)] + } + sdata = SpatialData(shapes={SHAPES_NAME: shapes}, tables=tables) + + if isdir(output_path): + shutil.rmtree(output_path) + sdata.write(output_path) + print(sdata) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input', type=str, required=True, help='Input RawCellStats .parquet file') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + args = parser.parse_args() + process(args.input, args.output) diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/src/download_zip_member.py b/demos/spatialdata-aviti24-teton-hela-tnfa/src/download_zip_member.py new file mode 100644 index 00000000..28e59d42 --- /dev/null +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/src/download_zip_member.py @@ -0,0 +1,93 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [] +# /// +"""Download a single member of a remote zip file, using HTTP range requests. + +The Zenodo record for this demo is one 10 GB zip, mostly bulk RNA-seq FASTQ files. +Only the AVITI24 (Teton) RawCellStats parquet file (~520 MB compressed) is needed here, +so we read the zip's central directory and then stream only that member's bytes. +""" +import argparse +import io +import os +import shutil +import time +import urllib.request +import zipfile + + +class HttpRangeFile(io.RawIOBase): + """A read-only, seekable file object backed by HTTP range requests.""" + + def __init__(self, url, retries=10): + self.retries = retries + response = self._open(urllib.request.Request(url, method="HEAD")) + self.url = response.url # Resolve redirects once. + self.size = int(response.headers["Content-Length"]) + self.pos = 0 + + def _open(self, request): + for attempt in range(self.retries): + try: + return urllib.request.urlopen(request, timeout=120) + except OSError: + if attempt == self.retries - 1: + raise + time.sleep(3) + + def readable(self): + return True + + def seekable(self): + return True + + def tell(self): + return self.pos + + def seek(self, offset, whence=io.SEEK_SET): + if whence == io.SEEK_SET: + self.pos = offset + elif whence == io.SEEK_CUR: + self.pos += offset + else: + self.pos = self.size + offset + return self.pos + + def read(self, n=-1): + if n is None or n < 0: + n = self.size - self.pos + n = min(n, self.size - self.pos) + if n <= 0: + return b"" + headers = {"Range": f"bytes={self.pos}-{self.pos + n - 1}"} + data = self._open(urllib.request.Request(self.url, headers=headers)).read() + self.pos += len(data) + return data + + def readinto(self, b): + data = self.read(len(b)) + b[:len(data)] = data + return len(data) + + +def download_member(url, member, output_path): + # Buffer reads in 16 MB blocks, so the member's data is streamed with few requests. + remote = io.BufferedReader(HttpRangeFile(url), buffer_size=1 << 24) + with zipfile.ZipFile(remote) as zf: + info = zf.getinfo(member) + print(f"Downloading {member} ({info.compress_size:,} bytes compressed, {info.file_size:,} bytes)") + tmp_path = f"{output_path}.tmp" + with zf.open(info) as src, open(tmp_path, "wb") as dst: + # ZipExtFile checks the CRC-32 of the member when it reaches the end. + shutil.copyfileobj(src, dst, length=1 << 24) + os.replace(tmp_path, output_path) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-u', '--url', type=str, required=True, help='URL of the remote zip file') + parser.add_argument('-m', '--member', type=str, required=True, help='Path of the member within the zip file') + parser.add_argument('-o', '--output', type=str, required=True, help='Output file') + args = parser.parse_args() + download_member(args.url, args.member, args.output) diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/vitessce.template.json b/demos/spatialdata-aviti24-teton-hela-tnfa/vitessce.template.json new file mode 100644 index 00000000..15d90f99 --- /dev/null +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/vitessce.template.json @@ -0,0 +1,180 @@ +{ + "version": "1.0.18", + "name": "AVITI24 Teton CytoProfiling of TNF-alpha-stimulated HeLa cells", + "description": "Element Biosciences AVITI24 RawCellStats from Zenodo 10.5281/zenodo.17394327 (Lopez et al.). Cells are circles at their centroids, with tiles laid out on the flow cell grid.", + "datasets": [ + { + "uid": "A", + "name": "AVITI24 Teton", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/aviti24_teton_hela_tnfa.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/counts/X" + }, + "obsSpots": { + "path": "shapes/cells", + "tablePath": "tables/counts", + "coordinateSystem": "global" + }, + "obsSets": { + "tablePath": "tables/counts", + "obsSets": [ + { + "name": "Leiden clusters", + "path": "tables/counts/obs/leiden" + }, + { + "name": "Treatment", + "path": "tables/counts/obs/treatment" + }, + { + "name": "Time (minutes)", + "path": "tables/counts/obs/time_min" + }, + { + "name": "Well label", + "path": "tables/counts/obs/well_label" + } + ] + }, + "obsEmbedding": [ + { + "path": "tables/counts/obsm/X_umap", + "dims": [0, 1], + "embeddingType": "UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "target" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "obsType": { + "A": "cell" + }, + "featureType": { + "A": "target" + }, + "embeddingType": { + "A": "UMAP" + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "spotLayer": { + "init_A_obsSpots_0": "__dummy__" + }, + "metaCoordinationScopes": { + "init_A_obsSpots_0": { + "spotLayer": [ + "init_A_obsSpots_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_obsSpots_0": { + "spotLayer": { + "obsType": { + "init_A_obsSpots_0": "A" + }, + "featureType": { + "init_A_obsSpots_0": "A" + }, + "obsColorEncoding": { + "init_A_obsSpots_0": "A" + } + } + } + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_obsSpots_0" + ], + "obsType": "A", + "featureType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_obsSpots_0" + ], + "obsType": "A", + "featureType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 4 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 4 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 4, + "w": 3, + "h": 8 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "embeddingType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 4, + "w": 3, + "h": 8 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-codex-hubmap-large-intestine/Snakefile b/demos/spatialdata-codex-hubmap-large-intestine/Snakefile new file mode 100644 index 00000000..4fe3b237 --- /dev/null +++ b/demos/spatialdata-codex-hubmap-large-intestine/Snakefile @@ -0,0 +1,72 @@ +import re + +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Akoya CODEX (now PhenoCycler) multiplexed immunofluorescence data from HuBMAP. +# +# Processed dataset: HBM996.CGFD.228 (CODEX [Cytokit + SPRM]), +# uuid c945cbd75f2da373d1ccfe86694f9c34 +# https://portal.hubmapconsortium.org/browse/dataset/c945cbd75f2da373d1ccfe86694f9c34 +# "CODEX [Cytokit + SPRM] data from the large intestine of a 37-year-old white male" (Stanford TMC). +# 54 channels (52 antibodies + nuclear stains), ~9.5k x 10k pixels at 377 nm/pixel. +# Raw (parent) dataset: HBM742.NHHQ.357, uuid 98c1bc0a44802108a6dcf8ce281628a7 +# https://doi.org/10.35079/HBM742.NHHQ.357 (sample B008-A-201, donor B008; Keyence BZ-X710). +# Publication: Hickey, J.W. et al. "Organization of the human intestine at single-cell resolution." +# Nature 619, 572-584 (2023). https://doi.org/10.1038/s41586-023-05915-x +# Pipeline: HuBMAP Cytokit segmentation + SPRM (https://github.com/hubmapconsortium/sprm). +# Access: HuBMAP public (open, no login) data; see https://hubmapconsortium.org/policies/ +# Related example (inspiration, different dataset): +# https://github.com/MicTott/spatialscape-examples/tree/main/phenocycler-lymph-node +# +# Files are downloaded from the HuBMAP assets server (https://assets.hubmapconsortium.org//). +# Note: the assets server returns HTTP 403 for the default curl User-Agent, so we set a generic one. +HUBMAP_UUID = "c945cbd75f2da373d1ccfe86694f9c34" +HUBMAP_ASSETS_URL = f"https://assets.hubmapconsortium.org/{HUBMAP_UUID}" +FILES = { + # Pyramidal (compressed) versions of the pipeline_output/{expr,mask} OME-TIFFs (~1.7 GB total). + "expr.ome.tif": "ometiff-pyramids/pipeline_output/expr/reg001_expr.ome.tif", + "mask.ome.tif": "ometiff-pyramids/pipeline_output/mask/reg001_mask.ome.tif", + # SPRM cell-by-marker table (AnnData-Zarr, zipped). + "anndata.zarr.zip": "anndata-zarr/reg001_expr-anndata.zarr.zip", +} + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Combine image, segmentation mask, and SPRM table into one SpatialData store. +rule convert_to_spatialdata: + input: + expr=(RAW_DIR / "expr.ome.tif"), + mask=(RAW_DIR / "mask.ome.tif"), + anndata_zip=(RAW_DIR / "anndata.zarr.zip"), + output: + directory(PROCESSED_DIR / "codex_hubmap_large_intestine.spatialdata.zarr") + params: + script=(SRC_DIR / "sprm_to_spatialdata.py") + shell: + ''' + uv run --script {params.script} \ + --expr {input.expr} \ + --mask {input.mask} \ + --anndata-zip {input.anndata_zip} \ + -o {output} + ''' + +rule download_data: + output: + (RAW_DIR / "{filename}") + wildcard_constraints: + filename="|".join(re.escape(k) for k in FILES.keys()) + params: + file_url=lambda w: f"{HUBMAP_ASSETS_URL}/{FILES[w.filename]}" + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -A "vitessce-demos" -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-codex-hubmap-large-intestine/config.yml b/demos/spatialdata-codex-hubmap-large-intestine/config.yml new file mode 100644 index 00000000..bebc6a98 --- /dev/null +++ b/demos/spatialdata-codex-hubmap-large-intestine/config.yml @@ -0,0 +1,2 @@ +output: +- codex_hubmap_large_intestine.spatialdata.zarr diff --git a/demos/spatialdata-codex-hubmap-large-intestine/src/sprm_to_spatialdata.py b/demos/spatialdata-codex-hubmap-large-intestine/src/sprm_to_spatialdata.py new file mode 100644 index 00000000..a950163e --- /dev/null +++ b/demos/spatialdata-codex-hubmap-large-intestine/src/sprm_to_spatialdata.py @@ -0,0 +1,189 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# # anndata 0.13 exposes X as layers[None], which spatialdata 0.7.3 validation rejects. +# "anndata<0.13", +# "tifffile>=2025.5.10", +# "imagecodecs", +# "dask", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +""" +Convert the outputs of the HuBMAP DeepCell/Cytokit + SPRM pipelines +(expression OME-TIFF, segmentation mask OME-TIFF, SPRM AnnData-Zarr zip) +into a single SpatialData Zarr store with: + +- images/image: multiscale (pyramidal) multiplexed image (c, y, x) +- labels/cell_labels: multiscale cell segmentation bitmask +- tables/table: cell-by-marker mean intensities, annotating labels/cell_labels, + with SPRM K-Means cluster assignments in obs and t-SNE in obsm. +""" +import argparse +import re +import tempfile +import zipfile + +import anndata as ad +import dask.array as da +import numpy as np +import pandas as pd +import tifffile +import zarr +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, Labels2DModel, TableModel + +LABELS_KEY = "cell_labels" +IMAGE_KEY = "image" +CHUNK_SIZE = 512 + + +class _ArrayLike: + """Minimal array-like wrapper around a (TIFF-backed) zarr array.""" + + def __init__(self, z): + self._z = z + self.shape = z.shape + self.dtype = z.dtype + self.ndim = len(z.shape) + + def __getitem__(self, key): + return np.asarray(self._z[key]) + + +def read_ome_tiff(path): + """Lazily read the full-resolution level of an OME-TIFF as (C, Y, X) dask array, plus channel names.""" + with tifffile.TiffFile(path) as tif: + ome = tifffile.xml2dict(tif.ome_metadata) + series = tif.series[0] + axes = series.axes + shape = series.shape + channels = ome["OME"]["Image"] + if isinstance(channels, list): + channels = channels[0] + channels = channels["Pixels"]["Channel"] + if isinstance(channels, dict): + channels = [channels] + names = [str(c.get("Name", f"Channel {i}")) for i, c in enumerate(channels)] + + store = tifffile.imread(path, aszarr=True, series=0, level=0) + z = zarr.open(store, mode="r") + # Wrap the zarr array so that spatialdata does not treat the TIFF-backed + # store as a "backing file" of the element (it expects a store with a .root). + arr = da.from_array(_ArrayLike(z), chunks=z.chunks, asarray=False) + # Squeeze singleton non-YX axes (e.g. "QQYX" with shape (C, 1, Y, X)). + keep = [i for i, (ax, n) in enumerate(zip(axes, shape)) if ax in "YX" or n > 1] + arr = arr.reshape(tuple(shape[i] for i in keep)) + if arr.ndim == 2: + arr = arr[np.newaxis, ...] + assert arr.ndim == 3, f"Unexpected image shape {shape} with axes {axes}" + if len(names) != arr.shape[0]: + names = [f"Channel {i}" for i in range(arr.shape[0])] + return arr, names + + +def make_unique(names): + seen = {} + result = [] + for n in names: + if n in seen: + seen[n] += 1 + result.append(f"{n}_{seen[n]}") + else: + seen[n] = 0 + result.append(n) + return result + + +def scale_factors_for(shape_yx, min_size=CHUNK_SIZE): + factors = [] + size = max(shape_yx) + while size > min_size: + factors.append(2) + size = size // 2 + return factors + + +def slugify(name): + return re.sub(r"[^0-9a-zA-Z]+", "_", name).strip("_").lower() + + +def read_sprm_table(anndata_zip_path, tmp_dir): + # The HuBMAP anndata-zarr zip contains the contents of an AnnData Zarr store at its root. + with zipfile.ZipFile(anndata_zip_path) as zf: + zf.extractall(tmp_dir) + adata = ad.read_zarr(tmp_dir) + + # Keep only the per-cell (not nucleus/boundary) cluster assignments, with zarr-path-friendly names. + cell_cols = [c for c in adata.obs.columns if c.startswith("Cell K-Means")] + obs = adata.obs[cell_cols].copy() + obs.columns = [slugify(c.removeprefix("Cell ")) for c in cell_cols] + for col in obs.columns: + obs[col] = pd.Categorical([f"Cluster {v}" for v in obs[col]], categories=[f"Cluster {v}" for v in sorted(obs[col].unique())]) + obs["cell_id"] = adata.obs_names.astype(int) + obs["region"] = pd.Categorical([LABELS_KEY] * adata.n_obs) + obs.index = adata.obs_names.astype(str) + + # X is the per-cell mean intensity of each channel (SPRM cell_channel_mean). + new_adata = ad.AnnData( + X=np.asarray(adata.X, dtype=np.float32), + obs=obs, + var=pd.DataFrame(index=make_unique([str(v) for v in adata.var_names])), + layers={ + "cell_x_antigen_total": np.asarray(adata.layers["cell_x_antigen_total"], dtype=np.float32), + }, + obsm={ + "spatial": np.asarray(adata.obsm["xy"], dtype=np.float32), + "X_tsne": np.asarray(adata.obsm["tsne"], dtype=np.float32), + }, + ) + return TableModel.parse(new_adata, region=LABELS_KEY, region_key="region", instance_key="cell_id") + + +def main(expr_path, mask_path, anndata_zip_path, output_path, mask_channel): + img, channel_names = read_ome_tiff(expr_path) + if img.dtype == np.int16: + # MIBI images are stored as int16 counts; Vitessce prefers unsigned types. + img = da.clip(img, 0, None).astype(np.uint16) + image = Image2DModel.parse( + img, + dims=("c", "y", "x"), + c_coords=make_unique(channel_names), + scale_factors=scale_factors_for(img.shape[1:]), + chunks=(1, CHUNK_SIZE, CHUNK_SIZE), + ) + + mask, mask_names = read_ome_tiff(mask_path) + mask_index = mask_names.index(mask_channel) if mask_channel in mask_names else 0 + labels = Labels2DModel.parse( + mask[mask_index], + dims=("y", "x"), + scale_factors=scale_factors_for(mask.shape[1:]), + chunks=(CHUNK_SIZE, CHUNK_SIZE), + ) + + with tempfile.TemporaryDirectory() as tmp_dir: + table = read_sprm_table(anndata_zip_path, tmp_dir) + sdata = SpatialData( + images={IMAGE_KEY: image}, + labels={LABELS_KEY: labels}, + tables={"table": table}, + ) + sdata.write(output_path, overwrite=True) + print(sdata) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--expr", required=True, help="Expression (multiplexed image) OME-TIFF") + parser.add_argument("--mask", required=True, help="Segmentation mask OME-TIFF") + parser.add_argument("--anndata-zip", required=True, help="SPRM AnnData-Zarr .zip") + parser.add_argument("--mask-channel", default="cells", help="Name of the mask channel to use as cell labels") + parser.add_argument("-o", "--output", required=True, help="Output SpatialData .zarr store") + args = parser.parse_args() + main(args.expr, args.mask, args.anndata_zip, args.output, args.mask_channel) diff --git a/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json b/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json new file mode 100644 index 00000000..e90864ed --- /dev/null +++ b/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json @@ -0,0 +1,364 @@ +{ + "version": "1.0.18", + "name": "CODEX human large intestine (HuBMAP HBM996.CGFD.228)", + "description": "Akoya CODEX 54-channel image of human large intestine (Hickey et al. 2023) with Cytokit segmentation and SPRM cell-by-marker table, from HuBMAP", + "datasets": [ + { + "uid": "A", + "name": "CODEX human large intestine (HuBMAP HBM996.CGFD.228)", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/codex_hubmap_large_intestine.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X", + "region": "cell_labels" + }, + "obsSets": { + "obsSets": [ + { + "name": "SPRM K-Means [Mean] Expression", + "path": "tables/table/obs/k_means_mean_expression" + }, + { + "name": "SPRM K-Means [Covariance] Expression", + "path": "tables/table/obs/k_means_covariance_expression" + }, + { + "name": "SPRM K-Means [Total] Expression", + "path": "tables/table/obs/k_means_total_expression" + }, + { + "name": "SPRM K-Means [UMAP All Features]", + "path": "tables/table/obs/k_means_umap_all_features" + } + ], + "tablePath": "tables/table", + "region": "cell_labels" + }, + "image": { + "path": "images/image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "labels/cell_labels", + "tablePath": "tables/table", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/table/obsm/X_tsne", + "dims": [ + 0, + 1 + ], + "embeddingType": "t-SNE" + } + ] + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "marker" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "embeddingType": { + "A": "t-SNE" + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "BlackIsZero" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0, + "init_A_obsSegmentations_0": 1.0 + }, + "imageChannel": { + "init_A_image_0": "__dummy__", + "init_A_image_1": "__dummy__", + "init_A_image_2": "__dummy__", + "init_A_image_3": "__dummy__", + "init_A_image_4": "__dummy__" + }, + "spatialTargetC": { + "init_A_image_0": 0, + "init_A_image_1": 50, + "init_A_image_2": 7, + "init_A_image_3": 46, + "init_A_image_4": 25 + }, + "spatialChannelColor": { + "init_A_image_0": [ + 0, + 0, + 255 + ], + "init_A_image_1": [ + 0, + 255, + 0 + ], + "init_A_image_2": [ + 255, + 0, + 0 + ], + "init_A_image_3": [ + 255, + 255, + 0 + ], + "init_A_image_4": [ + 255, + 0, + 255 + ] + }, + "spatialChannelWindow": { + "init_A_image_0": [ + 0, + 8000 + ], + "init_A_image_1": [ + 0, + 4000 + ], + "init_A_image_2": [ + 0, + 6000 + ], + "init_A_image_3": [ + 0, + 1500 + ], + "init_A_image_4": [ + 0, + 8000 + ] + }, + "spatialChannelVisible": { + "init_A_image_0": true, + "init_A_image_1": true, + "init_A_image_2": true, + "init_A_image_3": true, + "init_A_image_4": true, + "init_A_obsSegmentations_0": true + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + }, + "imageChannel": { + "init_A_image_0": [ + "init_A_image_0", + "init_A_image_1", + "init_A_image_2", + "init_A_image_3", + "init_A_image_4" + ] + } + }, + "imageChannel": { + "spatialTargetC": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelColor": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelWindow": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelVisible": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "spatialLayerVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialLayerOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsColorEncoding": { + "init_A_obsSegmentations_0": "A" + }, + "spatialChannelVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationStrokeWidth": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialLayerVisible": { + "init_A_obsSegmentations_0": true + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": false + }, + "spatialSegmentationStrokeWidth": { + "init_A_obsSegmentations_0": 1.0 + }, + "obsType": { + "A": "cell" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 6 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 3, + "coordinationScopesBy": {} + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 3, + "w": 3, + "h": 3, + "coordinationScopesBy": {} + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "heatmap", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 0, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-cosmx-nsclc/Snakefile b/demos/spatialdata-cosmx-nsclc/Snakefile new file mode 100644 index 00000000..187a8f1d --- /dev/null +++ b/demos/spatialdata-cosmx-nsclc/Snakefile @@ -0,0 +1,65 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Bruker (NanoString) CosMx SMI: non-small-cell lung cancer (NSCLC) FFPE dataset, +# section Lung9_Rep1 (20 FOVs, 960-plex RNA panel, ~90k cells). +# Publication: He et al. (2022) "High-plex imaging of RNA and proteins at subcellular resolution +# in fixed tissue by spatial molecular imaging", Nature Biotechnology 40, 1794-1806. +# https://doi.org/10.1038/s41587-022-01483-z +# Source (original, NanoString/Bruker public S3 bucket; listable and downloadable without an account or form): +# https://nanostring-public-share.s3.us-west-2.amazonaws.com/SMI-Compressed/SMI-ReadMe.html (file format descriptions) +# https://nanostring-public-share.s3.us-west-2.amazonaws.com/SMI-Compressed/Lung9_Rep1/Lung9_Rep1+SMI+Flat+data.tar.gz +# Product page: https://nanostring.com/products/cosmx-spatial-molecular-imager/ffpe-dataset/nsclc-ffpe-dataset/ +# License: not stated in the bucket's ReadMe; NanoString provides it as a public demo dataset. +# Inspiration (not used as data source): +# https://github.com/MicTott/spatialscape-examples/tree/main/cosmx-nsclc +# https://github.com/broadinstitute/celldega/blob/main/notebooks/CosMx_pre-process.ipynb +# Note: the paper's cell type annotations are only distributed as an R/Giotto object +# ("All SMI Giotto object.tar.gz"), so this pipeline computes Leiden clusters instead. +SECTION = "Lung9_Rep1" +TAR_URL = f"https://nanostring-public-share.s3.us-west-2.amazonaws.com/SMI-Compressed/{SECTION}/{SECTION}+SMI+Flat+data.tar.gz" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Stitch the per-FOV images, trace the cell boundaries from the label masks, +# build the cell-by-gene table, and add the morton-sorted transcripts. +rule convert_to_spatialdata: + input: + (RAW_DIR / SECTION / f"{SECTION}-Flat_files_and_images") + output: + directory(PROCESSED_DIR / "cosmx_nsclc_lung9_rep1.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py"), + section=SECTION + shell: + ''' + uv run --script {params.script} -i {input} -s {params.section} -o {output} + ''' + +# The CellOverlay and CompartmentLabels images are not needed. +rule extract_data: + input: + (RAW_DIR / f"{SECTION}_SMI_Flat_data.tar.gz") + output: + directory(RAW_DIR / SECTION / f"{SECTION}-Flat_files_and_images") + shell: + ''' + tar -xzf {input} -C "$(dirname {input})" --exclude '*/CellOverlay*' --exclude '*/CompartmentLabels*' + ''' + +rule download_data: + output: + (RAW_DIR / f"{SECTION}_SMI_Flat_data.tar.gz") + params: + file_url=TAR_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-cosmx-nsclc/config.yml b/demos/spatialdata-cosmx-nsclc/config.yml new file mode 100644 index 00000000..168544da --- /dev/null +++ b/demos/spatialdata-cosmx-nsclc/config.yml @@ -0,0 +1,2 @@ +output: +- cosmx_nsclc_lung9_rep1.spatialdata.zarr diff --git a/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py b/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py new file mode 100644 index 00000000..981f8d49 --- /dev/null +++ b/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py @@ -0,0 +1,265 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# "anndata==0.12.19", # anndata 0.13 exposes X as layers[None], which spatialdata 0.7.3 TableModel.parse rejects. +# "scikit-learn", +# "igraph", +# "rasterio", +# "shapely", +# "geopandas", +# "pillow", +# "tifffile", +# "imagecodecs", +# "pyarrow", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Convert one section of the CosMx SMI NSCLC "flat files" export to a SpatialData store. + +Elements written: +- images/composite: the per-FOV CellComposite RGB images stitched into one multiscale image. +- shapes/cell_boundaries: one polygon per cell, traced from the per-FOV CellLabels masks. +- points/transcripts: all transcripts, morton-sorted for tiled access in Vitessce. +- tables/table: cell-by-gene AnnData (X = log-normalized, layers/counts = raw counts), + with the cell metadata and Leiden clusters; annotates shapes/cell_boundaries. + +Coordinate system ("global"): pixels of the stitched image (0.18 um per pixel). +CosMx global coordinates count y upwards (within a FOV, the local y of a pixel in image row r +is FOV_HEIGHT - r), whereas image rows count downwards. To display the images as acquired, +we use X = x_global_px - x_min and Y = y_top - y_global_px, where y_top is the top edge of the +top-most FOV. The script checks this against the label masks (mask centroids vs. the metadata). +""" +import argparse +from os.path import join + +import numpy as np +import pandas as pd +import geopandas as gpd +import igraph as ig +import scipy.sparse as sp +import tifffile +import dask.dataframe as dd +from anndata import AnnData +from sklearn.decomposition import PCA +from sklearn.neighbors import NearestNeighbors +from PIL import Image +from rasterio.features import shapes as raster_shapes +from affine import Affine +from shapely.geometry import shape as to_shape +from spatialdata import SpatialData, read_zarr +from spatialdata.models import Image2DModel, ShapesModel, PointsModel, TableModel +from spatialdata.transformations import Identity +from vitessce.data_utils import ( + sdata_morton_sort_points, + sdata_points_process_columns, + sdata_points_modify_row_group_size, +) + +FOV_W, FOV_H = 5472, 3648 # CosMx FOV size in pixels. +CS = "global" +NON_GENE_PREFIXES = ("NegPrb", "SystemControl", "FalseCode") + + +def cell_key(fov, cell_id): + return f"{int(fov)}_{int(cell_id)}" + + +def load_fov_positions(flat_dir, section): + pos = pd.read_csv(join(flat_dir, f"{section}_fov_positions_file.csv")) + pos["fov"] = pos["fov"].astype(int) + return pos.set_index("fov") + + +def frame_from_positions(pos): + x_min = pos["x_global_px"].min() + y_top = pos["y_global_px"].max() + FOV_H + width = int(np.ceil(pos["x_global_px"].max() - x_min)) + FOV_W + height = int(np.ceil(y_top - pos["y_global_px"].min())) + return x_min, y_top, width, height + + +def fov_offsets(row, x_min, y_top): + # (column, row) of the FOV's top-left pixel within the stitched image. + return int(round(row["x_global_px"] - x_min)), int(round(y_top - (row["y_global_px"] + FOV_H))) + + +def stitch_composite(flat_dir, pos, x_min, y_top, width, height): + canvas = np.zeros((height, width, 3), dtype=np.uint8) + for fov, row in pos.iterrows(): + img = np.asarray(Image.open(join(flat_dir, "CellComposite", f"CellComposite_F{fov:03d}.jpg")).convert("RGB")) + assert img.shape[:2] == (FOV_H, FOV_W), img.shape + ox, oy = fov_offsets(row, x_min, y_top) + canvas[oy:oy + FOV_H, ox:ox + FOV_W] = img + return np.moveaxis(canvas, -1, 0) # (c, y, x) + + +def trace_boundaries(flat_dir, pos, x_min, y_top, meta): + geoms, ids, offsets = [], [], [] + for fov, row in pos.iterrows(): + labels = tifffile.imread(join(flat_dir, "CellLabels", f"CellLabels_F{fov:03d}.tif")).astype(np.int32) + assert labels.shape == (FOV_H, FOV_W), labels.shape + ox, oy = fov_offsets(row, x_min, y_top) + # Keep the largest connected piece of each label. + best = {} + for geom, value in raster_shapes(labels, mask=labels > 0, connectivity=4, transform=Affine.translation(ox, oy)): + poly = to_shape(geom) + value = int(value) + if value not in best or poly.area > best[value].area: + best[value] = poly + for value, poly in best.items(): + ids.append(cell_key(fov, value)) + geoms.append(poly.simplify(0.5, preserve_topology=True)) + # Orientation check on a sample of cells: polygon centroid vs. metadata center. + fov_meta = meta[meta["fov"] == fov].set_index("cell_ID") + for value in list(best.keys())[:200]: + if value in fov_meta.index: + c = best[value].centroid + m = fov_meta.loc[value] + offsets.append(np.hypot(c.x - (m["CenterX_global_px"] - x_min), c.y - (y_top - m["CenterY_global_px"]))) + med = float(np.median(offsets)) + print(f"Median distance between mask centroids and metadata cell centers: {med:.2f} px") + assert med < 10, "Label masks do not line up with the cell metadata; check the y-axis orientation." + return gpd.GeoDataFrame({"geometry": geoms}, index=pd.Index(ids, name="cell_id")) + + +def build_table(flat_dir, section, x_min, y_top, tx_targets): + expr = pd.read_csv(join(flat_dir, f"{section}_exprMat_file.csv")) + expr = expr[expr["cell_ID"] != 0] # cell_ID 0 sums the transcripts outside of cells. + meta = pd.read_csv(join(flat_dir, f"{section}_metadata_file.csv")) + meta["fov"] = meta["fov"].astype(int) + meta.index = [cell_key(f, c) for f, c in zip(meta["fov"], meta["cell_ID"])] + obs_index = [cell_key(f, c) for f, c in zip(expr["fov"], expr["cell_ID"])] + meta = meta.loc[obs_index] + + gene_cols = [c for c in expr.columns if c not in ("fov", "cell_ID") and not c.startswith(NON_GENE_PREFIXES)] + # The exprMat column names were mangled by R (e.g., "HLA.A"); use the transcript file's names (e.g., "HLA-A"). + def fix_name(col): + if col in tx_targets: + return col + alt = col.replace(".", "-") + return alt if alt in tx_targets else col + var_names = [fix_name(c) for c in gene_cols] + + counts = sp.csr_matrix(expr[gene_cols].to_numpy(dtype=np.float32)) + obs = meta.drop(columns=["fov", "cell_ID"]).copy() + obs.insert(0, "fov", pd.Categorical(meta["fov"].astype(str))) + obs.insert(1, "fov_cell_ID", meta["cell_ID"].astype(int).to_numpy()) + obs["region"] = pd.Categorical(["cell_boundaries"] * len(obs)) + obs["cell_id"] = obs.index.to_numpy() + adata = AnnData(X=counts, obs=obs, var=pd.DataFrame(index=pd.Index(var_names))) + adata.obs_names = pd.Index(obs_index) + adata.obsm["spatial"] = np.stack([ + meta["CenterX_global_px"].to_numpy() - x_min, + y_top - meta["CenterY_global_px"].to_numpy(), + ], axis=1) + + # Basic clustering for cell sets: log-normalization, PCA, kNN graph, and Leiden (via igraph). + # (Done without scanpy to avoid its numba/scipy version constraints.) + adata.layers["counts"] = adata.X.copy() + totals = np.asarray(adata.X.sum(axis=1)).ravel() + adata = adata[totals > 0].copy() + totals = totals[totals > 0] + target_sum = np.median(totals) + norm = sp.diags((target_sum / totals).astype(np.float32)) @ adata.layers["counts"] + norm = sp.csr_matrix(norm, dtype=np.float32) + norm.data = np.log1p(norm.data) + adata.X = norm + pcs = PCA(n_components=30, random_state=0).fit_transform(norm.toarray()) + adata.obsm["X_pca"] = pcs.astype(np.float32) + knn = NearestNeighbors(n_neighbors=15).fit(pcs).kneighbors_graph(mode="connectivity").tocoo() + graph = ig.Graph(n=adata.n_obs, edges=np.stack([knn.row, knn.col], axis=1).tolist(), directed=False).simplify() + partition = graph.community_leiden(objective_function="modularity", resolution=1.0, n_iterations=2) + membership = np.asarray(partition.membership) + # Order clusters by size (0 = largest). + order = {c: i for i, c in enumerate(pd.Series(membership).value_counts().index)} + adata.obs["leiden"] = pd.Categorical([str(order[c]) for c in membership], categories=[str(i) for i in range(len(order))]) + return adata, meta + + +def load_transcripts(flat_dir, section, x_min, y_top): + tx = pd.read_csv( + join(flat_dir, f"{section}_tx_file.csv"), + usecols=["fov", "cell_ID", "x_global_px", "y_global_px", "z", "target", "CellComp"], + engine="pyarrow", + ) + df = pd.DataFrame({ + "x": (tx["x_global_px"].to_numpy() - x_min).astype(np.float32), + "y": (y_top - tx["y_global_px"].to_numpy()).astype(np.float32), + # Named z_slice (rather than z) so that the points are treated as 2D. + "z_slice": tx["z"].astype(np.int16).to_numpy(), + "fov": tx["fov"].astype(np.int16).to_numpy(), + "cell_id": np.where( + tx["cell_ID"].to_numpy() == 0, + "", + tx["fov"].astype(str).to_numpy() + "_" + tx["cell_ID"].astype(str).to_numpy(), + ), + "target": tx["target"].astype(str).to_numpy(), + "CellComp": tx["CellComp"].astype(str).to_numpy(), + }) + return df + + +def process(flat_dir, section, output_path): + pos = load_fov_positions(flat_dir, section) + x_min, y_top, width, height = frame_from_positions(pos) + print(f"{len(pos)} FOVs; stitched image is {width} x {height} px") + + tx = load_transcripts(flat_dir, section, x_min, y_top) + print(f"{len(tx):,} transcripts") + tx_targets = set(tx["target"].unique()) + + adata, meta = build_table(flat_dir, section, x_min, y_top, tx_targets) + print(f"{adata.n_obs:,} cells x {adata.n_vars} genes; {adata.obs['leiden'].nunique()} Leiden clusters") + + boundaries = trace_boundaries(flat_dir, pos, x_min, y_top, meta) + boundaries = boundaries.loc[boundaries.index.intersection(adata.obs_names)] + # Keep only cells that have a boundary, in the same order as the boundaries. + adata = adata[adata.obs_names.isin(boundaries.index)].copy() + boundaries = boundaries.loc[adata.obs_names] + + image = stitch_composite(flat_dir, pos, x_min, y_top, width, height) + + identity = {CS: Identity()} + sdata = SpatialData( + images={ + "composite": Image2DModel.parse( + image, dims=("c", "y", "x"), c_coords=["r", "g", "b"], + scale_factors=[2, 2, 2, 2], chunks=(3, 1024, 1024), transformations=identity, + ), + }, + shapes={"cell_boundaries": ShapesModel.parse(boundaries, transformations=identity)}, + tables={"table": TableModel.parse(adata, region="cell_boundaries", region_key="region", instance_key="cell_id")}, + ) + sdata.points["transcripts"] = PointsModel.parse( + dd.from_pandas(tx, npartitions=max(1, len(tx) // 2_000_000)), + feature_key="target", instance_key="cell_id", transformations=identity, + ) + + # Make the points ready for tiled access. + # References: + # - https://vitessce.io/docs/data-troubleshooting/#points + # - ../spatialdata-xenium-rep1/src/morton_sort_points.py + sdata = sdata_morton_sort_points(sdata, "transcripts") + ddf = sdata_points_process_columns(sdata, "transcripts", var_name_col="target", table_name="table") + if "transform" in ddf.attrs: + del ddf.attrs["transform"] + sdata.points["transcripts"] = PointsModel.parse(ddf, feature_key="target", instance_key="cell_id", transformations=identity) + + sdata.write(output_path, overwrite=True) + sdata = read_zarr(output_path) + sdata_points_modify_row_group_size(sdata, "transcripts", row_group_size=25_000) + print(sdata) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input_dir', type=str, required=True, help='The
-Flat_files_and_images directory') + parser.add_argument('-s', '--section', type=str, required=True, help='The section name, e.g., Lung9_Rep1') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + args = parser.parse_args() + process(args.input_dir, args.section, args.output) diff --git a/demos/spatialdata-cosmx-nsclc/vitessce.template.json b/demos/spatialdata-cosmx-nsclc/vitessce.template.json new file mode 100644 index 00000000..ef1caeb4 --- /dev/null +++ b/demos/spatialdata-cosmx-nsclc/vitessce.template.json @@ -0,0 +1,238 @@ +{ + "version": "1.0.18", + "name": "CosMx SMI NSCLC (Lung9_Rep1)", + "description": "NanoString CosMx non-small-cell lung cancer FFPE dataset (He et al. 2022), section Lung9_Rep1: stitched CellComposite image, cell boundaries, Leiden clusters, and morton-sorted transcripts", + "datasets": [ + { + "uid": "A", + "name": "CosMx", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/cosmx_nsclc_lung9_rep1.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "obsSets": { + "obsSets": [ + { + "name": "Leiden", + "path": "tables/table/obs/leiden" + }, + { + "name": "FOV", + "path": "tables/table/obs/fov" + } + ], + "tablePath": "tables/table" + }, + "image": { + "path": "images/composite", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/cell_boundaries", + "tablePath": "tables/table", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "cell" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/cosmx_nsclc_lung9_rep1.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "obsPoints": { + "path": "points/transcripts", + "tablePath": "tables/table", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "point", + "featureType": "gene" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "RGB" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0 + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + }, + "init_A_obsPoints_0": { + "pointLayer": [ + "init_A_obsPoints_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "A" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + }, + "init_A_obsPoints_0": { + "pointLayer": { + "obsType": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "spatialLayerVisible": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "init_A_obsPoints_0": "point", + "A": "cell" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.5 + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": false + }, + "pointLayer": { + "init_A_obsPoints_0": "__dummy__" + }, + "spatialLayerVisible": { + "init_A_obsPoints_0": false + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 6, + "h": 3 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 3, + "w": 6, + "h": 3, + "coordinationScopesBy": {} + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile b/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile new file mode 100644 index 00000000..abd7c6f3 --- /dev/null +++ b/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile @@ -0,0 +1,66 @@ +import re + +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# DBiT-seq (Deterministic Barcoding in Tissue, academic) E10 mouse embryo, 50 um pixels, +# with co-profiled mRNA (whole transcriptome) and 22 proteins (antibody-derived tags). +# +# Publication: Liu Y, Yang M, Deng Y, et al. "High-Spatial-Resolution Multi-Omics Sequencing via +# Deterministic Barcoding in Tissue". Cell 183(6):1665-1681 (2020). https://doi.org/10.1016/j.cell.2020.10.026 +# Data: GEO series GSE137986 (https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE137986), public domain (NCBI GEO). +# - GSM4189613 (0702cL): mRNA count matrix (pixels x genes, pixel IDs "{x}x{y}") and the tissue image of the +# 50 x 50 pixel region. https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM4189613 +# - GSM4202307 (0702aL): protein (ADT) count matrix of the same tissue section. +# https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM4202307 +# +# Note: spatialdata-io has a `dbit` reader, but it expects an AnnData file with sequence barcodes plus a +# barcode-to-position file, while GEO provides plain TSV matrices indexed by grid position. +# So we build the SpatialData object directly (pixels as square polygons, as the `dbit` reader also does). +GEO_URL = "https://ftp.ncbi.nlm.nih.gov/geo/samples" +FILES = { + "GSM4189613_0702cL.tsv.gz": f"{GEO_URL}/GSM4189nnn/GSM4189613/suppl/GSM4189613_0702cL.tsv.gz", + "GSM4189613_0702cL-50um-e10.png.gz": f"{GEO_URL}/GSM4189nnn/GSM4189613/suppl/GSM4189613_0702cL-50um-e10.png.gz", + "GSM4202307_0702aL.tsv.gz": f"{GEO_URL}/GSM4202nnn/GSM4202307/suppl/GSM4202307_0702aL.tsv.gz", +} + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Build a SpatialData object with the tissue image, the pixels as square polygon Shapes, +# and one table per modality ("rna" and "protein"), both annotating the pixels. +rule convert_to_spatialdata: + input: + rna=(RAW_DIR / "GSM4189613_0702cL.tsv.gz"), + protein=(RAW_DIR / "GSM4202307_0702aL.tsv.gz"), + image=(RAW_DIR / "GSM4189613_0702cL-50um-e10.png.gz") + output: + directory(PROCESSED_DIR / "dbit_seq_mouse_embryo_e10.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py") + shell: + ''' + uv run --script {params.script} \ + --rna {input.rna} \ + --protein {input.protein} \ + --image {input.image} \ + -o {output} + ''' + +rule download_data: + output: + (RAW_DIR / "{filename}") + wildcard_constraints: + filename="|".join([re.escape(f) for f in FILES.keys()]) + params: + file_url=lambda w: FILES[w.filename] + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/config.yml b/demos/spatialdata-dbit-seq-mouse-embryo/config.yml new file mode 100644 index 00000000..252146ef --- /dev/null +++ b/demos/spatialdata-dbit-seq-mouse-embryo/config.yml @@ -0,0 +1,2 @@ +output: +- dbit_seq_mouse_embryo_e10.spatialdata.zarr diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/src/convert_to_spatialdata.py b/demos/spatialdata-dbit-seq-mouse-embryo/src/convert_to_spatialdata.py new file mode 100644 index 00000000..d9451cfc --- /dev/null +++ b/demos/spatialdata-dbit-seq-mouse-embryo/src/convert_to_spatialdata.py @@ -0,0 +1,130 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# "anndata>=0.12,<0.13", +# "scanpy[leiden]==1.12.6", +# "geopandas", +# "numpy", +# "pandas", +# "pillow", +# "scipy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse +import gzip + +import anndata as ad +import geopandas as gpd +import numpy as np +import pandas as pd +import scanpy as sc +from PIL import Image +from scipy import sparse +from shapely.geometry import box +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, ShapesModel, TableModel +from spatialdata.transformations import Identity, Scale + +# This DBiT-seq device has 50 x 50 channels (50 um wide), and the GEO image covers the 50 x 50 pixel region. +GRID_SIZE = 50 +# Fraction of each 50 um grid cell covered by a pixel (the rest is the gap between microfluidic channels). +PIXEL_FILL = 0.9 + +SHAPES_KEY = "pixels" + + +def read_matrix(path): + # Rows are pixels named "{x}x{y}" (1-based grid positions), columns are features. + df = pd.read_csv(path, sep="\t", index_col=0) + df.index = df.index.astype(str) + df.columns = df.columns.astype(str) + return df + + +def make_table(df, pixel_ids, table_key): + df = df.reindex(pixel_ids).fillna(0) + counts = sparse.csr_matrix(df.to_numpy(dtype=np.float32)) + adata = ad.AnnData(X=counts, obs=pd.DataFrame(index=pd.Index(pixel_ids, name=None)), var=pd.DataFrame(index=df.columns)) + adata.var_names_make_unique() + adata.layers["counts"] = counts.copy() + adata.obs["region"] = pd.Categorical([SHAPES_KEY] * adata.n_obs) + adata.obs["pixel_id"] = adata.obs.index.to_numpy() + adata.obs["total_counts"] = np.asarray(counts.sum(axis=1)).ravel() + adata.obs["n_features"] = np.diff(counts.indptr) + return adata + + +def convert(rna_path, protein_path, image_path, output_path): + rna_df = read_matrix(rna_path) + protein_df = read_matrix(protein_path) + pixel_ids = [p for p in rna_df.index if p in set(protein_df.index)] + print(f"{len(pixel_ids)} pixels in both modalities ({rna_df.shape[0]} RNA, {protein_df.shape[0]} protein)") + + # RNA: log-normalized expression, with Leiden clusters and UMAP. + rna = make_table(rna_df, pixel_ids, "rna") + sc.pp.normalize_total(rna, target_sum=1e4) + sc.pp.log1p(rna) + sc.pp.highly_variable_genes(rna, n_top_genes=2000) + rna_hvg = rna[:, rna.var["highly_variable"]].copy() + sc.pp.scale(rna_hvg, max_value=10) + sc.tl.pca(rna_hvg, n_comps=30) + sc.pp.neighbors(rna_hvg, n_neighbors=15) + sc.tl.umap(rna_hvg) + sc.tl.leiden(rna_hvg, resolution=0.8, flavor="igraph", n_iterations=2, directed=False) + rna.obs["leiden"] = rna_hvg.obs["leiden"].astype("category") + rna.obsm["X_umap"] = rna_hvg.obsm["X_umap"].astype(np.float32) + rna.X = sparse.csc_matrix(rna.X, dtype=np.float32) + del rna.uns["log1p"] + rna.uns.pop("hvg", None) + + # Protein (ADT): centered log-ratio (CLR) normalization across proteins within each pixel. + protein = make_table(protein_df, pixel_ids, "protein") + x = np.log1p(protein.layers["counts"].toarray()) + protein.X = sparse.csc_matrix((x - x.mean(axis=1, keepdims=True)).astype(np.float32)) + protein.obs["leiden"] = pd.Categorical(rna.obs["leiden"].to_numpy()) + + tables = { + "rna": TableModel.parse(rna, region=SHAPES_KEY, region_key="region", instance_key="pixel_id"), + "protein": TableModel.parse(protein, region=SHAPES_KEY, region_key="region", instance_key="pixel_id"), + } + + # Tissue image (the GEO PNG is grayscale stored as RGBA): keep the RGB channels. + with gzip.open(image_path, "rb") as f: + img = np.asarray(Image.open(f).convert("RGB")) + img_h, img_w = img.shape[:2] + image = Image2DModel.parse( + np.transpose(img, (2, 0, 1)), + dims=("c", "y", "x"), + c_coords=["r", "g", "b"], + transformations={"global": Identity()}, + ) + + # Pixels as squares in grid units (pixel "{x}x{y}" covers [x-1, x] x [y-1, y]), + # scaled to the image pixel space of the "global" coordinate system. + xy = np.array([[int(v) for v in p.split("x")] for p in pixel_ids], dtype=np.float64) + margin = (1.0 - PIXEL_FILL) / 2.0 + geoms = [box(x - 1 + margin, y - 1 + margin, x - margin, y - margin) for x, y in xy] + pixels = gpd.GeoDataFrame(geometry=geoms, index=pd.Index(pixel_ids, name=None)) + pixels = ShapesModel.parse(pixels, transformations={ + "global": Scale([img_w / GRID_SIZE, img_h / GRID_SIZE], axes=("x", "y")), + }) + + sdata = SpatialData(images={"tissue_image": image}, shapes={SHAPES_KEY: pixels}, tables=tables) + sdata.write(output_path, overwrite=True) + print(sdata) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--rna', type=str, required=True, help='Input mRNA matrix (pixels x genes) .tsv.gz file') + parser.add_argument('--protein', type=str, required=True, help='Input protein matrix (pixels x proteins) .tsv.gz file') + parser.add_argument('--image', type=str, required=True, help='Input tissue image .png.gz file') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + args = parser.parse_args() + convert(args.rna, args.protein, args.image, args.output) diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json b/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json new file mode 100644 index 00000000..2121d7df --- /dev/null +++ b/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json @@ -0,0 +1,416 @@ +{ + "version": "1.0.18", + "name": "DBiT-seq E10 mouse embryo (Liu et al. 2020)", + "description": "DBiT-seq 50 um pixels with co-profiled mRNA and protein (GEO GSE137986, samples GSM4189613 and GSM4202307)", + "datasets": [ + { + "uid": "A", + "name": "DBiT-seq E10 mouse embryo (Liu et al. 2020)", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/dbit_seq_mouse_embryo_e10.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/rna/X", + "region": "pixels" + }, + "obsSets": { + "obsSets": [ + { + "name": "Leiden (RNA)", + "path": "tables/rna/obs/leiden" + } + ], + "tablePath": "tables/rna", + "region": "pixels" + }, + "image": { + "path": "images/tissue_image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/pixels", + "tablePath": "tables/rna", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/rna/obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "pixel", + "featureType": "gene", + "featureValueType": "expression" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/dbit_seq_mouse_embryo_e10.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/protein/X", + "region": "pixels" + } + }, + "coordinationValues": { + "obsType": "pixel", + "featureType": "protein", + "featureValueType": "expression" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "spatialZoom": { + "A": null + }, + "spatialTargetX": { + "A": null + }, + "spatialTargetY": { + "A": null + }, + "imageLayer": { + "A": null, + "init_rna_0": "__dummy__", + "init_protein_0": "__dummy__" + }, + "obsColorEncoding": { + "A": "geneSelection", + "B": "geneSelection", + "C": "cellSetSelection" + }, + "featureSelection": { + "A": [ + "Hbb-y" + ], + "B": [ + "CD326-Ep-CAM" + ] + }, + "featureType": { + "A": "gene", + "B": "protein" + }, + "featureValueType": { + "A": "expression", + "B": "expression" + }, + "photometricInterpretation": { + "init_rna_0": "RGB", + "init_protein_0": "RGB" + }, + "spatialLayerOpacity": { + "init_rna_0": 1.0, + "init_rna_1": 1.0, + "init_protein_0": 1.0, + "init_protein_1": 1.0 + }, + "segmentationLayer": { + "init_rna_0": "__dummy__", + "init_protein_0": "__dummy__" + }, + "segmentationChannel": { + "init_rna_0": "__dummy__", + "init_protein_0": "__dummy__" + }, + "obsType": { + "init_rna_0": "pixel", + "init_protein_0": "pixel", + "A": "pixel" + }, + "spatialChannelOpacity": { + "init_rna_0": 0.8, + "init_protein_0": 0.8 + }, + "spatialSegmentationFilled": { + "init_rna_0": true, + "init_protein_0": true + }, + "spatialChannelVisible": { + "init_rna_0": true, + "init_protein_0": true + }, + "metaCoordinationScopes": { + "init_rna_0": { + "imageLayer": [ + "init_rna_0" + ], + "segmentationLayer": [ + "init_rna_0" + ] + }, + "init_protein_0": { + "imageLayer": [ + "init_protein_0" + ], + "segmentationLayer": [ + "init_protein_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_rna_0": { + "imageLayer": { + "photometricInterpretation": { + "init_rna_0": "init_rna_0" + }, + "spatialLayerOpacity": { + "init_rna_0": "init_rna_0" + } + }, + "segmentationLayer": { + "spatialLayerOpacity": { + "init_rna_0": "init_rna_1" + }, + "segmentationChannel": { + "init_rna_0": [ + "init_rna_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_rna_0": "init_rna_0" + }, + "featureType": { + "init_rna_0": "A" + }, + "featureValueType": { + "init_rna_0": "A" + }, + "featureSelection": { + "init_rna_0": "A" + }, + "obsColorEncoding": { + "init_rna_0": "A" + }, + "spatialChannelOpacity": { + "init_rna_0": "init_rna_0" + }, + "spatialSegmentationFilled": { + "init_rna_0": "init_rna_0" + }, + "spatialChannelVisible": { + "init_rna_0": "init_rna_0" + } + } + }, + "init_protein_0": { + "imageLayer": { + "photometricInterpretation": { + "init_protein_0": "init_protein_0" + }, + "spatialLayerOpacity": { + "init_protein_0": "init_protein_0" + } + }, + "segmentationLayer": { + "spatialLayerOpacity": { + "init_protein_0": "init_protein_1" + }, + "segmentationChannel": { + "init_protein_0": [ + "init_protein_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_protein_0": "init_protein_0" + }, + "featureType": { + "init_protein_0": "B" + }, + "featureValueType": { + "init_protein_0": "B" + }, + "featureSelection": { + "init_protein_0": "B" + }, + "obsColorEncoding": { + "init_protein_0": "B" + }, + "spatialChannelOpacity": { + "init_protein_0": "init_protein_0" + }, + "spatialSegmentationFilled": { + "init_protein_0": "init_protein_0" + }, + "spatialChannelVisible": { + "init_protein_0": "init_protein_0" + } + } + } + }, + "embeddingType": { + "A": "UMAP" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_rna_0" + ], + "metaCoordinationScopesBy": [ + "init_rna_0" + ], + "spatialZoom": "A", + "spatialTargetX": "A", + "spatialTargetY": "A", + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 3, + "h": 6, + "props": { + "title": "Spatial (mRNA)" + } + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_rna_0" + ], + "metaCoordinationScopesBy": [ + "init_rna_0" + ], + "obsType": "A" + }, + "x": 3, + "y": 0, + "w": 3, + "h": 3, + "props": { + "title": "Layers (mRNA)" + } + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A", + "obsType": "A" + }, + "x": 3, + "y": 3, + "w": 3, + "h": 3, + "props": { + "title": "mRNA features" + }, + "coordinationScopesBy": {} + }, + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_protein_0" + ], + "metaCoordinationScopesBy": [ + "init_protein_0" + ], + "spatialZoom": "A", + "spatialTargetX": "A", + "spatialTargetY": "A", + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 6, + "props": { + "title": "Spatial (Protein)" + } + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_protein_0" + ], + "metaCoordinationScopesBy": [ + "init_protein_0" + ], + "obsType": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 3, + "props": { + "title": "Layers (Protein)" + } + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "B", + "obsType": "A" + }, + "x": 9, + "y": 3, + "w": 3, + "h": 3, + "props": { + "title": "Protein features" + }, + "coordinationScopesBy": {} + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsColorEncoding": "C", + "obsType": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "obsColorEncoding": "C", + "obsType": "A" + }, + "x": 0, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-geomx-mouse-embryo/Snakefile b/demos/spatialdata-geomx-mouse-embryo/Snakefile new file mode 100644 index 00000000..7ac5d165 --- /dev/null +++ b/demos/spatialdata-geomx-mouse-embryo/Snakefile @@ -0,0 +1,79 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Bruker (NanoString) GeoMx DSP: Spatial Organ Atlas (SOA) "Mouse Embryonic Development" dataset, +# Mouse Whole Transcriptome Atlas (WTA), fixed-frozen C57BL/6 embryos, 5 um sagittal sections. +# This demo uses one E11 scan (mu_dev_E11_004: 52 ROIs/AOIs, 4-channel morphology image: +# SYTO 13 (DNA), autofluorescence, beta3-tubulin, p63). +# Source (original, NanoString/Bruker public S3 bucket; downloadable without an account or form): +# Product page: https://nanostring.com/products/geomx-digital-spatial-profiler/spatial-organ-atlas/ +# https://external-soa-downloads-p-1.s3.us-west-2.amazonaws.com/README_mu_dev.docx (file format descriptions) +# https://external-soa-downloads-p-1.s3.us-west-2.amazonaws.com/mu_dev_md5sums.txt +# https://external-soa-downloads-p-1.s3.us-west-2.amazonaws.com/mu_dev_count_results.tar.gz (237 MB; Q3-normalized AOI x gene counts + segment properties) +# https://external-soa-downloads-p-1.s3.us-west-2.amazonaws.com/mu_dev_E11_image_files.tar.gz (1.7 GB; OME-TIFFs with ROI/AOI shapes in the OME-XML) +# The same bucket is used by the Bioconductor SpatialOmicsOverlay package (downloadMouseBrainImage). +# License: not stated in the README; NanoString provides the SOA as a public demo dataset. +SCAN = "mu_dev_E11_004" +SOA_BUCKET_URL = "https://external-soa-downloads-p-1.s3.us-west-2.amazonaws.com" +# The OME-XML labels the non-DNA channels as "Custom"; the marker names are from README_mu_dev.docx. +CHANNEL_NAMES = "DNA (SYTO 13),Autofluorescence (Cy3),beta3-tubulin (Alexa 594),p63 (Cy5)" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +rule convert_to_spatialdata: + input: + image=(RAW_DIR / "mu_dev_E11_image_files" / f"{SCAN}.ome.tiff"), + counts=(RAW_DIR / "mu_dev_count_results" / "Export4_NormalizationQ3.xlsx") + output: + directory(PROCESSED_DIR / "geomx_mouse_embryo_e11.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py"), + scan=SCAN, + channel_names=CHANNEL_NAMES + shell: + ''' + uv run --script {params.script} -i {input.image} -c {input.counts} -s {params.scan} -o {output} --channel_names "{params.channel_names}" + ''' + +rule extract_image: + input: + (RAW_DIR / "mu_dev_E11_image_files.tar.gz") + output: + (RAW_DIR / "mu_dev_E11_image_files" / f"{SCAN}.ome.tiff") + params: + member=f"mu_dev_E11_image_files/{SCAN}.ome.tiff" + shell: + ''' + tar -xzf {input} -C "$(dirname {input})" {params.member} + touch {output} + ''' + +rule extract_counts: + input: + (RAW_DIR / "mu_dev_count_results.tar.gz") + output: + (RAW_DIR / "mu_dev_count_results" / "Export4_NormalizationQ3.xlsx") + shell: + ''' + tar -xzf {input} -C "$(dirname {input})" mu_dev_count_results/Export4_NormalizationQ3.xlsx + touch {output} + ''' + +rule download_data: + output: + (RAW_DIR / "{filename}.tar.gz") + params: + file_url=lambda w: f"{SOA_BUCKET_URL}/{w.filename}.tar.gz" + wildcard_constraints: + filename="mu_dev_count_results|mu_dev_E11_image_files" + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-geomx-mouse-embryo/config.yml b/demos/spatialdata-geomx-mouse-embryo/config.yml new file mode 100644 index 00000000..d0febedd --- /dev/null +++ b/demos/spatialdata-geomx-mouse-embryo/config.yml @@ -0,0 +1,2 @@ +output: +- geomx_mouse_embryo_e11.spatialdata.zarr diff --git a/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py b/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py new file mode 100644 index 00000000..a825b969 --- /dev/null +++ b/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py @@ -0,0 +1,196 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# "anndata==0.12.19", # anndata 0.13 exposes X as layers[None], which spatialdata 0.7.3 TableModel.parse rejects. +# "pandas", +# "python-calamine", +# "tifffile", +# "imagecodecs", +# "shapely", +# "geopandas", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Convert one GeoMx DSP scan (OME-TIFF with ROI annotations) plus the AOI-by-gene +Q3-normalized counts into a SpatialData store. + +Elements written: +- images/image: the 4-channel morphology image (multiscale). +- shapes/aois: one polygon per AOI (the ROI outline from the OME-XML; every AOI in this + dataset is a "Full ROI" segment, i.e., AOI geometry == ROI geometry). +- tables/table: AOI-by-gene AnnData (X = log2(Q3-normalized + 1), layers/q3 = Q3-normalized counts), + with the segment properties (tissue annotations, area, nuclei count, QC) as obs. + +Coordinate system ("global"): pixels of the full-resolution scan image (about 0.4 um per pixel). +The ROI shapes in the OME-XML are already in this pixel space. +""" +import argparse +import xml.etree.ElementTree as ET + +import numpy as np +import pandas as pd +import geopandas as gpd +import tifffile +import dask.array as da +import zarr +from anndata import AnnData +from shapely.geometry import Polygon, Point, box +from shapely import affinity +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, ShapesModel, TableModel +from spatialdata.transformations import Identity + +CS = "global" +NS = {"ome": "http://www.openmicroscopy.org/Schemas/OME/2016-06"} +OBS_COLUMNS = [ + "SlideName", "ScanLabel", "ROILabel", "SegmentLabel", "QCFlags", + "AOISurfaceArea", "AOINucleiCount", "ROICoordinateX", "ROICoordinateY", + "RawReads", "AlignedReads", "DeduplicatedReads", "SequencingSaturation", + "Tissue_annotation", "Tissue", "p63_expression", "Tissue_substructure", "Tissue_type", "Timepoint", + "NormalizationFactor", +] + + +def parse_channel_names(root): + """Channel names like 'DNA (SYTO 13)', from the GeoMx ChannelInfo annotations.""" + annotations = {} + for ann in root.iterfind(".//ome:StructuredAnnotations/ome:XMLAnnotation", NS): + info = ann.find(".//ome:ChannelInfo", NS) + if info is None: + info = ann.find(".//ChannelInfo") + if info is not None: + annotations[ann.get("ID")] = {child.tag.split("}")[-1]: (child.text or "") for child in info} + names = [] + for channel in root.iterfind(".//ome:Image/ome:Pixels/ome:Channel", NS): + fluor = channel.get("Fluor") or channel.get("Name") + target = None + for ref in channel.iterfind("ome:AnnotationRef", NS): + info = annotations.get(ref.get("ID")) + if info is not None: + target = info.get("BiologicalTarget") + name = f"{target} ({fluor})" if target and target.lower() not in ("", "n/a", "none", "custom") else fluor + names.append(name) + # Ensure uniqueness. + seen = {} + unique = [] + for n in names: + seen[n] = seen.get(n, 0) + 1 + unique.append(n if seen[n] == 1 else f"{n} {seen[n]}") + return unique + + +def parse_roi_geometries(root): + """Map ROI label (e.g., '001') to a shapely geometry (in image pixels).""" + rois = {} + for roi in root.iterfind("ome:ROI", NS): + union = roi.find("ome:Union", NS) + label = union.find("ome:Label", NS) + if label is None: + continue + geom = None + polygon = union.find("ome:Polygon", NS) + ellipse = union.find("ome:Ellipse", NS) + rect = union.find("ome:Rectangle", NS) + if polygon is not None: + pts = [tuple(map(float, p.split(","))) for p in polygon.get("Points").split()] + geom = Polygon(pts).buffer(0) + elif ellipse is not None: + cx, cy = float(ellipse.get("X")), float(ellipse.get("Y")) + rx, ry = float(ellipse.get("RadiusX")), float(ellipse.get("RadiusY")) + geom = affinity.scale(Point(cx, cy).buffer(1.0, resolution=32), rx, ry) + elif rect is not None: + x, y = float(rect.get("X")), float(rect.get("Y")) + geom = box(x, y, x + float(rect.get("Width")), y + float(rect.get("Height"))) + if geom is None: + raise ValueError(f"ROI {label.get('Text')} has no Polygon, Ellipse, or Rectangle shape.") + rois[label.get("Text")] = geom + return rois + + +def load_image(ome_tiff_path): + with tifffile.TiffFile(ome_tiff_path) as tif: + series = tif.series[0] + assert series.axes == "CYX", series.axes + store = series.aszarr(level=0) + arr = da.from_zarr(zarr.open(store, mode="r")).rechunk((1, 1024, 1024)) + arr = arr.compute() # ~2 GB (uint16) for a 16384 x 16384 x 4 scan. + ome_xml = tif.ome_metadata + return arr, ome_xml + + +def load_table(xlsx_path, scan_label): + segments = pd.read_excel(xlsx_path, sheet_name="SegmentProperties", engine="calamine") + segments = segments[segments["ScanLabel"] == scan_label].copy() + segments.index = segments["SegmentDisplayName"].astype(str) + counts = pd.read_excel(xlsx_path, sheet_name="TargetCountMatrix", engine="calamine").set_index("TargetName") + counts = counts[segments.index] + targets = pd.read_excel(xlsx_path, sheet_name="TargetProperties", engine="calamine").set_index("TargetName") + + obs = segments[[c for c in OBS_COLUMNS if c in segments.columns]].copy() + obs["ROILabel"] = obs["ROILabel"].astype(int).map(lambda v: f"{v:03d}") + for col in obs.columns: + if obs[col].dtype == object or col == "ROILabel": + obs[col] = pd.Categorical(obs[col].fillna("NA").astype(str)) + var = targets.reindex(counts.index) + var = var[[c for c in ["HUGOSymbol", "TargetGroup", "CodeClass"] if c in var.columns]].astype(str) + var.index.name = None + + q3 = counts.T.to_numpy(dtype=np.float32) + adata = AnnData(X=np.log2(q3 + 1.0), obs=obs, var=var) + adata.layers["q3"] = q3 + return adata + + +def process(ome_tiff_path, xlsx_path, scan_label, output_path, channel_names=None): + image, ome_xml = load_image(ome_tiff_path) + root = ET.fromstring(ome_xml) + if channel_names is None: + channel_names = parse_channel_names(root) + assert len(channel_names) == image.shape[0], (channel_names, image.shape) + print(f"Image {image.shape} {image.dtype}; channels: {channel_names}") + + rois = parse_roi_geometries(root) + adata = load_table(xlsx_path, scan_label) + print(f"{adata.n_obs} AOIs x {adata.n_vars} targets; {len(rois)} ROIs in the OME-XML") + + # Every AOI here is a "Full ROI" segment, so we use the ROI outline as the AOI geometry. + missing = set(adata.obs["ROILabel"].astype(str)) - set(rois.keys()) + assert not missing, f"AOIs without an ROI shape: {missing}" + geoms = [rois[label] for label in adata.obs["ROILabel"].astype(str)] + aois = gpd.GeoDataFrame({"geometry": geoms}, index=pd.Index(adata.obs_names, name="aoi_id")) + + adata.obs["region"] = pd.Categorical(["aois"] * adata.n_obs) + adata.obs["aoi_id"] = adata.obs_names.to_numpy() + centroids = aois.geometry.centroid + adata.obsm["spatial"] = np.stack([centroids.x.to_numpy(), centroids.y.to_numpy()], axis=1) + + identity = {CS: Identity()} + sdata = SpatialData( + images={ + "image": Image2DModel.parse( + image, dims=("c", "y", "x"), c_coords=channel_names, + scale_factors=[2, 2, 2, 2, 2], chunks=(1, 1024, 1024), transformations=identity, + ), + }, + shapes={"aois": ShapesModel.parse(aois, transformations=identity)}, + tables={"table": TableModel.parse(adata, region="aois", region_key="region", instance_key="aoi_id")}, + ) + sdata.write(output_path, overwrite=True) + print(sdata) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--image', type=str, required=True, help='GeoMx OME-TIFF for one scan') + parser.add_argument('-c', '--counts', type=str, required=True, help='Export4_NormalizationQ3.xlsx') + parser.add_argument('-s', '--scan', type=str, required=True, help='Scan label, e.g., mu_dev_E11_004') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + parser.add_argument('--channel_names', type=str, required=False, help='Comma-separated channel names, overriding the names derived from the OME-XML') + args = parser.parse_args() + channel_names = args.channel_names.split(",") if args.channel_names else None + process(args.image, args.counts, args.scan, args.output, channel_names=channel_names) diff --git a/demos/spatialdata-geomx-mouse-embryo/vitessce.template.json b/demos/spatialdata-geomx-mouse-embryo/vitessce.template.json new file mode 100644 index 00000000..6a719da5 --- /dev/null +++ b/demos/spatialdata-geomx-mouse-embryo/vitessce.template.json @@ -0,0 +1,301 @@ +{ + "version": "1.0.18", + "name": "GeoMx DSP mouse embryo (E11)", + "description": "NanoString Spatial Organ Atlas, mouse embryonic development, scan mu_dev_E11_004: AOI polygons with Q3-normalized whole-transcriptome counts", + "datasets": [ + { + "uid": "A", + "name": "GeoMx", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/geomx_mouse_embryo_e11.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "obsSets": { + "obsSets": [ + { + "name": "Tissue", + "path": "tables/table/obs/Tissue" + }, + { + "name": "Tissue annotation", + "path": "tables/table/obs/Tissue_annotation" + }, + { + "name": "Tissue substructure", + "path": "tables/table/obs/Tissue_substructure" + }, + { + "name": "Tissue type", + "path": "tables/table/obs/Tissue_type" + }, + { + "name": "p63 expression", + "path": "tables/table/obs/p63_expression" + } + ], + "tablePath": "tables/table" + }, + "image": { + "path": "images/image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/aois", + "tablePath": "tables/table", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "AOI" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "BlackIsZero" + }, + "imageChannel": { + "init_A_image_0": "__dummy__", + "init_A_image_1": "__dummy__", + "init_A_image_2": "__dummy__", + "init_A_image_3": "__dummy__" + }, + "spatialTargetC": { + "init_A_image_0": 0, + "init_A_image_1": 1, + "init_A_image_2": 2, + "init_A_image_3": 3 + }, + "spatialChannelColor": { + "init_A_image_0": [ + 0, + 0, + 255 + ], + "init_A_image_1": [ + 255, + 255, + 255 + ], + "init_A_image_2": [ + 0, + 255, + 0 + ], + "init_A_image_3": [ + 255, + 0, + 0 + ] + }, + "spatialChannelWindow": { + "init_A_image_0": [ + 0, + 3000 + ], + "init_A_image_1": [ + 0, + 500 + ], + "init_A_image_2": [ + 0, + 400 + ], + "init_A_image_3": [ + 0, + 1100 + ] + }, + "spatialChannelVisible": { + "init_A_image_0": true, + "init_A_image_1": false, + "init_A_image_2": true, + "init_A_image_3": true + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "imageChannel": { + "init_A_image_0": [ + "init_A_image_0", + "init_A_image_1", + "init_A_image_2", + "init_A_image_3" + ] + } + }, + "imageChannel": { + "spatialTargetC": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3" + }, + "spatialChannelColor": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3" + }, + "spatialChannelWindow": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3" + }, + "spatialChannelVisible": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsColorEncoding": { + "init_A_obsSegmentations_0": "A" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.6 + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": true + }, + "obsType": { + "A": "AOI" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 6 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 6, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 6, + "w": 3, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 6, + "w": 3, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "heatmap", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 0, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/Snakefile b/demos/spatialdata-illumina-stratamap-mouse-kidney/Snakefile new file mode 100644 index 00000000..2b90a109 --- /dev/null +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/Snakefile @@ -0,0 +1,56 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Illumina StrataMap Spatial Transcriptome ("Illumina spatial technology") demo dataset: +# normal fresh-frozen mouse kidney (C57BL/6, 8-week-old male), 10 um section, H&E (Keyence BZX-810, 20x), +# sequenced on NovaSeq X Plus, processed with DRAGEN Spatial Transcriptome v1.1.6 (~277k cells). +# https://www.illumina.com/techniques/multiomics/demo-datasets/spatial-transcriptomics-demo-dataset.html +# +# MANUAL DOWNLOAD REQUIRED: the "Access data set" link on that page is gated behind a registration form +# (Illumina marketing form), and as of 2026-12 there is no openly downloadable StrataMap dataset +# (no GEO/Zenodo/figshare deposit found). After obtaining the data, place the DRAGEN StrataMap +# per-sample results folder at: +# data/raw/stratamap_results// +# containing (file names per the DRAGEN StrataMap documentation, +# https://help.bioinsight.illumina.com/dragen-stratamap/dragen-stratamap/outputs/results-folder): +# _cell_binned/{matrix.mtx.gz,features.tsv.gz,barcodes.tsv.gz} +# _Expanded_5um_cell_contour_coords.csv +# .ome.tiff (registered H&E; *_registered.ome.tiff is also accepted) +# and set SAMPLE_ID below to the folder name. +# License: Illumina's terms for the demo data apply (see the form); not redistributable without checking them. +SAMPLE_ID = "mouse_kidney" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +rule convert_to_spatialdata: + input: + (RAW_DIR / "stratamap_results" / SAMPLE_ID) + output: + directory(PROCESSED_DIR / "stratamap_mouse_kidney.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py"), + sample_id=SAMPLE_ID + shell: + ''' + uv run --script {params.script} -i {input} -s {params.sample_id} -o {output} + ''' + +# The raw data cannot be downloaded automatically (see above). +rule manual_download: + output: + directory(RAW_DIR / "stratamap_results" / SAMPLE_ID) + params: + page_url="https://www.illumina.com/techniques/multiomics/demo-datasets/spatial-transcriptomics-demo-dataset.html" + shell: + ''' + echo "The Illumina StrataMap demo data requires a manual download (registration form) from {params.page_url}." >&2 + echo "Place the DRAGEN StrataMap results folder for the sample at {output} (see the comments in this Snakefile)." >&2 + exit 1 + ''' diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/config.yml b/demos/spatialdata-illumina-stratamap-mouse-kidney/config.yml new file mode 100644 index 00000000..1053f384 --- /dev/null +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/config.yml @@ -0,0 +1,2 @@ +output: +- stratamap_mouse_kidney.spatialdata.zarr diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/src/convert_to_spatialdata.py b/demos/spatialdata-illumina-stratamap-mouse-kidney/src/convert_to_spatialdata.py new file mode 100644 index 00000000..87a0ad04 --- /dev/null +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/src/convert_to_spatialdata.py @@ -0,0 +1,244 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# "anndata==0.12.19", # anndata 0.13 exposes X as layers[None], which spatialdata 0.7.3 TableModel.parse rejects. +# "scikit-learn", +# "igraph", +# "shapely", +# "geopandas", +# "tifffile", +# "imagecodecs", +# "ome-types", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Convert one sample of the DRAGEN StrataMap (Illumina StrataMap Spatial Transcriptome) results +folder into a SpatialData store. + +Expected inputs (per the DRAGEN StrataMap output documentation, +https://help.bioinsight.illumina.com/dragen-stratamap/dragen-stratamap/outputs/results-folder): + /_cell_binned/{matrix.mtx.gz, features.tsv.gz, barcodes.tsv.gz} + matrix is genes x cells; barcodes are "cell::" (cell centroid, global substrate um) + /_Expanded_5um_cell_contour_coords.csv + columns cell_id, vertex_x, vertex_y (global substrate um) + /.ome.tiff (or *_registered.ome.tiff) + pages: original-resolution H&E (RGB), 1 um/pixel H&E (RGB), tissue mask (1 um/pixel); + local sample coordinates, with the sample's global offset (Global_left, Global_top, in um) + in the OME metadata. + +Elements written: +- images/he: the 1 um/pixel registered H&E image (multiscale, RGB). +- shapes/cell_boundaries: cell polygons (nuclei expanded by 5 um). +- tables/table: cell-by-gene AnnData (X = log-normalized, layers/counts = raw counts) with Leiden clusters. + +Coordinate system ("global"): the sample's local frame in um (= pixels of the 1 um/pixel H&E). +Global substrate coordinates are converted by subtracting (Global_left, Global_top). +""" +import argparse +import glob +import json +import re +from os.path import join, isdir, basename + +import numpy as np +import pandas as pd +import geopandas as gpd +import igraph as ig +import scipy.io +import scipy.sparse as sp +import tifffile +from anndata import AnnData +from shapely.geometry import Polygon +from sklearn.decomposition import PCA +from sklearn.neighbors import NearestNeighbors +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, ShapesModel, TableModel +from spatialdata.transformations import Identity + +CS = "global" + + +def find_one(patterns, what): + for pattern in patterns: + matches = sorted(glob.glob(pattern)) + if matches: + return matches[0] + raise FileNotFoundError(f"Could not find the {what}; tried {patterns}") + + +def read_global_offset(ome_xml): + """Return (global_left, global_top) in um from the OME-XML, or None.""" + from ome_types import from_xml + ome = from_xml(ome_xml) + # Method 1: map annotation with GlobalPos_left / GlobalPos_top. + if ome.structured_annotations is not None: + obj = json.loads(ome.structured_annotations.model_dump_json()) if hasattr(ome.structured_annotations, "model_dump_json") else {} + for ann in obj.get("map_annotations", []): + value = ann.get("value") + if isinstance(value, dict) and "GlobalPos_left" in value and "GlobalPos_top" in value: + return float(value["GlobalPos_left"]), float(value["GlobalPos_top"]) + if isinstance(value, dict) and "ms" in value: # list of {k, value} pairs + kv = {m.get("k"): m.get("value") for m in value["ms"]} + if "GlobalPos_left" in kv and "GlobalPos_top" in kv: + return float(kv["GlobalPos_left"]), float(kv["GlobalPos_top"]) + # Method 2: plane position. + for image in ome.images: + if image.pixels and image.pixels.planes: + plane = image.pixels.planes[0] + if plane.position_x is not None and plane.position_y is not None: + return float(plane.position_x), float(plane.position_y) + # Method 3: regex fallback on the raw XML. + left = re.search(r'GlobalPos_left[^0-9\-]*?(-?[0-9.]+)', ome_xml) + top = re.search(r'GlobalPos_top[^0-9\-]*?(-?[0-9.]+)', ome_xml) + if left and top: + return float(left.group(1)), float(top.group(1)) + return None + + +def load_he_image(ome_tiff_path): + """Return the 1 um/pixel H&E image as (c, y, x) uint8, plus the global offset.""" + with tifffile.TiffFile(ome_tiff_path) as tif: + # The docs list the planes in different orders on different pages, so pick + # the smallest RGB page: the original-resolution H&E is finer than 1 um/pixel. + rgb_pages = [p for p in tif.pages if p.samplesperpixel >= 3] + if not rgb_pages: + raise ValueError("No RGB page found in the OME-TIFF.") + page = min(rgb_pages, key=lambda p: p.shape[0] * p.shape[1]) + image = page.asarray()[..., :3] + offset = read_global_offset(tif.ome_metadata) if tif.ome_metadata else None + if image.dtype != np.uint8: + image = (255 * (image.astype(np.float32) / max(1, image.max()))).astype(np.uint8) + return np.moveaxis(image, -1, 0), offset + + +def load_cell_binned(mtx_dir): + X = sp.csr_matrix(scipy.io.mmread(join(mtx_dir, "matrix.mtx.gz")).T, dtype=np.float32) # cells x genes + barcodes = pd.read_csv(join(mtx_dir, "barcodes.tsv.gz"), sep="\t", header=None)[0].astype(str) + features = pd.read_csv(join(mtx_dir, "features.tsv.gz"), sep="\t", header=None) + parts = barcodes.str.split(":", expand=True) + cell_ids = parts[0].str.replace(r"^cell", "", regex=True) + gene_names = features[1] if features.shape[1] > 1 else features[0] + var = pd.DataFrame(index=pd.Index(gene_names.astype(str).to_numpy(), name=None)) + var["gene_ids"] = features[0].astype(str).to_numpy() + if features.shape[1] > 2: + var["feature_types"] = features[2].astype(str).to_numpy() + adata = AnnData(X=X, obs=pd.DataFrame(index=pd.Index(cell_ids.to_numpy())), var=var) + adata.var_names_make_unique() + adata.obs["barcode"] = barcodes.to_numpy() + # Barcode format: cell:: (global um). + adata.obsm["spatial"] = np.stack([parts[2].astype(float).to_numpy(), parts[1].astype(float).to_numpy()], axis=1) + return adata + + +def load_contours(csv_path, left, top): + df = pd.read_csv(csv_path) + df["cell_id"] = df["cell_id"].astype(str) + geoms, ids = [], [] + for cell_id, group in df.groupby("cell_id", sort=False): + pts = np.stack([group["vertex_x"].to_numpy() - left, group["vertex_y"].to_numpy() - top], axis=1) + if len(pts) < 3: + continue + poly = Polygon(pts) + if not poly.is_valid: + poly = poly.buffer(0) + if poly.is_empty: + continue + if poly.geom_type == "MultiPolygon": + poly = max(poly.geoms, key=lambda g: g.area) + geoms.append(poly) + ids.append(cell_id) + return gpd.GeoDataFrame({"geometry": geoms}, index=pd.Index(ids, name="cell_id")) + + +def cluster(adata): + adata.layers["counts"] = adata.X.copy() + totals = np.asarray(adata.X.sum(axis=1)).ravel() + adata = adata[totals > 0].copy() + totals = totals[totals > 0] + norm = sp.csr_matrix(sp.diags((np.median(totals) / totals).astype(np.float32)) @ adata.layers["counts"], dtype=np.float32) + norm.data = np.log1p(norm.data) + adata.X = norm + # Use the most variable genes for PCA, to keep memory bounded for whole-transcriptome data. + mean = np.asarray(norm.mean(axis=0)).ravel() + sq = np.asarray(norm.multiply(norm).mean(axis=0)).ravel() + top = np.argsort(sq - mean ** 2)[::-1][:2000] + n_comps = int(min(30, adata.n_obs - 1, len(top) - 1)) + pcs = PCA(n_components=n_comps, random_state=0).fit_transform(norm[:, top].toarray()) + adata.obsm["X_pca"] = pcs.astype(np.float32) + k = int(min(15, adata.n_obs - 1)) + knn = NearestNeighbors(n_neighbors=k).fit(pcs).kneighbors_graph(mode="connectivity").tocoo() + graph = ig.Graph(n=adata.n_obs, edges=np.stack([knn.row, knn.col], axis=1).tolist(), directed=False).simplify() + membership = np.asarray(graph.community_leiden(objective_function="modularity", resolution=0.5, n_iterations=2).membership) + order = {c: i for i, c in enumerate(pd.Series(membership).value_counts().index)} + adata.obs["leiden"] = pd.Categorical([str(order[c]) for c in membership], categories=[str(i) for i in range(len(order))]) + return adata + + +def process(results_dir, sample_id, output_path, global_left=None, global_top=None): + mtx_dir = join(results_dir, f"{sample_id}_cell_binned") + if not isdir(mtx_dir): + mtx_dir = find_one([join(results_dir, "*_cell_binned")], "cell-binned MTX directory") + contours_csv = find_one([ + join(results_dir, f"{sample_id}_Expanded_5um_cell_contour_coords.csv"), + join(results_dir, "*cell_contour_coords.csv"), + ], "cell contours CSV") + ome_tiff = find_one([ + join(results_dir, f"{sample_id}.ome.tiff"), + join(results_dir, f"{sample_id}_registered.ome.tiff"), + join(results_dir, "*.ome.tif*"), + ], "registered OME-TIFF") + print(f"Inputs: {basename(mtx_dir)}, {basename(contours_csv)}, {basename(ome_tiff)}") + + image, offset = load_he_image(ome_tiff) + if global_left is not None and global_top is not None: + offset = (global_left, global_top) + if offset is None: + raise ValueError("Could not find GlobalPos_left/GlobalPos_top in the OME-TIFF; pass --global_left and --global_top.") + left, top = offset + print(f"H&E image {image.shape}; global offset (left, top) = ({left}, {top}) um") + + adata = load_cell_binned(mtx_dir) + adata.obsm["spatial"] = adata.obsm["spatial"] - np.array([left, top]) + print(f"{adata.n_obs:,} cells x {adata.n_vars:,} genes") + + boundaries = load_contours(contours_csv, left, top) + shared = adata.obs_names.intersection(boundaries.index) + print(f"{len(boundaries):,} cell contours; {len(shared):,} match cells in the matrix") + if len(shared) < 0.5 * adata.n_obs: + raise ValueError("Fewer than half of the cells have a contour; check the cell ID format of the inputs.") + adata = adata[shared].copy() + adata = cluster(adata) + boundaries = boundaries.loc[adata.obs_names] + + adata.obs["region"] = pd.Categorical(["cell_boundaries"] * adata.n_obs) + adata.obs["cell_id"] = adata.obs_names.to_numpy() + + identity = {CS: Identity()} + sdata = SpatialData( + images={ + "he": Image2DModel.parse( + image, dims=("c", "y", "x"), c_coords=["r", "g", "b"], + scale_factors=[2, 2, 2, 2], chunks=(3, 1024, 1024), transformations=identity, + ), + }, + shapes={"cell_boundaries": ShapesModel.parse(boundaries, transformations=identity)}, + tables={"table": TableModel.parse(adata, region="cell_boundaries", region_key="region", instance_key="cell_id")}, + ) + sdata.write(output_path, overwrite=True) + print(sdata) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--results_dir', type=str, required=True, help='DRAGEN StrataMap per-sample results directory (results/)') + parser.add_argument('-s', '--sample_id', type=str, required=True, help='Sample ID') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + parser.add_argument('--global_left', type=float, required=False, help='Override Global_left (um)') + parser.add_argument('--global_top', type=float, required=False, help='Override Global_top (um)') + args = parser.parse_args() + process(args.results_dir, args.sample_id, args.output, args.global_left, args.global_top) diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/vitessce.template.json b/demos/spatialdata-illumina-stratamap-mouse-kidney/vitessce.template.json new file mode 100644 index 00000000..6625efde --- /dev/null +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/vitessce.template.json @@ -0,0 +1,180 @@ +{ + "version": "1.0.18", + "name": "Illumina StrataMap Spatial (mouse kidney demo)", + "description": "Illumina StrataMap Spatial Transcriptome demo dataset (DRAGEN StrataMap outputs): registered H&E, 5 um-expanded cell contours, cell-binned counts, Leiden clusters", + "datasets": [ + { + "uid": "A", + "name": "StrataMap", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/stratamap_mouse_kidney.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "obsSets": { + "obsSets": [ + { + "name": "Leiden", + "path": "tables/table/obs/leiden" + } + ], + "tablePath": "tables/table" + }, + "image": { + "path": "images/he", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/cell_boundaries", + "tablePath": "tables/table", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "cell" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "RGB" + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsColorEncoding": { + "init_A_obsSegmentations_0": "A" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.5 + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": false + }, + "obsType": { + "A": "cell" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 6, + "h": 3 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 3, + "w": 6, + "h": 3, + "coordinationScopesBy": {} + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/Snakefile b/demos/spatialdata-maldi-msi-timstof-mouse-brain/Snakefile new file mode 100644 index 00000000..b5198c41 --- /dev/null +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/Snakefile @@ -0,0 +1,94 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# MALDI mass spectrometry imaging (MSI) of a sagittal mouse brain section, +# acquired on a Bruker timsTOF fleX (MALDI, positive mode, 250-1200 Da, 5 um raster, 1007 x 1469 pixels). +# - Source: Zenodo record 18326569, "Datasets used for the benchmarking and figures of the Thyra package article." +# https://zenodo.org/records/18326569 (DOI: 10.5281/zenodo.18326569) +# The record also has Xenium (13 GB) and H&E (851 MB) data of the same specimen, which are not used here. +# - License: CC-BY-4.0. +# - Converted with Thyra: https://github.com/M4i-Imaging-Mass-Spectrometry/thyra (PyPI: thyra) +# Tutorial for this dataset: https://M4i-Imaging-Mass-Spectrometry.github.io/thyra/tutorial/#part-2-the-published-example-dataset +# +# Requirements: +# - About 60 GB of free disk: 19.1 GB archive, 19 GB extracted, plus the Thyra store and the output. +# - Linux or Windows: Thyra reads Bruker timsTOF data with Bruker's SDK, which is not available for macOS. +TAR_URL = "https://zenodo.org/api/records/18326569/files/MALDI-MSI_Sagittal_Mouse_Brain.tar.gz/content" +TAR_MD5 = "1dbd2ea14dcb6bd99baf7af6ca843018" +# Paths within the archive (note the spaces in the top-level folder name). +TAR_TOP_DIR = "MALDI-MSI Sagittal Mouse Brain" +D_DIR_NAME = "20240826_Xenium_0041899.d" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Select the most intense peaks of the average spectrum, rasterize the MSI pixels +# to a Labels element annotated by a (pixels x peaks) table, cluster the pixels, +# and keep the TIC image and the aligned optical image. +rule make_vitessce_store: + input: + (DATA_DIR / "intermediate" / "maldi_msi_mouse_brain_thyra.spatialdata.zarr") + output: + directory(PROCESSED_DIR / "maldi_msi_mouse_brain.spatialdata.zarr") + params: + script=(SRC_DIR / "make_vitessce_store.py") + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + -o {output} \ + --num-peaks 100 \ + --n-clusters 10 + ''' + +# Convert the Bruker timsTOF .d acquisition (plus the optical images next to it) +# to SpatialData with Thyra. +rule convert_with_thyra: + input: + (RAW_DIR / "maldi_msi_extracted") + output: + directory(DATA_DIR / "intermediate" / "maldi_msi_mouse_brain_thyra.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_with_thyra.py"), + d_dir_rel=f"{TAR_TOP_DIR}/{D_DIR_NAME}" + shell: + ''' + if [ "$(uname)" = "Darwin" ]; then + echo "Thyra cannot read Bruker timsTOF data on macOS (no Bruker SDK). Run this step on Linux or Windows." >&2 + exit 1 + fi + uv run --script {params.script} \ + -i "{input}/{params.d_dir_rel}" \ + -o {output} + ''' + +rule extract_data: + input: + (RAW_DIR / "MALDI-MSI_Sagittal_Mouse_Brain.tar.gz") + output: + directory(RAW_DIR / "maldi_msi_extracted") + shell: + ''' + rm -rf {output} {output}.tmp + mkdir -p {output}.tmp + tar -xzf {input} -C {output}.tmp + mv {output}.tmp {output} + ''' + +rule download_data: + output: + (RAW_DIR / "MALDI-MSI_Sagittal_Mouse_Brain.tar.gz") + params: + file_url=TAR_URL, + md5=TAR_MD5 + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + python3 -c "import hashlib, sys; h = hashlib.md5(); f = open(sys.argv[1], 'rb'); [h.update(b) for b in iter(lambda: f.read(1 << 24), b'')]; sys.exit(0 if h.hexdigest() == sys.argv[2] else 'MD5 mismatch for ' + sys.argv[1])" {output} {params.md5} + ''' diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/config.yml b/demos/spatialdata-maldi-msi-timstof-mouse-brain/config.yml new file mode 100644 index 00000000..4e225df1 --- /dev/null +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/config.yml @@ -0,0 +1,2 @@ +output: +- maldi_msi_mouse_brain.spatialdata.zarr diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/convert_with_thyra.py b/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/convert_with_thyra.py new file mode 100644 index 00000000..7e6d3c06 --- /dev/null +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/convert_with_thyra.py @@ -0,0 +1,43 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "thyra==4.9.0", +# ] +# /// +"""Convert a Bruker timsTOF .d MALDI-MSI acquisition to SpatialData with Thyra. + +Note: Thyra reads Bruker timsTOF data with Bruker's own SDK, which ships with Thyra +for Windows and Linux only. This step cannot run on macOS. +Reference: https://M4i-Imaging-Mass-Spectrometry.github.io/thyra/tutorial/#platform-requirements + +Any other input Thyra supports (e.g., an .imzML file) also works here. +""" +import argparse + +from thyra import convert_msi + + +def convert(input_path, output_path, dataset_id, resample_bins): + # From Python, Thyra only resamples when a resampling_config is given. + # An empty dict gives the same automatic choice as the `thyra` command. + # Reference: https://M4i-Imaging-Mass-Spectrometry.github.io/thyra/settings/#convert-from-python + resampling_config = {} if resample_bins is None else {"target_bins": resample_bins} + convert_msi( + input_path, + output_path, + dataset_id=dataset_id, + resampling_config=resampling_config, + include_optical=True, + apply_optical_alignment=True, + raise_on_failure=True, + ) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input', type=str, required=True, help='Input MSI acquisition (e.g., Bruker .d directory)') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + parser.add_argument('--dataset-id', type=str, default='msi_dataset', help='Thyra dataset ID (prefix of element names)') + parser.add_argument('--resample-bins', type=int, default=None, help='Number of m/z bins (default: automatic)') + args = parser.parse_args() + convert(args.input, args.output, args.dataset_id, args.resample_bins) diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/make_vitessce_store.py b/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/make_vitessce_store.py new file mode 100644 index 00000000..f51fd09a --- /dev/null +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/make_vitessce_store.py @@ -0,0 +1,225 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# # Match the versions that Thyra 4.9.0 writes with. +# "spatialdata==0.8.0", +# "anndata==0.13.4", +# "zarr>=3.4,<3.5", +# "scipy", +# "scikit-learn", +# ] +# /// +"""Make a Vitessce-friendly SpatialData store from a Thyra MSI store. + +A Thyra table has one row per MSI pixel and one column per m/z bin (often 10^5 bins or more), +and one polygon per pixel in a Shapes element. Both are too large to visualize directly +for a ~1.5 million pixel acquisition. Here, we: +- pick the most intense peaks of the average spectrum and sum each peak's m/z window per pixel, + giving a (pixels x peaks) table, +- rasterize the pixels into a Labels element on the TIC image grid (one label per pixel), + annotated by that table, +- cluster the pixels (TIC-normalized, log-transformed peak intensities) with k-means, +- keep the TIC image and the optical image that Thyra aligned to the MSI data (if any). + +Output elements (fixed names, used by vitessce.template.json): +- images/background_image: the optical image that Thyra aligned the MSI data to, or the TIC image if there is none +- images/tic_image: the total ion current image +- labels/pixel_labels: MSI pixels, one label ID per pixel +- tables/msi_peaks: (pixels x peaks) intensities, annotating labels/pixel_labels +""" +import argparse +import shutil +from os.path import isdir + +import anndata as ad +import numpy as np +import pandas as pd +import spatialdata as sd +import zarr +from anndata.io import read_elem, sparse_dataset +from scipy.signal import find_peaks +from sklearn.cluster import MiniBatchKMeans +from sklearn.decomposition import PCA +from spatialdata.models import Image2DModel, Labels2DModel, TableModel +from spatialdata.transformations import Affine, get_transformation, set_transformation +from xarray import DataArray + +LABELS_NAME = "pixel_labels" +TABLE_NAME = "msi_peaks" +TIC_NAME = "tic_image" +BACKGROUND_NAME = "background_image" +# Images larger than this (in x or y) are converted to multiscale images. +MULTISCALE_THRESHOLD = 2048 + + +def pick_peaks(avg_spectrum, num_peaks, half_window): + # Local maxima of the average spectrum, at least one window apart, keeping the most intense. + peak_idx, props = find_peaks(avg_spectrum, distance=2 * half_window + 1, height=0) + order = np.argsort(props["peak_heights"])[::-1][:num_peaks] + return np.sort(peak_idx[order]) + + +def sum_peak_windows(X, peak_idx, half_window, n_vars, row_block=100_000): + # X is a backed (on-disk) sparse matrix. + values = np.zeros((X.shape[0], len(peak_idx)), dtype=np.float32) + windows = [(max(0, p - half_window), min(n_vars, p + half_window + 1)) for p in peak_idx] + if X.format == "csc": + # Each contiguous column slice reads only those columns. + for i, (lo, hi) in enumerate(windows): + values[:, i] = np.asarray(X[:, lo:hi].sum(axis=1)).ravel() + else: + # CSR: read blocks of rows, and sum every window within each block. + for r0 in range(0, X.shape[0], row_block): + block = X[r0:r0 + row_block].tocsc() + for i, (lo, hi) in enumerate(windows): + values[r0:r0 + row_block, i] = np.asarray(block[:, lo:hi].sum(axis=1)).ravel() + return values, windows + + +def cluster_pixels(values, tic, n_clusters): + # TIC normalization is the usual normalization for MALDI-MSI spectra. + has_signal = tic > 0 + norm = np.zeros_like(values) + norm[has_signal] = values[has_signal] / tic[has_signal, None] * np.median(tic[has_signal]) + norm = np.log1p(norm) + n_comps = min(20, values.shape[1] - 1) + pcs = PCA(n_components=n_comps, random_state=0).fit_transform(norm[has_signal]) + km = MiniBatchKMeans(n_clusters=n_clusters, random_state=0, batch_size=10_000, n_init=3) + clusters = np.full(values.shape[0], "no signal", dtype=object) + clusters[has_signal] = [f"Cluster {c + 1}" for c in km.fit_predict(pcs)] + return pd.Categorical(clusters) + + +def to_yx_affine(element, cs): + # Express an element's transformation to `cs` as a (y, x) Affine, for a Labels element on the same grid. + matrix = get_transformation(element, to_coordinate_system=cs).to_affine_matrix( + input_axes=("y", "x"), output_axes=("y", "x") + ) + return Affine(matrix, input_axes=("y", "x"), output_axes=("y", "x")) + + +def as_multiscale(image): + if not isinstance(image, DataArray): + # Already multiscale (a DataTree). + return image + if max(image.sizes["y"], image.sizes["x"]) <= MULTISCALE_THRESHOLD: + return image + n_levels = int(np.ceil(np.log2(max(image.sizes["y"], image.sizes["x"]) / 512))) + return Image2DModel.parse( + image.data, + dims=image.dims, + c_coords=image.coords["c"].values if "c" in image.coords else None, + scale_factors=[2] * n_levels, + transformations=get_transformation(image, get_all=True), + chunks=(1, 512, 512), + ) + + +def rechunk_dense_X(sdata_path, table_name, n_obs): + # One chunk per feature column, so Vitessce can load one m/z peak at a time. + group = zarr.open_group(f"{sdata_path}/tables/{table_name}", mode="r+") + old = group["X"] + data = old[:] + attrs = dict(old.attrs) + del group["X"] + new = group.create_array("X", shape=data.shape, dtype=data.dtype, chunks=(n_obs, 1)) + new[:] = data + new.attrs.update(attrs) + + +def process(input_path, output_path, dataset_id, num_peaks, half_window, n_clusters): + table_key = f"{dataset_id}_z0" + tic_key = f"{dataset_id}_z0_tic" + + # Read the (large) table lazily, without spatialdata.read_zarr, which would load X into memory. + table_group = zarr.open_group(f"{input_path}/tables/{table_key}", mode="r") + obs = read_elem(table_group["obs"]) + var = read_elem(table_group["var"]) + avg_spectrum = np.asarray(read_elem(table_group["uns/average_spectrum"]), dtype=np.float64) + X = sparse_dataset(table_group["X"]) + mz = var["mz"].to_numpy() + print(f"Table {table_key}: {X.shape[0]} pixels x {X.shape[1]} m/z bins ({X.format})") + + peak_idx = pick_peaks(avg_spectrum, num_peaks, half_window) + values, windows = sum_peak_windows(X, peak_idx, half_window, len(mz)) + + # Images (lazy). Skip the per-pixel Shapes element, which is replaced by the Labels element below. + src = sd.read_zarr(input_path, selection=("images",)) + tic_image = src.images[tic_key] + _, ny, nx = tic_image.shape + + # Rasterize the pixels: label i + 1 for table row i, 0 for the background. + px_x = obs["x"].to_numpy().astype(np.int64) + px_y = obs["y"].to_numpy().astype(np.int64) + assert px_x.min() >= 0 and px_x.max() < nx and px_y.min() >= 0 and px_y.max() < ny + label_ids = np.arange(1, len(obs) + 1, dtype=np.uint32) + raster = np.zeros((ny, nx), dtype=np.uint32) + raster[px_y, px_x] = label_ids + labels = Labels2DModel.parse(raster, dims=("y", "x")) + for cs in get_transformation(tic_image, get_all=True).keys(): + set_transformation(labels, to_yx_affine(tic_image, cs), to_coordinate_system=cs) + + tic = obs["tic"].to_numpy().astype(np.float32) if "tic" in obs else np.asarray(X.sum(axis=1)).ravel() + new_obs = pd.DataFrame( + { + "label_id": label_ids, + "region": pd.Categorical([LABELS_NAME] * len(obs)), + "tic": tic, + "pixel_x": px_x, + "pixel_y": px_y, + }, + index=pd.Index([str(i) for i in label_ids]), + ) + for col in ["spatial_x", "spatial_y"]: + if col in obs: + new_obs[col] = obs[col].to_numpy() + if "region_number" in obs: + new_obs["region_number"] = pd.Categorical(obs["region_number"].astype(str).to_numpy()) + new_obs["kmeans"] = cluster_pixels(values, tic, n_clusters) + + new_var = pd.DataFrame( + { + "mz": mz[peak_idx], + "mz_min": [mz[lo] for lo, _ in windows], + "mz_max": [mz[hi - 1] for _, hi in windows], + "mean_intensity": avg_spectrum[peak_idx], + }, + index=pd.Index([f"m/z {m:.4f}" for m in mz[peak_idx]]), + ) + table = TableModel.parse( + ad.AnnData(X=values, obs=new_obs, var=new_var), + region=LABELS_NAME, + region_key="region", + instance_key="label_id", + ) + + images = {TIC_NAME: tic_image} + optical = src.attrs.get("optical_images") or {} + alignment_element = optical.get("alignment_element") + if alignment_element and alignment_element in src.images: + print(f"Using the optical image {alignment_element} as the background image") + images[BACKGROUND_NAME] = as_multiscale(src.images[alignment_element]) + else: + print("No aligned optical image, using the TIC image as the background image") + images[BACKGROUND_NAME] = tic_image + + out = sd.SpatialData(images=images, labels={LABELS_NAME: labels}, tables={TABLE_NAME: table}) + out.attrs.update({k: v for k, v in src.attrs.items() if k.startswith("pixel_size") or k == "coordinate_systems"}) + + if isdir(output_path): + shutil.rmtree(output_path) + out.write(output_path) + rechunk_dense_X(output_path, TABLE_NAME, values.shape[0]) + print(f"Wrote {output_path}: {len(obs)} pixels, {len(peak_idx)} peaks") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input', type=str, required=True, help='Input SpatialData .zarr store written by Thyra') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + parser.add_argument('--dataset-id', type=str, default='msi_dataset', help='Thyra dataset ID (prefix of element names)') + parser.add_argument('--num-peaks', type=int, default=100, help='Number of peaks of the average spectrum to keep') + parser.add_argument('--half-window', type=int, default=3, help='Half-width, in m/z bins, of the window summed around each peak') + parser.add_argument('--n-clusters', type=int, default=10, help='Number of k-means clusters of pixels') + args = parser.parse_args() + process(args.input, args.output, args.dataset_id, args.num_peaks, args.half_window, args.n_clusters) diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/vitessce.template.json b/demos/spatialdata-maldi-msi-timstof-mouse-brain/vitessce.template.json new file mode 100644 index 00000000..3d6b0248 --- /dev/null +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/vitessce.template.json @@ -0,0 +1,188 @@ +{ + "version": "1.0.18", + "name": "MALDI-MSI sagittal mouse brain (Bruker timsTOF)", + "description": "MALDI mass spectrometry imaging from Zenodo 10.5281/zenodo.18326569, converted with Thyra, with the 100 most intense peaks of the average spectrum and k-means clusters of pixels", + "datasets": [ + { + "uid": "A", + "name": "MALDI-MSI", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/maldi_msi_mouse_brain.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/msi_peaks/X" + }, + "image": { + "path": "images/background_image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "labels/pixel_labels", + "tablePath": "tables/msi_peaks", + "coordinateSystem": "global" + }, + "obsSets": { + "tablePath": "tables/msi_peaks", + "obsSets": [ + { + "name": "K-means clusters", + "path": "tables/msi_peaks/obs/kmeans" + } + ] + } + }, + "coordinationValues": { + "obsType": "pixel", + "featureType": "peak", + "featureValueType": "intensity" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "obsType": { + "A": "pixel" + }, + "featureType": { + "A": "peak" + }, + "featureValueType": { + "A": "intensity" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.75 + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": {}, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "A" + }, + "featureType": { + "init_A_obsSegmentations_0": "A" + }, + "featureValueType": { + "init_A_obsSegmentations_0": "A" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "A" + } + } + } + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "x": 0, + "y": 0, + "w": 8, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "x": 8, + "y": 0, + "w": 4, + "h": 4 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureValueType": "A", + "obsColorEncoding": "A" + }, + "x": 8, + "y": 4, + "w": 4, + "h": 4 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureValueType": "A", + "obsColorEncoding": "A" + }, + "x": 8, + "y": 8, + "w": 4, + "h": 4 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-merfish-zhuang-abca-4/Snakefile b/demos/spatialdata-merfish-zhuang-abca-4/Snakefile new file mode 100644 index 00000000..3b025ef2 --- /dev/null +++ b/demos/spatialdata-merfish-zhuang-abca-4/Snakefile @@ -0,0 +1,69 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Academic MERFISH: Zhuang-ABCA-4 (Zhuang lab, Harvard), a whole mouse brain MERFISH dataset +# (1,122-gene panel), from: +# Zhang M, Pan X, Jung W, et al. Molecularly defined and spatially resolved cell atlas of the +# whole mouse brain. Nature 624, 343-354 (2023). https://doi.org/10.1038/s41586-023-06808-9 +# Downloaded from the original source, the Allen Brain Cell (ABC) Atlas public S3 bucket +# (no login required), which hosts the Zhuang lab's processed data with cell type labels +# mapped to the Allen whole mouse brain taxonomy (Yao et al. 2023): +# https://alleninstitute.github.io/abc_atlas_access/descriptions/Zhuang_dataset.html +# https://allen-brain-cell-atlas.s3.us-west-2.amazonaws.com/index.html +# License: CC BY 4.0 (Allen Institute ABC Atlas terms: +# https://alleninstitute.github.io/abc_atlas_access/notebooks/getting_started.html). +# The ABC atlas does not include cell segmentations or transcript locations for this dataset, +# so cells are represented as circles at their centroids. +# +# Note: the TODO suggestion for academic MERFISH was the thick-tissue 3D MERFISH dataset +# (Fang et al. 2024 eLife, https://doi.org/10.7554/eLife.90029, https://github.com/broadinstitute/scverse-owkin_thick_merfish), +# whose data is deposited at Dryad (https://doi.org/10.5061/dryad.w0vt4b922, CC0). Dryad file +# downloads currently require a browser session or a Dryad API token, so it is not used here. +ABC_ATLAS_URL = "https://allen-brain-cell-atlas.s3.us-west-2.amazonaws.com" +EXPRESSION_URL = f"{ABC_ATLAS_URL}/expression_matrices/Zhuang-ABCA-4/20230830/Zhuang-ABCA-4-raw.h5ad" +METADATA_URL = f"{ABC_ATLAS_URL}/metadata/Zhuang-ABCA-4/20241115/views/cell_metadata_with_cluster_annotation.csv" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +rule to_spatialdata: + input: + expression=(RAW_DIR / "Zhuang-ABCA-4-raw.h5ad"), + metadata=(RAW_DIR / "cell_metadata_with_cluster_annotation.csv") + output: + directory(PROCESSED_DIR / "zhuang_abca_4.spatialdata.zarr") + params: + script=(SRC_DIR / "to_spatialdata.py") + shell: + ''' + uv run --script {params.script} \ + -e {input.expression} \ + -m {input.metadata} \ + -o {output} + ''' + +rule download_expression: + output: + (RAW_DIR / "Zhuang-ABCA-4-raw.h5ad") + params: + file_url=EXPRESSION_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' + +rule download_metadata: + output: + (RAW_DIR / "cell_metadata_with_cluster_annotation.csv") + params: + file_url=METADATA_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-merfish-zhuang-abca-4/config.yml b/demos/spatialdata-merfish-zhuang-abca-4/config.yml new file mode 100644 index 00000000..c079671f --- /dev/null +++ b/demos/spatialdata-merfish-zhuang-abca-4/config.yml @@ -0,0 +1,2 @@ +output: +- zhuang_abca_4.spatialdata.zarr diff --git a/demos/spatialdata-merfish-zhuang-abca-4/src/to_spatialdata.py b/demos/spatialdata-merfish-zhuang-abca-4/src/to_spatialdata.py new file mode 100644 index 00000000..caeb6707 --- /dev/null +++ b/demos/spatialdata-merfish-zhuang-abca-4/src/to_spatialdata.py @@ -0,0 +1,139 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# "anndata>=0.12,<0.13", # anndata 0.13 (X as a None-keyed layer) breaks spatialdata 0.7.3 table validation +# "pandas", +# "geopandas", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse +import shutil +from os.path import isdir + +import anndata as ad +import geopandas as gpd +import numpy as np +import pandas as pd +from shapely.geometry import Point +from spatialdata import SpatialData +from spatialdata.models import ShapesModel, TableModel +from spatialdata.transformations import Identity +from vitessce.data_utils import optimize_adata + +# The Allen Brain Cell (ABC) Atlas does not distribute cell segmentations for the +# Zhuang MERFISH datasets, only per-cell centroids. We represent each cell as a circle. +# Approximate cell radius in micrometers (the centroid coordinates are in millimeters). +CELL_RADIUS_UM = 5.0 + +# Gap (in micrometers) between brain sections when laying them out side by side. +SECTION_GAP_UM = 500.0 + +ANNOTATION_COLS = ["neurotransmitter", "class", "subclass", "supertype", "cluster"] + + +def process(expression_path, metadata_path, output_path): + # Raw counts (dense matrix, cells x 1,122 genes). + adata = ad.read_h5ad(expression_path) + + # Use gene symbols as the var index (for display in Vitessce). + adata.var["gene_identifier"] = adata.var.index.astype(str) + adata.var.index = pd.Index(adata.var["gene_symbol"].astype(str).values) + adata.var_names_make_unique() + adata.var = adata.var[["gene_identifier"]] + + obs = pd.read_csv(metadata_path, index_col="cell_label", dtype={"cell_label": str}) + # Keep only cells with both expression and metadata. + shared = adata.obs_names.intersection(obs.index) + adata = adata[shared, :].copy() + obs = obs.loc[shared] + + for col in ANNOTATION_COLS + ["brain_section_label"]: + obs[col] = obs[col].fillna("NA").astype(str).astype("category") + + # Coordinates in the ABC atlas are in millimeters, in a per-section reconstructed space. + # Convert to micrometers, and lay out the sections side by side + # (ordered by their z position along the anterior-posterior axis) so they do not overlap. + x_um = obs["x"].to_numpy() * 1000.0 + y_um = obs["y"].to_numpy() * 1000.0 + section_order = ( + obs.groupby("brain_section_label", observed=True)["z"].mean().sort_values().index.tolist() + ) + offsets = {} + cur_x = 0.0 + for section in section_order: + mask = (obs["brain_section_label"] == section).to_numpy() + sec_min = x_um[mask].min() + sec_max = x_um[mask].max() + offsets[section] = cur_x - sec_min + cur_x += (sec_max - sec_min) + SECTION_GAP_UM + x_offset = obs["brain_section_label"].astype(str).map(offsets).to_numpy() + x_layout = x_um + x_offset + y_layout = y_um - y_um.min() + + obs["x_layout_um"] = x_layout + obs["y_layout_um"] = y_layout + + # Per-category colors from the ABC atlas, stored in uns (as scanpy does) for reference. + uns = {} + for col in ANNOTATION_COLS: + color_col = f"{col}_color" + if color_col in obs.columns: + color_map = obs.groupby(col, observed=True)[color_col].first() + uns[f"{col}_colors"] = [ + (color_map.get(c) if isinstance(color_map.get(c), str) else "#808080") + for c in obs[col].cat.categories + ] + + keep_cols = [ + "brain_section_label", "donor_label", "donor_sex", + "x", "y", "z", "x_layout_um", "y_layout_um", + "subclass_confidence_score", "cluster_confidence_score", + ] + ANNOTATION_COLS + obs = obs[keep_cols] + adata.obs = obs + adata.obsm["spatial"] = np.column_stack([x_layout, y_layout]) + + adata = optimize_adata( + adata, + obs_cols=keep_cols, + obsm_keys=["spatial"], + var_cols=["gene_identifier"], + layer_keys=[], + optimize_X=True, + ) + adata.uns.update(uns) + + # Shapes: one circle per cell. + cell_ids = adata.obs_names.astype(str) + circles = gpd.GeoDataFrame( + {"radius": np.full(adata.n_obs, CELL_RADIUS_UM, dtype=np.float32)}, + geometry=[Point(x, y) for x, y in zip(x_layout, y_layout)], + index=pd.Index(cell_ids, name="cell_id"), + ) + shapes = ShapesModel.parse(circles, transformations={"global": Identity()}) + + # Table annotating the circles. + adata.obs["region"] = pd.Categorical(["cell_circles"] * adata.n_obs) + adata.obs["cell_id"] = cell_ids + table = TableModel.parse(adata, region="cell_circles", region_key="region", instance_key="cell_id") + + sdata = SpatialData(shapes={"cell_circles": shapes}, tables={"table": table}) + + if isdir(output_path): + shutil.rmtree(output_path) + sdata.write(output_path) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-e', '--expression', type=str, required=True, help='Raw counts .h5ad file from the ABC atlas') + parser.add_argument('-m', '--metadata', type=str, required=True, help='cell_metadata_with_cluster_annotation.csv') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + args = parser.parse_args() + process(args.expression, args.metadata, args.output) diff --git a/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json b/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json new file mode 100644 index 00000000..62db9bc3 --- /dev/null +++ b/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json @@ -0,0 +1,144 @@ +{ + "version": "1.0.18", + "name": "MERFISH whole mouse brain (Zhuang-ABCA-4)", + "description": "Zhuang lab MERFISH (Zhang et al. 2023), three coronal sections laid out side by side, with ABC atlas cell type labels", + "datasets": [ + { + "uid": "A", + "name": "Zhuang-ABCA-4", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/zhuang_abca_4.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "obsSpots": { + "path": "shapes/cell_circles", + "tablePath": "tables/table", + "coordinateSystem": "global" + }, + "obsSets": { + "tablePath": "tables/table", + "obsSets": [ + { + "name": "Class", + "path": "tables/table/obs/class" + }, + { + "name": "Subclass", + "path": "tables/table/obs/subclass" + }, + { + "name": "Supertype", + "path": "tables/table/obs/supertype" + }, + { + "name": "Neurotransmitter", + "path": "tables/table/obs/neurotransmitter" + }, + { + "name": "Brain section", + "path": "tables/table/obs/brain_section_label" + } + ] + } + }, + "coordinationValues": { + "obsType": "cell" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "metaCoordinationScopes": { + "init_A_obsSpots_0": { + "spotLayer": [ + "init_A_obsSpots_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_obsSpots_0": { + "spotLayer": { + "obsColorEncoding": { + "init_A_obsSpots_0": "init_A_obsSpots_0" + } + } + } + }, + "spotLayer": { + "init_A_obsSpots_0": "__dummy__" + }, + "obsColorEncoding": { + "init_A_obsSpots_0": "cellSetSelection" + }, + "obsType": { + "A": "cell" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_obsSpots_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 8, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_obsSpots_0" + ], + "obsType": "A" + }, + "x": 8, + "y": 0, + "w": 4, + "h": 3 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 8, + "y": 3, + "w": 4, + "h": 5 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 8, + "y": 8, + "w": 4, + "h": 4 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-merscope-mouse-brain/Snakefile b/demos/spatialdata-merscope-mouse-brain/Snakefile new file mode 100644 index 00000000..625446aa --- /dev/null +++ b/demos/spatialdata-merscope-mouse-brain/Snakefile @@ -0,0 +1,128 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Vizgen MERSCOPE: MERFISH Mouse Brain Receptor Map (483-gene panel, 3 coronal slices x 3 replicates). +# We use Slice 2, Replicate 1. +# Source (Vizgen data release; no login needed for this public Google Cloud Storage bucket): +# https://info.vizgen.com/mouse-brain-map +# https://console.cloud.google.com/storage/browser/vizgen-mouse-brain-map/BrainReceptorShowcase +# (read over HTTPS via https://storage.googleapis.com/vizgen-mouse-brain-map/...) +# License: Vizgen's open-access data terms (see https://info.vizgen.com/mouse-brain-map); +# the data is free to use and was released by Vizgen as a "showcase" dataset. +# Inspired by https://github.com/MicTott/spatialscape-examples/tree/main/merscope-mouse-brain +# +# Download size: ~34 GB (detected_transcripts.csv 3.2 GB, cell boundaries 5.8 GB in 1,242 HDF5 files, +# and two 12.4 GB uncompressed mosaic images, DAPI and polyT, at the middle z-plane). +# +# This dataset predates the MERSCOPE cell_boundaries.parquet output, so the per-FOV +# HDF5 cell boundary files are first converted to GeoParquet (src/hdf5_boundaries_to_parquet.py). +BUCKET_URL = "https://storage.googleapis.com/vizgen-mouse-brain-map" +SLICE_PREFIX = "BrainReceptorShowcase/Slice2/Replicate1" +SLICE_URL = f"{BUCKET_URL}/{SLICE_PREFIX}" +# Google Cloud Storage JSON API listing of the cell boundary files. +BOUNDARIES_LIST_URL = ( + "https://storage.googleapis.com/storage/v1/b/vizgen-mouse-brain-map/o" + f"?prefix={SLICE_PREFIX}/cell_boundaries/&maxResults=5000&fields=items(name),nextPageToken" +) + +REGION_NAME = "slice2_replicate1" +# The middle of the 7 z-planes (z0 to z6), used for both the images and the cell boundaries. +Z_LAYER = 3 +STAINS = ["DAPI", "polyT"] +SLICE_DIR = RAW_DIR / REGION_NAME +INTERMEDIATE_DIR = DATA_DIR / "intermediate" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +rule to_spatialdata: + input: + counts=(SLICE_DIR / "cell_by_gene.csv"), + metadata=(SLICE_DIR / "cell_metadata.csv"), + transcripts=(SLICE_DIR / "detected_transcripts.csv"), + transform=(SLICE_DIR / "images" / "micron_to_mosaic_pixel_transform.csv"), + mosaics=[ (SLICE_DIR / "images" / f"mosaic_{stain}_z{Z_LAYER}.tif") for stain in STAINS ], + boundaries=(INTERMEDIATE_DIR / "cell_boundaries.parquet") + output: + directory(PROCESSED_DIR / "merscope_mouse_brain_slice2_replicate1.spatialdata.zarr") + params: + script=(SRC_DIR / "to_spatialdata.py"), + region_name=REGION_NAME, + z_layer=Z_LAYER + shell: + ''' + uv run --script {params.script} \ + -i "$(dirname {input.counts})" \ + -b {input.boundaries} \ + -r {params.region_name} \ + -z {params.z_layer} \ + -o {output} + ''' + +rule boundaries_to_parquet: + input: + (RAW_DIR / "cell_boundaries_hdf5") + output: + (INTERMEDIATE_DIR / "cell_boundaries.parquet") + params: + script=(SRC_DIR / "hdf5_boundaries_to_parquet.py"), + z_layer=Z_LAYER + shell: + ''' + uv run --script {params.script} -i {input} -o {output} -z {params.z_layer} + ''' + +rule download_boundaries: + output: + directory(RAW_DIR / "cell_boundaries_hdf5") + params: + list_url=BOUNDARIES_LIST_URL, + bucket_url=BUCKET_URL + shell: + ''' + mkdir -p {output} + curl -sL --retry 999 --retry-delay 3 "{params.list_url}" \ + | python3 -c 'import sys, json; d = json.load(sys.stdin); assert "nextPageToken" not in d; print("\\n".join(i["name"] for i in d["items"]))' \ + > {output}/files.txt + while read -r name; do + curl -sL --retry 999 --retry-delay 3 -C - -o "{output}/$(basename "$name")" "{params.bucket_url}/$name" + done < {output}/files.txt + ''' + +rule download_mosaic: + output: + (SLICE_DIR / "images" / "mosaic_{stain}_z{z}.tif") + params: + file_url=lambda w: f"{SLICE_URL}/images/mosaic_{w.stain}_z{w.z}.tif" + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' + +rule download_transform: + output: + (SLICE_DIR / "images" / "micron_to_mosaic_pixel_transform.csv") + params: + file_url=f"{SLICE_URL}/images/micron_to_mosaic_pixel_transform.csv" + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' + +rule download_csv: + output: + (SLICE_DIR / "{name}.csv") + wildcard_constraints: + name="cell_by_gene|cell_metadata|detected_transcripts" + params: + file_url=lambda w: f"{SLICE_URL}/{w.name}.csv" + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-merscope-mouse-brain/config.yml b/demos/spatialdata-merscope-mouse-brain/config.yml new file mode 100644 index 00000000..0650a0ff --- /dev/null +++ b/demos/spatialdata-merscope-mouse-brain/config.yml @@ -0,0 +1,2 @@ +output: +- merscope_mouse_brain_slice2_replicate1.spatialdata.zarr diff --git a/demos/spatialdata-merscope-mouse-brain/src/hdf5_boundaries_to_parquet.py b/demos/spatialdata-merscope-mouse-brain/src/hdf5_boundaries_to_parquet.py new file mode 100644 index 00000000..bc6f97c8 --- /dev/null +++ b/demos/spatialdata-merscope-mouse-brain/src/hdf5_boundaries_to_parquet.py @@ -0,0 +1,85 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "h5py", +# "numpy", +# "pandas", +# "geopandas", +# "pyarrow", +# "shapely>=2", +# ] +# /// +"""Convert legacy MERSCOPE per-FOV cell boundary HDF5 files to a single GeoParquet file. + +Older MERSCOPE outputs (such as the Vizgen Mouse Brain Receptor Map) store cell boundaries +as one HDF5 file per field of view (cell_boundaries/feature_data_{fov}.hdf5), with the structure + featuredata/{cell_id}/zIndex_{z}/p_{i}/coordinates (shape: 1 x n_vertices x 2, in micrometers) +Newer outputs (and spatialdata-io's merscope reader) use a cell_boundaries.parquet file instead. +""" +import argparse +from os import listdir +from os.path import join + +import geopandas as gpd +import h5py +import numpy as np +from shapely.geometry import MultiPolygon, Polygon + + +def read_fov_file(path, z_index): + cell_ids = [] + geometries = [] + with h5py.File(path, "r") as f: + if "featuredata" not in f: + return cell_ids, geometries + for cell_id, cell_group in f["featuredata"].items(): + z_key = f"zIndex_{z_index}" + if z_key not in cell_group: + continue + polygons = [] + for p_key in sorted(cell_group[z_key].keys()): + coords = np.asarray(cell_group[z_key][p_key]["coordinates"][0]) + if coords.shape[0] >= 3: + polygon = Polygon(coords) + if not polygon.is_valid: + polygon = polygon.buffer(0) + if not polygon.is_empty: + polygons.append(polygon) + if len(polygons) == 0: + continue + geometry = polygons[0] if len(polygons) == 1 else MultiPolygon( + [g for p in polygons for g in (p.geoms if hasattr(p, "geoms") else [p])] + ) + cell_ids.append(str(cell_id)) + geometries.append(geometry) + return cell_ids, geometries + + +def convert(input_dir, output_path, z_index): + all_cell_ids = [] + all_geometries = [] + hdf5_files = sorted(f for f in listdir(input_dir) if f.endswith(".hdf5")) + for i, filename in enumerate(hdf5_files): + cell_ids, geometries = read_fov_file(join(input_dir, filename), z_index) + all_cell_ids += cell_ids + all_geometries += geometries + if i % 100 == 0: + print(f"Processed {i + 1} / {len(hdf5_files)} files ({len(all_cell_ids)} cells)") + + gdf = gpd.GeoDataFrame( + {"EntityID": all_cell_ids, "ZIndex": np.full(len(all_cell_ids), z_index, dtype=np.int32)}, + geometry=all_geometries, + ) + # Cells on FOV borders can appear in more than one file. + gdf = gdf.drop_duplicates(subset="EntityID", keep="first").reset_index(drop=True) + gdf.to_parquet(output_path) + print(f"Wrote {gdf.shape[0]} cell boundaries to {output_path}") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input_dir', type=str, required=True, help='Directory of feature_data_*.hdf5 files') + parser.add_argument('-o', '--output', type=str, required=True, help='Output .parquet file') + parser.add_argument('-z', '--z_index', type=int, default=3, help='Which z-plane of the boundaries to keep') + args = parser.parse_args() + convert(args.input_dir, args.output, args.z_index) diff --git a/demos/spatialdata-merscope-mouse-brain/src/to_spatialdata.py b/demos/spatialdata-merscope-mouse-brain/src/to_spatialdata.py new file mode 100644 index 00000000..b90e4d76 --- /dev/null +++ b/demos/spatialdata-merscope-mouse-brain/src/to_spatialdata.py @@ -0,0 +1,138 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# "spatialdata-io==0.7.2", +# "anndata>=0.12,<0.13", # anndata 0.13 (X as a None-keyed layer) breaks spatialdata 0.7.3 table validation +# "geopandas", +# "scanpy", +# "igraph", +# "rioxarray", # lazy, windowed reads of the (uncompressed, ~12 GB per channel) mosaic TIFFs +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse +import os +import shutil +import tempfile +from os.path import abspath, isdir, join + +import geopandas as gpd +import pandas as pd +import scanpy as sc +from shapely.geometry import MultiPolygon +from spatialdata import read_zarr +from spatialdata.models import PointsModel, ShapesModel +from spatialdata.transformations import get_transformation +from spatialdata_io import merscope +from vitessce.data_utils import ( + sdata_morton_sort_points, + sdata_points_process_columns, + sdata_points_modify_row_group_size, +) + +SLIDE_NAME = "mouse_brain" + + +def add_clusters(table): + # This data release does not include cell type annotations, + # so we compute Leiden clusters (and a UMAP) for the cell sets view. + # X remains the raw counts. + adata = table.copy() + sc.pp.filter_cells(adata, min_counts=10) + sc.pp.normalize_total(adata) + sc.pp.log1p(adata) + sc.pp.pca(adata, n_comps=30) + sc.pp.neighbors(adata) + sc.tl.leiden(adata, resolution=1.0, flavor="igraph", n_iterations=2) + sc.tl.umap(adata) + table.obs["leiden"] = adata.obs["leiden"].reindex(table.obs_names).cat.add_categories(["filtered"]).fillna("filtered") + umap = adata.obsm["X_umap"] + table.obsm["X_umap"] = ( + pd.DataFrame(umap, index=adata.obs_names).reindex(table.obs_names).fillna(0).to_numpy(dtype="float32") + ) + + +def process(input_dir, boundaries_path, region_name, z_layer, output_path): + # spatialdata-io's merscope reader expects the files in a single directory + # (cell_by_gene.csv, cell_metadata.csv, detected_transcripts.csv, images/). + # The cell boundaries are handled separately below, as this dataset predates the + # cell_boundaries.parquet output format. + with tempfile.TemporaryDirectory() as tmp_dir: + region_dir = join(tmp_dir, SLIDE_NAME, region_name) + os.makedirs(region_dir) + for name in os.listdir(input_dir): + os.symlink(abspath(join(input_dir, name)), join(region_dir, name)) + + sdata = merscope( + region_dir, + z_layers=z_layer, + region_name=region_name, + slide_name=SLIDE_NAME, + cells_boundaries=False, + backend="rioxarray", + ) + + dataset_id = f"{SLIDE_NAME}_{region_name}" + points_key = f"{dataset_id}_transcripts" + # The table annotates this (not yet present) shapes element. + shapes_key = f"{dataset_id}_polygons" + + # Cell boundaries (in micrometers, like the transcripts), at the same z-plane as the image. + transformations = get_transformation(sdata[points_key], get_all=True) + boundaries = gpd.read_parquet(boundaries_path) + boundaries = boundaries[boundaries.geometry.is_valid] + boundaries.geometry = boundaries.geometry.map(lambda g: g if isinstance(g, MultiPolygon) else MultiPolygon([g])) + boundaries.index = boundaries["EntityID"].astype(str) + boundaries.index.name = None + # Only keep the boundaries of cells in the table (and vice versa is not required). + table_cell_ids = set(sdata["table"].obs["EntityID"].astype(str)) + boundaries = boundaries[boundaries.index.isin(table_cell_ids)] + sdata[shapes_key] = ShapesModel.parse(boundaries[["geometry"]], transformations=transformations) + + add_clusters(sdata["table"]) + + if isdir(output_path): + shutil.rmtree(output_path) + sdata.write(output_path) + + # Re-read from disk, then make the transcripts ready for tiled access in Vitessce. + # References: + # - https://vitessce.io/docs/data-troubleshooting/#points + # - https://github.com/vitessce/vitessce-python/blob/main/docs/notebooks/spatial_data_xenium_morton.ipynb + sdata = read_zarr(output_path) + transformations = get_transformation(sdata[points_key], get_all=True) + + sdata = sdata_morton_sort_points(sdata, points_key) + ddf = sdata_points_process_columns(sdata, points_key, var_name_col="gene", table_name="table") + if "transform" in ddf.attrs: + del ddf.attrs["transform"] + # Drop the unnamed row index column from the original CSV file. + ddf = ddf.drop(columns=[c for c in ddf.columns if c.startswith("Unnamed")]) + + morton_key = "transcripts_with_morton_codes" + sdata[morton_key] = PointsModel.parse(ddf, feature_key="gene", transformations=transformations) + sdata.write_element(morton_key) + sdata_points_modify_row_group_size(sdata, morton_key, row_group_size=25_000) + + # Remove the unsorted copy of the transcripts to save space. + sdata = read_zarr(output_path) + del sdata[points_key] + sdata.delete_element_from_disk(points_key) + + print(read_zarr(output_path)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input_dir', type=str, required=True, help='Directory with cell_by_gene.csv, cell_metadata.csv, detected_transcripts.csv, and images/') + parser.add_argument('-b', '--boundaries', type=str, required=True, help='cell_boundaries.parquet (GeoParquet)') + parser.add_argument('-r', '--region_name', type=str, required=True, help='Name of the region (e.g., slice2_replicate1)') + parser.add_argument('-z', '--z_layer', type=int, default=3, help='Which z-plane of the mosaic images to keep') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + args = parser.parse_args() + process(args.input_dir, args.boundaries, args.region_name, args.z_layer, args.output) diff --git a/demos/spatialdata-merscope-mouse-brain/vitessce.template.json b/demos/spatialdata-merscope-mouse-brain/vitessce.template.json new file mode 100644 index 00000000..6fe02d8f --- /dev/null +++ b/demos/spatialdata-merscope-mouse-brain/vitessce.template.json @@ -0,0 +1,352 @@ +{ + "version": "1.0.18", + "name": "MERSCOPE mouse brain receptor map (slice 2, replicate 1)", + "description": "Vizgen MERFISH Mouse Brain Receptor Map (483 genes), with Leiden clusters computed in the processing script", + "datasets": [ + { + "uid": "A", + "name": "MERSCOPE mouse brain receptor map (slice 2, replicate 1)", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/merscope_mouse_brain_slice2_replicate1.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "obsSets": { + "obsSets": [ + { + "name": "Leiden", + "path": "tables/table/obs/leiden" + } + ], + "tablePath": "tables/table" + }, + "image": { + "path": "images/mouse_brain_slice2_replicate1_z3", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/mouse_brain_slice2_replicate1_polygons", + "tablePath": "tables/table", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/table/obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "cell", + "fileUid": "cells" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/merscope_mouse_brain_slice2_replicate1.spatialdata.zarr", + "options": { + "obsPoints": { + "path": "points/transcripts_with_morton_codes", + "tablePath": "tables/table", + "coordinateSystem": "global", + "featureIndexColumn": "gene_codes", + "mortonCodeColumn": "morton_code_2d" + } + }, + "coordinationValues": { + "obsType": "point", + "featureType": "gene", + "fileUid": "points" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "embeddingType": { + "A": "UMAP" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "fileUid": { + "init_A_image_0": "cells", + "init_A_obsSegmentations_0": "cells", + "init_A_obsPoints_0": "points" + }, + "photometricInterpretation": { + "init_A_image_0": "BlackIsZero" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0, + "init_A_obsSegmentations_0": 1.0, + "init_A_obsPoints_0": 1.0 + }, + "spatialLayerVisible": { + "init_A_image_0": true, + "init_A_obsSegmentations_0": true, + "init_A_obsPoints_0": false + }, + "imageChannel": { + "init_A_image_0": "__dummy__", + "init_A_image_1": "__dummy__" + }, + "spatialTargetC": { + "init_A_image_0": 0, + "init_A_image_1": 1 + }, + "spatialChannelColor": { + "init_A_image_0": [ + 0, + 0, + 255 + ], + "init_A_image_1": [ + 0, + 255, + 0 + ], + "init_A_obsSegmentations_0": [ + 255, + 255, + 255 + ] + }, + "spatialChannelVisible": { + "init_A_image_0": true, + "init_A_image_1": true, + "init_A_obsSegmentations_0": true + }, + "spatialChannelOpacity": { + "init_A_image_0": 1.0, + "init_A_image_1": 1.0, + "init_A_obsSegmentations_0": 0.75 + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + }, + "init_A_obsPoints_0": { + "pointLayer": [ + "init_A_obsPoints_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "fileUid": { + "init_A_image_0": "init_A_image_0" + }, + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerVisible": { + "init_A_image_0": "init_A_image_0" + }, + "imageChannel": { + "init_A_image_0": [ + "init_A_image_0", + "init_A_image_1" + ] + } + }, + "imageChannel": { + "spatialTargetC": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1" + }, + "spatialChannelColor": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1" + }, + "spatialChannelVisible": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1" + }, + "spatialChannelOpacity": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "fileUid": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialLayerOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialLayerVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialChannelVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialChannelColor": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + }, + "init_A_obsPoints_0": { + "pointLayer": { + "fileUid": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "obsType": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "spatialLayerOpacity": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "spatialLayerVisible": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + }, + "obsColorEncoding": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "init_A_obsPoints_0": "point", + "A": "cell" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "cellSetSelection", + "init_A_obsPoints_0": "geneSelection" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": true + }, + "pointLayer": { + "init_A_obsPoints_0": "__dummy__" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 6, + "y": 6, + "w": 3, + "h": 6 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "obsType": "A" + }, + "x": 9, + "y": 6, + "w": 3, + "h": 6 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-mibi-hubmap-uterus/Snakefile b/demos/spatialdata-mibi-hubmap-uterus/Snakefile new file mode 100644 index 00000000..85eca2f1 --- /dev/null +++ b/demos/spatialdata-mibi-hubmap-uterus/Snakefile @@ -0,0 +1,70 @@ +import re + +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Ionpath MIBIscope (multiplexed ion beam imaging) data from HuBMAP. +# +# Processed dataset: HBM957.GCWC.626 (MIBI [DeepCell + SPRM]), +# uuid cdb49a41bf77bbdfe7f7b40b360e7f56 +# https://portal.hubmapconsortium.org/browse/dataset/cdb49a41bf77bbdfe7f7b40b360e7f56 +# "MIBI [DeepCell + SPRM] data from the uterus of a 33.3-year-old unknown female" (Stanford RTI). +# Raw (parent) dataset: HBM574.RBCK.759, uuid 8aabd9b3e3b03a19d47cf85f1af62d9e +# https://doi.org/10.35079/HBM574.RBCK.759 +# Instrument: Ionpath MIBIscope. Decidua basalis (maternal-fetal interface) FFPE tissue. +# Publication: Greenbaum, S. et al. "A spatially resolved timeline of the human maternal-fetal interface." +# Nature 619, 595-605 (2023). https://doi.org/10.1038/s41586-023-06298-9 +# Pipeline: HuBMAP DeepCell segmentation + SPRM (https://github.com/hubmapconsortium/sprm). +# Access: HuBMAP public (open, no login) data; see https://hubmapconsortium.org/policies/ +# +# Files are downloaded from the HuBMAP assets server (https://assets.hubmapconsortium.org//). +# Note: the assets server returns HTTP 403 for the default curl User-Agent, so we set a generic one. +HUBMAP_UUID = "cdb49a41bf77bbdfe7f7b40b360e7f56" +HUBMAP_ASSETS_URL = f"https://assets.hubmapconsortium.org/{HUBMAP_UUID}" +FILES = { + # Pyramidal (compressed) versions of the pipeline_output/{expr,mask} OME-TIFFs. + "expr.ome.tif": "ometiff-pyramids/pipeline_output/expr/3D_image_stack_expr.ome.tif", + "mask.ome.tif": "ometiff-pyramids/pipeline_output/mask/3D_image_stack_mask.ome.tif", + # SPRM cell-by-marker table (AnnData-Zarr, zipped). + "anndata.zarr.zip": "anndata-zarr/3D_image_stack_expr-anndata.zarr.zip", +} + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Combine image, segmentation mask, and SPRM table into one SpatialData store. +rule convert_to_spatialdata: + input: + expr=(RAW_DIR / "expr.ome.tif"), + mask=(RAW_DIR / "mask.ome.tif"), + anndata_zip=(RAW_DIR / "anndata.zarr.zip"), + output: + directory(PROCESSED_DIR / "mibi_hubmap_uterus.spatialdata.zarr") + params: + script=(SRC_DIR / "sprm_to_spatialdata.py") + shell: + ''' + uv run --script {params.script} \ + --expr {input.expr} \ + --mask {input.mask} \ + --anndata-zip {input.anndata_zip} \ + -o {output} + ''' + +rule download_data: + output: + (RAW_DIR / "{filename}") + wildcard_constraints: + filename="|".join(re.escape(k) for k in FILES.keys()) + params: + file_url=lambda w: f"{HUBMAP_ASSETS_URL}/{FILES[w.filename]}" + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -A "vitessce-demos" -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-mibi-hubmap-uterus/config.yml b/demos/spatialdata-mibi-hubmap-uterus/config.yml new file mode 100644 index 00000000..cfd2a14b --- /dev/null +++ b/demos/spatialdata-mibi-hubmap-uterus/config.yml @@ -0,0 +1,2 @@ +output: +- mibi_hubmap_uterus.spatialdata.zarr diff --git a/demos/spatialdata-mibi-hubmap-uterus/src/sprm_to_spatialdata.py b/demos/spatialdata-mibi-hubmap-uterus/src/sprm_to_spatialdata.py new file mode 100644 index 00000000..a950163e --- /dev/null +++ b/demos/spatialdata-mibi-hubmap-uterus/src/sprm_to_spatialdata.py @@ -0,0 +1,189 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# # anndata 0.13 exposes X as layers[None], which spatialdata 0.7.3 validation rejects. +# "anndata<0.13", +# "tifffile>=2025.5.10", +# "imagecodecs", +# "dask", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +""" +Convert the outputs of the HuBMAP DeepCell/Cytokit + SPRM pipelines +(expression OME-TIFF, segmentation mask OME-TIFF, SPRM AnnData-Zarr zip) +into a single SpatialData Zarr store with: + +- images/image: multiscale (pyramidal) multiplexed image (c, y, x) +- labels/cell_labels: multiscale cell segmentation bitmask +- tables/table: cell-by-marker mean intensities, annotating labels/cell_labels, + with SPRM K-Means cluster assignments in obs and t-SNE in obsm. +""" +import argparse +import re +import tempfile +import zipfile + +import anndata as ad +import dask.array as da +import numpy as np +import pandas as pd +import tifffile +import zarr +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, Labels2DModel, TableModel + +LABELS_KEY = "cell_labels" +IMAGE_KEY = "image" +CHUNK_SIZE = 512 + + +class _ArrayLike: + """Minimal array-like wrapper around a (TIFF-backed) zarr array.""" + + def __init__(self, z): + self._z = z + self.shape = z.shape + self.dtype = z.dtype + self.ndim = len(z.shape) + + def __getitem__(self, key): + return np.asarray(self._z[key]) + + +def read_ome_tiff(path): + """Lazily read the full-resolution level of an OME-TIFF as (C, Y, X) dask array, plus channel names.""" + with tifffile.TiffFile(path) as tif: + ome = tifffile.xml2dict(tif.ome_metadata) + series = tif.series[0] + axes = series.axes + shape = series.shape + channels = ome["OME"]["Image"] + if isinstance(channels, list): + channels = channels[0] + channels = channels["Pixels"]["Channel"] + if isinstance(channels, dict): + channels = [channels] + names = [str(c.get("Name", f"Channel {i}")) for i, c in enumerate(channels)] + + store = tifffile.imread(path, aszarr=True, series=0, level=0) + z = zarr.open(store, mode="r") + # Wrap the zarr array so that spatialdata does not treat the TIFF-backed + # store as a "backing file" of the element (it expects a store with a .root). + arr = da.from_array(_ArrayLike(z), chunks=z.chunks, asarray=False) + # Squeeze singleton non-YX axes (e.g. "QQYX" with shape (C, 1, Y, X)). + keep = [i for i, (ax, n) in enumerate(zip(axes, shape)) if ax in "YX" or n > 1] + arr = arr.reshape(tuple(shape[i] for i in keep)) + if arr.ndim == 2: + arr = arr[np.newaxis, ...] + assert arr.ndim == 3, f"Unexpected image shape {shape} with axes {axes}" + if len(names) != arr.shape[0]: + names = [f"Channel {i}" for i in range(arr.shape[0])] + return arr, names + + +def make_unique(names): + seen = {} + result = [] + for n in names: + if n in seen: + seen[n] += 1 + result.append(f"{n}_{seen[n]}") + else: + seen[n] = 0 + result.append(n) + return result + + +def scale_factors_for(shape_yx, min_size=CHUNK_SIZE): + factors = [] + size = max(shape_yx) + while size > min_size: + factors.append(2) + size = size // 2 + return factors + + +def slugify(name): + return re.sub(r"[^0-9a-zA-Z]+", "_", name).strip("_").lower() + + +def read_sprm_table(anndata_zip_path, tmp_dir): + # The HuBMAP anndata-zarr zip contains the contents of an AnnData Zarr store at its root. + with zipfile.ZipFile(anndata_zip_path) as zf: + zf.extractall(tmp_dir) + adata = ad.read_zarr(tmp_dir) + + # Keep only the per-cell (not nucleus/boundary) cluster assignments, with zarr-path-friendly names. + cell_cols = [c for c in adata.obs.columns if c.startswith("Cell K-Means")] + obs = adata.obs[cell_cols].copy() + obs.columns = [slugify(c.removeprefix("Cell ")) for c in cell_cols] + for col in obs.columns: + obs[col] = pd.Categorical([f"Cluster {v}" for v in obs[col]], categories=[f"Cluster {v}" for v in sorted(obs[col].unique())]) + obs["cell_id"] = adata.obs_names.astype(int) + obs["region"] = pd.Categorical([LABELS_KEY] * adata.n_obs) + obs.index = adata.obs_names.astype(str) + + # X is the per-cell mean intensity of each channel (SPRM cell_channel_mean). + new_adata = ad.AnnData( + X=np.asarray(adata.X, dtype=np.float32), + obs=obs, + var=pd.DataFrame(index=make_unique([str(v) for v in adata.var_names])), + layers={ + "cell_x_antigen_total": np.asarray(adata.layers["cell_x_antigen_total"], dtype=np.float32), + }, + obsm={ + "spatial": np.asarray(adata.obsm["xy"], dtype=np.float32), + "X_tsne": np.asarray(adata.obsm["tsne"], dtype=np.float32), + }, + ) + return TableModel.parse(new_adata, region=LABELS_KEY, region_key="region", instance_key="cell_id") + + +def main(expr_path, mask_path, anndata_zip_path, output_path, mask_channel): + img, channel_names = read_ome_tiff(expr_path) + if img.dtype == np.int16: + # MIBI images are stored as int16 counts; Vitessce prefers unsigned types. + img = da.clip(img, 0, None).astype(np.uint16) + image = Image2DModel.parse( + img, + dims=("c", "y", "x"), + c_coords=make_unique(channel_names), + scale_factors=scale_factors_for(img.shape[1:]), + chunks=(1, CHUNK_SIZE, CHUNK_SIZE), + ) + + mask, mask_names = read_ome_tiff(mask_path) + mask_index = mask_names.index(mask_channel) if mask_channel in mask_names else 0 + labels = Labels2DModel.parse( + mask[mask_index], + dims=("y", "x"), + scale_factors=scale_factors_for(mask.shape[1:]), + chunks=(CHUNK_SIZE, CHUNK_SIZE), + ) + + with tempfile.TemporaryDirectory() as tmp_dir: + table = read_sprm_table(anndata_zip_path, tmp_dir) + sdata = SpatialData( + images={IMAGE_KEY: image}, + labels={LABELS_KEY: labels}, + tables={"table": table}, + ) + sdata.write(output_path, overwrite=True) + print(sdata) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--expr", required=True, help="Expression (multiplexed image) OME-TIFF") + parser.add_argument("--mask", required=True, help="Segmentation mask OME-TIFF") + parser.add_argument("--anndata-zip", required=True, help="SPRM AnnData-Zarr .zip") + parser.add_argument("--mask-channel", default="cells", help="Name of the mask channel to use as cell labels") + parser.add_argument("-o", "--output", required=True, help="Output SpatialData .zarr store") + args = parser.parse_args() + main(args.expr, args.mask, args.anndata_zip, args.output, args.mask_channel) diff --git a/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json b/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json new file mode 100644 index 00000000..69bf4da7 --- /dev/null +++ b/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json @@ -0,0 +1,364 @@ +{ + "version": "1.0.18", + "name": "MIBI maternal-fetal interface (HuBMAP HBM957.GCWC.626)", + "description": "Ionpath MIBIscope image of human decidua (Greenbaum et al. 2023) with DeepCell segmentation and SPRM cell-by-marker table, from HuBMAP", + "datasets": [ + { + "uid": "A", + "name": "MIBI maternal-fetal interface (HuBMAP HBM957.GCWC.626)", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/mibi_hubmap_uterus.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X", + "region": "cell_labels" + }, + "obsSets": { + "obsSets": [ + { + "name": "SPRM K-Means [Mean] Expression", + "path": "tables/table/obs/k_means_mean_expression" + }, + { + "name": "SPRM K-Means [Covariance] Expression", + "path": "tables/table/obs/k_means_covariance_expression" + }, + { + "name": "SPRM K-Means [Total] Expression", + "path": "tables/table/obs/k_means_total_expression" + }, + { + "name": "SPRM K-Means [UMAP All Features]", + "path": "tables/table/obs/k_means_umap_all_features" + } + ], + "tablePath": "tables/table", + "region": "cell_labels" + }, + "image": { + "path": "images/image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "labels/cell_labels", + "tablePath": "tables/table", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/table/obsm/X_tsne", + "dims": [ + 0, + 1 + ], + "embeddingType": "t-SNE" + } + ] + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "marker" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "embeddingType": { + "A": "t-SNE" + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "BlackIsZero" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0, + "init_A_obsSegmentations_0": 1.0 + }, + "imageChannel": { + "init_A_image_0": "__dummy__", + "init_A_image_1": "__dummy__", + "init_A_image_2": "__dummy__", + "init_A_image_3": "__dummy__", + "init_A_image_4": "__dummy__" + }, + "spatialTargetC": { + "init_A_image_0": 26, + "init_A_image_1": 44, + "init_A_image_2": 28, + "init_A_image_3": 2, + "init_A_image_4": 37 + }, + "spatialChannelColor": { + "init_A_image_0": [ + 0, + 0, + 255 + ], + "init_A_image_1": [ + 0, + 255, + 0 + ], + "init_A_image_2": [ + 255, + 0, + 0 + ], + "init_A_image_3": [ + 255, + 255, + 0 + ], + "init_A_image_4": [ + 255, + 0, + 255 + ] + }, + "spatialChannelWindow": { + "init_A_image_0": [ + 0, + 40 + ], + "init_A_image_1": [ + 0, + 20 + ], + "init_A_image_2": [ + 0, + 8 + ], + "init_A_image_3": [ + 0, + 15 + ], + "init_A_image_4": [ + 0, + 10 + ] + }, + "spatialChannelVisible": { + "init_A_image_0": true, + "init_A_image_1": true, + "init_A_image_2": true, + "init_A_image_3": true, + "init_A_image_4": true, + "init_A_obsSegmentations_0": true + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + }, + "imageChannel": { + "init_A_image_0": [ + "init_A_image_0", + "init_A_image_1", + "init_A_image_2", + "init_A_image_3", + "init_A_image_4" + ] + } + }, + "imageChannel": { + "spatialTargetC": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelColor": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelWindow": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelVisible": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "spatialLayerVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialLayerOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsColorEncoding": { + "init_A_obsSegmentations_0": "A" + }, + "spatialChannelVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationStrokeWidth": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialLayerVisible": { + "init_A_obsSegmentations_0": true + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": false + }, + "spatialSegmentationStrokeWidth": { + "init_A_obsSegmentations_0": 1.0 + }, + "obsType": { + "A": "cell" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 6 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 3, + "coordinationScopesBy": {} + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 3, + "w": 3, + "h": 3, + "coordinationScopesBy": {} + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "heatmap", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 0, + "y": 6, + "w": 6, + "h": 6, + "coordinationScopesBy": {} + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/Snakefile b/demos/spatialdata-slide-seq-hubmap-kidney/Snakefile new file mode 100644 index 00000000..807ca6c0 --- /dev/null +++ b/demos/spatialdata-slide-seq-hubmap-kidney/Snakefile @@ -0,0 +1,54 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Slide-seq (Slide-seqV2, academic) human kidney dataset from HuBMAP. +# +# Dataset: HBM537.GVTL.683, "Slide-seq [Salmon] data from the kidney (right) of a 67-year-old white male" +# (data provider: Broad Institute RTI; processed by the HuBMAP Salmon RNA-seq pipeline, which also +# runs Leiden clustering, UMAP, and Azimuth cell type annotation). +# - Portal: https://portal.hubmapconsortium.org/browse/dataset/17fb6d5db17936acc8fb613ce98ab808 +# - Processed files: https://assets.hubmapconsortium.org/17fb6d5db17936acc8fb613ce98ab808/ +# - Found via the HuBMAP search API (https://search.api.hubmapconsortium.org/v3/search), +# dataset_type "Slide-seq [Salmon]", data_access_level "public". +# - Pipeline: https://github.com/hubmapconsortium/salmon-rnaseq +# - Slide-seqV2 method: Stickels et al. 2021, Nature Biotechnology, https://doi.org/10.1038/s41587-020-0739-1 +# - License/terms: HuBMAP public data, see https://hubmapconsortium.org/policies/ +# +# Note: assets.hubmapconsortium.org returns 403 Forbidden for curl's default User-Agent, +# so we send a generic one with -A. +H5AD_URL = "https://assets.hubmapconsortium.org/17fb6d5db17936acc8fb613ce98ab808/secondary_analysis.h5ad" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Convert the HuBMAP AnnData object to a SpatialData object, +# with beads as circle Shapes annotated by the table. +rule convert_to_spatialdata: + input: + (RAW_DIR / "secondary_analysis.h5ad") + output: + directory(PROCESSED_DIR / "hubmap_slide_seq_kidney.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py") + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + -o {output} + ''' + +rule download_data: + output: + (RAW_DIR / "secondary_analysis.h5ad") + params: + file_url=H5AD_URL + shell: + ''' + curl -L -A "vitessce-demos" --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/config.yml b/demos/spatialdata-slide-seq-hubmap-kidney/config.yml new file mode 100644 index 00000000..fdd9f8e3 --- /dev/null +++ b/demos/spatialdata-slide-seq-hubmap-kidney/config.yml @@ -0,0 +1,2 @@ +output: +- hubmap_slide_seq_kidney.spatialdata.zarr diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/src/convert_to_spatialdata.py b/demos/spatialdata-slide-seq-hubmap-kidney/src/convert_to_spatialdata.py new file mode 100644 index 00000000..f099a2b4 --- /dev/null +++ b/demos/spatialdata-slide-seq-hubmap-kidney/src/convert_to_spatialdata.py @@ -0,0 +1,92 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# "anndata>=0.12,<0.13", +# "geopandas", +# "numpy", +# "pandas", +# "scipy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse + +import anndata as ad +import geopandas as gpd +import numpy as np +import pandas as pd +from scipy import sparse +from shapely.geometry import Point +from spatialdata import SpatialData +from spatialdata.models import ShapesModel, TableModel +from spatialdata.transformations import Scale + +# Slide-seqV2 bead locations are in units of puck image pixels (0.65 um per pixel), +# and beads are 10 um in diameter. +# Reference: Stickels et al. 2021, https://doi.org/10.1038/s41587-020-0739-1 +MICRONS_PER_PIXEL = 0.65 +BEAD_DIAMETER_UM = 10.0 + +SHAPES_KEY = "beads" +TABLE_KEY = "table" + + +def convert(input_path, output_path): + adata = ad.read_h5ad(input_path) + + # The HuBMAP pipeline output has a scaled (dense) X, and the log-normalized values in layers/unscaled. + X = sparse.csc_matrix(adata.layers["unscaled"], dtype=np.float32) + + # Use gene symbols (falling back to Ensembl IDs) as the var index. + var = adata.var[["hugo_symbol", "highly_variable"]].copy() + var["ensembl_id"] = var.index.astype(str) + symbols = var["hugo_symbol"].astype(object).where(var["hugo_symbol"].notna(), var["ensembl_id"]) + var.index = pd.Index(symbols.astype(str).to_numpy(), name=None) + var["hugo_symbol"] = var["hugo_symbol"].astype(str) + + obs = adata.obs[["n_genes", "n_counts", "leiden", "predicted.ASCT.celltype", "predicted.ASCT.celltype.score"]].copy() + obs = obs.rename(columns={ + "predicted.ASCT.celltype": "predicted_ASCT_celltype", + "predicted.ASCT.celltype.score": "predicted_ASCT_celltype_score", + }) + obs.index = obs.index.astype(str) + obs["region"] = pd.Categorical([SHAPES_KEY] * obs.shape[0]) + obs["bead_id"] = obs.index.to_numpy() + + table = ad.AnnData( + X=X, + obs=obs, + var=var, + obsm={ + "X_umap": adata.obsm["X_umap"].astype(np.float32), + "spatial": adata.obsm["X_spatial"].astype(np.float32), + }, + ) + table.var_names_make_unique() + table = TableModel.parse(table, region=SHAPES_KEY, region_key="region", instance_key="bead_id") + + # Beads as circles, in puck pixel units; the "global" coordinate system is in microns. + xy = adata.obsm["X_spatial"] + beads = gpd.GeoDataFrame( + {"radius": np.full(xy.shape[0], BEAD_DIAMETER_UM / MICRONS_PER_PIXEL / 2.0)}, + geometry=[Point(x, y) for x, y in xy], + index=obs.index, + ) + beads = ShapesModel.parse(beads, transformations={"global": Scale([MICRONS_PER_PIXEL, MICRONS_PER_PIXEL], axes=("x", "y"))}) + + sdata = SpatialData(shapes={SHAPES_KEY: beads}, tables={TABLE_KEY: table}) + sdata.write(output_path, overwrite=True) + print(sdata) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input', type=str, required=True, help='Input HuBMAP Slide-seq secondary_analysis.h5ad file') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + args = parser.parse_args() + convert(args.input, args.output) diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/vitessce.template.json b/demos/spatialdata-slide-seq-hubmap-kidney/vitessce.template.json new file mode 100644 index 00000000..39cc8260 --- /dev/null +++ b/demos/spatialdata-slide-seq-hubmap-kidney/vitessce.template.json @@ -0,0 +1,165 @@ +{ + "version": "1.0.18", + "name": "Slide-seq human kidney (HuBMAP HBM537.GVTL.683)", + "description": "Slide-seqV2 beads from HuBMAP dataset HBM537.GVTL.683, with Leiden clusters, UMAP, and Azimuth cell type predictions from the HuBMAP Salmon pipeline", + "datasets": [ + { + "uid": "A", + "name": "Slide-seq", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/hubmap_slide_seq_kidney.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X", + "region": "beads" + }, + "obsSets": { + "obsSets": [ + { + "name": "Leiden", + "path": "tables/table/obs/leiden" + }, + { + "name": "Predicted cell type (Azimuth)", + "path": "tables/table/obs/predicted_ASCT_celltype" + } + ], + "tablePath": "tables/table", + "region": "beads" + }, + "obsSpots": { + "path": "shapes/beads", + "tablePath": "tables/table", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/table/obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "bead" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "embeddingType": { + "A": "UMAP" + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "spotLayer": { + "init_A_obsSpots_0": "__dummy__" + }, + "metaCoordinationScopes": { + "init_A_obsSpots_0": { + "spotLayer": [ + "init_A_obsSpots_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_obsSpots_0": { + "spotLayer": { + "obsColorEncoding": { + "init_A_obsSpots_0": "A" + } + } + } + }, + "obsType": { + "A": "bead" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_obsSpots_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 4, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_obsSpots_0" + ], + "obsType": "A" + }, + "x": 4, + "y": 0, + "w": 4, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 8, + "y": 0, + "w": 4, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 8, + "y": 6, + "w": 4, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 4, + "y": 6, + "w": 4, + "h": 6, + "coordinationScopesBy": {} + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/Snakefile b/demos/spatialdata-spatial-atac-rna-mouse-brain/Snakefile new file mode 100644 index 00000000..ca7c2fcb --- /dev/null +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/Snakefile @@ -0,0 +1,77 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Spatial ATAC-RNA-seq (spatial co-profiling of chromatin accessibility and gene expression, +# DBiT-seq-based, 50 x 50 pixels of 20 um) of a postnatal day 21/22 mouse brain section. +# - Publication: Zhang, D., Deng, Y., Kukanja, P. et al. "Spatial epigenome-transcriptome co-profiling +# of mammalian tissues." Nature 616, 113-122 (2023). https://doi.org/10.1038/s41586-023-05795-1 +# - GEO SuperSeries GSE205055 (ATAC: GSE205052, RNA: GSE205054). https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE205055 +# - ATAC fragments + spatial folder: GSM6204623 (MouseBrain_20um) +# - RNA matrix: GSM6204636 (MouseBrain_20um) +# - GEO data are publicly available (NCBI/GEO data use: https://www.ncbi.nlm.nih.gov/geo/info/disclaimer.html). +# - Inspired by https://github.com/MicTott/spatialscape-examples/tree/main/spatial-atac-rna-mouse-brain +# Gene annotation (for ATAC gene activity): GENCODE mouse release M25 (GRCm38/mm10), basic annotation. +# - https://www.gencodegenes.org/mouse/release_M25.html +GEO_URL = "https://ftp.ncbi.nlm.nih.gov/geo/samples" +FILE_URLS = { + "GSM6204623_MouseBrain_20um_fragments.tsv.gz": f"{GEO_URL}/GSM6204nnn/GSM6204623/suppl/GSM6204623_MouseBrain_20um_fragments.tsv.gz", + "GSM6204623_MouseBrain_20um_spatial.tar.gz": f"{GEO_URL}/GSM6204nnn/GSM6204623/suppl/GSM6204623_MouseBrain_20um_spatial.tar.gz", + "GSM6204636_MouseBrain_20um_matrix.tsv.gz": f"{GEO_URL}/GSM6204nnn/GSM6204636/suppl/GSM6204636_MouseBrain_20um_matrix.tsv.gz", + "gencode.vM25.basic.annotation.gtf.gz": "https://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_mouse/release_M25/gencode.vM25.basic.annotation.gtf.gz", +} + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# RNA + ATAC + image -> SpatialData-Zarr store, and pseudobulk ATAC tracks -> genomic-profiles Zarr store. +rule process_spatial_atac_rna: + input: + rna=(RAW_DIR / "GSM6204636_MouseBrain_20um_matrix.tsv.gz"), + fragments=(RAW_DIR / "GSM6204623_MouseBrain_20um_fragments.tsv.gz"), + spatial_dir=(RAW_DIR / "MouseBrain_20um_spatial"), + gtf=(RAW_DIR / "gencode.vM25.basic.annotation.gtf.gz"), + output: + sdata=directory(PROCESSED_DIR / "spatial_atac_rna_mouse_brain.spatialdata.zarr"), + profiles=directory(PROCESSED_DIR / "spatial_atac_rna_mouse_brain.genomic-profiles.zarr"), + params: + script=(SRC_DIR / "process_spatial_atac_rna.py") + shell: + ''' + uv run --script {params.script} \ + --rna {input.rna} \ + --fragments {input.fragments} \ + --spatial_dir {input.spatial_dir} \ + --gtf {input.gtf} \ + --output_sdata {output.sdata} \ + --output_profiles {output.profiles} + ''' + +# The archive contains a single MouseBrain_20um_spatial/ folder +# (tissue image, tissue_positions_list.csv, scalefactors_json.json). +rule untar_spatial: + input: + (RAW_DIR / "GSM6204623_MouseBrain_20um_spatial.tar.gz") + output: + directory(RAW_DIR / "MouseBrain_20um_spatial") + shell: + ''' + tar -xzf {input} -C "$(dirname {output})" + ''' + +rule download_data: + output: + (RAW_DIR / "{filename}") + wildcard_constraints: + filename="|".join([f.replace(".", r"\.") for f in FILE_URLS.keys()]) + params: + file_url=lambda w: FILE_URLS[w.filename] + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/config.yml b/demos/spatialdata-spatial-atac-rna-mouse-brain/config.yml new file mode 100644 index 00000000..7a36f676 --- /dev/null +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/config.yml @@ -0,0 +1,3 @@ +output: +- spatial_atac_rna_mouse_brain.spatialdata.zarr +- spatial_atac_rna_mouse_brain.genomic-profiles.zarr diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/src/process_spatial_atac_rna.py b/demos/spatialdata-spatial-atac-rna-mouse-brain/src/process_spatial_atac_rna.py new file mode 100644 index 00000000..c37ca3d0 --- /dev/null +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/src/process_spatial_atac_rna.py @@ -0,0 +1,282 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all,notebook]", +# "spatialdata==0.7.3", +# "anndata==0.12.19", +# "scanpy==1.12.6", +# "scikit-learn==1.9.1", +# "igraph", +# "leidenalg", +# "pillow", +# "geopandas", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Convert one spatial ATAC-RNA-seq section (Zhang et al. 2023, Nature) to SpatialData, +plus a genomic-profiles (multivec) Zarr store of pseudobulk ATAC tracks. + +Inputs: + - RNA count matrix (genes x pixels, TSV) + - ATAC fragments file (chrom, start, end, barcode, count; barcodes have a "-1" suffix) + - Space Ranger-style spatial/ folder (tissue image, tissue_positions_list.csv, scalefactors_json.json) + - GENCODE mouse (mm10) gene annotation GTF, for ATAC gene activity scores + +Outputs: + - SpatialData-Zarr store with: + images/tissue_image: the tissue image of the section + shapes/pixels: one circle per 20 um DBiT-seq pixel (in image pixel coordinates) + tables/rna: log-normalized RNA expression, RNA Leiden clusters and UMAP + tables/atac: ATAC gene activity (log-normalized Tn5 insertions in gene body + 2 kb upstream), + ATAC Leiden clusters (TF-IDF + LSI of 5 kb tiles) and UMAP + - genomic-profiles (multivec) Zarr store: pseudobulk ATAC insertions per RNA cluster (mm10). +""" +import argparse +import json +from pathlib import Path + +import anndata as ad +import geopandas as gpd +import negspy.coordinates as nc +import numpy as np +import pandas as pd +import scanpy as sc +import scipy.sparse as sp +from PIL import Image +from shapely.geometry import Point +from sklearn.decomposition import TruncatedSVD +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, ShapesModel, TableModel +from spatialdata.transformations import Identity +from vitessce.data_utils import adata_to_multivec_zarr, optimize_adata + +TILE_SIZE = 500 +GENOMIC_RESOLUTION = 5000 +PROMOTER_UPSTREAM = 2000 +REGION = "pixels" +CHROMS = [f"chr{i}" for i in range(1, 20)] + ["chrX", "chrY"] +Image.MAX_IMAGE_PIXELS = None + + +def read_tiles(fragments_path, barcodes): + """Count Tn5 insertions (both fragment ends) per barcode in fixed-size genome tiles.""" + chrom_lengths = nc.get_chrominfo("mm10").chrom_lengths + n_tiles = np.array([chrom_lengths[c] // TILE_SIZE + 1 for c in CHROMS], dtype=np.int64) + offsets = dict(zip(CHROMS, np.concatenate([[0], np.cumsum(n_tiles)[:-1]]))) + bc_to_i = {b: i for i, b in enumerate(barcodes)} + mtx = sp.csr_matrix((len(barcodes), int(n_tiles.sum())), dtype=np.float32) + reader = pd.read_csv( + fragments_path, sep="\t", comment="#", header=None, + names=["chrom", "start", "end", "barcode", "count"], + dtype={"chrom": str, "start": np.int64, "end": np.int64, "barcode": str, "count": np.int32}, + chunksize=5_000_000, + ) + for chunk in reader: + chunk = chunk[chunk["chrom"].isin(CHROMS)] + bc = chunk["barcode"].str.replace(r"-1$", "", regex=True).map(bc_to_i) + keep = bc.notna().values + chunk, bc = chunk[keep], bc[keep].astype(np.int64).values + offset = chunk["chrom"].map(offsets).values.astype(np.int64) + for pos in (chunk["start"].values, chunk["end"].values - 1): + mtx = mtx + sp.csr_matrix( + (np.ones(len(bc), dtype=np.float32), (bc, offset + pos // TILE_SIZE)), + shape=mtx.shape, + ) + print(f" {int(mtx.sum())} insertions so far") + tiles = pd.DataFrame({ + "chrom": np.repeat(CHROMS, n_tiles), + "tile": np.concatenate([np.arange(n) for n in n_tiles]), + }) + # Drop empty tiles. + nonzero = np.flatnonzero(np.asarray(mtx.sum(axis=0)).ravel() > 0) + return mtx[:, nonzero].tocsr(), tiles.iloc[nonzero].reset_index(drop=True) + + +def rebin(mtx, chroms, starts, resolution): + """Sum the columns of a (rows x regions) matrix into fixed-size bins of the genome.""" + bins_df = pd.DataFrame({"chrom": np.asarray(chroms).astype(str), "bin": np.asarray(starts).astype(np.int64) // resolution}) + bin_idx, _ = pd.factorize(bins_df["chrom"] + ":" + bins_df["bin"].astype(str)) + B = sp.csr_matrix( + (np.ones(len(bin_idx), dtype=np.float32), (np.arange(len(bin_idx)), bin_idx)), + shape=(len(bin_idx), bin_idx.max() + 1), + ) + first_idx = pd.Series(np.arange(len(bin_idx))).groupby(bin_idx).first().values + return (sp.csr_matrix(mtx) @ B).tocsr(), bins_df.iloc[first_idx].reset_index(drop=True) + + +def tfidf_lsi(counts, n_components=30): + """TF-IDF + truncated SVD (LSI); drops the first component, which tracks sequencing depth.""" + X = counts.tocsr().astype(np.float32, copy=True) + X.data[:] = 1 + tf = sp.diags(1.0 / np.maximum(np.asarray(X.sum(axis=1)).ravel(), 1)) @ X + idf = np.log1p(X.shape[0] / np.maximum(np.asarray(X.sum(axis=0)).ravel(), 1)) + tfidf = (tf @ sp.diags(idf)).tocsr() + tfidf.data = np.log1p(tfidf.data * 1e4).astype(np.float32) + lsi = TruncatedSVD(n_components=n_components, random_state=0).fit_transform(tfidf)[:, 1:] + lsi /= np.linalg.norm(lsi, axis=1, keepdims=True) + 1e-9 + return lsi + + +def gene_activity(tile_mtx, tiles, gtf_path): + """Sum Tn5 insertions in the tiles overlapping each protein-coding gene body plus 2 kb upstream.""" + gtf = pd.read_csv( + gtf_path, sep="\t", comment="#", header=None, + names=["chrom", "source", "feature", "start", "end", "score", "strand", "frame", "attrs"], + ) + genes = gtf[gtf["feature"] == "gene"].copy() + genes["gene_name"] = genes["attrs"].str.extract(r'gene_name "([^"]+)"', expand=False) + genes["gene_type"] = genes["attrs"].str.extract(r'gene_type "([^"]+)"', expand=False) + genes = genes[(genes["gene_type"] == "protein_coding") & genes["chrom"].isin(CHROMS)] + genes = genes.drop_duplicates("gene_name") + start = np.where(genes["strand"] == "+", genes["start"] - PROMOTER_UPSTREAM, genes["start"]) + end = np.where(genes["strand"] == "+", genes["end"], genes["end"] + PROMOTER_UPSTREAM) + genes["t0"] = np.maximum(start, 0) // TILE_SIZE + genes["t1"] = end // TILE_SIZE + + tile_index = pd.Series(np.arange(len(tiles)), index=tiles["chrom"] + ":" + tiles["tile"].astype(str)) + gene_i = np.repeat(np.arange(len(genes)), (genes["t1"] - genes["t0"] + 1).values) + tile_t = np.concatenate([np.arange(a, b + 1) for a, b in zip(genes["t0"].values, genes["t1"].values)]) + tile_chrom = np.repeat(genes["chrom"].values, (genes["t1"] - genes["t0"] + 1).values) + tile_j = tile_index.reindex(pd.Series(tile_chrom) + ":" + pd.Series(tile_t).astype(str)).values + keep = ~np.isnan(tile_j) + link = sp.csr_matrix( + (np.ones(keep.sum(), dtype=np.float32), (tile_j[keep].astype(np.int64), gene_i[keep])), + shape=(len(tiles), len(genes)), + ) + return (tile_mtx @ link).tocsr(), genes["gene_name"].values + + +def write_genomic_profiles(tile_mtx, tiles, groups, output_path, obs_set_name): + """Pseudobulk the tile counts per group, re-bin to GENOMIC_RESOLUTION, normalize to CPM, write multivec Zarr.""" + groups = pd.Categorical(groups) + group_names = [str(g) for g in groups.categories] + G = sp.csr_matrix( + (np.ones(len(groups), dtype=np.float32), (groups.codes, np.arange(len(groups)))), + shape=(len(group_names), len(groups)), + ) + binned, bins = rebin(G @ tile_mtx, tiles["chrom"].values, tiles["tile"].values * TILE_SIZE, GENOMIC_RESOLUTION) + binned = binned.toarray() + binned = binned / np.maximum(binned.sum(axis=1, keepdims=True), 1) * 1e6 + order = bins.sort_values(["chrom", "bin"]).index.values + bins, binned = bins.iloc[order].reset_index(drop=True), binned[:, order] + start = bins["bin"] * GENOMIC_RESOLUTION + var = pd.DataFrame(index=[str(i) for i in range(len(bins))]) + var["interval"] = (bins["chrom"] + ":" + start.astype(str) + "-" + (start + GENOMIC_RESOLUTION - 1).astype(str)).values + obs = pd.DataFrame({"group": group_names}, index=group_names) + adata_to_multivec_zarr( + ad.AnnData(X=binned.astype(np.float32), obs=obs, var=var), output_path, + obs_set_col="group", obs_set_name=obs_set_name, obs_set_vals=group_names, + var_interval_col="interval", assembly="mm10", starting_resolution=GENOMIC_RESOLUTION, + ) + + +def cluster(adata, use_rep, key, resolution=0.8): + sc.pp.neighbors(adata, use_rep=use_rep, n_neighbors=15) + sc.tl.leiden(adata, resolution=resolution, key_added=key, flavor="igraph", n_iterations=2, directed=False) + sc.tl.umap(adata, random_state=0) + adata.obs[key] = pd.Categorical(["Cluster " + str(c) for c in adata.obs[key]]) + + +def make_table(adata, obs_cols, obsm_keys): + adata = optimize_adata(adata, obs_cols=obs_cols, var_cols=[], obsm_keys=obsm_keys, varm_keys=[], layer_keys=[], to_dense_X=True) + adata.obs["region"] = pd.Categorical([REGION] * adata.n_obs) + adata.obs["barcode"] = adata.obs_names.values + return TableModel.parse(adata, region=REGION, region_key="region", instance_key="barcode") + + +def main(args): + spatial_dir = Path(args.spatial_dir) + + # RNA (genes x pixels) -> pixels x genes. + counts = pd.read_csv(args.rna, sep="\t", index_col=0) + rna = ad.AnnData( + X=sp.csr_matrix(counts.to_numpy().T.astype(np.float32)), + obs=pd.DataFrame(index=counts.columns.astype(str)), + var=pd.DataFrame(index=counts.index.astype(str)), + ) + rna.var_names_make_unique() + + # Pixel positions (Space Ranger-style; all pixels are "in tissue"). + pos = pd.read_csv( + spatial_dir / "tissue_positions_list.csv", header=None, index_col=0, + names=["barcode", "in_tissue", "array_row", "array_col", "pxl_row_in_fullres", "pxl_col_in_fullres"], + ) + pos.index = pos.index.astype(str) + rna = rna[rna.obs_names.isin(pos.index)].copy() + pos = pos.loc[rna.obs_names] + xy = pos[["pxl_col_in_fullres", "pxl_row_in_fullres"]].to_numpy(dtype=np.float64) + with open(spatial_dir / "scalefactors_json.json") as f: + scalefactors = json.load(f) + radius = scalefactors["spot_diameter_fullres"] / 2.0 + print(f"RNA: {rna.n_obs} pixels x {rna.n_vars} genes") + + sc.pp.calculate_qc_metrics(rna, inplace=True, percent_top=None) + sc.pp.filter_genes(rna, min_cells=10) + sc.pp.normalize_total(rna, target_sum=1e4) + sc.pp.log1p(rna) + sc.pp.highly_variable_genes(rna, n_top_genes=2000) + sc.pp.pca(rna, n_comps=30, mask_var="highly_variable") + cluster(rna, "X_pca", "rna_cluster") + rna.obsm["spatial"] = xy + + # ATAC: 500 bp tiles -> 5 kb tiles for LSI/clustering, and gene activity. + tile_mtx, tiles = read_tiles(args.fragments, list(rna.obs_names)) + print(f"ATAC: {tile_mtx.shape[1]} tiles, {int(tile_mtx.sum())} insertions") + tiles5k, _ = rebin(tile_mtx, tiles["chrom"].values, tiles["tile"].values * TILE_SIZE, GENOMIC_RESOLUTION) + n_pix = np.asarray((tiles5k > 0).sum(axis=0)).ravel() + tiles5k = tiles5k[:, n_pix >= 10] + act, gene_names = gene_activity(tile_mtx, tiles, args.gtf) + atac = ad.AnnData(X=act, obs=pd.DataFrame(index=rna.obs_names.copy()), var=pd.DataFrame(index=gene_names)) + atac.obs["atac_insertions"] = np.asarray(tile_mtx.sum(axis=1)).ravel() + atac.obsm["X_lsi"] = tfidf_lsi(tiles5k) + cluster(atac, "X_lsi", "atac_cluster") + sc.pp.filter_genes(atac, min_cells=10) + sc.pp.normalize_total(atac, target_sum=1e4) + sc.pp.log1p(atac) + atac.obsm["spatial"] = xy + atac.obs["rna_cluster"] = rna.obs["rna_cluster"].values + rna.obs["atac_cluster"] = atac.obs["atac_cluster"].values + rna.obs["atac_insertions"] = atac.obs["atac_insertions"].values + print(f"ATAC gene activity: {atac.n_vars} genes") + + # Tissue image (RGBA PNG -> RGB, channels first), in the same (full-resolution) pixel coordinates. + img = np.asarray(Image.open(spatial_dir / "tissue_hires_image.png").convert("RGB")) + img = np.transpose(img, (2, 0, 1)) + image = Image2DModel.parse( + img, dims=("c", "y", "x"), c_coords=["r", "g", "b"], + scale_factors=[2, 2], chunks=(3, 512, 512), + transformations={"global": Identity()}, + ) + + pixels = gpd.GeoDataFrame( + {"radius": np.full(rna.n_obs, radius)}, + geometry=[Point(x, y) for x, y in xy], + index=rna.obs_names.copy(), + ) + shapes = ShapesModel.parse(pixels, transformations={"global": Identity()}) + + sdata = SpatialData( + images={"tissue_image": image}, + shapes={REGION: shapes}, + tables={ + "rna": make_table(rna, ["rna_cluster", "atac_cluster", "total_counts", "n_genes_by_counts", "atac_insertions"], ["X_umap", "X_pca", "spatial"]), + "atac": make_table(atac, ["atac_cluster", "rna_cluster", "atac_insertions"], ["X_umap", "X_lsi", "spatial"]), + }, + ) + sdata.write(args.output_sdata, overwrite=True) + + write_genomic_profiles(tile_mtx, tiles, rna.obs["rna_cluster"].astype(str).values, args.output_profiles, obs_set_name="RNA Cluster") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--rna", type=str, required=True, help="RNA count matrix TSV (genes x pixels)") + parser.add_argument("--fragments", type=str, required=True, help="ATAC fragments .tsv.gz") + parser.add_argument("--spatial_dir", type=str, required=True, help="Space Ranger-style spatial/ folder") + parser.add_argument("--gtf", type=str, required=True, help="GENCODE mouse gene annotation GTF (mm10)") + parser.add_argument("--output_sdata", type=str, required=True, help="Output SpatialData-Zarr store") + parser.add_argument("--output_profiles", type=str, required=True, help="Output genomic-profiles Zarr store") + main(parser.parse_args()) diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json b/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json new file mode 100644 index 00000000..4c7710c7 --- /dev/null +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json @@ -0,0 +1,284 @@ +{ + "version": "1.0.18", + "name": "Spatial ATAC-RNA-seq mouse brain (Zhang et al. 2023)", + "description": "Spatial co-profiling of chromatin accessibility and gene expression (20 um pixels) in a P21/22 mouse brain section, GEO GSE205055", + "datasets": [ + { + "uid": "A", + "name": "Spatial ATAC-RNA-seq", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/spatial_atac_rna_mouse_brain.spatialdata.zarr", + "options": { + "image": { + "path": "images/tissue_image", + "coordinateSystem": "global" + }, + "obsSpots": { + "path": "shapes/pixels", + "tablePath": "tables/rna", + "coordinateSystem": "global" + }, + "obsFeatureMatrix": { + "path": "tables/rna/X" + }, + "obsSets": { + "tablePath": "tables/rna", + "obsSets": [ + { + "name": "RNA Cluster", + "path": "tables/rna/obs/rna_cluster" + }, + { + "name": "ATAC Cluster", + "path": "tables/rna/obs/atac_cluster" + } + ] + }, + "obsEmbedding": [ + { + "path": "tables/rna/obsm/X_umap", + "embeddingType": "RNA UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "spot", + "featureType": "gene", + "featureValueType": "expression" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/spatial_atac_rna_mouse_brain.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/atac/X" + }, + "obsEmbedding": [ + { + "path": "tables/atac/obsm/X_umap", + "embeddingType": "ATAC UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "spot", + "featureType": "gene activity", + "featureValueType": "accessibility" + } + }, + { + "fileType": "genomic-profiles.zarr", + "url": "{{ base_url }}/spatial_atac_rna_mouse_brain.genomic-profiles.zarr" + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "obsType": { + "A": "spot", + "init_A_obsSpots_0": "spot" + }, + "embeddingType": { + "RNA": "RNA UMAP", + "ATAC": "ATAC UMAP" + }, + "featureType": { + "RNA": "gene", + "ATAC": "gene activity" + }, + "featureValueType": { + "RNA": "expression", + "ATAC": "accessibility" + }, + "featureSelection": { + "RNA": null, + "ATAC": null + }, + "obsColorEncoding": { + "RNA": "cellSetSelection", + "ATAC": "cellSetSelection" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "RGB" + }, + "spotLayer": { + "init_A_obsSpots_0": "__dummy__" + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSpots_0": { + "spotLayer": [ + "init_A_obsSpots_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + } + } + }, + "init_A_obsSpots_0": { + "spotLayer": { + "obsType": { + "init_A_obsSpots_0": "init_A_obsSpots_0" + }, + "featureType": { + "init_A_obsSpots_0": "RNA" + }, + "featureValueType": { + "init_A_obsSpots_0": "RNA" + }, + "featureSelection": { + "init_A_obsSpots_0": "RNA" + }, + "obsColorEncoding": { + "init_A_obsSpots_0": "RNA" + } + } + } + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSpots_0" + ] + }, + "x": 0, + "y": 0, + "w": 5, + "h": 8 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSpots_0" + ] + }, + "x": 5, + "y": 0, + "w": 3, + "h": 4 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 5, + "y": 4, + "w": 3, + "h": 4 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "RNA", + "featureValueType": "RNA", + "featureSelection": "RNA", + "obsColorEncoding": "RNA" + }, + "x": 8, + "y": 0, + "w": 4, + "h": 4 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "ATAC", + "featureValueType": "ATAC", + "featureSelection": "ATAC", + "obsColorEncoding": "ATAC" + }, + "x": 8, + "y": 4, + "w": 4, + "h": 4 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "embeddingType": "RNA", + "featureType": "RNA", + "featureValueType": "RNA", + "featureSelection": "RNA", + "obsColorEncoding": "RNA" + }, + "x": 0, + "y": 8, + "w": 3, + "h": 4 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "embeddingType": "ATAC", + "featureType": "ATAC", + "featureValueType": "ATAC", + "featureSelection": "ATAC", + "obsColorEncoding": "ATAC" + }, + "x": 3, + "y": 8, + "w": 3, + "h": 4 + }, + { + "component": "genomicProfiles", + "coordinationScopes": { + "dataset": "A" + }, + "props": { + "assembly": "mm10" + }, + "x": 6, + "y": 8, + "w": 6, + "h": 4 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile new file mode 100644 index 00000000..3eb410b6 --- /dev/null +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile @@ -0,0 +1,105 @@ +import re + +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Spatial CUT&Tag-RNA-seq (academic, DBiT-based) of a P22 mouse brain section: histone mark H3K27me3 +# and the transcriptome co-profiled in the same 20 um pixels (100 x 100 barcodes). +# +# Publication: Zhang D, Deng Y, Kukanja P, et al. "Spatial epigenome-transcriptome co-profiling of +# mammalian tissues". Nature 616:113-122 (2023). https://doi.org/10.1038/s41586-023-05795-1 +# Data: GEO superseries GSE205055 (https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE205055), +# public domain (NCBI GEO). +# - GSM6704978 "MouseBrain, 20um, 100barcodes, H3K27me3": CUT&Tag fragments (cellranger-atac format, mm10). +# https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM6704978 +# - GSM6753044 "MouseBrain_20um_100barcodes_H3K27me3": RNA count matrix (genes x pixels) and a +# Space Ranger-style spatial/ folder (pixel positions, tissue image). +# https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM6753044 +# Inspiration: https://github.com/MicTott/spatialscape-examples/tree/main/spatial-atac-rna-mouse-brain +# (the spatial ATAC-RNA-seq samples of the same paper). +# +# GEO has no cluster labels for these sections, so we compute Leiden clusters and UMAPs for each modality. +# The CUT&Tag modality is represented as a gene score matrix (SnapATAC2, gene body + 2 kb upstream). +GEO_URL = "https://ftp.ncbi.nlm.nih.gov/geo/samples" +FILES = { + "GSM6704978_MouseBrain_20um_100barcodes_H3K27me3_fragments.tsv.gz": f"{GEO_URL}/GSM6704nnn/GSM6704978/suppl/GSM6704978_MouseBrain_20um_100barcodes_H3K27me3_fragments.tsv.gz", + "GSM6753044_MouseBrain_20um_100barcodes_H3K27me3_matrix.tsv.gz": f"{GEO_URL}/GSM6753nnn/GSM6753044/suppl/GSM6753044_MouseBrain_20um_100barcodes_H3K27me3_matrix.tsv.gz", + "GSM6753044_MouseBrain_20um_100barcodes_H3K27me3_spatial.tar.gz": f"{GEO_URL}/GSM6753nnn/GSM6753044/suppl/GSM6753044_MouseBrain_20um_100barcodes_H3K27me3_spatial.tar.gz", +} +INTERIM_DIR = DATA_DIR / "interim" +SPATIAL_DIR = INTERIM_DIR / "MouseBrain_20um_100barcodes_H3K27me3_spatial" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Build a SpatialData object with the tissue image, the pixels as square polygon Shapes, +# and one table per modality ("rna" and "cut_and_tag"), both annotating the pixels. +rule convert_to_spatialdata: + input: + rna=(RAW_DIR / "GSM6753044_MouseBrain_20um_100barcodes_H3K27me3_matrix.tsv.gz"), + positions=(SPATIAL_DIR / "tissue_positions_list.csv"), + gene_scores=(INTERIM_DIR / "cut_and_tag_gene_scores.h5ad") + output: + directory(PROCESSED_DIR / "spatial_cut_and_tag_rna_mouse_brain_h3k27me3.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py") + shell: + # Note: the spatial/ directory is derived from an input path (rather than a param), + # so that the module prefix is applied when this Snakefile is used as a module of ../Snakefile. + ''' + uv run --script {params.script} \ + --rna {input.rna} \ + --spatial "$(dirname {input.positions})" \ + --gene_scores {input.gene_scores} \ + -o {output} + ''' + +# Compute CUT&Tag gene scores, clusters, and UMAP from the fragments of the in-tissue pixels. +rule fragments_to_gene_scores: + input: + fragments=(RAW_DIR / "GSM6704978_MouseBrain_20um_100barcodes_H3K27me3_fragments.tsv.gz"), + positions=(SPATIAL_DIR / "tissue_positions_list.csv") + output: + (INTERIM_DIR / "cut_and_tag_gene_scores.h5ad") + params: + script=(SRC_DIR / "fragments_to_gene_scores.py") + threads: 4 + shell: + ''' + uv run --script {params.script} \ + -f {input.fragments} \ + -p {input.positions} \ + -o {output} \ + -j {threads} + ''' + +rule untar_spatial: + input: + (RAW_DIR / "GSM6753044_MouseBrain_20um_100barcodes_H3K27me3_spatial.tar.gz") + output: + (SPATIAL_DIR / "tissue_positions_list.csv") + shell: + ''' + INTERIM_DIR="$(dirname "$(dirname {output})")" + mkdir -p "$INTERIM_DIR" + tar -xzf {input} -C "$INTERIM_DIR" + touch {output} + ''' + +rule download_data: + output: + (RAW_DIR / "{filename}") + wildcard_constraints: + filename="|".join([re.escape(f) for f in FILES.keys()]) + params: + file_url=lambda w: FILES[w.filename] + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/config.yml b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/config.yml new file mode 100644 index 00000000..748633a2 --- /dev/null +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/config.yml @@ -0,0 +1,2 @@ +output: +- spatial_cut_and_tag_rna_mouse_brain_h3k27me3.spatialdata.zarr diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/convert_to_spatialdata.py b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/convert_to_spatialdata.py new file mode 100644 index 00000000..ee902d4a --- /dev/null +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/convert_to_spatialdata.py @@ -0,0 +1,158 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# "anndata>=0.12,<0.13", +# "scanpy[leiden]==1.12.6", +# "geopandas", +# "numpy", +# "pandas", +# "pillow", +# "scipy", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse +import json +from os.path import join + +import anndata as ad +import geopandas as gpd +import numpy as np +import pandas as pd +import scanpy as sc +from PIL import Image +from scipy import sparse +from shapely.geometry import box +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, ShapesModel, TableModel +from spatialdata.transformations import Identity + +# Fraction of each grid cell covered by a pixel (the rest is the gap between microfluidic channels). +PIXEL_FILL = 0.9 + +SHAPES_KEY = "pixels" + +# The tissue image is large and has no full-resolution scale factor besides 1, +# so Image() would refuse it without this. +Image.MAX_IMAGE_PIXELS = None + + +def read_positions(spatial_dir): + # Space Ranger v1 style tissue_positions_list.csv (no header). + pos = pd.read_csv( + join(spatial_dir, "tissue_positions_list.csv"), + header=None, + names=["barcode", "in_tissue", "array_row", "array_col", "pxl_row", "pxl_col"], + index_col=0, + ) + pos.index = pos.index.astype(str) + return pos[pos["in_tissue"] == 1] + + +def to_table(adata, pixel_ids): + adata = adata[pixel_ids].copy() + adata.obs["region"] = pd.Categorical([SHAPES_KEY] * adata.n_obs) + adata.obs["pixel_id"] = adata.obs.index.to_numpy() + adata.X = sparse.csc_matrix(adata.X, dtype=np.float32) + return TableModel.parse(adata, region=SHAPES_KEY, region_key="region", instance_key="pixel_id") + + +def convert(rna_path, spatial_dir, gene_scores_path, output_path): + pos = read_positions(spatial_dir) + with open(join(spatial_dir, "scalefactors_json.json")) as f: + spot_diameter = json.load(f)["spot_diameter_fullres"] + + # RNA: genes x pixels TSV. + counts = pd.read_csv(rna_path, sep="\t", index_col=0) + rna = ad.AnnData( + X=sparse.csr_matrix(counts.to_numpy(dtype=np.float32).T), + obs=pd.DataFrame(index=pd.Index(counts.columns.astype(str), name=None)), + var=pd.DataFrame(index=pd.Index(counts.index.astype(str), name=None)), + ) + rna.var_names_make_unique() + + # CUT&Tag gene scores (from fragments_to_gene_scores.py). + cut = ad.read_h5ad(gene_scores_path) + cut.obs.index = cut.obs.index.astype(str) + cut.var.index.name = None + + pixel_ids = [p for p in pos.index if p in set(rna.obs_names) and p in set(cut.obs_names)] + print(f"{len(pixel_ids)} in-tissue pixels in both modalities ({rna.n_obs} RNA, {cut.n_obs} CUT&Tag, {pos.shape[0]} in tissue)") + rna = rna[pixel_ids].copy() + cut = cut[pixel_ids].copy() + + # RNA: QC metrics, log-normalization, Leiden clusters, and UMAP. + rna.layers["counts"] = rna.X.copy() + rna.obs["total_counts"] = np.asarray(rna.X.sum(axis=1)).ravel() + rna.obs["n_genes"] = np.diff(rna.X.indptr) + sc.pp.normalize_total(rna, target_sum=1e4) + sc.pp.log1p(rna) + sc.pp.highly_variable_genes(rna, n_top_genes=2000) + hvg = rna[:, rna.var["highly_variable"]].copy() + sc.pp.scale(hvg, max_value=10) + sc.tl.pca(hvg, n_comps=30) + sc.pp.neighbors(hvg, n_neighbors=15) + sc.tl.umap(hvg) + sc.tl.leiden(hvg, resolution=0.8, flavor="igraph", n_iterations=2, directed=False) + rna.obs["rna_leiden"] = hvg.obs["leiden"].astype("category") + rna.obsm["X_umap_rna"] = hvg.obsm["X_umap"].astype(np.float32) + rna.uns.pop("log1p", None) + rna.uns.pop("hvg", None) + + # CUT&Tag: log-normalized gene scores; clusters and UMAP from the tile matrix. + cut.layers["counts"] = sparse.csr_matrix(cut.X, dtype=np.float32) + cut.X = sparse.csr_matrix(cut.X, dtype=np.float32) + sc.pp.normalize_total(cut, target_sum=1e4) + sc.pp.log1p(cut) + cut.uns.pop("log1p", None) + cut.obs["cut_and_tag_leiden"] = pd.Categorical(cut.obs.pop("leiden").astype(str)) + cut.obsm["X_umap_cut_and_tag"] = cut.obsm.pop("X_umap").astype(np.float32) + + # Copy the cross-modality annotations to both tables, so that either can be used for obsSets/embeddings. + rna.obs["cut_and_tag_leiden"] = pd.Categorical(cut.obs["cut_and_tag_leiden"].to_numpy()) + rna.obsm["X_umap_cut_and_tag"] = cut.obsm["X_umap_cut_and_tag"] + cut.obs["rna_leiden"] = pd.Categorical(rna.obs["rna_leiden"].to_numpy()) + cut.obsm["X_umap_rna"] = rna.obsm["X_umap_rna"] + + tables = { + "rna": to_table(rna, pixel_ids), + "cut_and_tag": to_table(cut, pixel_ids), + } + + # Tissue image (RGBA PNG): keep the RGB channels. + img = np.asarray(Image.open(join(spatial_dir, "tissue_hires_image.png")).convert("RGB")) + image = Image2DModel.parse( + np.transpose(img, (2, 0, 1)), + dims=("c", "y", "x"), + c_coords=["r", "g", "b"], + scale_factors=[2, 2, 2], + chunks=(3, 1024, 1024), + transformations={"global": Identity()}, + ) + + # Pixels as squares centered on the spot positions, in image pixel units + # (scalefactors_json.json has tissue_hires_scalef = 1). + p = pos.loc[pixel_ids] + half = spot_diameter * PIXEL_FILL / 2.0 + geoms = [box(x - half, y - half, x + half, y + half) for x, y in zip(p["pxl_col"], p["pxl_row"])] + pixels = gpd.GeoDataFrame(geometry=geoms, index=pd.Index(pixel_ids, name=None)) + pixels = ShapesModel.parse(pixels, transformations={"global": Identity()}) + + sdata = SpatialData(images={"tissue_image": image}, shapes={SHAPES_KEY: pixels}, tables=tables) + sdata.write(output_path, overwrite=True) + print(sdata) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--rna', type=str, required=True, help='Input RNA matrix (genes x pixels) .tsv.gz file') + parser.add_argument('--spatial', type=str, required=True, help='Input Space Ranger-style spatial/ directory') + parser.add_argument('--gene_scores', type=str, required=True, help='Input CUT&Tag gene score .h5ad file') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + args = parser.parse_args() + convert(args.rna, args.spatial, args.gene_scores, args.output) diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/fragments_to_gene_scores.py b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/fragments_to_gene_scores.py new file mode 100644 index 00000000..29900863 --- /dev/null +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/fragments_to_gene_scores.py @@ -0,0 +1,71 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "snapatac2==2.10.0", +# "umap-learn", +# "pandas", +# "numpy", +# ] +# /// +"""Compute a CUT&Tag gene score matrix (and a tile-based clustering / UMAP) from a fragments file with SnapATAC2. + +The gene score of a gene is the number of fragment insertions in its gene body plus 2 kb upstream (SnapATAC2 +`make_gene_matrix`, with the GENCODE mm10 annotation). Clusters and UMAP are computed from a 5 kb tile matrix +(5 kb tiles, rather than the 500 bp default, suit the broad domains of H3K27me3). +""" +import argparse + +import numpy as np +import pandas as pd +import snapatac2 as snap + + +def read_in_tissue_barcodes(positions_path): + # Space Ranger v1 style tissue_positions_list.csv (no header): + # barcode, in_tissue, array_row, array_col, pxl_row_in_fullres, pxl_col_in_fullres + pos = pd.read_csv(positions_path, header=None, names=["barcode", "in_tissue", "array_row", "array_col", "pxl_row", "pxl_col"]) + return pos.loc[pos["in_tissue"] == 1, "barcode"].astype(str).tolist() + + +def compute(fragments_path, positions_path, output_path, n_jobs): + # The fragment file spells barcodes with a "-1" suffix. + whitelist = [f"{b}-1" for b in read_in_tissue_barcodes(positions_path)] + + data = snap.pp.import_fragments( + fragments_path, + chrom_sizes=snap.genome.mm10, + file=None, # in memory + sorted_by_barcode=False, + min_num_fragments=0, + whitelist=whitelist, + n_jobs=n_jobs, + ) + print(data) + + # Tile matrix -> spectral embedding -> clusters and UMAP. + snap.pp.add_tile_matrix(data, bin_size=5000, n_jobs=n_jobs) + snap.pp.select_features(data, n_features=50000, n_jobs=n_jobs) + snap.tl.spectral(data) + snap.pp.knn(data) + snap.tl.leiden(data, resolution=0.8) + snap.tl.umap(data) + + # Gene scores (gene body + 2 kb upstream). + gene = snap.pp.make_gene_matrix(data, gene_anno=snap.genome.mm10) + gene.obs["leiden"] = data.obs["leiden"].to_numpy() + gene.obs["n_fragment"] = data.obs["n_fragment"].to_numpy() + gene.obsm["X_umap"] = np.asarray(data.obsm["X_umap"], dtype=np.float32) + gene.obs.index = [b.removesuffix("-1") for b in gene.obs_names] + gene.var_names_make_unique() + print(gene) + gene.write_h5ad(output_path) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-f', '--fragments', type=str, required=True, help='Input fragments .tsv.gz file') + parser.add_argument('-p', '--positions', type=str, required=True, help='Input tissue_positions_list.csv file') + parser.add_argument('-o', '--output', type=str, required=True, help='Output gene score .h5ad file') + parser.add_argument('-j', '--n_jobs', type=int, default=4, help='Number of threads') + args = parser.parse_args() + compute(args.fragments, args.positions, args.output, args.n_jobs) diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json new file mode 100644 index 00000000..600b03ce --- /dev/null +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json @@ -0,0 +1,443 @@ +{ + "version": "1.0.18", + "name": "Spatial CUT&Tag-RNA-seq mouse brain, H3K27me3 (Zhang et al. 2023)", + "description": "H3K27me3 CUT&Tag gene scores and RNA co-profiled in 20 um pixels of P22 mouse brain (GEO GSE205055, samples GSM6704978 and GSM6753044)", + "datasets": [ + { + "uid": "A", + "name": "Spatial CUT&Tag-RNA-seq mouse brain, H3K27me3 (Zhang et al. 2023)", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/spatial_cut_and_tag_rna_mouse_brain_h3k27me3.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/rna/X", + "region": "pixels" + }, + "obsSets": { + "obsSets": [ + { + "name": "Leiden (RNA)", + "path": "tables/rna/obs/rna_leiden" + }, + { + "name": "Leiden (H3K27me3)", + "path": "tables/rna/obs/cut_and_tag_leiden" + } + ], + "tablePath": "tables/rna", + "region": "pixels" + }, + "image": { + "path": "images/tissue_image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/pixels", + "tablePath": "tables/rna", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/rna/obsm/X_umap_rna", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP (RNA)" + }, + { + "path": "tables/rna/obsm/X_umap_cut_and_tag", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP (H3K27me3)" + } + ] + }, + "coordinationValues": { + "obsType": "pixel", + "featureType": "gene", + "featureValueType": "expression" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/spatial_cut_and_tag_rna_mouse_brain_h3k27me3.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/cut_and_tag/X", + "region": "pixels" + } + }, + "coordinationValues": { + "obsType": "pixel", + "featureType": "geneScore", + "featureValueType": "score" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "spatialZoom": { + "A": null + }, + "spatialTargetX": { + "A": null + }, + "spatialTargetY": { + "A": null + }, + "imageLayer": { + "A": null, + "init_rna_0": "__dummy__", + "init_cut_and_tag_0": "__dummy__" + }, + "obsColorEncoding": { + "A": "geneSelection", + "B": "geneSelection", + "C": "cellSetSelection" + }, + "featureSelection": { + "A": [ + "Mbp" + ], + "B": [ + "Hoxa9" + ] + }, + "featureType": { + "A": "gene", + "B": "geneScore" + }, + "featureValueType": { + "A": "expression", + "B": "score" + }, + "photometricInterpretation": { + "init_rna_0": "RGB", + "init_cut_and_tag_0": "RGB" + }, + "spatialLayerOpacity": { + "init_rna_0": 1.0, + "init_rna_1": 1.0, + "init_cut_and_tag_0": 1.0, + "init_cut_and_tag_1": 1.0 + }, + "segmentationLayer": { + "init_rna_0": "__dummy__", + "init_cut_and_tag_0": "__dummy__" + }, + "segmentationChannel": { + "init_rna_0": "__dummy__", + "init_cut_and_tag_0": "__dummy__" + }, + "obsType": { + "init_rna_0": "pixel", + "init_cut_and_tag_0": "pixel", + "A": "pixel" + }, + "spatialChannelOpacity": { + "init_rna_0": 0.8, + "init_cut_and_tag_0": 0.8 + }, + "spatialSegmentationFilled": { + "init_rna_0": true, + "init_cut_and_tag_0": true + }, + "spatialChannelVisible": { + "init_rna_0": true, + "init_cut_and_tag_0": true + }, + "metaCoordinationScopes": { + "init_rna_0": { + "imageLayer": [ + "init_rna_0" + ], + "segmentationLayer": [ + "init_rna_0" + ] + }, + "init_cut_and_tag_0": { + "imageLayer": [ + "init_cut_and_tag_0" + ], + "segmentationLayer": [ + "init_cut_and_tag_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_rna_0": { + "imageLayer": { + "photometricInterpretation": { + "init_rna_0": "init_rna_0" + }, + "spatialLayerOpacity": { + "init_rna_0": "init_rna_0" + } + }, + "segmentationLayer": { + "spatialLayerOpacity": { + "init_rna_0": "init_rna_1" + }, + "segmentationChannel": { + "init_rna_0": [ + "init_rna_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_rna_0": "init_rna_0" + }, + "featureType": { + "init_rna_0": "A" + }, + "featureValueType": { + "init_rna_0": "A" + }, + "featureSelection": { + "init_rna_0": "A" + }, + "obsColorEncoding": { + "init_rna_0": "A" + }, + "spatialChannelOpacity": { + "init_rna_0": "init_rna_0" + }, + "spatialSegmentationFilled": { + "init_rna_0": "init_rna_0" + }, + "spatialChannelVisible": { + "init_rna_0": "init_rna_0" + } + } + }, + "init_cut_and_tag_0": { + "imageLayer": { + "photometricInterpretation": { + "init_cut_and_tag_0": "init_cut_and_tag_0" + }, + "spatialLayerOpacity": { + "init_cut_and_tag_0": "init_cut_and_tag_0" + } + }, + "segmentationLayer": { + "spatialLayerOpacity": { + "init_cut_and_tag_0": "init_cut_and_tag_1" + }, + "segmentationChannel": { + "init_cut_and_tag_0": [ + "init_cut_and_tag_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_cut_and_tag_0": "init_cut_and_tag_0" + }, + "featureType": { + "init_cut_and_tag_0": "B" + }, + "featureValueType": { + "init_cut_and_tag_0": "B" + }, + "featureSelection": { + "init_cut_and_tag_0": "B" + }, + "obsColorEncoding": { + "init_cut_and_tag_0": "B" + }, + "spatialChannelOpacity": { + "init_cut_and_tag_0": "init_cut_and_tag_0" + }, + "spatialSegmentationFilled": { + "init_cut_and_tag_0": "init_cut_and_tag_0" + }, + "spatialChannelVisible": { + "init_cut_and_tag_0": "init_cut_and_tag_0" + } + } + } + }, + "embeddingType": { + "A": "UMAP (RNA)", + "B": "UMAP (H3K27me3)" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_rna_0" + ], + "metaCoordinationScopesBy": [ + "init_rna_0" + ], + "spatialZoom": "A", + "spatialTargetX": "A", + "spatialTargetY": "A", + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 3, + "h": 6, + "props": { + "title": "Spatial (RNA)" + } + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_rna_0" + ], + "metaCoordinationScopesBy": [ + "init_rna_0" + ], + "obsType": "A" + }, + "x": 3, + "y": 0, + "w": 3, + "h": 3, + "props": { + "title": "Layers (RNA)" + } + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A", + "obsType": "A" + }, + "x": 3, + "y": 3, + "w": 3, + "h": 3, + "props": { + "title": "RNA features" + }, + "coordinationScopesBy": {} + }, + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_cut_and_tag_0" + ], + "metaCoordinationScopesBy": [ + "init_cut_and_tag_0" + ], + "spatialZoom": "A", + "spatialTargetX": "A", + "spatialTargetY": "A", + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 6, + "props": { + "title": "Spatial (H3K27me3 gene score)" + } + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_cut_and_tag_0" + ], + "metaCoordinationScopesBy": [ + "init_cut_and_tag_0" + ], + "obsType": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 3, + "props": { + "title": "Layers (H3K27me3 gene score)" + } + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "B", + "obsType": "A" + }, + "x": 9, + "y": 3, + "w": 3, + "h": 3, + "props": { + "title": "H3K27me3 gene score features" + }, + "coordinationScopesBy": {} + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsColorEncoding": "C", + "obsType": "A" + }, + "x": 8, + "y": 6, + "w": 4, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "obsColorEncoding": "C", + "obsType": "A" + }, + "x": 0, + "y": 6, + "w": 4, + "h": 6, + "coordinationScopesBy": {} + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "B", + "obsColorEncoding": "C", + "obsType": "A" + }, + "x": 4, + "y": 6, + "w": 4, + "h": 6, + "coordinationScopesBy": {} + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-stellaromics-pyxa-small/Snakefile b/demos/spatialdata-stellaromics-pyxa-small/Snakefile new file mode 100644 index 00000000..2dde41a7 --- /dev/null +++ b/demos/spatialdata-stellaromics-pyxa-small/Snakefile @@ -0,0 +1,62 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Stellaromics Pyxa (3D in situ spatial transcriptomics) demo dataset. +# - Source: Stellaromics/demo on Hugging Face (official Stellaromics release, not gated). +# https://huggingface.co/datasets/Stellaromics/demo +# We use the `small/` folder (~1310 x 443 x 130 um, 4,372 cells, 395,667 transcripts, ~290 MB), +# the "full demo region". The `colon/` folder (~30 GB) is the whole Glasgow colon H1K region. +# - License: BSD 3-Clause (per the dataset card). +# - Reader: the experimental `spatialdata_io.experimental.pyxa` reader, which is pending review in +# https://github.com/scverse/spatialdata-io/pull/425 (pinned to a commit in src/convert_to_spatialdata.py). +# - Related: https://github.com/stellaromics/pyxa_scverse_demo +# and the spatialdata-sandbox conversion https://github.com/giovp/spatialdata-sandbox/pull/65 (pyxa_v1_io). +HF_BASE_URL = "https://huggingface.co/datasets/Stellaromics/demo/resolve/main/small" +PYXA_FILES = [ + "cell_assigned_gene_v1.csv", + "cell_by_gene_v1.csv", + "cell_metadata_v1.csv", + "segmentation_geometries_v1.parquet", + # Multiscale 3D DAPI mosaic (OME-Zarr v0.5, zipped). The reader reads it in place. + "mosaic_3d.ome.zarr.zip", +] +PYXA_RAW_DIR = RAW_DIR / "pyxa_small" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Read the Pyxa output files into a SpatialData object (3D image, 3D transcripts, +# 2D cell footprints and per-z-plane cell polygons, and the cell x gene table), +# add Leiden clusters and a UMAP to the table, write the SpatialData store, +# and add a morton-sorted copy of the transcripts Points element for tiled access. +rule convert_to_spatialdata: + input: + [ (PYXA_RAW_DIR / f) for f in PYXA_FILES ] + output: + directory(PROCESSED_DIR / "stellaromics_pyxa_small.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py") + shell: + ''' + uv run --script {params.script} \ + -i "$(dirname {input[0]})" \ + -o {output} + ''' + +rule download_data: + output: + (PYXA_RAW_DIR / "{filename}") + params: + file_url=lambda wildcards: f"{HF_BASE_URL}/{wildcards.filename}" + wildcard_constraints: + filename="|".join([f.replace(".", r"\.") for f in PYXA_FILES]) + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-stellaromics-pyxa-small/config.yml b/demos/spatialdata-stellaromics-pyxa-small/config.yml new file mode 100644 index 00000000..70e6f75c --- /dev/null +++ b/demos/spatialdata-stellaromics-pyxa-small/config.yml @@ -0,0 +1,2 @@ +output: +- stellaromics_pyxa_small.spatialdata.zarr diff --git a/demos/spatialdata-stellaromics-pyxa-small/src/convert_to_spatialdata.py b/demos/spatialdata-stellaromics-pyxa-small/src/convert_to_spatialdata.py new file mode 100644 index 00000000..9ce84bd5 --- /dev/null +++ b/demos/spatialdata-stellaromics-pyxa-small/src/convert_to_spatialdata.py @@ -0,0 +1,100 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# # anndata 0.13 exposes X as a None-keyed layer, which spatialdata 0.7.3 table validation rejects. +# "anndata==0.12.19", +# # The experimental Pyxa (Stellaromics) reader is pending review upstream. +# # Reference: https://github.com/scverse/spatialdata-io/pull/425 +# "spatialdata-io @ git+https://github.com/ckmah/spatialdata-io.git@7a7bb99f577d4893c9b965435903dcef7c677237", +# "scanpy==1.12.6", +# "leidenalg", +# "igraph", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse +import shutil +from os.path import isdir + +import numpy as np +import scanpy as sc +from spatialdata import read_zarr +from spatialdata.models import PointsModel +from spatialdata_io.experimental import pyxa +from vitessce.data_utils import ( + sdata_morton_sort_points, + sdata_points_process_columns, + sdata_points_modify_row_group_size, +) + +TABLE = "rna" +POINTS = "transcripts" + + +def add_clusters(adata): + # The small/ demo region does not include the Pyxa Studio export (clusters and UMAP), + # so compute Leiden clusters and a 2D UMAP for display in Vitessce. + # The raw counts are kept in X. + tmp = adata.copy() + sc.pp.filter_cells(tmp, min_counts=1) + sc.pp.normalize_total(tmp) + sc.pp.log1p(tmp) + sc.pp.pca(tmp, n_comps=30) + sc.pp.neighbors(tmp) + sc.tl.leiden(tmp, flavor="igraph", n_iterations=2, resolution=0.5, random_state=0) + sc.tl.umap(tmp, random_state=0) + + adata.obs["leiden"] = tmp.obs["leiden"].reindex(adata.obs_names) + adata.obs["leiden"] = adata.obs["leiden"].cat.add_categories(["unassigned"]).fillna("unassigned") + umap = np.full((adata.n_obs, 2), np.nan, dtype=np.float32) + umap[adata.obs_names.get_indexer(tmp.obs_names)] = tmp.obsm["X_umap"] + adata.obsm["X_umap"] = umap + + +def process(input_dir, output_path): + # Shapes: cell_boundaries (2D footprint per cell, annotated by the table) and + # cell_boundaries_z (per-cell, per-z-plane polygons, with a Z_um column). + # Image: mosaic_image (3D, multiscale DAPI). + # Points: transcripts (3D, x/y/z in um). + sdata = pyxa(input_dir, labels=False) + add_clusters(sdata.tables[TABLE]) + # Store X as CSC, so that Vitessce can read one gene (column) at a time. + sdata.tables[TABLE].X = sdata.tables[TABLE].X.tocsc() + + if isdir(output_path): + shutil.rmtree(output_path) + sdata.write(output_path) + + # Make the points ready for tiled access. + # References: + # - https://vitessce.io/docs/data-troubleshooting/#points + # - ../../spatialdata-xenium-rep1/src/morton_sort_points.py + sdata = read_zarr(output_path) + transformations = sdata[POINTS].attrs["transform"] + + sdata = sdata_morton_sort_points(sdata, POINTS) + + # Add a Gene_codes column (index into the table's var) and make the + # dictionary-encoded columns the rightmost columns. + ddf = sdata_points_process_columns(sdata, POINTS, var_name_col="Gene", table_name=TABLE) + + del ddf.attrs["transform"] + sdata[f"{POINTS}_with_morton_codes"] = PointsModel.parse( + ddf, feature_key="Gene", instance_key="cell_id", transformations=transformations + ) + sdata.write_element(f"{POINTS}_with_morton_codes") + + sdata_points_modify_row_group_size(sdata, f"{POINTS}_with_morton_codes", row_group_size=25_000) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input', type=str, required=True, help='Directory of Pyxa output files') + parser.add_argument('-o', '--output', type=str, required=True, help='Output SpatialData .zarr store') + args = parser.parse_args() + process(args.input, args.output) diff --git a/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json b/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json new file mode 100644 index 00000000..363d5c75 --- /dev/null +++ b/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json @@ -0,0 +1,230 @@ +{ + "version": "1.0.18", + "name": "Stellaromics Pyxa (small demo region)", + "description": "3D in situ transcriptomics from the Stellaromics/demo Hugging Face dataset (small/), read with the spatialdata-io pyxa reader, with Leiden clusters and morton-sorted transcripts", + "datasets": [ + { + "uid": "A", + "name": "Stellaromics Pyxa", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/stellaromics_pyxa_small.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/rna/X" + }, + "image": { + "path": "images/mosaic_image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/cell_boundaries", + "tablePath": "tables/rna", + "coordinateSystem": "global" + }, + "obsSets": { + "tablePath": "tables/rna", + "obsSets": [ + { + "name": "Leiden clusters", + "path": "tables/rna/obs/leiden" + } + ] + }, + "obsEmbedding": [ + { + "path": "tables/rna/obsm/X_umap", + "dims": [0, 1], + "embeddingType": "UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/stellaromics_pyxa_small.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/rna/X" + }, + "obsPoints": { + "path": "points/transcripts_with_morton_codes", + "tablePath": "tables/rna", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "point", + "featureType": "gene" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "embeddingType": { + "A": "UMAP" + }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "init_A_obsPoints_0": "point", + "A": "cell" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "pointLayer": { + "init_A_obsPoints_0": "__dummy__" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.5 + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "cellSetSelection", + "A": "cellSetSelection" + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + }, + "init_A_obsPoints_0": { + "pointLayer": [ + "init_A_obsPoints_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": {}, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + }, + "init_A_obsPoints_0": { + "pointLayer": { + "obsType": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + } + } + } + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "obsColorEncoding": "A" + }, + "x": 6, + "y": 6, + "w": 3, + "h": 6 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "embeddingType": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 6, + "w": 3, + "h": 6 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-visium-hd-3.0.0/Snakefile b/demos/spatialdata-visium-hd-3.0.0/Snakefile new file mode 100644 index 00000000..3f166bde --- /dev/null +++ b/demos/spatialdata-visium-hd-3.0.0/Snakefile @@ -0,0 +1,44 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Visium HD (Space Ranger 3.0.0) mouse small intestine dataset from the SpatialData sandbox. +# Reference: https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html +ZIP_URL = f"{SPATIALDATA_SANDBOX_URL}/visium_hd_3.0.0_io_spatialdata_0.7.1.zip" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Unzip the SpatialData store (the zip file contains a single +# top-level data.zarr directory) and then, in place, rasterize the bins +# (Visium HD squares) to Labels elements. +rule rasterize_bins: + input: + (RAW_DIR / "visium_hd_3.0.0_io_spatialdata_0.7.1.zip") + output: + directory(PROCESSED_DIR / "visium_hd_3.0.0_io.spatialdata.zarr") + params: + script=(SRC_DIR / "rasterize_bins.py") + shell: + ''' + rm -rf {output} {output}.tmp + unzip -q {input} -d {output}.tmp + mv {output}.tmp/data.zarr {output} + rm -rf {output}.tmp + uv run --script {params.script} -s {output} + ''' + +rule download_data: + output: + (RAW_DIR / "visium_hd_3.0.0_io_spatialdata_0.7.1.zip") + params: + file_url=ZIP_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-visium-hd-3.0.0/config.yml b/demos/spatialdata-visium-hd-3.0.0/config.yml new file mode 100644 index 00000000..41002dfc --- /dev/null +++ b/demos/spatialdata-visium-hd-3.0.0/config.yml @@ -0,0 +1,2 @@ +output: +- visium_hd_3.0.0_io.spatialdata.zarr diff --git a/demos/spatialdata-visium-hd-3.0.0/src/rasterize_bins.py b/demos/spatialdata-visium-hd-3.0.0/src/rasterize_bins.py new file mode 100644 index 00000000..32c92815 --- /dev/null +++ b/demos/spatialdata-visium-hd-3.0.0/src/rasterize_bins.py @@ -0,0 +1,63 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse + +from spatialdata import ( + read_zarr, + rasterize_bins, + rasterize_bins_link_table_to_labels, +) + +# Prefix of the Shapes element names in this dataset. +DATASET_NAME = "Visium_HD_Mouse_Small_Intestine" +BIN_SIZES = ["016", "008", "002"] + + +def process(sdata_path): + # Note: this modifies the SpatialData store in place. + sdata = read_zarr(sdata_path) + + # Rasterize bins. + # Reference: https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/technology_visium_hd.html#performant-on-the-fly-data-rasterization + # Reference: https://github.com/vitessce/vitessce-python/blob/main/docs/notebooks/spatial_data_visium_hd.ipynb + for bin_size in BIN_SIZES: + table_name = f"square_{bin_size}um" + bins_name = f"{DATASET_NAME}_square_{bin_size}um" + labels_name = f"rasterized_{bin_size}um" + if table_name not in sdata.tables or bins_name not in sdata.shapes: + raise ValueError(f"Expected table {table_name} and shapes {bins_name}. Got tables {list(sdata.tables.keys())} and shapes {list(sdata.shapes.keys())}.") + + # rasterize_bins() requires a compressed sparse column (csc) matrix + sdata.tables[table_name].X = sdata.tables[table_name].X.tocsc() + rasterized = rasterize_bins( + sdata, + bins_name, + table_name, + "array_col", + "array_row", + # We want to rasterize to a Labels element, rather than an Image element. + return_region_as_labels=True + ) + sdata[labels_name] = rasterized + rasterize_bins_link_table_to_labels( + sdata, + table_name=table_name, + rasterized_labels_name=labels_name, + ) + sdata.write_element(labels_name) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-s', '--sdata', type=str, required=True, help='SpatialData .zarr store to modify in place') + args = parser.parse_args() + process(args.sdata) diff --git a/demos/spatialdata-visium-hd-3.0.0/vitessce.template.json b/demos/spatialdata-visium-hd-3.0.0/vitessce.template.json new file mode 100644 index 00000000..7389fb8e --- /dev/null +++ b/demos/spatialdata-visium-hd-3.0.0/vitessce.template.json @@ -0,0 +1,179 @@ +{ + "version": "1.0.18", + "name": "Visium HD (Space Ranger 3.0.0) mouse small intestine", + "description": "SpatialData sandbox dataset visium_hd_3.0.0_io, with bins rasterized to Labels elements", + "datasets": [ + { + "uid": "A", + "name": "Visium HD", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/visium_hd_3.0.0_io.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/square_016um/X" + }, + "image": { + "path": "images/Visium_HD_Mouse_Small_Intestine_full_image", + "coordinateSystem": "Visium_HD_Mouse_Small_Intestine" + }, + "obsSegmentations": { + "path": "labels/rasterized_016um", + "tablePath": "tables/square_016um", + "coordinateSystem": "Visium_HD_Mouse_Small_Intestine" + } + }, + "coordinationValues": { + "obsType": "bin" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "RGB" + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "featureValueColormapRange": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.5 + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "geneSelection" + }, + "featureValueColormapRange": { + "init_A_obsSegmentations_0": [ + 0, + 0.5 + ] + }, + "obsType": { + "A": "bin" + }, + "featureSelection": { + "A": [ + "AA986860" + ] + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A", + "featureSelection": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureSelection": "A" + }, + "x": 6, + "y": 0, + "w": 6, + "h": 3 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A", + "featureSelection": "A" + }, + "x": 6, + "y": 3, + "w": 6, + "h": 3 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureSelection": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-visium-hd-4.0.1/Snakefile b/demos/spatialdata-visium-hd-4.0.1/Snakefile new file mode 100644 index 00000000..71f18bc2 --- /dev/null +++ b/demos/spatialdata-visium-hd-4.0.1/Snakefile @@ -0,0 +1,41 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Visium HD (Space Ranger 4.0.1) 3' mouse brain dataset from the SpatialData sandbox. +# Reference: https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html +ZIP_URL = f"{SPATIALDATA_SANDBOX_URL}/visium_hd_4.0.1_io_spatialdata_0.7.1.zip" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# No processing is needed beyond unzipping: this dataset contains cell and nucleus segmentation +# Shapes (polygons) with annotating tables, but no square bins to rasterize. +# The zip file contains a single top-level data.zarr directory. +rule unzip_data: + input: + (RAW_DIR / "visium_hd_4.0.1_io_spatialdata_0.7.1.zip") + output: + directory(PROCESSED_DIR / "visium_hd_4.0.1_io.spatialdata.zarr") + shell: + ''' + rm -rf {output}.tmp + unzip -q {input} -d {output}.tmp + mv {output}.tmp/data.zarr {output} + rm -rf {output}.tmp + ''' + +rule download_data: + output: + (RAW_DIR / "visium_hd_4.0.1_io_spatialdata_0.7.1.zip") + params: + file_url=ZIP_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-visium-hd-4.0.1/config.yml b/demos/spatialdata-visium-hd-4.0.1/config.yml new file mode 100644 index 00000000..af8d0cd9 --- /dev/null +++ b/demos/spatialdata-visium-hd-4.0.1/config.yml @@ -0,0 +1,2 @@ +output: +- visium_hd_4.0.1_io.spatialdata.zarr diff --git a/demos/spatialdata-visium-hd-4.0.1/vitessce.template.json b/demos/spatialdata-visium-hd-4.0.1/vitessce.template.json new file mode 100644 index 00000000..7c048dd4 --- /dev/null +++ b/demos/spatialdata-visium-hd-4.0.1/vitessce.template.json @@ -0,0 +1,150 @@ +{ + "version": "1.0.18", + "name": "Visium HD (Space Ranger 4.0.1) 3' mouse brain", + "description": "SpatialData sandbox dataset visium_hd_4.0.1_io, with cell segmentations", + "datasets": [ + { + "uid": "A", + "name": "Visium HD", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/visium_hd_4.0.1_io.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/cell_segmentations/X" + }, + "image": { + "path": "images/Visium_HD_3prime_Mouse_Brain_hires_image", + "coordinateSystem": "Visium_HD_3prime_Mouse_Brain" + }, + "obsSegmentations": { + "path": "shapes/Visium_HD_3prime_Mouse_Brain_cell_segmentations", + "tablePath": "tables/cell_segmentations", + "coordinateSystem": "Visium_HD_3prime_Mouse_Brain" + } + }, + "coordinationValues": { + "obsType": "cell" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "RGB" + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.5 + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "geneSelection" + }, + "obsType": { + "A": "cell" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 6, + "h": 6 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-visium/Snakefile b/demos/spatialdata-visium/Snakefile new file mode 100644 index 00000000..59133731 --- /dev/null +++ b/demos/spatialdata-visium/Snakefile @@ -0,0 +1,40 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Visium mouse brain dataset (two sections, ST8059048 and ST8059050) from the SpatialData sandbox. +# Reference: https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html +ZIP_URL = f"{SPATIALDATA_SANDBOX_URL}/visium_spatialdata_0.7.1.zip" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# No processing is needed beyond unzipping: the spots are Shapes (circles) annotated by the table. +# The zip file contains a single top-level data.zarr directory. +rule unzip_data: + input: + (RAW_DIR / "visium_spatialdata_0.7.1.zip") + output: + directory(PROCESSED_DIR / "visium.spatialdata.zarr") + shell: + ''' + rm -rf {output}.tmp + unzip -q {input} -d {output}.tmp + mv {output}.tmp/data.zarr {output} + rm -rf {output}.tmp + ''' + +rule download_data: + output: + (RAW_DIR / "visium_spatialdata_0.7.1.zip") + params: + file_url=ZIP_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-visium/config.yml b/demos/spatialdata-visium/config.yml new file mode 100644 index 00000000..0873d569 --- /dev/null +++ b/demos/spatialdata-visium/config.yml @@ -0,0 +1,2 @@ +output: +- visium.spatialdata.zarr diff --git a/demos/spatialdata-visium/vitessce.template.json b/demos/spatialdata-visium/vitessce.template.json new file mode 100644 index 00000000..4ef32963 --- /dev/null +++ b/demos/spatialdata-visium/vitessce.template.json @@ -0,0 +1,136 @@ +{ + "version": "1.0.18", + "name": "Visium mouse brain", + "description": "SpatialData sandbox dataset visium, section ST8059048", + "datasets": [ + { + "uid": "A", + "name": "Visium", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/visium.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X", + "region": "ST8059048" + }, + "obsSpots": { + "path": "shapes/ST8059048", + "tablePath": "tables/table", + "region": "ST8059048", + "coordinateSystem": "ST8059048" + }, + "image": { + "path": "images/ST8059048_hires_image", + "coordinateSystem": "ST8059048" + } + }, + "coordinationValues": { + "obsType": "spot" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_A_image_0": "RGB" + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSpots_0": { + "spotLayer": [ + "init_A_obsSpots_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + } + } + }, + "init_A_obsSpots_0": { + "spotLayer": { + "obsColorEncoding": { + "init_A_obsSpots_0": "init_A_obsSpots_0" + } + } + } + }, + "spotLayer": { + "init_A_obsSpots_0": "__dummy__" + }, + "obsColorEncoding": { + "init_A_obsSpots_0": "geneSelection" + }, + "obsType": { + "A": "spot" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSpots_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 6, + "h": 6 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSpots_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-xenium-rep1/Snakefile b/demos/spatialdata-xenium-rep1/Snakefile new file mode 100644 index 00000000..85da79d7 --- /dev/null +++ b/demos/spatialdata-xenium-rep1/Snakefile @@ -0,0 +1,44 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Xenium (replicate 1) human breast cancer dataset from the SpatialData sandbox. +# Reference: https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html +ZIP_URL = f"{SPATIALDATA_SANDBOX_URL}/xenium_rep1_io_spatialdata_0.7.1.zip" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ] + +# Unzip the SpatialData store (the zip file contains a single +# top-level data.zarr directory) and then, in place, add a morton-sorted +# copy of the transcripts Points element for tiled access. +rule morton_sort_points: + input: + (RAW_DIR / "xenium_rep1_io_spatialdata_0.7.1.zip") + output: + directory(PROCESSED_DIR / "xenium_rep1_io.spatialdata.zarr") + params: + script=(SRC_DIR / "morton_sort_points.py") + shell: + ''' + rm -rf {output} {output}.tmp + unzip -q {input} -d {output}.tmp + mv {output}.tmp/data.zarr {output} + rm -rf {output}.tmp + uv run --script {params.script} -s {output} + ''' + +rule download_data: + output: + (RAW_DIR / "xenium_rep1_io_spatialdata_0.7.1.zip") + params: + file_url=ZIP_URL + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + ''' diff --git a/demos/spatialdata-xenium-rep1/config.yml b/demos/spatialdata-xenium-rep1/config.yml new file mode 100644 index 00000000..9da4c4ed --- /dev/null +++ b/demos/spatialdata-xenium-rep1/config.yml @@ -0,0 +1,2 @@ +output: +- xenium_rep1_io.spatialdata.zarr diff --git a/demos/spatialdata-xenium-rep1/src/morton_sort_points.py b/demos/spatialdata-xenium-rep1/src/morton_sort_points.py new file mode 100644 index 00000000..b105deb0 --- /dev/null +++ b/demos/spatialdata-xenium-rep1/src/morton_sort_points.py @@ -0,0 +1,58 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# "spatialdata==0.7.3", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +import argparse +import shutil +from os.path import join, isdir + +from spatialdata import read_zarr +from spatialdata.models import PointsModel +from vitessce.data_utils import ( + sdata_morton_sort_points, + sdata_points_process_columns, + sdata_points_modify_row_group_size, +) + + +def process(sdata_path): + # Note: this modifies the SpatialData store in place. + + # This Xenium dataset has an AnnData "raw" element. + # Reference: https://github.com/giovp/spatialdata-sandbox/issues/55 + raw_dir = join(sdata_path, "tables", "table", "raw") + if isdir(raw_dir): + shutil.rmtree(raw_dir) + + sdata = read_zarr(sdata_path) + + # Make the points ready for tiled access. + # References: + # - https://vitessce.io/docs/data-troubleshooting/#points + # - https://github.com/vitessce/vitessce-python/blob/main/docs/notebooks/spatial_data_xenium_morton.ipynb + transformations = sdata['transcripts'].attrs['transform'] + + sdata = sdata_morton_sort_points(sdata, "transcripts") + + # Add feature_index column to dataframe, and reorder columns so that feature_name (dict column) is the rightmost column. + ddf = sdata_points_process_columns(sdata, "transcripts", var_name_col="feature_name", table_name="table") + + del ddf.attrs['transform'] + sdata["transcripts_with_morton_codes"] = PointsModel.parse(ddf, feature_key="feature_name", instance_key="cell_id", transformations=transformations) + sdata.write_element("transcripts_with_morton_codes") + + sdata_points_modify_row_group_size(sdata, "transcripts_with_morton_codes", row_group_size=25_000) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-s', '--sdata', type=str, required=True, help='SpatialData .zarr store to modify in place') + args = parser.parse_args() + process(args.sdata) diff --git a/demos/spatialdata-xenium-rep1/vitessce.template.json b/demos/spatialdata-xenium-rep1/vitessce.template.json new file mode 100644 index 00000000..b9aac948 --- /dev/null +++ b/demos/spatialdata-xenium-rep1/vitessce.template.json @@ -0,0 +1,169 @@ +{ + "version": "1.0.18", + "name": "Xenium human breast cancer (replicate 1)", + "description": "SpatialData sandbox dataset xenium_rep1_io, with morton-sorted transcripts", + "datasets": [ + { + "uid": "A", + "name": "Xenium", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/xenium_rep1_io.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "image": { + "path": "images/morphology_focus", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "shapes/cell_boundaries", + "tablePath": "tables/table", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "cell" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/xenium_rep1_io.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X" + }, + "obsPoints": { + "path": "points/transcripts_with_morton_codes", + "tablePath": "tables/table", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "point", + "featureType": "gene" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "init_A_obsPoints_0": "point", + "A": "cell" + }, + "metaCoordinationScopes": { + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + }, + "init_A_obsPoints_0": { + "pointLayer": [ + "init_A_obsPoints_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + }, + "init_A_obsPoints_0": { + "pointLayer": { + "obsType": { + "init_A_obsPoints_0": "init_A_obsPoints_0" + } + } + } + }, + "pointLayer": { + "init_A_obsPoints_0": "__dummy__" + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 6, + "h": 3 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "metaCoordinationScopesBy": [ + "init_A_obsSegmentations_0", + "init_A_obsPoints_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 3, + "w": 6, + "h": 3 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 6, + "y": 6, + "w": 6, + "h": 6 + } + ], + "initStrategy": "auto" +} From add647aebc0a6a0041293ee595b3b3f5e76f34dc Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:19:16 -0500 Subject: [PATCH 4/9] Update pipelines. Add README files --- demos/anndata-chromium-pbmc/README.md | 16 ++++++++++++++++ demos/anndata-chromium-pbmc/Snakefile | 2 +- demos/anndata-parse-pbmc/README.md | 19 +++++++++++++++++++ demos/combat-2022/README.md | 12 ++++++++++++ demos/habib-2017/README.md | 9 +++++++++ demos/human-lymph-node-10x-visium/README.md | 14 ++++++++++++++ demos/kuppe-2022/README.md | 17 +++++++++++++++++ demos/kuppe-2022/src/convert_to_zarr.py | 4 ++-- demos/marshall-2022/README.md | 13 +++++++++++++ demos/meta-2022-azimuth/README.md | 13 +++++++++++++ demos/meta-2022-azimuth/Snakefile | 6 ++++-- .../meta-2022-azimuth/src/convert_to_zarr.py | 2 +- demos/mudata-cite-seq-pbmc/README.md | 17 +++++++++++++++++ demos/mudata-cite-seq-pbmc/Snakefile | 2 +- demos/mudata-pbmc-multiome-10x/README.md | 14 ++++++++++++++ demos/mudata-snareseq2-lung-hubmap/README.md | 15 +++++++++++++++ .../README.md | 15 +++++++++++++++ demos/spatialdata-atera-kidney/README.md | 13 +++++++++++++ .../README.md | 13 +++++++++++++ .../README.md | 18 ++++++++++++++++++ demos/spatialdata-cosmx-nsclc/README.md | 9 +++++++++ .../README.md | 13 +++++++++++++ .../Snakefile | 2 +- .../spatialdata-geomx-mouse-embryo/README.md | 10 ++++++++++ .../README.md | 13 +++++++++++++ .../README.md | 12 ++++++++++++ .../README.md | 15 +++++++++++++++ .../src/to_spatialdata.py | 2 +- .../vitessce.template.json | 2 +- .../README.md | 15 +++++++++++++++ .../spatialdata-mibi-hubmap-uterus/README.md | 18 ++++++++++++++++++ .../README.md | 16 ++++++++++++++++ .../README.md | 19 +++++++++++++++++++ .../README.md | 13 +++++++++++++ .../Snakefile | 2 +- .../README.md | 15 +++++++++++++++ demos/spatialdata-visium-hd-3.0.0/README.md | 13 +++++++++++++ demos/spatialdata-visium-hd-4.0.1/README.md | 13 +++++++++++++ demos/spatialdata-visium/README.md | 12 ++++++++++++ demos/spatialdata-xenium-rep1/README.md | 13 +++++++++++++ 40 files changed, 450 insertions(+), 11 deletions(-) create mode 100644 demos/anndata-chromium-pbmc/README.md create mode 100644 demos/anndata-parse-pbmc/README.md create mode 100644 demos/combat-2022/README.md create mode 100644 demos/habib-2017/README.md create mode 100644 demos/human-lymph-node-10x-visium/README.md create mode 100644 demos/kuppe-2022/README.md create mode 100644 demos/marshall-2022/README.md create mode 100644 demos/meta-2022-azimuth/README.md create mode 100644 demos/mudata-cite-seq-pbmc/README.md create mode 100644 demos/mudata-pbmc-multiome-10x/README.md create mode 100644 demos/mudata-snareseq2-lung-hubmap/README.md create mode 100644 demos/ome-zarr-lightsheet-hubmap-spleen/README.md create mode 100644 demos/spatialdata-atera-kidney/README.md create mode 100644 demos/spatialdata-aviti24-teton-hela-tnfa/README.md create mode 100644 demos/spatialdata-codex-hubmap-large-intestine/README.md create mode 100644 demos/spatialdata-cosmx-nsclc/README.md create mode 100644 demos/spatialdata-dbit-seq-mouse-embryo/README.md create mode 100644 demos/spatialdata-geomx-mouse-embryo/README.md create mode 100644 demos/spatialdata-illumina-stratamap-mouse-kidney/README.md create mode 100644 demos/spatialdata-maldi-msi-timstof-mouse-brain/README.md create mode 100644 demos/spatialdata-merfish-zhuang-abca-4/README.md create mode 100644 demos/spatialdata-merscope-mouse-brain/README.md create mode 100644 demos/spatialdata-mibi-hubmap-uterus/README.md create mode 100644 demos/spatialdata-slide-seq-hubmap-kidney/README.md create mode 100644 demos/spatialdata-spatial-atac-rna-mouse-brain/README.md create mode 100644 demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/README.md create mode 100644 demos/spatialdata-stellaromics-pyxa-small/README.md create mode 100644 demos/spatialdata-visium-hd-3.0.0/README.md create mode 100644 demos/spatialdata-visium-hd-4.0.1/README.md create mode 100644 demos/spatialdata-visium/README.md create mode 100644 demos/spatialdata-xenium-rep1/README.md diff --git a/demos/anndata-chromium-pbmc/README.md b/demos/anndata-chromium-pbmc/README.md new file mode 100644 index 00000000..d1c9a531 --- /dev/null +++ b/demos/anndata-chromium-pbmc/README.md @@ -0,0 +1,16 @@ +# 10x Chromium PBMCs from a healthy donor + +## Data source + +Dataset: "PBMCs from a Healthy Donor: Whole Transcriptome Analysis" (Universal 3', Cell Ranger 4.0.0, 10,194 cells, published 2020-07-07), provided by 10x Genomics. +- https://www.10xgenomics.com/datasets/pbm-cs-from-a-healthy-donor-whole-transcriptome-analysis-3-1-standard-4-0-0 +- Files downloaded by this pipeline: + - `https://cf.10xgenomics.com/samples/cell-exp/4.0.0/Parent_NGSC3_DI_PBMC/Parent_NGSC3_DI_PBMC_filtered_feature_bc_matrix.h5` (~35 MB) +- Publication: none is associated with this dataset. Cite it according to the [10x Genomics citation guidelines](https://www.10xgenomics.com/support/software/cell-ranger/latest/miscellaneous/cr-citations). + +## Data sharing policy +CC BY 4.0 + +## Processing + +The [celldega Chromium tutorial](https://github.com/broadinstitute/celldega/blob/main/notebooks/Chromium_pre-process.ipynb) uses the same dataset and was used as a reference for the data processing steps here. diff --git a/demos/anndata-chromium-pbmc/Snakefile b/demos/anndata-chromium-pbmc/Snakefile index f12090f3..bc9e1de7 100644 --- a/demos/anndata-chromium-pbmc/Snakefile +++ b/demos/anndata-chromium-pbmc/Snakefile @@ -10,7 +10,7 @@ OUTPUTS = load_demo_outputs(DEMO_DIR) # Dataset: "PBMCs from a Healthy Donor: Whole Transcriptome Analysis" # (Cell Ranger 4.0.0; the parent whole-transcriptome library of the # 10x Targeted Gene Expression demo datasets), published by 10x Genomics. -# https://www.10xgenomics.com/datasets/pbm-cs-from-a-healthy-donor-whole-transcriptome-analysis-1-1-standard-4-0-0 +# https://www.10xgenomics.com/datasets/pbm-cs-from-a-healthy-donor-whole-transcriptome-analysis-3-1-standard-4-0-0 # License: 10x Genomics public datasets are released under CC BY 4.0. # This is the same dataset used by the celldega Chromium tutorial: # https://github.com/broadinstitute/celldega/blob/main/notebooks/Chromium_pre-process.ipynb diff --git a/demos/anndata-parse-pbmc/README.md b/demos/anndata-parse-pbmc/README.md new file mode 100644 index 00000000..dbbbaffe --- /dev/null +++ b/demos/anndata-parse-pbmc/README.md @@ -0,0 +1,19 @@ +# Parse Biosciences Evercode WT human PBMCs + +Single-cell RNA-seq of human peripheral blood mononuclear cells (PBMCs), profiled with Parse Biosciences Evercode Whole Transcriptome (WT v1, split-pool combinatorial barcoding). + +## Data source + +Dataset: "Performance of Evercode WT in Human Immune Cells (PBMCs)", provided by Parse Biosciences. +https://www.parsebiosciences.com/datasets/pbmc/performance-of-evercode-wt-in-human-immune-cells-pbmcs/ (four fixed PBMC samples, each processed with WT v1 and WT v2. This demo uses the WT v1 files.) +- Files downloaded by this pipeline (split-pipe outputs, direct CDN links with no form or login): + - https://cdn.parsebiosciences.com/pbmc/v1/DGE.mtx (~200 MB) + - https://cdn.parsebiosciences.com/pbmc/v1/all_genes.csv + - https://cdn.parsebiosciences.com/pbmc/v1/cell_metadata.csv +- Publication: Tran V, Papalexi E, Schroeder S, et al. "High sensitivity single cell RNA sequencing with split pool barcoding." bioRxiv (2022). https://doi.org/10.1101/2022.08.27.505512 + +## Data sharing policy + +CC BY 4.0 + +> All users are free to share and adapt the data by providing appropriate credit. diff --git a/demos/combat-2022/README.md b/demos/combat-2022/README.md new file mode 100644 index 00000000..b4196a60 --- /dev/null +++ b/demos/combat-2022/README.md @@ -0,0 +1,12 @@ +# COMBAT COVID-19 Multi-omic Blood Atlas (COMBAT Consortium, 2022) + +CITE-seq (RNA plus surface protein) of human blood cells from COVID-19 patients and comparison groups. + +## Data source +Dataset: "A blood atlas of COVID-19 defines hallmarks of disease severity and specificity: Associated data", Zenodo record 6120249 (DOI [10.5281/zenodo.6120249](https://doi.org/10.5281/zenodo.6120249)), provided by the COvid-19 Multi-omics Blood ATlas (COMBAT) Consortium. https://zenodo.org/records/6120249 +- Files downloaded by this pipeline: + - `https://zenodo.org/record/6120249/files/COMBAT-CITESeq-EXPRESSION-ATLAS.h5ad?download=1` (about 6.6 GB) +- Publication: COvid-19 Multi-omics Blood ATlas (COMBAT) Consortium. "A blood atlas of COVID-19 defines hallmarks of disease severity and specificity." *Cell* 185(5):916–938.e58 (2022). https://doi.org/10.1016/j.cell.2022.01.012 + +## Data sharing policy +CC BY 4.0 diff --git a/demos/habib-2017/README.md b/demos/habib-2017/README.md new file mode 100644 index 00000000..9d98165e --- /dev/null +++ b/demos/habib-2017/README.md @@ -0,0 +1,9 @@ +# DroNc-seq of archived human brain (Habib et al., 2017) + +Single-nucleus RNA-seq (DroNc-seq) of archived frozen adult human post-mortem brain tissue. + +## Data source +Dataset: processed `habib17` AnnData object, provided by the COVID-19 Cell Atlas (hosted by the Wellcome Sanger Institute). https://www.covid19cellatlas.org/index.healthy.html#habib17. That page lists the GTEx Portal (http://www.gtexportal.org/home/data-sets) as the original data source. +- Files downloaded by this pipeline: + - `https://covid19.cog.sanger.ac.uk/habib17.processed.h5ad` +- Publication: Habib N, Avraham-Davidi I, Basu A, Burks T, et al. "Massively parallel single-nucleus RNA-seq with DroNc-seq." *Nature Methods* 14(10):955–958 (2017). https://doi.org/10.1038/nmeth.4407 diff --git a/demos/human-lymph-node-10x-visium/README.md b/demos/human-lymph-node-10x-visium/README.md new file mode 100644 index 00000000..2471a1ab --- /dev/null +++ b/demos/human-lymph-node-10x-visium/README.md @@ -0,0 +1,14 @@ +# Human lymph node, 10x Genomics Visium + +10x Genomics Visium spatial gene expression of a fresh frozen human lymph node section. + +## Data source +Dataset: "Human Lymph Node" (`V1_Human_Lymph_Node`, Space Ranger 1.1.0, published 2020-06-23), provided by 10x Genomics. https://www.10xgenomics.com/datasets/human-lymph-node-1-standard-1-1-0 +- Files downloaded by this pipeline. There is no separate download rule: `scanpy.datasets.visium_sge(sample_id="V1_Human_Lymph_Node", include_hires_tiff=True)` downloads these to `data/raw/V1_Human_Lymph_Node/`: + - `https://cf.10xgenomics.com/samples/spatial-exp/1.1.0/V1_Human_Lymph_Node/V1_Human_Lymph_Node_spatial.tar.gz` (~8 MB) + - `https://cf.10xgenomics.com/samples/spatial-exp/1.1.0/V1_Human_Lymph_Node/V1_Human_Lymph_Node_filtered_feature_bc_matrix.h5` (~31 MB) + - `https://cf.10xgenomics.com/samples/spatial-exp/1.1.0/V1_Human_Lymph_Node/V1_Human_Lymph_Node_image.tif` (~400 MB) +- Publication: none is associated with this dataset. + +## Data sharing policy +CC BY 4.0 diff --git a/demos/kuppe-2022/README.md b/demos/kuppe-2022/README.md new file mode 100644 index 00000000..3b6465f1 --- /dev/null +++ b/demos/kuppe-2022/README.md @@ -0,0 +1,17 @@ +# Spatial multi-omic map of human myocardial infarction (Kuppe et al., 2022) + +snRNA-seq, snATAC-seq and 10x Visium of human heart tissue after myocardial infarction. + +## Data source +Dataset: CZ CELLxGENE Discover collection "Spatial multi-omic map of human myocardial infarction" (https://cellxgene.cziscience.com/collections/8191c283-0816-424b-9b61-c3e1d6258a77), plus the authors' Zenodo record "Raw Data - Part 3 : Spatial multi-omic map of human myocardial infarction" (DOI [10.5281/zenodo.6580069](https://doi.org/10.5281/zenodo.6580069)) for the Visium image. +- Files downloaded by this pipeline: + - `https://datasets.cellxgene.cziscience.com/4780eb7d-4c7c-4630-8705-471f0de8e27a.h5ad` (CELLxGENE "All-snRNA-Spatial multi-omic map of human myocardial infarction") + - `https://datasets.cellxgene.cziscience.com/febd9a43-ebb8-4776-b15a-535544c28dfe.h5ad` (CELLxGENE "All-snATAC-Spatial multi-omic map of human myocardial infarction") + - `https://datasets.cellxgene.cziscience.com/11e82612-24b9-4490-813a-bd0970df0a98.h5ad` (CELLxGENE "GT_IZ_P9 (ACH0012)-Spatial multi-omic map of human myocardial infarction") + - `https://zenodo.org/record/6580069/files/10X_Visium_ACH0012.tar.gz?download=1` (Space Ranger output for ACH0012, about 830 MB) +- Publication: Kuppe C, Ramirez Flores RO, Li Z, Hayat S, et al. "Spatial multi-omic map of human myocardial infarction." *Nature* 608(7924):766–777 (2022). https://doi.org/10.1038/s41586-022-05060-x + + +## Data sharing policy +- CELLxGENE files: CC BY 4.0 +- Zenodo record 6580069: open access, CC BY 4.0 diff --git a/demos/kuppe-2022/src/convert_to_zarr.py b/demos/kuppe-2022/src/convert_to_zarr.py index 6f8ab7dc..84879b76 100644 --- a/demos/kuppe-2022/src/convert_to_zarr.py +++ b/demos/kuppe-2022/src/convert_to_zarr.py @@ -58,8 +58,8 @@ def process_h5ad_files(args): rna_adata = read_h5ad(args.input_rna) atac_adata = read_h5ad(args.input_atac) - rna_adata.layers['X_uint8'] = to_uint8(rna_adata.X, norm_along="global") - atac_adata.layers['X_uint8'] = to_uint8(atac_adata.X, norm_along="global") + rna_adata.layers['X_uint8'] = to_uint8(rna_adata.X.copy(), norm_along="global") + atac_adata.layers['X_uint8'] = to_uint8(atac_adata.X.copy(), norm_along="global") visium_adata.layers['X_uint8'] = to_uint8(visium_adata.X, norm_along="var") diff --git a/demos/marshall-2022/README.md b/demos/marshall-2022/README.md new file mode 100644 index 00000000..de24eb59 --- /dev/null +++ b/demos/marshall-2022/README.md @@ -0,0 +1,13 @@ +# Slide-seqV2 of healthy human kidney (Marshall et al., 2022) + +Slide-seqV2 spatial transcriptomics of healthy human kidney (puck `Puck_200903_13`). + +## Data source +Dataset: "Spatial transcriptomics in the healthy human kidney: Puck_200903_13", in the CZ CELLxGENE Discover collection "High Resolution Slide-seqV2 Spatial Transcriptomics Enables Discovery of Disease-Specific Cell Neighborhoods and Pathways". https://cellxgene.cziscience.com/collections/8e880741-bf9a-4c8e-9227-934204631d2a. The raw data are in GEO, [GSE190094](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE190094). +- Files downloaded by this pipeline: + - `https://datasets.cellxgene.cziscience.com/69ecc4ce-5bb2-4f2c-9ce7-15452392d140.h5ad` +- Publication: Marshall JL, Noel T, Wang QS, Chen H, et al. "High-resolution Slide-seqV2 spatial transcriptomics enables discovery of disease-specific cell neighborhoods and pathways." *iScience* 25(4):104097 (2022). https://doi.org/10.1016/j.isci.2022.104097 + + +## Data sharing policy +CC BY 4.0 diff --git a/demos/meta-2022-azimuth/README.md b/demos/meta-2022-azimuth/README.md new file mode 100644 index 00000000..adfd6ddb --- /dev/null +++ b/demos/meta-2022-azimuth/README.md @@ -0,0 +1,13 @@ +# Azimuth meta-analysis of human lung scRNA-seq (Satija Lab / HuBMAP, 2022) + +Human lung single-cell RNA-seq data mapped to an Azimuth reference for harmonized annotation. + +## Data source +Dataset: CZ CELLxGENE Discover collection "Azimuth meta-analysis of human scRNA-seq datasets" (contact: Rahul Satija; consortia: CZ Biohub, HuBMAP). https://cellxgene.cziscience.com/collections/2f75d249-1bec-459b-bf2b-b86221097ced +- Files downloaded by this pipeline: + - `https://datasets.cellxgene.cziscience.com/d084f1e1-42f1-4f65-8e5a-3ae93a05756c.h5ad` (about 6.7 GB). This is the original 2022 dataset version, "Azimuth meta-analysis of 10 datasets of healthy and diseased human lung" (982,538 cells; healthy donors plus COVID-19, COPD and interstitial lung disease). +- Publication: the CELLxGENE collection lists no publication DOI. Azimuth is described in Hao Y, Hao S, Andersen-Nissen E, Mauck WM, et al. "Integrated analysis of multimodal single-cell data." *Cell* 184(13):3573–3587.e29 (2021), https://doi.org/10.1016/j.cell.2021.04.048. + + +## Data sharing policy +CC BY 4.0 diff --git a/demos/meta-2022-azimuth/Snakefile b/demos/meta-2022-azimuth/Snakefile index d06c2a04..2289e02e 100644 --- a/demos/meta-2022-azimuth/Snakefile +++ b/demos/meta-2022-azimuth/Snakefile @@ -11,8 +11,10 @@ OUTPUTS = load_demo_outputs(DEMO_DIR) # cellxgene portal AWS URLs expire in one week. # May need to get new URLs from https://cellxgene.cziscience.com/collections/2f75d249-1bec-459b-bf2b-b86221097ced -# Azimuth meta-analysis of 10 datasets of healthy and diseased human lung -H5AD_URL = "https://datasets.cellxgene.cziscience.com/2c01a563-73dd-47a1-8fc4-d1779364bedf.h5ad" +# Azimuth meta-analysis of 10 datasets of healthy and diseased human lung. +# Pinned to the original 2022 dataset version (d084f1e1, 982,538 cells, healthy and diseased). +# The collection's current version (2c01a563, "Human - Lung v2 (HLCA)", healthy only) is a different dataset. +H5AD_URL = "https://datasets.cellxgene.cziscience.com/d084f1e1-42f1-4f65-8e5a-3ae93a05756c.h5ad" rule all: input: diff --git a/demos/meta-2022-azimuth/src/convert_to_zarr.py b/demos/meta-2022-azimuth/src/convert_to_zarr.py index 274d284a..e526b9e0 100644 --- a/demos/meta-2022-azimuth/src/convert_to_zarr.py +++ b/demos/meta-2022-azimuth/src/convert_to_zarr.py @@ -21,7 +21,7 @@ def convert_h5ad_to_zarr(input_path, output_path): adata = read_h5ad(input_path) - adata.layers['X_uint8'] = to_uint8(adata.X, norm_along="global") + adata.layers['X_uint8'] = to_uint8(adata.X.copy(), norm_along="global") # Vitessce plays nicely with csc matrices # TODO: automate conversion to csc in optimize_adata function diff --git a/demos/mudata-cite-seq-pbmc/README.md b/demos/mudata-cite-seq-pbmc/README.md new file mode 100644 index 00000000..8f09b66c --- /dev/null +++ b/demos/mudata-cite-seq-pbmc/README.md @@ -0,0 +1,17 @@ +# 10x Flex v2 PBMC CITE-seq (TotalSeq-C) + +Paired gene expression and cell surface protein (antibody-derived tag) profiling of about 12k human PBMCs. The cells come from four probe-barcoded samples, stained with the TotalSeq-C Human Universal Cocktail v2.0 and profiled with 10x GEM-X Flex v2. + +## Data source +Dataset: "Human PBMCs labeled with cell surface antibodies using TotalSeq™-C Human Universal Cocktail v2.0" (Flex, `cellranger multi`, Cell Ranger 10.0.0, published 2026-05-27), provided by 10x Genomics. https://www.10xgenomics.com/datasets/Flexv2_16k_Human_PBMCs_TotalseqC_4plex +- Files downloaded by this pipeline: + - `https://cf.10xgenomics.com/samples/cell-exp/10.0.0/16k_Human_PBMCs_TotalseqC_4plex_Multiplex/16k_Human_PBMCs_TotalseqC_4plex_Multiplex_filtered_feature_bc_matrix.h5` (~62 MB). This is the "Multiplex" filtered feature-barcode matrix with the called cells of all four samples. +- Publication: none is associated with this dataset. + + +## Data sharing policy +CC BY 4.0 + +## Processing + +The Broad Institute Celldega project publishes a pre-built MuData file of the same data on [Hugging Face](https://huggingface.co/datasets/broadinstitute/Celldega_Supporting_Data/blob/main/Flex_16k_PBMC_CITE-seq/Flex_16k_PBMC_CITE-seq.h5mu). Its [pre-processing notebook](https://huggingface.co/datasets/broadinstitute/Celldega_Supporting_Data/blob/main/Flex_16k_PBMC_CITE-seq/Flex_16k_PBMC_CITE-seq_Pre-process.ipynb) was used as a reference for the RNA/protein split and the probe-barcode-to-sample mapping here. diff --git a/demos/mudata-cite-seq-pbmc/Snakefile b/demos/mudata-cite-seq-pbmc/Snakefile index a07fee18..a9cf11df 100644 --- a/demos/mudata-cite-seq-pbmc/Snakefile +++ b/demos/mudata-cite-seq-pbmc/Snakefile @@ -10,7 +10,7 @@ OUTPUTS = load_demo_outputs(DEMO_DIR) # of human PBMCs: four probe-barcoded PBMC samples stained with the TotalSeq-C # Human Universal Cocktail v2.0 and profiled with 10x GEM-X Flex v2 # (Cell Ranger 10.0.0, 12,242 cells, 18,132 genes, 184 antibodies). -# Dataset: "16k Human PBMCs, TotalSeq-C 4-plex (Flex v2)", 10x Genomics. +# Dataset: "Human PBMCs labeled with cell surface antibodies using TotalSeq-C Human Universal Cocktail v2.0", 10x Genomics. # https://www.10xgenomics.com/datasets/Flexv2_16k_Human_PBMCs_TotalseqC_4plex # License: CC BY 4.0. # The file below is the original 10x Genomics download ("Multiplex" filtered diff --git a/demos/mudata-pbmc-multiome-10x/README.md b/demos/mudata-pbmc-multiome-10x/README.md new file mode 100644 index 00000000..e377e205 --- /dev/null +++ b/demos/mudata-pbmc-multiome-10x/README.md @@ -0,0 +1,14 @@ +# 10x Multiome PBMC (granulocytes removed, 10k) + +10x Genomics Single Cell Multiome ATAC + Gene Expression of human PBMC nuclei from a healthy donor. + +## Data source +Dataset: "PBMC from a Healthy Donor - Granulocytes Removed Through Cell Sorting (10k)" (Epi Multiome, Cell Ranger ARC 2.0.0, 11,898 nuclei, published 2021-05-03), provided by 10x Genomics. https://www.10xgenomics.com/datasets/pbmc-from-a-healthy-donor-granulocytes-removed-through-cell-sorting-10-k-1-standard-2-0-0 +- Files downloaded by this pipeline: + - `https://cf.10xgenomics.com/samples/cell-arc/2.0.0/pbmc_granulocyte_sorted_10k/pbmc_granulocyte_sorted_10k_filtered_feature_bc_matrix.h5` (~190 MB) + - `https://cf.10xgenomics.com/samples/cell-arc/2.0.0/pbmc_granulocyte_sorted_10k/pbmc_granulocyte_sorted_10k_atac_peak_annotation.tsv` (~8 MB) + - `https://cf.10xgenomics.com/samples/cell-arc/2.0.0/pbmc_granulocyte_sorted_10k/pbmc_granulocyte_sorted_10k_per_barcode_metrics.csv` (~89 MB) +- Publication: none is associated with this dataset. + +## Data sharing policy +CC BY 4.0 diff --git a/demos/mudata-snareseq2-lung-hubmap/README.md b/demos/mudata-snareseq2-lung-hubmap/README.md new file mode 100644 index 00000000..aa1455cd --- /dev/null +++ b/demos/mudata-snareseq2-lung-hubmap/README.md @@ -0,0 +1,15 @@ +# SNARE-seq2 human lung (HuBMAP HBM582.RKVK.974) + +Joint single-nucleus RNA + chromatin accessibility (SNARE-seq2) of human left lung from HuBMAP, as processed by the HuBMAP Salmon + ArchR + Muon pipeline. + +## Data source +Dataset: HuBMAP [HBM582.RKVK.974](https://portal.hubmapconsortium.org/browse/dataset/cd0996bebdc726bd2a8bf418ba6ed845) (uuid `cd0996bebdc726bd2a8bf418ba6ed845`), "SNARE-seq2 [Salmon + ArchR + Muon] data from the lung (left) of a 23.8-year-old white male", provided by the University of California San Diego TMC. Its DOI is [10.35079/HBM582.RKVK.974](https://doi.org/10.35079/HBM582.RKVK.974). + - Raw (parent) datasets: 12 SNARE-seq2 library datasets from the same donor. They are listed as ancestors on the portal page. This demo uses only the public processed output. +- File downloaded by this pipeline (about 2.8 GB): + - `https://assets.hubmapconsortium.org/cd0996bebdc726bd2a8bf418ba6ed845/secondary_analysis.h5mu` +- Publication: HuBMAP Consortium. "The human body at cellular resolution: the NIH Human Biomolecular Atlas Program." *Nature* 574, 187–192 (2019). https://doi.org/10.1038/s41586-019-1629-x + + +## Data sharing policy + +CC-BY 4.0 diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/README.md b/demos/ome-zarr-lightsheet-hubmap-spleen/README.md new file mode 100644 index 00000000..dcbf115d --- /dev/null +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/README.md @@ -0,0 +1,15 @@ +# Light-sheet human spleen (HuBMAP HBM759.DQHR.327) + +3D light-sheet fluorescence microscopy of cleared human spleen stained for Iba1, from HuBMAP (University of Florida TMC). The image is converted to a multiscale 3D OME-Zarr, which Vitessce shows as a volume rendering. + +## Data source +- Dataset: HuBMAP [HBM759.DQHR.327](https://portal.hubmapconsortium.org/browse/dataset/71b3fdd770de565e5d48a73060b72189) (uuid `71b3fdd770de565e5d48a73060b72189`), "Light Sheet [Image Pyramid] data from the spleen of a 20-year-old white male", provided by the University of Florida TMC. It is the image pyramid that HuBMAP generated from the raw dataset. The HuBMAP entity API lists no DOI for this pyramid dataset. + - Raw (parent) dataset: [HBM423.JZTB.864](https://portal.hubmapconsortium.org/browse/dataset/073cad035ce246a0134e2214569adde9), DOI [10.35079/HBM423.JZTB.864](https://doi.org/10.35079/HBM423.JZTB.864) ("LS_20-007_SP_CC2-F dataset"). +- File downloaded by this pipeline (about 3.5 GB): + - `https://assets.hubmapconsortium.org/71b3fdd770de565e5d48a73060b72189/ometiff-pyramids/Level0/Channel1/UFL0007-SP-2-3-1.ome.tif` +- Publication: HuBMAP Consortium. "The human body at cellular resolution: the NIH Human Biomolecular Atlas Program." *Nature* 574, 187–192 (2019). https://doi.org/10.1038/s41586-019-1629-x + + +## Data sharing policy + +CC-BY 4.0 diff --git a/demos/spatialdata-atera-kidney/README.md b/demos/spatialdata-atera-kidney/README.md new file mode 100644 index 00000000..d84ca947 --- /dev/null +++ b/demos/spatialdata-atera-kidney/README.md @@ -0,0 +1,13 @@ +# Atera WTA non-diseased human kidney (FFPE) + +10x Genomics Atera whole-transcriptome in situ gene expression of a non-diseased FFPE human kidney section (399,120 cells), converted to a SpatialData Zarr store. + +## Data source +Dataset: "Atera In Situ Gene Expression, FFPE Human Kidney" (Atera Human WTA panel, Atera Onboard Analysis 1.0.4), provided by 10x Genomics. https://www.10xgenomics.com/datasets/atera-wta-ffpe-human-nd-kidney +- Files downloaded by this pipeline: + - `https://cf.10xgenomics.com/samples/atera/1.0.4/Atera_v1_WTA_Kidney_non_diseased_FFPE/Atera_v1_WTA_Kidney_non_diseased_FFPE_outs.zip` (45.7 GB) + - Optional, for quick testing only: `https://cf.10xgenomics.com/samples/atera/1.0.0/tiny_atera_dataset/tiny_atera_dataset_outs.zip` (3.6 MB). This is a small synthetic bundle that demonstrates the Atera output format, from the [Atera Onboard Analysis example data](https://www.10xgenomics.com/support/software/atera-onboard-analysis/latest/resources/example-data) page. +- Publication: none is associated with this dataset. + +## Data sharing policy +CC BY 4.0 diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/README.md b/demos/spatialdata-aviti24-teton-hela-tnfa/README.md new file mode 100644 index 00000000..a27e45b5 --- /dev/null +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/README.md @@ -0,0 +1,13 @@ +# AVITI24 Teton CytoProfiling of TNF-alpha-stimulated HeLa cells + +Element Biosciences AVITI24 (Teton CytoProfiling) per-cell targeted transcript counts and cell paint morphology features for HeLa cells stimulated with TNF-alpha over a time course. + +## Data source +Dataset: "High-Throughput Multiomics Profiling of Model Systems Using the AVITI24 Platform (Lopez et al.)", deposited on Zenodo by Element Biosciences, Tyler Lopez, and Semyon Kruglyak (2025). https://zenodo.org/records/17394327, DOI [10.5281/zenodo.17394327](https://doi.org/10.5281/zenodo.17394327) +- Files downloaded by this pipeline: one member, `GEO_submission/Teton/RawCellStats_ACE_3678.parquet` (~520 MB), of https://zenodo.org/api/records/17394327/files/GEO_submission.zip/content. The full zip is 10.3 GB, mostly bulk RNA-seq FASTQ files; HTTP range requests fetch only the parquet member. +- Publication: Lopez et al. (2025): Lopez T, Honigfort D, Mah A, et al. "High-Throughput Multiomics Profiling of Model Systems Using the AVITI24 Platform." bioRxiv (2025). https://doi.org/10.1101/2025.05.03.651997 + + +## Data sharing policy + +CC BY 4.0 diff --git a/demos/spatialdata-codex-hubmap-large-intestine/README.md b/demos/spatialdata-codex-hubmap-large-intestine/README.md new file mode 100644 index 00000000..9db30f21 --- /dev/null +++ b/demos/spatialdata-codex-hubmap-large-intestine/README.md @@ -0,0 +1,18 @@ +# CODEX human large intestine (HuBMAP HBM996.CGFD.228) + +Akoya CODEX (now PhenoCycler) multiplexed immunofluorescence image of human large intestine from HuBMAP, with its cell segmentation and SPRM cell-by-marker table. + +## Data source +Dataset: HuBMAP [HBM996.CGFD.228](https://portal.hubmapconsortium.org/browse/dataset/c945cbd75f2da373d1ccfe86694f9c34) (uuid `c945cbd75f2da373d1ccfe86694f9c34`), "CODEX [Cytokit + SPRM] data from the large intestine of a 37-year-old white male", provided by the Stanford TMC. HuBMAP produced this dataset by running its Cytokit segmentation and [SPRM](https://github.com/hubmapconsortium/sprm) pipelines. The HuBMAP entity API lists no DOI for this processed dataset. + - Raw (parent) dataset: [HBM742.NHHQ.357](https://portal.hubmapconsortium.org/browse/dataset/98c1bc0a44802108a6dcf8ce281628a7), DOI [10.35079/HBM742.NHHQ.357](https://doi.org/10.35079/HBM742.NHHQ.357). It is sample B008-A-201 from donor B008. +- Files downloaded by this pipeline (about 1.7 GB in total): + - `https://assets.hubmapconsortium.org/c945cbd75f2da373d1ccfe86694f9c34/ometiff-pyramids/pipeline_output/expr/reg001_expr.ome.tif` (about 1.68 GB) + - `https://assets.hubmapconsortium.org/c945cbd75f2da373d1ccfe86694f9c34/ometiff-pyramids/pipeline_output/mask/reg001_mask.ome.tif` + - `https://assets.hubmapconsortium.org/c945cbd75f2da373d1ccfe86694f9c34/anndata-zarr/reg001_expr-anndata.zarr.zip` + +- Publication (linked to the raw dataset in HuBMAP as publication HBM222.STTH.665): Hickey, J.W. et al. "Organization of the human intestine at single-cell resolution." *Nature* 619, 572–584 (2023). https://doi.org/10.1038/s41586-023-05915-x +- HuBMAP consortium: HuBMAP Consortium. "The human body at cellular resolution: the NIH Human Biomolecular Atlas Program." *Nature* 574, 187–192 (2019). https://doi.org/10.1038/s41586-019-1629-x + + +## Data sharing policy +CC-BY 4.0 diff --git a/demos/spatialdata-cosmx-nsclc/README.md b/demos/spatialdata-cosmx-nsclc/README.md new file mode 100644 index 00000000..f55f6972 --- /dev/null +++ b/demos/spatialdata-cosmx-nsclc/README.md @@ -0,0 +1,9 @@ +# CosMx SMI non-small-cell lung cancer (Lung9_Rep1) + +Bruker (NanoString) CosMx Spatial Molecular Imager data of a formalin-fixed paraffin-embedded (FFPE) human non-small-cell lung cancer (NSCLC) section, profiled with a 960-gene RNA panel. + +## Data source +Dataset: CosMx SMI NSCLC FFPE dataset (section Lung9_Rep1), provided by NanoString Technologies (now Bruker Spatial Biology). https://www.brukerspatialbiology.com/products/cosmx-spatial-molecular-imager/ffpe-dataset/nsclc-ffpe-dataset/ +- File format descriptions: https://nanostring-public-share.s3.us-west-2.amazonaws.com/SMI-Compressed/SMI-ReadMe.html +- Files downloaded by this pipeline: https://nanostring-public-share.s3.us-west-2.amazonaws.com/SMI-Compressed/Lung9_Rep1/Lung9_Rep1+SMI+Flat+data.tar.gz (~1.1 GB). The public S3 bucket needs no account or form. +- Publication: He S, Bhatt R, Brown C, Brown EA, et al. "High-plex imaging of RNA and proteins at subcellular resolution in fixed tissue by spatial molecular imaging." Nature Biotechnology 40, 1794–1806 (2022). https://doi.org/10.1038/s41587-022-01483-z diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/README.md b/demos/spatialdata-dbit-seq-mouse-embryo/README.md new file mode 100644 index 00000000..fcc3daf3 --- /dev/null +++ b/demos/spatialdata-dbit-seq-mouse-embryo/README.md @@ -0,0 +1,13 @@ +# DBiT-seq E10 mouse embryo, mRNA + protein (Liu et al., 2020) + +DBiT-seq (Deterministic Barcoding in Tissue) of an embryonic day 10 mouse embryo section with 50 µm pixels, co-profiling the whole transcriptome and 22 proteins (antibody-derived tags). + +## Data source +- Dataset: GEO series [GSE137986](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE137986), "High spatial resolution multi-omics atlas sequencing of mouse embryos", provided by NCBI GEO. Samples used: + - [GSM4189613](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM4189613) (`0702cL`): mRNA counts (pixels x genes) and the tissue image. + - [GSM4202307](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM4202307) (`0702aL`): protein (ADT) counts of the same section. +- Files downloaded by this pipeline: + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM4189nnn/GSM4189613/suppl/GSM4189613_0702cL.tsv.gz` + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM4189nnn/GSM4189613/suppl/GSM4189613_0702cL-50um-e10.png.gz` + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM4202nnn/GSM4202307/suppl/GSM4202307_0702aL.tsv.gz` +- Publication: Liu Y, Yang M, Deng Y, Su G, et al. "High-Spatial-Resolution Multi-Omics Sequencing via Deterministic Barcoding in Tissue." *Cell* 183(6):1665–1681.e18 (2020). https://doi.org/10.1016/j.cell.2020.10.026 diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile b/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile index abd7c6f3..59281910 100644 --- a/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile +++ b/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile @@ -13,7 +13,7 @@ OUTPUTS = load_demo_outputs(DEMO_DIR) # # Publication: Liu Y, Yang M, Deng Y, et al. "High-Spatial-Resolution Multi-Omics Sequencing via # Deterministic Barcoding in Tissue". Cell 183(6):1665-1681 (2020). https://doi.org/10.1016/j.cell.2020.10.026 -# Data: GEO series GSE137986 (https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE137986), public domain (NCBI GEO). +# Data: GEO series GSE137986 (https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE137986). Data use: see the NCBI GEO disclaimer (https://www.ncbi.nlm.nih.gov/geo/info/disclaimer.html); submitters may claim IP rights. # - GSM4189613 (0702cL): mRNA count matrix (pixels x genes, pixel IDs "{x}x{y}") and the tissue image of the # 50 x 50 pixel region. https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM4189613 # - GSM4202307 (0702aL): protein (ADT) count matrix of the same tissue section. diff --git a/demos/spatialdata-geomx-mouse-embryo/README.md b/demos/spatialdata-geomx-mouse-embryo/README.md new file mode 100644 index 00000000..f7c00ceb --- /dev/null +++ b/demos/spatialdata-geomx-mouse-embryo/README.md @@ -0,0 +1,10 @@ +# GeoMx DSP mouse embryo (E11) + +Bruker (NanoString) GeoMx Digital Spatial Profiler data, Mouse Whole Transcriptome Atlas, from a fixed-frozen sagittal section of an E11 C57BL/6 mouse embryo (scan `mu_dev_E11_004`). + +## Data source +Dataset: Spatial Organ Atlas (SOA), "Mouse Embryonic Development GeoMx Spatial Dataset", provided by NanoString Technologies (now Bruker Spatial Biology). SOA product page: https://www.brukerspatialbiology.com/products/geomx-digital-spatial-profiler/spatial-organ-atlas/ +- File format descriptions: https://external-soa-downloads-p-1.s3.us-west-2.amazonaws.com/README_mu_dev.docx (README v4.1) +- Files downloaded by this pipeline (public S3 bucket, no account or form): + - https://external-soa-downloads-p-1.s3.us-west-2.amazonaws.com/mu_dev_count_results.tar.gz (~250 MB). Only `Export4_NormalizationQ3.xlsx` is extracted. + - https://external-soa-downloads-p-1.s3.us-west-2.amazonaws.com/mu_dev_E11_image_files.tar.gz (~1.8 GB). Only `mu_dev_E11_004.ome.tiff` is extracted. diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/README.md b/demos/spatialdata-illumina-stratamap-mouse-kidney/README.md new file mode 100644 index 00000000..7a7323d7 --- /dev/null +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/README.md @@ -0,0 +1,13 @@ +# Illumina StrataMap Spatial Transcriptome mouse kidney + +Illumina StrataMap Spatial Transcriptome data of a normal fresh-frozen mouse kidney section (8-week-old male C57BL/6, 10 µm, H&E stained), processed with DRAGEN Spatial Transcriptome. + +## Data source +Dataset: "Spatial transcriptomics demo data set" (StrataMap Spatial Transcriptome, mouse kidney), provided by Illumina. https://www.illumina.com/techniques/multiomics/demo-datasets/spatial-transcriptomics-demo-dataset.html +- Files downloaded by this pipeline: none. You must download the data manually (see below). +- Expected inputs: one DRAGEN StrataMap per-sample results folder, placed at `data/raw/stratamap_results//` (with `SAMPLE_ID` set in the `Snakefile`, default `mouse_kidney`). The folder must contain: + - `_cell_binned/{matrix.mtx.gz,features.tsv.gz,barcodes.tsv.gz}` + - `_Expanded_5um_cell_contour_coords.csv` + - `.ome.tiff` (`*_registered.ome.tiff` is also accepted) + + The file layout follows the [DRAGEN StrataMap results folder documentation](https://help.bioinsight.illumina.com/dragen-stratamap/dragen-stratamap/outputs/results-folder). diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/README.md b/demos/spatialdata-maldi-msi-timstof-mouse-brain/README.md new file mode 100644 index 00000000..a3b32ee3 --- /dev/null +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/README.md @@ -0,0 +1,12 @@ +# MALDI-MSI sagittal mouse brain (Bruker timsTOF) + +MALDI mass spectrometry imaging (MSI) of a sagittal mouse brain section, acquired on a Bruker timsTOF fleX: positive mode, 250–1200 Da, 5 µm raster, 1007 x 1469 pixels. The data are converted to SpatialData with Thyra. + +## Data source +Dataset: "Datasets used for the benchmarking and figures of the Thyra package article.", deposited on Zenodo by Theodoros Visvikis, Eva Cuypers, and Tim Hendriks (2026). https://zenodo.org/records/18326569, DOI [10.5281/zenodo.18326569](https://doi.org/10.5281/zenodo.18326569) +- Files downloaded by this pipeline: https://zenodo.org/api/records/18326569/files/MALDI-MSI_Sagittal_Mouse_Brain.tar.gz/content (19.1 GB). The pipeline verifies it against the record's MD5 checksum. The record also has Xenium (13.0 GB) and H&E (851 MB) archives of the same specimen, which this pipeline does not use. +- Publication: Visvikis T, Vierdag W-M, Marconato L, Heeren RMA, Cuypers E. "Thyra: Bridging Mass Spectrometry Imaging and SpatialData for Unified Multi-Modal Analysis." bioRxiv (2026). https://doi.org/10.64898/2026.01.26.700792 + + +## Data sharing policy +CC BY 4.0 diff --git a/demos/spatialdata-merfish-zhuang-abca-4/README.md b/demos/spatialdata-merfish-zhuang-abca-4/README.md new file mode 100644 index 00000000..7badd2b4 --- /dev/null +++ b/demos/spatialdata-merfish-zhuang-abca-4/README.md @@ -0,0 +1,15 @@ +# MERFISH whole mouse brain (Zhuang-ABCA-4) + +MERFISH spatial transcriptomics (1,122-gene panel) of 3 sagittal sections of an adult mouse brain, from the Zhuang lab, with cell type labels from the Allen whole mouse brain taxonomy. + +## Data source +Dataset: "MERFISH spatial transcriptomics dataset of a single adult mouse brain (Zhuang-ABCA-4)", distributed by the Allen Institute through the Allen Brain Cell (ABC) Atlas. + - Dataset page: https://alleninstitute.github.io/abc_atlas_access/descriptions/Zhuang-ABCA-4.html + - Overview of the Zhuang datasets: https://alleninstitute.github.io/abc_atlas_access/descriptions/Zhuang_dataset.html +- Files downloaded by this pipeline (ABC Atlas public S3 bucket, no login): + - https://allen-brain-cell-atlas.s3.us-west-2.amazonaws.com/expression_matrices/Zhuang-ABCA-4/20230830/Zhuang-ABCA-4-raw.h5ad + - https://allen-brain-cell-atlas.s3.us-west-2.amazonaws.com/metadata/Zhuang-ABCA-4/20241115/views/cell_metadata_with_cluster_annotation.csv +- Publication: Zhang M, Pan X, Jung W, Halpern AR, et al. "Molecularly defined and spatially resolved cell atlas of the whole mouse brain." Nature 624, 343–354 (2023). https://doi.org/10.1038/s41586-023-06808-9 + +## Data sharing policy +CC BY 4.0 diff --git a/demos/spatialdata-merfish-zhuang-abca-4/src/to_spatialdata.py b/demos/spatialdata-merfish-zhuang-abca-4/src/to_spatialdata.py index caeb6707..aac5f863 100644 --- a/demos/spatialdata-merfish-zhuang-abca-4/src/to_spatialdata.py +++ b/demos/spatialdata-merfish-zhuang-abca-4/src/to_spatialdata.py @@ -58,7 +58,7 @@ def process(expression_path, metadata_path, output_path): # Coordinates in the ABC atlas are in millimeters, in a per-section reconstructed space. # Convert to micrometers, and lay out the sections side by side - # (ordered by their z position along the anterior-posterior axis) so they do not overlap. + # (ordered by their z position along the medial-lateral axis) so they do not overlap. x_um = obs["x"].to_numpy() * 1000.0 y_um = obs["y"].to_numpy() * 1000.0 section_order = ( diff --git a/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json b/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json index 62db9bc3..0cdf86b8 100644 --- a/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json +++ b/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json @@ -1,7 +1,7 @@ { "version": "1.0.18", "name": "MERFISH whole mouse brain (Zhuang-ABCA-4)", - "description": "Zhuang lab MERFISH (Zhang et al. 2023), three coronal sections laid out side by side, with ABC atlas cell type labels", + "description": "Zhuang lab MERFISH (Zhang et al. 2023), three sagittal sections laid out side by side, with ABC atlas cell type labels", "datasets": [ { "uid": "A", diff --git a/demos/spatialdata-merscope-mouse-brain/README.md b/demos/spatialdata-merscope-mouse-brain/README.md new file mode 100644 index 00000000..0434fe54 --- /dev/null +++ b/demos/spatialdata-merscope-mouse-brain/README.md @@ -0,0 +1,15 @@ +# MERSCOPE mouse brain receptor map (slice 2, replicate 1) + +Vizgen MERSCOPE (MERFISH) data of a coronal mouse brain slice, profiled with a 483-gene panel. + +## Data source +Dataset: MERFISH Mouse Brain Receptor Map, provided by Vizgen as part of its data release program. It covers 3 coronal slices x 3 biological replicates. This demo uses Slice 2, Replicate 1. https://info.vizgen.com/mouse-brain-map +- Files downloaded by this pipeline, read from the Google Cloud Storage bucket `vizgen-mouse-brain-map` (no login): + - https://storage.googleapis.com/vizgen-mouse-brain-map/BrainReceptorShowcase/Slice2/Replicate1/cell_by_gene.csv + - https://storage.googleapis.com/vizgen-mouse-brain-map/BrainReceptorShowcase/Slice2/Replicate1/cell_metadata.csv + - https://storage.googleapis.com/vizgen-mouse-brain-map/BrainReceptorShowcase/Slice2/Replicate1/detected_transcripts.csv (3.2 GB) + - https://storage.googleapis.com/vizgen-mouse-brain-map/BrainReceptorShowcase/Slice2/Replicate1/images/micron_to_mosaic_pixel_transform.csv + - https://storage.googleapis.com/vizgen-mouse-brain-map/BrainReceptorShowcase/Slice2/Replicate1/images/mosaic_DAPI_z3.tif (12.4 GB) + - https://storage.googleapis.com/vizgen-mouse-brain-map/BrainReceptorShowcase/Slice2/Replicate1/images/mosaic_polyT_z3.tif (12.4 GB) + - All per-FOV cell boundary HDF5 files under `BrainReceptorShowcase/Slice2/Replicate1/cell_boundaries/`, listed through the GCS JSON API (`https://storage.googleapis.com/storage/v1/b/vizgen-mouse-brain-map/o?prefix=...`) +- Publication: "Vizgen Data Release V1.0. May 2021". diff --git a/demos/spatialdata-mibi-hubmap-uterus/README.md b/demos/spatialdata-mibi-hubmap-uterus/README.md new file mode 100644 index 00000000..e409f4ab --- /dev/null +++ b/demos/spatialdata-mibi-hubmap-uterus/README.md @@ -0,0 +1,18 @@ +# MIBI human maternal-fetal interface (HuBMAP HBM957.GCWC.626) + +Ionpath MIBIscope (multiplexed ion beam imaging) image of human decidua basalis (uterus, maternal-fetal interface) from HuBMAP, with its cell segmentation and SPRM cell-by-marker table. The data is converted to a SpatialData store. + +## Data source +Dataset: HuBMAP [HBM957.GCWC.626](https://portal.hubmapconsortium.org/browse/dataset/cdb49a41bf77bbdfe7f7b40b360e7f56) (uuid `cdb49a41bf77bbdfe7f7b40b360e7f56`), "MIBI [DeepCell + SPRM] data from the uterus of a 33.3-year-old unknown female", provided by the Stanford RTI. HuBMAP produced this dataset by running its DeepCell segmentation and [SPRM](https://github.com/hubmapconsortium/sprm) pipelines. The HuBMAP entity API lists no DOI for this processed dataset. + - Raw (parent) dataset: [HBM574.RBCK.759](https://portal.hubmapconsortium.org/browse/dataset/8aabd9b3e3b03a19d47cf85f1af62d9e), DOI [10.35079/HBM574.RBCK.759](https://doi.org/10.35079/HBM574.RBCK.759). Its description reads: "high resolution, high dimensional images of the maternal-fetal interface in the first 20 weeks of pregnancy", mostly decidua basalis from archival FFPE tissue. +- Files downloaded by this pipeline: + - `https://assets.hubmapconsortium.org/cdb49a41bf77bbdfe7f7b40b360e7f56/ometiff-pyramids/pipeline_output/expr/3D_image_stack_expr.ome.tif` + - `https://assets.hubmapconsortium.org/cdb49a41bf77bbdfe7f7b40b360e7f56/ometiff-pyramids/pipeline_output/mask/3D_image_stack_mask.ome.tif` + - `https://assets.hubmapconsortium.org/cdb49a41bf77bbdfe7f7b40b360e7f56/anndata-zarr/3D_image_stack_expr-anndata.zarr.zip` + +- Publication (linked to the raw dataset in HuBMAP as publication HBM222.ZBCX.885): Greenbaum, S. et al. "A spatially resolved timeline of the human maternal–fetal interface." *Nature* 619, 595–605 (2023). https://doi.org/10.1038/s41586-023-06298-9 +- HuBMAP consortium: HuBMAP Consortium. "The human body at cellular resolution: the NIH Human Biomolecular Atlas Program." *Nature* 574, 187–192 (2019). https://doi.org/10.1038/s41586-019-1629-x + + +## Data sharing policy +CC-BY 4.0 diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/README.md b/demos/spatialdata-slide-seq-hubmap-kidney/README.md new file mode 100644 index 00000000..d3e6b479 --- /dev/null +++ b/demos/spatialdata-slide-seq-hubmap-kidney/README.md @@ -0,0 +1,16 @@ +# Slide-seq human kidney (HuBMAP HBM537.GVTL.683) + +Slide-seq (Slide-seqV2) spatial transcriptomics of human kidney (right kidney cortex) from HuBMAP. The data is converted to a SpatialData store in which each bead is a circle shape. + +## Data source +Dataset: HuBMAP [HBM537.GVTL.683](https://portal.hubmapconsortium.org/browse/dataset/17fb6d5db17936acc8fb613ce98ab808) (uuid `17fb6d5db17936acc8fb613ce98ab808`), "Slide-seq [Salmon] data from the kidney (right) of a 67-year-old white male", provided by the Broad Institute RTI. HuBMAP processed it with the [salmon-rnaseq](https://github.com/hubmapconsortium/salmon-rnaseq) pipeline. The HuBMAP entity API lists no DOI for this processed dataset. + - Raw (parent) dataset: [HBM874.WGDB.764](https://portal.hubmapconsortium.org/browse/dataset/78921a68236f92d654904844051dd4bb), DOI [10.35079/HBM874.WGDB.764](https://doi.org/10.35079/HBM874.WGDB.764). It holds "19 Slide-seq arrays of the right kidney cortex from donor UCSD0020". The listed contributors are Evan Macosko, Fei Chen, Evan Murray, Jilong Li, Karol Balderrama and Jonah Langlieb (Broad Institute). This raw sequencing dataset is **protected** (controlled access) in HuBMAP. This demo uses only the public processed output. +- File downloaded by this pipeline (about 456 MB): + - `https://assets.hubmapconsortium.org/17fb6d5db17936acc8fb613ce98ab808/secondary_analysis.h5ad` + +- Publication: HuBMAP lists no primary publication for this dataset. It is linked to HuBMAP Human Reference Atlas papers, for example [10.1038/s41597-025-05183-6](https://doi.org/10.1038/s41597-025-05183-6). The Slide-seqV2 method is described in Stickels, R.R. et al. "Highly sensitive spatial transcriptomics at near-cellular resolution with Slide-seqV2." *Nature Biotechnology* 39, 313–319 (2021). https://doi.org/10.1038/s41587-020-0739-1 +- HuBMAP consortium: HuBMAP Consortium. "The human body at cellular resolution: the NIH Human Biomolecular Atlas Program." *Nature* 574, 187–192 (2019). https://doi.org/10.1038/s41586-019-1629-x + + +## Data sharing policy +CC-BY 4.0 diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/README.md b/demos/spatialdata-spatial-atac-rna-mouse-brain/README.md new file mode 100644 index 00000000..abfbe344 --- /dev/null +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/README.md @@ -0,0 +1,19 @@ +# Spatial ATAC-RNA-seq of mouse brain (Zhang et al., 2023) + +Spatial ATAC-RNA-seq, a DBiT-seq-based method that co-profiles chromatin accessibility and gene expression in the same 20 µm pixels (50 x 50 grid), on a postnatal day 21 (P21) mouse brain section. + +## Data source +Dataset: GEO SuperSeries [GSE205055](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE205055), "Spatial epigenome-transcriptome co-profiling of mammalian tissues", provided by NCBI GEO. Samples used: + - [GSM6204623](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM6204623) (`MouseBrain_20um`, ATAC SubSeries GSE205052): ATAC fragments (mm10) and the Space Ranger-style `spatial/` folder. + - [GSM6204636](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM6204636) (`MouseBrain 20um`, RNA SubSeries GSE205054): RNA count matrix (genes x pixels). +- The gene annotation for ATAC gene activity comes from GENCODE mouse release M25 (GRCm38/mm10), basic annotation: https://www.gencodegenes.org/mouse/release_M25.html +- Files downloaded by this pipeline: + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM6204nnn/GSM6204623/suppl/GSM6204623_MouseBrain_20um_fragments.tsv.gz` + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM6204nnn/GSM6204623/suppl/GSM6204623_MouseBrain_20um_spatial.tar.gz` + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM6204nnn/GSM6204636/suppl/GSM6204636_MouseBrain_20um_matrix.tsv.gz` + - `https://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_mouse/release_M25/gencode.vM25.basic.annotation.gtf.gz` +- Publication: Zhang D, Deng Y, Kukanja P, Agirre E, et al. "Spatial epigenome–transcriptome co-profiling of mammalian tissues." *Nature* 616(7955):113–122 (2023). https://doi.org/10.1038/s41586-023-05795-1 + + +## Processing +The following MIT-licensed repo was used as a reference for the processing code here: https://github.com/MicTott/spatialscape-examples/tree/main/spatial-atac-rna-mouse-brain. diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/README.md b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/README.md new file mode 100644 index 00000000..a5bb02a3 --- /dev/null +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/README.md @@ -0,0 +1,13 @@ +# Spatial CUT&Tag-RNA-seq of mouse brain, H3K27me3 (Zhang et al., 2023) + +Spatial CUT&Tag-RNA-seq, a DBiT-based method, on a postnatal day 22 (P22) mouse brain section. It co-profiles the histone mark H3K27me3 and the transcriptome in the same 20 µm pixels (100 x 100 barcodes). + +## Data source +Dataset: GEO SuperSeries [GSE205055](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE205055), "Spatial epigenome-transcriptome co-profiling of mammalian tissues", provided by NCBI GEO. Samples used: + - [GSM6704978](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM6704978) ("MouseBrain, 20um, 100barcodes, H3K27me3", SubSeries GSE217091): CUT&Tag fragments (mm10). The antibody is H3K27me3 (Cell Signaling Technology, 9733). + - [GSM6753044](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM6753044) ("MouseBrain_20um_100barcodes_H3K27me3", SubSeries GSE218593): RNA count matrix (genes x pixels) and a Space Ranger-style `spatial/` folder. +- Files downloaded by this pipeline: + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM6704nnn/GSM6704978/suppl/GSM6704978_MouseBrain_20um_100barcodes_H3K27me3_fragments.tsv.gz` (about 1.2 GB) + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM6753nnn/GSM6753044/suppl/GSM6753044_MouseBrain_20um_100barcodes_H3K27me3_matrix.tsv.gz` + - `https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM6753nnn/GSM6753044/suppl/GSM6753044_MouseBrain_20um_100barcodes_H3K27me3_spatial.tar.gz` +- Publication: Zhang D, Deng Y, Kukanja P, Agirre E, et al. "Spatial epigenome–transcriptome co-profiling of mammalian tissues." *Nature* 616(7955):113–122 (2023). https://doi.org/10.1038/s41586-023-05795-1 diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile index 3eb410b6..677d46cb 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile @@ -14,7 +14,7 @@ OUTPUTS = load_demo_outputs(DEMO_DIR) # Publication: Zhang D, Deng Y, Kukanja P, et al. "Spatial epigenome-transcriptome co-profiling of # mammalian tissues". Nature 616:113-122 (2023). https://doi.org/10.1038/s41586-023-05795-1 # Data: GEO superseries GSE205055 (https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE205055), -# public domain (NCBI GEO). +# Data use: see the NCBI GEO disclaimer (https://www.ncbi.nlm.nih.gov/geo/info/disclaimer.html); submitters may claim IP rights. # - GSM6704978 "MouseBrain, 20um, 100barcodes, H3K27me3": CUT&Tag fragments (cellranger-atac format, mm10). # https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM6704978 # - GSM6753044 "MouseBrain_20um_100barcodes_H3K27me3": RNA count matrix (genes x pixels) and a diff --git a/demos/spatialdata-stellaromics-pyxa-small/README.md b/demos/spatialdata-stellaromics-pyxa-small/README.md new file mode 100644 index 00000000..2b92ec49 --- /dev/null +++ b/demos/spatialdata-stellaromics-pyxa-small/README.md @@ -0,0 +1,15 @@ +# Stellaromics Pyxa (small demo region) + +3D in situ spatial transcriptomics from the Stellaromics Pyxa platform: the `small/` demo region, about 1310 x 443 x 130 µm, with 4,372 cells and 395,667 transcripts. + +## Data source +Dataset: Stellaromics Pyxa demo dataset (`small/` folder, the "full demo region"), provided by Stellaromics on Hugging Face. https://huggingface.co/datasets/Stellaromics/demo +- Files downloaded by this pipeline (~290 MB, not gated): + - https://huggingface.co/datasets/Stellaromics/demo/resolve/main/small/cell_assigned_gene_v1.csv + - https://huggingface.co/datasets/Stellaromics/demo/resolve/main/small/cell_by_gene_v1.csv + - https://huggingface.co/datasets/Stellaromics/demo/resolve/main/small/cell_metadata_v1.csv + - https://huggingface.co/datasets/Stellaromics/demo/resolve/main/small/segmentation_geometries_v1.parquet + - https://huggingface.co/datasets/Stellaromics/demo/resolve/main/small/mosaic_3d.ome.zarr.zip (multiscale DAPI, OME-Zarr v0.5, zipped) + +## Data sharing policy +BSD 3-Clause diff --git a/demos/spatialdata-visium-hd-3.0.0/README.md b/demos/spatialdata-visium-hd-3.0.0/README.md new file mode 100644 index 00000000..406d9a39 --- /dev/null +++ b/demos/spatialdata-visium-hd-3.0.0/README.md @@ -0,0 +1,13 @@ +# Visium HD mouse small intestine, Space Ranger 3.0.0 (SpatialData sandbox) + +10x Genomics Visium HD spatial gene expression of an FFPE mouse small intestine (Swiss roll), stored as a SpatialData Zarr store. + +## Data source +Dataset: "Visium HD Spatial Gene Expression Library, Mouse Small Intestine (FFPE)", provided by 10x Genomics (Space Ranger 3.0.0, published 2024-03-25). https://www.10xgenomics.com/datasets/visium-hd-cytassist-gene-expression-libraries-of-mouse-intestine +- Files downloaded by this pipeline: + - `https://exampledata.scverse.org/spatialdata/spatialdata-sandbox/visium_hd_3.0.0_io_spatialdata_0.7.1.zip` (~2.4 GB) +- Publication: none is associated with this dataset. +- Mirror: the [scverse SpatialData sandbox](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html) (dataset `visium_hd_3.0.0_io`). + +## Data sharing policy +CC BY 4.0 diff --git a/demos/spatialdata-visium-hd-4.0.1/README.md b/demos/spatialdata-visium-hd-4.0.1/README.md new file mode 100644 index 00000000..bd878d3a --- /dev/null +++ b/demos/spatialdata-visium-hd-4.0.1/README.md @@ -0,0 +1,13 @@ +# Visium HD 3' mouse brain, Space Ranger 4.0.1 (SpatialData sandbox) + +10x Genomics Visium HD 3' spatial gene expression of a fresh frozen mouse brain section, stored as a SpatialData Zarr store. + +## Data source +Dataset: "Visium HD 3' Gene Expression Library, Mouse Brain (Fresh Frozen)", provided by 10x Genomics (Space Ranger 4.0.1, published 2025-07-24). https://www.10xgenomics.com/datasets/visium-hd-three-prime-mouse-brain-fresh-frozen +- Files downloaded by this pipeline: + - `https://exampledata.scverse.org/spatialdata/spatialdata-sandbox/visium_hd_4.0.1_io_spatialdata_0.7.1.zip` (~180 MB) +- Publication: none is associated with this dataset. +- Mirror: the [scverse SpatialData sandbox](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html) (dataset `visium_hd_4.0.1_io`). + +## Data sharing policy +CC BY 4.0 diff --git a/demos/spatialdata-visium/README.md b/demos/spatialdata-visium/README.md new file mode 100644 index 00000000..0c13126f --- /dev/null +++ b/demos/spatialdata-visium/README.md @@ -0,0 +1,12 @@ +# Visium mouse brain (SpatialData sandbox) + +10x Genomics Visium spatial gene expression of two adult mouse brain sections (ST8059048 and ST8059050), stored as a SpatialData Zarr store. + +## Data source +Dataset: "10X Visium spatial RNA-seq from adult mouse brain sections paired to single-nucleus RNA-seq", ArrayExpress/BioStudies accession [E-MTAB-11114](https://www.ebi.ac.uk/biostudies/arrayexpress/studies/E-MTAB-11114), deposited by the cell2location authors (Wellcome Sanger Institute). This is not a 10x Genomics demo dataset. +- Files downloaded by this pipeline: + - `https://exampledata.scverse.org/spatialdata/spatialdata-sandbox/visium_spatialdata_0.7.1.zip` (~68 MB) +- Publication: SpatialData: Marconato, L., Palla, G., Yamauchi, K. A., et al. "SpatialData: an open and universal data framework for spatial omics." *Nature Methods* 22, 58–62 (2025). [doi:10.1038/s41592-024-02212-x](https://doi.org/10.1038/s41592-024-02212-x) + +## Data sharing policy +CC BY 4.0 diff --git a/demos/spatialdata-xenium-rep1/README.md b/demos/spatialdata-xenium-rep1/README.md new file mode 100644 index 00000000..c6cb4fe4 --- /dev/null +++ b/demos/spatialdata-xenium-rep1/README.md @@ -0,0 +1,13 @@ +# Xenium human breast cancer, replicate 1 (SpatialData sandbox) + +10x Genomics Xenium In Situ data of an FFPE human breast cancer section ("In Situ Sample 1, Replicate 1"), stored as a SpatialData Zarr store. + +## Data source +Dataset: "Xenium FFPE Human Breast Cancer, In Situ Sample 1, Replicate 1" (`Xenium_FFPE_Human_Breast_Cancer_Rep1`), provided by 10x Genomics on the human breast preview dataset page. https://www.10xgenomics.com/products/xenium-in-situ/preview-dataset-human-breast +- Files downloaded by this pipeline: + - `https://exampledata.scverse.org/spatialdata/spatialdata-sandbox/xenium_rep1_io_spatialdata_0.7.1.zip` (~3.6 GB) +- Publication: Janesick, A., Shelansky, R., Gottscho, A. D., Wagner, F., Williams, S. R., Rouault, M., et al. "High resolution mapping of the tumor microenvironment using integrated single-cell, spatial and in situ analysis." *Nature Communications* 14, 8353 (2023). [doi:10.1038/s41467-023-43458-x](https://doi.org/10.1038/s41467-023-43458-x). The raw data are also in GEO under [GSE243280](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE243280). +- Mirror: the [scverse SpatialData sandbox](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html) (dataset `xenium_rep1_io`). + +## Data sharing policy +CC BY 4.0 From 15ec4b19776466cb387210c115b3b5e8c0cb03eb Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:04:37 -0500 Subject: [PATCH 5/9] Use VitessceConfig API to construct the demo configs, rather than writing the JSON directly --- demos/README.md | 20 +- demos/Snakefile | 17 +- demos/anndata-chromium-pbmc/Snakefile | 17 +- .../src/vitessce_config.py | 68 +++ .../vitessce.template.json | 128 +++-- demos/anndata-parse-pbmc/Snakefile | 17 +- .../anndata-parse-pbmc/src/vitessce_config.py | 69 +++ .../anndata-parse-pbmc/vitessce.template.json | 134 ++++-- demos/combat-2022/Snakefile | 16 +- demos/combat-2022/src/vitessce_config.py | 97 ++++ demos/combat-2022/vitessce.template.json | 234 +++++----- demos/create_demo.sh | 61 ++- demos/habib-2017/Snakefile | 16 +- demos/habib-2017/src/vitessce_config.py | 64 +++ demos/habib-2017/vitessce.template.json | 145 +++--- demos/human-lymph-node-10x-visium/Snakefile | 16 +- .../src/vitessce_config.py | 99 ++++ .../vitessce.template.json | 111 +++-- demos/kuppe-2022/Snakefile | 17 +- demos/kuppe-2022/src/vitessce_config.py | 143 ++++++ demos/kuppe-2022/vitessce.template.json | 439 ++++++++++-------- demos/marshall-2022/Snakefile | 17 +- demos/marshall-2022/src/vitessce_config.py | 74 +++ demos/marshall-2022/vitessce.template.json | 178 +++---- demos/meta-2022-azimuth/Snakefile | 17 +- .../meta-2022-azimuth/src/vitessce_config.py | 84 ++++ .../meta-2022-azimuth/vitessce.template.json | 200 ++++---- demos/mudata-cite-seq-pbmc/Snakefile | 17 +- .../src/vitessce_config.py | 87 ++++ .../vitessce.template.json | 251 +++++----- demos/mudata-pbmc-multiome-10x/Snakefile | 17 +- .../src/vitessce_config.py | 88 ++++ .../vitessce.template.json | 78 ++-- demos/mudata-snareseq2-lung-hubmap/Snakefile | 17 +- .../src/vitessce_config.py | 99 ++++ .../vitessce.template.json | 80 ++-- .../Snakefile | 17 +- .../src/vitessce_config.py | 69 +++ demos/spatialdata-atera-kidney/Snakefile | 17 +- .../src/vitessce_config.py | 133 ++++++ .../Snakefile | 17 +- .../src/vitessce_config.py | 91 ++++ .../vitessce.template.json | 27 +- .../Snakefile | 17 +- .../src/vitessce_config.py | 124 +++++ .../vitessce.template.json | 28 +- demos/spatialdata-cosmx-nsclc/Snakefile | 17 +- .../src/vitessce_config.py | 106 +++++ .../vitessce.template.json | 14 +- .../Snakefile | 17 +- .../src/vitessce_config.py | 120 +++++ .../vitessce.template.json | 103 ++-- .../spatialdata-geomx-mouse-embryo/Snakefile | 17 +- .../src/vitessce_config.py | 113 +++++ .../vitessce.template.json | 21 +- .../Snakefile | 17 +- .../src/vitessce_config.py | 87 ++++ .../vitessce.template.json | 14 +- .../Snakefile | 17 +- .../src/vitessce_config.py | 95 ++++ .../vitessce.template.json | 58 +-- .../Snakefile | 17 +- .../src/vitessce_config.py | 78 ++++ .../vitessce.template.json | 26 +- .../Snakefile | 17 +- .../src/vitessce_config.py | 126 +++++ .../spatialdata-mibi-hubmap-uterus/Snakefile | 17 +- .../src/vitessce_config.py | 124 +++++ .../vitessce.template.json | 28 +- .../Snakefile | 17 +- .../src/vitessce_config.py | 79 ++++ .../vitessce.template.json | 27 +- .../Snakefile | 17 +- .../src/vitessce_config.py | 123 +++++ .../vitessce.template.json | 108 +++-- .../Snakefile | 17 +- .../src/vitessce_config.py | 125 +++++ .../vitessce.template.json | 114 +++-- .../Snakefile | 17 +- .../src/vitessce_config.py | 98 ++++ .../vitessce.template.json | 67 +-- demos/spatialdata-visium-hd-3.0.0/Snakefile | 17 +- .../src/vitessce_config.py | 79 ++++ demos/spatialdata-visium-hd-4.0.1/Snakefile | 17 +- .../src/vitessce_config.py | 76 +++ demos/spatialdata-visium/Snakefile | 17 +- .../spatialdata-visium/src/vitessce_config.py | 75 +++ demos/spatialdata-xenium-rep1/Snakefile | 17 +- .../src/vitessce_config.py | 85 ++++ 89 files changed, 5002 insertions(+), 1211 deletions(-) create mode 100644 demos/anndata-chromium-pbmc/src/vitessce_config.py create mode 100644 demos/anndata-parse-pbmc/src/vitessce_config.py create mode 100644 demos/combat-2022/src/vitessce_config.py create mode 100644 demos/habib-2017/src/vitessce_config.py create mode 100644 demos/human-lymph-node-10x-visium/src/vitessce_config.py create mode 100644 demos/kuppe-2022/src/vitessce_config.py create mode 100644 demos/marshall-2022/src/vitessce_config.py create mode 100644 demos/meta-2022-azimuth/src/vitessce_config.py create mode 100644 demos/mudata-cite-seq-pbmc/src/vitessce_config.py create mode 100644 demos/mudata-pbmc-multiome-10x/src/vitessce_config.py create mode 100644 demos/mudata-snareseq2-lung-hubmap/src/vitessce_config.py create mode 100644 demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py create mode 100644 demos/spatialdata-atera-kidney/src/vitessce_config.py create mode 100644 demos/spatialdata-aviti24-teton-hela-tnfa/src/vitessce_config.py create mode 100644 demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py create mode 100644 demos/spatialdata-cosmx-nsclc/src/vitessce_config.py create mode 100644 demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py create mode 100644 demos/spatialdata-geomx-mouse-embryo/src/vitessce_config.py create mode 100644 demos/spatialdata-illumina-stratamap-mouse-kidney/src/vitessce_config.py create mode 100644 demos/spatialdata-maldi-msi-timstof-mouse-brain/src/vitessce_config.py create mode 100644 demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py create mode 100644 demos/spatialdata-merscope-mouse-brain/src/vitessce_config.py create mode 100644 demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py create mode 100644 demos/spatialdata-slide-seq-hubmap-kidney/src/vitessce_config.py create mode 100644 demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py create mode 100644 demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py create mode 100644 demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py create mode 100644 demos/spatialdata-visium-hd-3.0.0/src/vitessce_config.py create mode 100644 demos/spatialdata-visium-hd-4.0.1/src/vitessce_config.py create mode 100644 demos/spatialdata-visium/src/vitessce_config.py create mode 100644 demos/spatialdata-xenium-rep1/src/vitessce_config.py diff --git a/demos/README.md b/demos/README.md index 87108aac..b55ec59f 100644 --- a/demos/README.md +++ b/demos/README.md @@ -58,7 +58,8 @@ Then, - Specify the output filenames in the `output` list in `./{new_demo_dir}/config.yml` - Fill in the Snakefile in `./{new_demo_dir}/Snakefile` - Write the processing script(s) in `./{new_demo_dir}/src/`, declaring their dependencies in the PEP 723 `# /// script` block, and call them from rules via `uv run --script {params.script}` -- Write a test Vitessce configuration in `./{new_demo_dir}/vitessce.template.json` +- Write a `./{new_demo_dir}/README.md` describing the data source (with citations/links) and the dataset's data sharing policy +- Build the Vitessce configuration in `./{new_demo_dir}/src/vitessce_config.py` using the `VitessceConfig` and wrapper class (e.g., `AnnDataWrapper`, `SpatialDataWrapper`) APIs. The demo Snakefile's `vitessce_config` rule runs it to generate `vitessce.template.json` (see below). Do not write `vitessce.template.json` by hand. - Test the demo by running the Vitessce frontend locally and navigating to `http://localhost:3000/?url=http://localhost:8000/{new_demo_dir}/vitessce.json` See existing demo Snakefiles and scripts for examples. @@ -70,17 +71,26 @@ Note that the name of `new_demo_dir` should match the intended key in `https://g ### Render all Vitessce config templates -To use the same configuration for both development (with localhost file URLs) and production/testing (with AWS/GCP file URLs), we write them as Jinja2 templates in the `vitessce.template.json` files where `{{ base_url }}` and `{{ base_url_gcp }}` are replaced at template render time. +To use the same configuration for both development (with localhost file URLs) and production/testing (with AWS/GCP file URLs), each demo's configuration is a Jinja2 template, `vitessce.template.json`, where `{{ base_url }}` and `{{ base_url_gcp }}` are replaced at template render time. -We can render the template to `vitessce.local.json` and `vitessce.remote.json` using the following commands: +The template is not written by hand. Each demo's `src/vitessce_config.py` builds it with the `VitessceConfig` and wrapper class APIs, passing file URLs such as `sdata_url="{{ base_url }}/my.spatialdata.zarr"` to the wrappers (use `{{ base_url_gcp }}` for `.ome.zarr` outputs, which are uploaded to GCS). Each demo Snakefile has a `vitessce_config` rule that runs this script to write `vitessce.template.json`, and the demo's `all` rule depends on it. See `./spatialdata-xenium-rep1/src/vitessce_config.py` for an example. + +We can generate every template (via each demo's `vitessce_config` rule) and render it to `vitessce.local.json` and `vitessce.remote.json` using the following command: ```sh uv run snakemake fill_templates -j 1 ``` -Be sure to re-run after making changes to `vitessce.template.json`. +Templates are regenerated automatically when `src/vitessce_config.py` changes. + +#### Generate and render an individual template + +Template (from within the demo directory): -#### Render an individual template +```sh +cd habib-2017 +uv run snakemake -j 1 vitessce.template.json +``` Local: diff --git a/demos/Snakefile b/demos/Snakefile index 9f67f9f1..275e781a 100644 --- a/demos/Snakefile +++ b/demos/Snakefile @@ -288,17 +288,22 @@ rule all: shell(f"echo \"{in_file} gs://{out_file}\"") +# Render each demo's vitessce.template.json to vitessce.local.json and vitessce.remote.json. +# The templates are generated by each demo module's `vitessce_config` rule +# (which runs the demo's src/vitessce_config.py). rule fill_templates: - params: - demo_dirs=[ - demo_dir + input: + templates=[ + os.path.join(demo_dir, "vitessce.template.json") for demo_dir in DEMO_DIRS + MANUAL_DEMO_DIRS - if os.path.exists(os.path.join(demo_dir, "vitessce.template.json")) - ], + ] + params: version=BUCKET_VERSION shell: ''' - for demo_dir in {params.demo_dirs}; do + set -e + for template in {input.templates}; do + demo_dir=$(dirname "$template") uv run --script fill_template.py -d "$demo_dir" -t local > "$demo_dir/vitessce.local.json" uv run --script fill_template.py -d "$demo_dir" -t remote -v {params.version} > "$demo_dir/vitessce.remote.json" done diff --git a/demos/anndata-chromium-pbmc/Snakefile b/demos/anndata-chromium-pbmc/Snakefile index bc9e1de7..fd774a88 100644 --- a/demos/anndata-chromium-pbmc/Snakefile +++ b/demos/anndata-chromium-pbmc/Snakefile @@ -19,7 +19,8 @@ H5_URL = "https://cf.10xgenomics.com/samples/cell-exp/4.0.0/Parent_NGSC3_DI_PBMC rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # QC, normalize, HVG, PCA, UMAP, Leiden, marker genes, then write AnnData-Zarr. rule process: @@ -46,3 +47,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/anndata-chromium-pbmc/src/vitessce_config.py b/demos/anndata-chromium-pbmc/src/vitessce_config.py new file mode 100644 index 00000000..9afd3b1e --- /dev/null +++ b/demos/anndata-chromium-pbmc/src/vitessce_config.py @@ -0,0 +1,68 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="10x Chromium PBMCs from a Healthy Donor", + description=( + "10x Genomics Chromium single-cell gene expression (3' v3.1) of ~10k PBMCs from a healthy donor. " + "Processed with Scanpy (QC, normalization, HVG, PCA, UMAP, Leiden clustering, marker genes)." + ), + ) + dataset = vc.add_dataset(name="Chromium PBMC", uid="chromium-pbmc").add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/chromium_pbmc_healthy_donor.h5ad.zarr", + obs_feature_matrix_path="X", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["UMAP"], + obs_set_paths=["obs/leiden"], + obs_set_names=["Leiden Cluster"], + coordination_values={ + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression", + }, + )) + + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=5, h=6) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=5, y=0, w=3, h=3) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=0, w=4, h=3) + feature_list = vc.add_view("featureList", dataset=dataset, x=5, y=3, w=3, h=3) + violin = vc.add_view("obsSetFeatureValueDistribution", dataset=dataset, x=8, y=3, w=4, h=3) + heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=9, h=4).set_props(transpose=True) + vc.add_view("description", dataset=dataset, x=9, y=6, w=3, h=4) + + vc.link_views([scatterplot, obs_sets, obs_set_sizes, violin, heatmap], ["obsType"], ["cell"]) + vc.link_views([scatterplot, feature_list, violin, heatmap], ["featureType"], ["gene"]) + vc.link_views([scatterplot, violin, heatmap], ["featureValueType"], ["expression"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/anndata-chromium-pbmc/vitessce.template.json b/demos/anndata-chromium-pbmc/vitessce.template.json index cf8755c0..b578d617 100644 --- a/demos/anndata-chromium-pbmc/vitessce.template.json +++ b/demos/anndata-chromium-pbmc/vitessce.template.json @@ -2,36 +2,50 @@ "version": "1.0.15", "name": "10x Chromium PBMCs from a Healthy Donor", "description": "10x Genomics Chromium single-cell gene expression (3' v3.1) of ~10k PBMCs from a healthy donor. Processed with Scanpy (QC, normalization, HVG, PCA, UMAP, Leiden clustering, marker genes).", - "datasets": [{ - "uid": "chromium-pbmc", - "name": "Chromium PBMC", - "files": [{ - "fileType": "anndata.zarr", - "url": "{{ base_url }}/chromium_pbmc_healthy_donor.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression", - "embeddingType": "UMAP" - }, - "options": { - "obsFeatureMatrix": { - "path": "X" - }, - "obsEmbedding": { - "path": "obsm/X_umap" - }, - "obsSets": [{ - "name": "Leiden Cluster", - "path": "obs/leiden" - }] - } - }] - }], - "initStrategy": "auto", + "datasets": [ + { + "uid": "chromium-pbmc", + "name": "Chromium PBMC", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/chromium_pbmc_healthy_donor.h5ad.zarr", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ], + "obsSets": [ + { + "name": "Leiden Cluster", + "path": "obs/leiden" + } + ], + "obsFeatureMatrix": { + "path": "X" + } + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression" + } + } + ] + } + ], "coordinationSpace": { + "dataset": { + "A": "chromium-pbmc" + }, "embeddingType": { - "UMAP": "UMAP" + "A": "UMAP" }, "obsType": { "A": "cell" @@ -46,66 +60,90 @@ "layout": [ { "component": "scatterplot", - "h": 6, "w": 5, "x": 0, "y": 0, "coordinationScopes": { - "embeddingType": "UMAP", + "dataset": "A", + "embeddingType": "A", "obsType": "A", "featureType": "A", "featureValueType": "A" }, - "uid": "A" + "x": 0, + "y": 0, + "w": 5, + "h": 6 }, { "component": "obsSets", - "h": 3, "w": 3, "x": 5, "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "B" + "x": 5, + "y": 0, + "w": 3, + "h": 3 }, { "component": "obsSetSizes", - "h": 3, "w": 4, "x": 8, "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "C" + "x": 8, + "y": 0, + "w": 4, + "h": 3 }, { "component": "featureList", - "h": 3, "w": 3, "x": 5, "y": 3, "coordinationScopes": { + "dataset": "A", "featureType": "A" }, - "uid": "D" + "x": 5, + "y": 3, + "w": 3, + "h": 3 }, { "component": "obsSetFeatureValueDistribution", - "h": 3, "w": 4, "x": 8, "y": 3, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A", "featureValueType": "A" }, - "uid": "E" + "x": 8, + "y": 3, + "w": 4, + "h": 3 }, { "component": "heatmap", - "h": 4, "w": 9, "x": 0, "y": 6, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A", "featureValueType": "A" }, + "x": 0, + "y": 6, + "w": 9, + "h": 4, "props": { "transpose": true - }, - "uid": "F" + } }, { "component": "description", - "h": 4, "w": 3, "x": 9, "y": 6, - "uid": "G" + "coordinationScopes": { + "dataset": "A" + }, + "x": 9, + "y": 6, + "w": 3, + "h": 4 } - ] + ], + "initStrategy": "auto" } diff --git a/demos/anndata-parse-pbmc/Snakefile b/demos/anndata-parse-pbmc/Snakefile index 2c75c685..f4590db9 100644 --- a/demos/anndata-parse-pbmc/Snakefile +++ b/demos/anndata-parse-pbmc/Snakefile @@ -21,7 +21,8 @@ RAW_FILES = ["DGE.mtx", "all_genes.csv", "cell_metadata.csv"] rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # QC, normalize, HVG, PCA, UMAP, Leiden, marker genes, then write AnnData-Zarr. rule process: @@ -54,3 +55,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/anndata-parse-pbmc/src/vitessce_config.py b/demos/anndata-parse-pbmc/src/vitessce_config.py new file mode 100644 index 00000000..d6a0a34b --- /dev/null +++ b/demos/anndata-parse-pbmc/src/vitessce_config.py @@ -0,0 +1,69 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="Parse Biosciences Evercode WT PBMCs", + description=( + "Parse Biosciences Evercode Whole Transcriptome (WT v1, split-pool combinatorial barcoding) " + "of ~10k PBMCs from four healthy donors. " + "Processed with Scanpy (QC, normalization, HVG, PCA, UMAP, Leiden clustering, marker genes)." + ), + ) + dataset = vc.add_dataset(name="Parse PBMC", uid="parse-pbmc").add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/parse_pbmc_wt_v1.h5ad.zarr", + obs_feature_matrix_path="X", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["UMAP"], + obs_set_paths=["obs/leiden", "obs/sample"], + obs_set_names=["Leiden Cluster", "Donor"], + coordination_values={ + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression", + }, + )) + + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=5, h=6) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=5, y=0, w=3, h=3) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=0, w=4, h=3) + feature_list = vc.add_view("featureList", dataset=dataset, x=5, y=3, w=3, h=3) + violin = vc.add_view("obsSetFeatureValueDistribution", dataset=dataset, x=8, y=3, w=4, h=3) + heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=9, h=4).set_props(transpose=True) + vc.add_view("description", dataset=dataset, x=9, y=6, w=3, h=4) + + vc.link_views([scatterplot, obs_sets, obs_set_sizes, violin, heatmap], ["obsType"], ["cell"]) + vc.link_views([scatterplot, feature_list, violin, heatmap], ["featureType"], ["gene"]) + vc.link_views([scatterplot, violin, heatmap], ["featureValueType"], ["expression"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/anndata-parse-pbmc/vitessce.template.json b/demos/anndata-parse-pbmc/vitessce.template.json index 91faae13..8a6e3037 100644 --- a/demos/anndata-parse-pbmc/vitessce.template.json +++ b/demos/anndata-parse-pbmc/vitessce.template.json @@ -2,42 +2,54 @@ "version": "1.0.15", "name": "Parse Biosciences Evercode WT PBMCs", "description": "Parse Biosciences Evercode Whole Transcriptome (WT v1, split-pool combinatorial barcoding) of ~10k PBMCs from four healthy donors. Processed with Scanpy (QC, normalization, HVG, PCA, UMAP, Leiden clustering, marker genes).", - "datasets": [{ - "uid": "parse-pbmc", - "name": "Parse PBMC", - "files": [{ - "fileType": "anndata.zarr", - "url": "{{ base_url }}/parse_pbmc_wt_v1.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression", - "embeddingType": "UMAP" - }, - "options": { - "obsFeatureMatrix": { - "path": "X" - }, - "obsEmbedding": { - "path": "obsm/X_umap" - }, - "obsSets": [ - { - "name": "Leiden Cluster", - "path": "obs/leiden" + "datasets": [ + { + "uid": "parse-pbmc", + "name": "Parse PBMC", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/parse_pbmc_wt_v1.h5ad.zarr", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ], + "obsSets": [ + { + "name": "Leiden Cluster", + "path": "obs/leiden" + }, + { + "name": "Donor", + "path": "obs/sample" + } + ], + "obsFeatureMatrix": { + "path": "X" + } }, - { - "name": "Donor", - "path": "obs/sample" + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression" } - ] - } - }] - }], - "initStrategy": "auto", + } + ] + } + ], "coordinationSpace": { + "dataset": { + "A": "parse-pbmc" + }, "embeddingType": { - "UMAP": "UMAP" + "A": "UMAP" }, "obsType": { "A": "cell" @@ -52,66 +64,90 @@ "layout": [ { "component": "scatterplot", - "h": 6, "w": 5, "x": 0, "y": 0, "coordinationScopes": { - "embeddingType": "UMAP", + "dataset": "A", + "embeddingType": "A", "obsType": "A", "featureType": "A", "featureValueType": "A" }, - "uid": "A" + "x": 0, + "y": 0, + "w": 5, + "h": 6 }, { "component": "obsSets", - "h": 3, "w": 3, "x": 5, "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "B" + "x": 5, + "y": 0, + "w": 3, + "h": 3 }, { "component": "obsSetSizes", - "h": 3, "w": 4, "x": 8, "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "C" + "x": 8, + "y": 0, + "w": 4, + "h": 3 }, { "component": "featureList", - "h": 3, "w": 3, "x": 5, "y": 3, "coordinationScopes": { + "dataset": "A", "featureType": "A" }, - "uid": "D" + "x": 5, + "y": 3, + "w": 3, + "h": 3 }, { "component": "obsSetFeatureValueDistribution", - "h": 3, "w": 4, "x": 8, "y": 3, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A", "featureValueType": "A" }, - "uid": "E" + "x": 8, + "y": 3, + "w": 4, + "h": 3 }, { "component": "heatmap", - "h": 4, "w": 9, "x": 0, "y": 6, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A", "featureValueType": "A" }, + "x": 0, + "y": 6, + "w": 9, + "h": 4, "props": { "transpose": true - }, - "uid": "F" + } }, { "component": "description", - "h": 4, "w": 3, "x": 9, "y": 6, - "uid": "G" + "coordinationScopes": { + "dataset": "A" + }, + "x": 9, + "y": 6, + "w": 3, + "h": 4 } - ] + ], + "initStrategy": "auto" } diff --git a/demos/combat-2022/Snakefile b/demos/combat-2022/Snakefile index d55be363..d324185e 100644 --- a/demos/combat-2022/Snakefile +++ b/demos/combat-2022/Snakefile @@ -13,7 +13,8 @@ H5AD_URL = "https://zenodo.org/record/6120249/files/COMBAT-CITESeq-EXPRESSION-AT rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Convert the raw AnnData .h5ad file to a processed AnnData .zarr store. rule convert_to_zarr: @@ -41,3 +42,16 @@ rule download_data: curl -L --retry 999 --retry-delay 3 -C - -o {output} {params.file_url} ''' +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/combat-2022/src/vitessce_config.py b/demos/combat-2022/src/vitessce_config.py new file mode 100644 index 00000000..8ed04116 --- /dev/null +++ b/demos/combat-2022/src/vitessce_config.py @@ -0,0 +1,97 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper + +BASE_URL = "{{ base_url }}" +ADATA_URL = f"{BASE_URL}/combat_2022_cell.h5ad.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="COMBAT Consortium, 2022 Cell", + description="COVID-19 Multi-omic Blood Atlas", + ) + dataset = vc.add_dataset(name="CITE-Seq", uid="a") + # Gene expression, UMAP, and cell sets. + dataset.add_object(AnnDataWrapper( + adata_url=ADATA_URL, + obs_feature_matrix_path="obsm/X_gene_expression_uint8", + feature_filter_path="var/is_gene_expression", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["UMAP"], + obs_set_paths=["obs/cell_type", "obs/Source"], + obs_set_names=["Cell Type", "Source"], + coordination_values={ + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression", + }, + )) + # Antibody capture (surface protein). + dataset.add_object(AnnDataWrapper( + adata_url=ADATA_URL, + obs_feature_matrix_path="obsm/X_antibody_capture_uint8", + feature_filter_path="var/is_antibody_capture", + coordination_values={ + "obsType": "cell", + "featureType": "antibody", + "featureValueType": "capture", + }, + )) + + obs_sets = vc.add_view("obsSets", dataset=dataset, x=7, y=0, w=3, h=4) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=7, y=4, w=5, h=4) + gene_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=4, h=4) + antibody_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=4, w=4, h=4) + vc.add_view("description", dataset=dataset, x=10, y=0, w=2, h=4) + gene_list = vc.add_view("featureList", dataset=dataset, x=4, y=0, w=3, h=4) + antibody_list = vc.add_view("featureList", dataset=dataset, x=4, y=4, w=3, h=4) + + # Both scatterplots share the same embedding, camera, and obsType. + vc.link_views( + [gene_scatterplot, antibody_scatterplot], + ["embeddingType", "embeddingZoom", "embeddingTargetX", "embeddingTargetY", "embeddingObsSetLabelsVisible"], + ["UMAP", None, None, None, True], + ) + vc.link_views([obs_sets, obs_set_sizes, gene_scatterplot, antibody_scatterplot, gene_list, antibody_list], ["obsType"], ["cell"]) + # One feature type (with its own selection and color encoding) per scatterplot/feature list pair. + vc.link_views( + [gene_scatterplot, gene_list], + ["featureType", "obsColorEncoding", "featureSelection"], + ["gene", "cellSetSelection", None], + ) + vc.link_views( + [antibody_scatterplot, antibody_list], + ["featureType", "obsColorEncoding", "featureSelection"], + ["antibody", "cellSetSelection", None], + ) + vc.link_views([gene_scatterplot], ["featureValueType", "featureValueColormapRange"], ["expression", [0, 0.05]]) + vc.link_views([antibody_scatterplot], ["featureValueType", "featureValueColormapRange"], ["capture", [0, 0.05]]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/combat-2022/vitessce.template.json b/demos/combat-2022/vitessce.template.json index 4cb8107d..3489f9f7 100644 --- a/demos/combat-2022/vitessce.template.json +++ b/demos/combat-2022/vitessce.template.json @@ -2,70 +2,70 @@ "version": "1.0.15", "name": "COMBAT Consortium, 2022 Cell", "description": "COVID-19 Multi-omic Blood Atlas", - "datasets": [{ - "uid": "a", - "name": "CITE-Seq", - "files": [ - { - "fileType": "obsEmbedding.anndata.zarr", - "url": "{{ base_url }}/combat_2022_cell.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "embeddingType": "UMAP" - }, - "options": { - "path": "obsm/X_umap" - } - }, - { - "fileType": "obsSets.anndata.zarr", - "url": "{{ base_url }}/combat_2022_cell.h5ad.zarr", - "coordinationValues": { - "obsType": "cell" - }, - "options": [ - { - "name": "Cell Type", - "path": "obs/cell_type" + "datasets": [ + { + "uid": "a", + "name": "CITE-Seq", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/combat_2022_cell.h5ad.zarr", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ], + "obsSets": [ + { + "name": "Cell Type", + "path": "obs/cell_type" + }, + { + "name": "Source", + "path": "obs/Source" + } + ], + "obsFeatureMatrix": { + "path": "obsm/X_gene_expression_uint8", + "featureFilterPath": "var/is_gene_expression" + } }, - { - "name": "Source", - "path": "obs/Source" + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression" } - ] - }, - { - "fileType": "obsFeatureMatrix.anndata.zarr", - "url": "{{ base_url }}/combat_2022_cell.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression" }, - "options": { - "path": "obsm/X_gene_expression_uint8", - "featureFilterPath": "var/is_gene_expression" - } - }, - { - "fileType": "obsFeatureMatrix.anndata.zarr", - "url": "{{ base_url }}/combat_2022_cell.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "antibody", - "featureValueType": "capture" - }, - "options": { - "path": "obsm/X_antibody_capture_uint8", - "featureFilterPath": "var/is_antibody_capture" + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/combat_2022_cell.h5ad.zarr", + "options": { + "obsFeatureMatrix": { + "path": "obsm/X_antibody_capture_uint8", + "featureFilterPath": "var/is_antibody_capture" + } + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "antibody", + "featureValueType": "capture" + } } - } - ] - }], - "initStrategy": "auto", + ] + } + ], "coordinationSpace": { + "dataset": { + "A": "a" + }, "embeddingType": { - "UMAP": "UMAP" + "A": "UMAP" }, "embeddingZoom": { "A": null @@ -86,10 +86,6 @@ "A": "gene", "B": "antibody" }, - "featureValueType": { - "A": "expression", - "B": "capture" - }, "obsColorEncoding": { "A": "cellSetSelection", "B": "cellSetSelection" @@ -98,110 +94,124 @@ "A": null, "B": null }, + "featureValueType": { + "A": "expression", + "B": "capture" + }, "featureValueColormapRange": { - "A": [0, 0.05], - "B": [0, 0.05] + "A": [ + 0, + 0.05 + ], + "B": [ + 0, + 0.05 + ] } }, - "layout": [{ + "layout": [ + { "component": "obsSets", - "h": 4, - "w": 3, - "x": 7, - "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "A" + "x": 7, + "y": 0, + "w": 3, + "h": 4 }, { "component": "obsSetSizes", - "h": 4, - "w": 5, - "x": 7, - "y": 4, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "B" + "x": 7, + "y": 4, + "w": 5, + "h": 4 }, { "component": "scatterplot", - "h": 4, - "w": 4, - "x": 0, - "y": 0, "coordinationScopes": { - "embeddingType": "UMAP", - "obsType": "A", - "featureType": "A", - "featureValueType": "A", - "obsColorEncoding": "A", - "featureSelection": "A", + "dataset": "A", + "embeddingType": "A", "embeddingZoom": "A", "embeddingTargetX": "A", "embeddingTargetY": "A", "embeddingObsSetLabelsVisible": "A", + "obsType": "A", + "featureType": "A", + "obsColorEncoding": "A", + "featureSelection": "A", + "featureValueType": "A", "featureValueColormapRange": "A" }, - "uid": "C" + "x": 0, + "y": 0, + "w": 4, + "h": 4 }, { "component": "scatterplot", - "h": 4, - "w": 4, - "x": 0, - "y": 4, "coordinationScopes": { - "embeddingType": "UMAP", - "obsType": "A", - "featureType": "B", - "featureValueType": "B", - "obsColorEncoding": "B", - "featureSelection": "B", + "dataset": "A", + "embeddingType": "A", "embeddingZoom": "A", "embeddingTargetX": "A", "embeddingTargetY": "A", "embeddingObsSetLabelsVisible": "A", + "obsType": "A", + "featureType": "B", + "obsColorEncoding": "B", + "featureSelection": "B", + "featureValueType": "B", "featureValueColormapRange": "B" }, - "uid": "D" + "x": 0, + "y": 4, + "w": 4, + "h": 4 }, { "component": "description", - "h": 4, - "w": 2, + "coordinationScopes": { + "dataset": "A" + }, "x": 10, "y": 0, - "uid": "E" + "w": 2, + "h": 4 }, { "component": "featureList", - "h": 4, - "w": 3, - "x": 4, - "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A", "obsColorEncoding": "A", "featureSelection": "A" }, - "uid": "F" + "x": 4, + "y": 0, + "w": 3, + "h": 4 }, { "component": "featureList", - "h": 4, - "w": 3, - "x": 4, - "y": 4, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "B", "obsColorEncoding": "B", "featureSelection": "B" }, - "uid": "G" + "x": 4, + "y": 4, + "w": 3, + "h": 4 } - ] -} \ No newline at end of file + ], + "initStrategy": "auto" +} diff --git a/demos/create_demo.sh b/demos/create_demo.sh index 1cc69234..68a8a2c8 100755 --- a/demos/create_demo.sh +++ b/demos/create_demo.sh @@ -12,7 +12,6 @@ DEMO_KEY=${DEMO_DIR//-/_} mkdir "./$DEMO_DIR" mkdir "./$DEMO_DIR/src" -touch "./$DEMO_DIR/vitessce.template.json" cat << 'EOF2' > "./$DEMO_DIR/Snakefile" include: "../common.smk" @@ -25,7 +24,22 @@ OUTPUTS = load_demo_outputs(DEMO_DIR) rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' EOF2 cat << EOF2 > "./$DEMO_DIR/config.yml" @@ -62,6 +76,49 @@ if __name__ == '__main__': convert_h5ad_to_zarr(args.input, args.output) EOF2 +cat << 'EOF2' > "./$DEMO_DIR/src/vitessce_config.py" +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig(schema_version="1.0.18", name="TODO") + dataset = vc.add_dataset(name="TODO").add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/TODO.h5ad.zarr", + obs_feature_matrix_path="X", + )) + vc.layout(vc.add_view("featureList", dataset=dataset)) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + with open(args.output, "w") as f: + json.dump(create_config().to_dict(), f, indent=2) + f.write("\n") +EOF2 + cat << EOF2 Add "$DEMO_DIR" to DEMO_DIRS in the main demos Snakefile, along with: diff --git a/demos/habib-2017/Snakefile b/demos/habib-2017/Snakefile index 1e6ae6d4..155d595e 100644 --- a/demos/habib-2017/Snakefile +++ b/demos/habib-2017/Snakefile @@ -13,7 +13,8 @@ H5AD_URL = "https://covid19.cog.sanger.ac.uk/habib17.processed.h5ad" # Rules rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Convert the raw AnnData .h5ad file to a processed AnnData .zarr store. rule convert_to_zarr: @@ -41,3 +42,16 @@ rule download_data: curl -L -o {output} {params.file_url} ''' +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/habib-2017/src/vitessce_config.py b/demos/habib-2017/src/vitessce_config.py new file mode 100644 index 00000000..a8676592 --- /dev/null +++ b/demos/habib-2017/src/vitessce_config.py @@ -0,0 +1,64 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="Habib et al., 2017 Nature Methods", + description="Archived frozen adult human post-mortem brain tissue profiled by snRNA-seq (DroNc-seq)", + ) + dataset = vc.add_dataset(name="Habib 2017", uid="habib-2017").add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/habib_2017_nature_methods.h5ad.zarr", + obs_feature_matrix_path="layers/X_uint8", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["UMAP"], + obs_set_paths=["obs/CellType"], + obs_set_names=["Cell Type"], + coordination_values={ + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression", + }, + )) + + obs_sets = vc.add_view("obsSets", dataset=dataset, x=4, y=0, w=4, h=4) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=0, w=4, h=4) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=4, h=4) + heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=4, w=8, h=4).set_props(transpose=True) + feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=2, h=4) + vc.add_view("description", dataset=dataset, x=10, y=4, w=2, h=4) + + vc.link_views([obs_sets, obs_set_sizes, scatterplot, heatmap], ["obsType"], ["cell"]) + vc.link_views([scatterplot, heatmap, feature_list], ["featureType"], ["gene"]) + vc.link_views([scatterplot, heatmap], ["featureValueType", "featureValueColormapRange"], ["expression", [0.0, 0.35]]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/habib-2017/vitessce.template.json b/demos/habib-2017/vitessce.template.json index 81d30b71..d56a233a 100644 --- a/demos/habib-2017/vitessce.template.json +++ b/demos/habib-2017/vitessce.template.json @@ -2,36 +2,50 @@ "version": "1.0.15", "name": "Habib et al., 2017 Nature Methods", "description": "Archived frozen adult human post-mortem brain tissue profiled by snRNA-seq (DroNc-seq)", - "datasets": [{ - "uid": "habib-2017", - "name": "Habib 2017", - "files": [{ - "fileType": "anndata.zarr", - "url": "{{ base_url }}/habib_2017_nature_methods.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression", - "embeddingType": "UMAP" - }, - "options": { - "obsFeatureMatrix": { - "path": "layers/X_uint8" - }, - "obsEmbedding": { - "path": "obsm/X_umap" - }, - "obsSets": [{ - "name": "Cell Type", - "path": "obs/CellType" - }] - } - }] - }], - "initStrategy": "auto", + "datasets": [ + { + "uid": "habib-2017", + "name": "Habib 2017", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/habib_2017_nature_methods.h5ad.zarr", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ], + "obsSets": [ + { + "name": "Cell Type", + "path": "obs/CellType" + } + ], + "obsFeatureMatrix": { + "path": "layers/X_uint8" + } + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression" + } + } + ] + } + ], "coordinationSpace": { + "dataset": { + "A": "habib-2017" + }, "embeddingType": { - "UMAP": "UMAP" + "A": "UMAP" }, "obsType": { "A": "cell" @@ -43,81 +57,88 @@ "A": "expression" }, "featureValueColormapRange": { - "A": [0.0, 0.35] + "A": [ + 0.0, + 0.35 + ] } }, - "layout": [{ + "layout": [ + { "component": "obsSets", - "h": 4, - "w": 4, - "x": 4, - "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "A" + "x": 4, + "y": 0, + "w": 4, + "h": 4 }, { "component": "obsSetSizes", - "h": 4, - "w": 4, - "x": 8, - "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "B" + "x": 8, + "y": 0, + "w": 4, + "h": 4 }, { "component": "scatterplot", - "h": 4, - "w": 4, - "x": 0, - "y": 0, "coordinationScopes": { - "embeddingType": "UMAP", + "dataset": "A", + "embeddingType": "A", "obsType": "A", "featureType": "A", "featureValueType": "A", "featureValueColormapRange": "A" }, - "uid": "C" + "x": 0, + "y": 0, + "w": 4, + "h": 4 }, { "component": "heatmap", - "h": 4, - "w": 8, - "x": 0, - "y": 4, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A", "featureValueType": "A", "featureValueColormapRange": "A" }, + "x": 0, + "y": 4, + "w": 8, + "h": 4, "props": { "transpose": true - }, - "uid": "D" + } }, { "component": "featureList", - "h": 4, - "w": 2, - "x": 8, - "y": 4, "coordinationScopes": { + "dataset": "A", "featureType": "A" }, - "uid": "E" + "x": 8, + "y": 4, + "w": 2, + "h": 4 }, { "component": "description", - "h": 4, - "w": 2, + "coordinationScopes": { + "dataset": "A" + }, "x": 10, "y": 4, - "uid": "F" + "w": 2, + "h": 4 } - ] -} \ No newline at end of file + ], + "initStrategy": "auto" +} diff --git a/demos/human-lymph-node-10x-visium/Snakefile b/demos/human-lymph-node-10x-visium/Snakefile index 935f8537..8aa90dc2 100644 --- a/demos/human-lymph-node-10x-visium/Snakefile +++ b/demos/human-lymph-node-10x-visium/Snakefile @@ -9,7 +9,8 @@ OUTPUTS = load_demo_outputs(DEMO_DIR) # Rules rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" #(PROCESSED_DIR / "human_lymph_node_10x_visium.ome.zarr"), # Convert the raw AnnData .h5ad file to a processed AnnData .zarr store. @@ -26,3 +27,16 @@ rule create_zarr: -oi {output.img} ''' +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/human-lymph-node-10x-visium/src/vitessce_config.py b/demos/human-lymph-node-10x-visium/src/vitessce_config.py new file mode 100644 index 00000000..5f8a68f9 --- /dev/null +++ b/demos/human-lymph-node-10x-visium/src/vitessce_config.py @@ -0,0 +1,99 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper, ImageOmeZarrWrapper + +BASE_URL = "{{ base_url }}" +# OME-Zarr outputs are uploaded to GCS. +BASE_URL_GCP = "{{ base_url_gcp }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="Human lymph node, 10X Genomics", + description="Visium Spatial Gene Expression data from 10x Genomics", + ) + dataset = vc.add_dataset(uid="visium") + dataset.add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/human_lymph_node_10x_visium.h5ad.zarr", + obs_feature_matrix_path="X", + initial_feature_filter_path="var/highly_variable", + obs_locations_path="obsm/spatial", + obs_segmentations_path="obsm/segmentations", + obs_embedding_paths=["obsm/X_umap", "obsm/X_pca"], + obs_embedding_names=["UMAP", "PCA"], + obs_set_paths=["obs/clusters"], + obs_set_names=["Leiden Cluster"], + coordination_values={ + "obsType": "spot", + "featureType": "gene", + "featureValueType": "expression", + }, + )) + dataset.add_object(ImageOmeZarrWrapper( + img_url=f"{BASE_URL_GCP}/human_lymph_node_10x_visium.ome.zarr", + )) + + spatial_sets = vc.add_view("spatial", dataset=dataset, x=0, y=0, w=6, h=6) + spatial_genes = vc.add_view("spatial", dataset=dataset, x=6, y=0, w=6, h=6) + heatmap = vc.add_view("heatmap", dataset=dataset, x=6, y=6, w=6, h=6).set_props(transpose=True) + layer_controller = vc.add_view("layerController", dataset=dataset, x=0, y=6, w=2, h=6).set_props(disableChannelsIfRgbDetected=True) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=2, y=6, w=2, h=6) + feature_list = vc.add_view("featureList", dataset=dataset, x=4, y=6, w=2, h=6) + + vc.link_views([spatial_sets, spatial_genes, heatmap, layer_controller, obs_sets, feature_list], ["obsType"], ["spot"]) + vc.link_views( + [spatial_sets, spatial_genes, layer_controller], + ["spatialImageLayer", "spatialSegmentationLayer"], + [ + [{ + "type": "raster", + "index": 0, + "colormap": None, + "transparentColor": None, + "opacity": 1, + "domainType": "Min/Max", + "channels": [ + {"selection": {"c": 0}, "color": [255, 0, 0], "visible": True, "slider": [0, 255]}, + {"selection": {"c": 1}, "color": [0, 255, 0], "visible": True, "slider": [0, 255]}, + {"selection": {"c": 2}, "color": [0, 0, 255], "visible": True, "slider": [0, 255]}, + ], + }], + {"radius": 65, "stroked": True, "visible": True, "opacity": 1}, + ], + ) + vc.link_views( + [spatial_sets, spatial_genes], + ["spatialZoom", "spatialTargetX", "spatialTargetY"], + [-2.598, 1008.88, 1004.69], + ) + # Left spatial view: colored by cell set. Right spatial view: colored by gene. + vc.link_views([spatial_sets, heatmap, obs_sets], ["obsColorEncoding"], ["cellSetSelection"]) + vc.link_views([spatial_genes, feature_list], ["obsColorEncoding", "featureSelection"], ["geneSelection", ["CR2"]]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/human-lymph-node-10x-visium/vitessce.template.json b/demos/human-lymph-node-10x-visium/vitessce.template.json index f03ae7da..572d7b46 100644 --- a/demos/human-lymph-node-10x-visium/vitessce.template.json +++ b/demos/human-lymph-node-10x-visium/vitessce.template.json @@ -2,24 +2,15 @@ "version": "1.0.15", "name": "Human lymph node, 10X Genomics", "description": "Visium Spatial Gene Expression data from 10x Genomics", - "initStrategy": "auto", "datasets": [ { "uid": "visium", + "name": "", "files": [ { "fileType": "anndata.zarr", "url": "{{ base_url }}/human_lymph_node_10x_visium.h5ad.zarr", - "coordinationValues": { - "obsType": "spot", - "featureType": "gene", - "featureValueType": "expression" - }, "options": { - "obsFeatureMatrix": { - "path": "X", - "initialFeatureFilterPath": "var/highly_variable" - }, "obsLocations": { "path": "obsm/spatial" }, @@ -29,10 +20,18 @@ "obsEmbedding": [ { "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], "embeddingType": "UMAP" }, { "path": "obsm/X_pca", + "dims": [ + 0, + 1 + ], "embeddingType": "PCA" } ], @@ -41,7 +40,16 @@ "name": "Leiden Cluster", "path": "obs/clusters" } - ] + ], + "obsFeatureMatrix": { + "path": "X", + "initialFeatureFilterPath": "var/highly_variable" + } + }, + "coordinationValues": { + "obsType": "spot", + "featureType": "gene", + "featureValueType": "expression" } }, { @@ -52,12 +60,12 @@ } ], "coordinationSpace": { + "dataset": { + "A": "visium" + }, "obsType": { "A": "spot" }, - "spatialSegmentationLayer": { - "A": { "radius": 65, "stroked": true, "visible": true, "opacity": 1 } - }, "spatialImageLayer": { "A": [ { @@ -69,7 +77,9 @@ "domainType": "Min/Max", "channels": [ { - "selection": { "c": 0 }, + "selection": { + "c": 0 + }, "color": [ 255, 0, @@ -82,7 +92,9 @@ ] }, { - "selection": { "c": 1 }, + "selection": { + "c": 1 + }, "color": [ 0, 255, @@ -95,7 +107,9 @@ ] }, { - "selection": { "c": 2 }, + "selection": { + "c": 2 + }, "color": [ 0, 0, @@ -111,9 +125,13 @@ } ] }, - "obsColorEncoding": { - "A": "cellSetSelection", - "B": "geneSelection" + "spatialSegmentationLayer": { + "A": { + "radius": 65, + "stroked": true, + "visible": true, + "opacity": 1 + } }, "spatialZoom": { "A": -2.598 @@ -124,14 +142,21 @@ "spatialTargetY": { "A": 1004.69 }, + "obsColorEncoding": { + "A": "cellSetSelection", + "B": "geneSelection" + }, "featureSelection": { - "A": ["CR2"] + "A": [ + "CR2" + ] } }, "layout": [ { "component": "spatial", "coordinationScopes": { + "dataset": "A", "obsType": "A", "spatialImageLayer": "A", "spatialSegmentationLayer": "A", @@ -140,11 +165,15 @@ "spatialTargetY": "A", "obsColorEncoding": "A" }, - "x": 0, "y": 0, "w": 6, "h": 6 + "x": 0, + "y": 0, + "w": 6, + "h": 6 }, { "component": "spatial", "coordinationScopes": { + "dataset": "A", "obsType": "A", "spatialImageLayer": "A", "spatialSegmentationLayer": "A", @@ -154,47 +183,67 @@ "obsColorEncoding": "B", "featureSelection": "A" }, - "x": 6, "y": 0, "w": 6, "h": 6 + "x": 6, + "y": 0, + "w": 6, + "h": 6 }, { "component": "heatmap", "coordinationScopes": { + "dataset": "A", "obsType": "A", "obsColorEncoding": "A" }, + "x": 6, + "y": 6, + "w": 6, + "h": 6, "props": { "transpose": true - }, - "x": 6, "y": 6, "w": 6, "h": 6 + } }, { "component": "layerController", "coordinationScopes": { + "dataset": "A", "obsType": "A", "spatialImageLayer": "A", "spatialSegmentationLayer": "A" }, + "x": 0, + "y": 6, + "w": 2, + "h": 6, "props": { "disableChannelsIfRgbDetected": true - }, - "x": 0, "y": 6, "w": 2, "h": 6 + } }, { "component": "obsSets", "coordinationScopes": { + "dataset": "A", "obsType": "A", "obsColorEncoding": "A" }, - "x": 2, "y": 6, "w": 2, "h": 6 + "x": 2, + "y": 6, + "w": 2, + "h": 6 }, { "component": "featureList", "coordinationScopes": { + "dataset": "A", "obsType": "A", "obsColorEncoding": "B", "featureSelection": "A" }, - "x": 4, "y": 6, "w": 2, "h": 6 + "x": 4, + "y": 6, + "w": 2, + "h": 6 } - ] -} \ No newline at end of file + ], + "initStrategy": "auto" +} diff --git a/demos/kuppe-2022/Snakefile b/demos/kuppe-2022/Snakefile index 2e2ff38f..823d2d63 100644 --- a/demos/kuppe-2022/Snakefile +++ b/demos/kuppe-2022/Snakefile @@ -27,7 +27,8 @@ IMG_DIR = (RAW_DIR / "ACH0012" / "outs" / "Volumes" / "RicoData2" / "MI_project" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" rule convert_to_zarr: @@ -127,3 +128,17 @@ rule download_atac: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/kuppe-2022/src/vitessce_config.py b/demos/kuppe-2022/src/vitessce_config.py new file mode 100644 index 00000000..7ca2f004 --- /dev/null +++ b/demos/kuppe-2022/src/vitessce_config.py @@ -0,0 +1,143 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper, ImageOmeZarrWrapper + +BASE_URL = "{{ base_url }}" +# OME-Zarr outputs are uploaded to GCS. +BASE_URL_GCP = "{{ base_url_gcp }}" + +SPATIAL_IMAGE_LAYER = [{ + "type": "raster", + "index": 0, + "colormap": None, + "transparentColor": None, + "opacity": 1, + "domainType": "Min/Max", + "channels": [ + {"selection": {"c": 0}, "color": [255, 0, 0], "visible": True, "slider": [0, 255]}, + {"selection": {"c": 1}, "color": [0, 255, 0], "visible": True, "slider": [0, 255]}, + {"selection": {"c": 2}, "color": [0, 0, 255], "visible": True, "slider": [0, 255]}, + ], +}] + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="Kuppe et al., 2022 Nature", + description="Spatial multi-omic map of human myocardial infarction. Visium slide from patient P9, region GT/IZ_P9", + ) + dataset = vc.add_dataset(name="kuppe_2022_nature", uid="kuppe_2022_nature") + # Cell sets shared by the snRNA-seq and snATAC-seq cells. + dataset.add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/kuppe_2022_nature.joint.h5ad.zarr", + obs_set_paths=["obs/cell_type", "obs/development_stage", "obs/disease", "obs/sex"], + obs_set_names=["Cell Type", "Development Stage", "Disease", "Sex"], + coordination_values={"obsType": "cell"}, + )) + dataset.add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/kuppe_2022_nature.rna.h5ad.zarr", + obs_feature_matrix_path="X", + feature_labels_path="var/feature_name", + obs_embedding_paths=["obsm/X_umap", "obsm/X_pca"], + obs_embedding_names=["snRNA UMAP", "snRNA PCA"], + coordination_values={"obsType": "cell", "featureType": "gene", "featureValueType": "transcript count"}, + )) + dataset.add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/kuppe_2022_nature.atac.h5ad.zarr", + obs_feature_matrix_path="X", + feature_labels_path="var/feature_name", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["snATAC UMAP"], + coordination_values={"obsType": "cell", "featureType": "gene", "featureValueType": "mapped peak count"}, + )) + dataset.add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/kuppe_2022_nature.visium.h5ad.zarr", + obs_locations_path="obsm/xy_scaled", + obs_segmentations_path="obsm/xy_segmentations_scaled", + obs_feature_matrix_path="layers/X_uint8", + feature_labels_path="var/feature_name", + obs_set_paths=["obs/cell_type", "obs/development_stage", "obs/disease", "obs/sex"], + obs_set_names=["Spot Type", "Development Stage", "Disease", "Sex"], + coordination_values={"obsType": "spot", "featureType": "gene", "featureValueType": "detection count"}, + )) + dataset.add_object(ImageOmeZarrWrapper( + img_url=f"{BASE_URL_GCP}/kuppe_2022_nature.visium.ome.zarr", + )) + + cell_sets = vc.add_view("obsSets", dataset=dataset, x=3, y=4, w=3, h=2, uid="A-cell") + spot_sets = vc.add_view("obsSets", dataset=dataset, x=3, y=6, w=3, h=2, uid="A-spot") + spatial = vc.add_view("spatial", dataset=dataset, x=8, y=0, w=4, h=4, uid="B") + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=4, h=4, uid="C") + atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=4, y=0, w=4, h=4, uid="D") + feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=4, w=3, h=4, uid="E") + vc.add_view("description", dataset=dataset, x=0, y=4, w=3, h=4, uid="H") + layer_controller = vc.add_view( + "layerController", dataset=dataset, x=9, y=4, w=3, h=4, uid="I", + ).set_props(disableChannelsIfRgbDetected=True) + + vc.link_views([rna_scatterplot], ["embeddingType"], ["snRNA UMAP"]) + vc.link_views([atac_scatterplot], ["embeddingType"], ["snATAC UMAP"]) + + # Cells (snRNA-seq and snATAC-seq). + vc.link_views( + [cell_sets, rna_scatterplot, atac_scatterplot], + ["obsType", "obsSetSelection", "obsSetColor"], + ["cell", None, None], + ) + vc.link_views([rna_scatterplot, atac_scatterplot], ["embeddingObsSetLabelsVisible"], [True]) + vc.link_views([rna_scatterplot], ["featureValueType", "featureValueColormapRange"], ["transcript count", [0, 0.1]]) + vc.link_views([atac_scatterplot], ["featureValueType", "featureValueColormapRange"], ["mapped peak count", [0, 0.1]]) + + # Visium spots. + vc.link_views( + [spot_sets, spatial, layer_controller], + ["obsType"], + ["spot"], + ) + vc.link_views([spot_sets, spatial], ["obsSetSelection", "obsSetColor"], [None, None]) + vc.link_views([spatial], ["featureValueType"], ["detection count"]) + vc.link_views( + [spatial, layer_controller], + ["spatialSegmentationLayer", "spatialImageLayer"], + [{"radius": 65, "stroked": True, "visible": True, "opacity": 1}, SPATIAL_IMAGE_LAYER], + ) + + # Shared gene selection and color encoding. + vc.link_views( + [cell_sets, spot_sets, spatial, rna_scatterplot, atac_scatterplot, feature_list], + ["obsColorEncoding"], + ["cellSetSelection"], + ) + vc.link_views( + [spatial, rna_scatterplot, atac_scatterplot, feature_list], + ["featureType", "featureSelection"], + ["gene", None], + ) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/kuppe-2022/vitessce.template.json b/demos/kuppe-2022/vitessce.template.json index 08be5a92..79772119 100644 --- a/demos/kuppe-2022/vitessce.template.json +++ b/demos/kuppe-2022/vitessce.template.json @@ -2,157 +2,160 @@ "version": "1.0.15", "name": "Kuppe et al., 2022 Nature", "description": "Spatial multi-omic map of human myocardial infarction. Visium slide from patient P9, region GT/IZ_P9", - "datasets": [{ - "uid": "kuppe_2022_nature", - "name": "kuppe_2022_nature", - "files": [ - { - "fileType": "obsSets.anndata.zarr", - "url": "{{ base_url }}/kuppe_2022_nature.joint.h5ad.zarr", - "coordinationValues": { - "obsType": "cell" - }, - "options": [ - { - "name": "Cell Type", - "path": "obs/cell_type" - }, - { - "name": "Development Stage", - "path": "obs/development_stage" - }, - { - "name": "Disease", - "path": "obs/disease" + "datasets": [ + { + "uid": "kuppe_2022_nature", + "name": "kuppe_2022_nature", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/kuppe_2022_nature.joint.h5ad.zarr", + "options": { + "obsSets": [ + { + "name": "Cell Type", + "path": "obs/cell_type" + }, + { + "name": "Development Stage", + "path": "obs/development_stage" + }, + { + "name": "Disease", + "path": "obs/disease" + }, + { + "name": "Sex", + "path": "obs/sex" + } + ] }, - { - "name": "Sex", - "path": "obs/sex" + "coordinationValues": { + "obsType": "cell" } - ] - }, - { - "fileType": "anndata.zarr", - "url": "{{ base_url }}/kuppe_2022_nature.rna.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "transcript count" }, - "options": { - "obsFeatureMatrix": { - "path": "X" - }, - "featureLabels": { - "path": "var/feature_name" - }, - "obsEmbedding": [ - { - "path": "obsm/X_umap", - "embeddingType": "snRNA UMAP" + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/kuppe_2022_nature.rna.h5ad.zarr", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "snRNA UMAP" + }, + { + "path": "obsm/X_pca", + "dims": [ + 0, + 1 + ], + "embeddingType": "snRNA PCA" + } + ], + "obsFeatureMatrix": { + "path": "X" }, - { - "path": "obsm/X_pca", - "embeddingType": "snRNA PCA" + "featureLabels": { + "path": "var/feature_name" } - ] - } - }, - { - "fileType": "anndata.zarr", - "url": "{{ base_url }}/kuppe_2022_nature.atac.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "mapped peak count" - }, - "options": { - "obsFeatureMatrix": { - "path": "X" }, - "featureLabels": { - "path": "var/feature_name" - }, - "obsEmbedding": [ - { - "path": "obsm/X_umap", - "embeddingType": "snATAC UMAP" - } - ] - } - }, - { - "fileType": "anndata.zarr", - "url": "{{ base_url }}/kuppe_2022_nature.visium.h5ad.zarr", - "coordinationValues": { - "obsType": "spot", - "featureType": "gene", - "featureValueType": "detection count" + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "transcript count" + } }, - "options": { - "obsLocations": { - "path": "obsm/xy_scaled" - }, - "obsSegmentations": { - "path": "obsm/xy_segmentations_scaled" - }, - "obsFeatureMatrix": { - "path": "layers/X_uint8" - }, - "featureLabels": { - "path": "var/feature_name" + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/kuppe_2022_nature.atac.h5ad.zarr", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "snATAC UMAP" + } + ], + "obsFeatureMatrix": { + "path": "X" + }, + "featureLabels": { + "path": "var/feature_name" + } }, - "obsSets": [ - { - "name": "Spot Type", - "path": "obs/cell_type" + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "mapped peak count" + } + }, + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/kuppe_2022_nature.visium.h5ad.zarr", + "options": { + "obsLocations": { + "path": "obsm/xy_scaled" }, - { - "name": "Development Stage", - "path": "obs/development_stage" + "obsSegmentations": { + "path": "obsm/xy_segmentations_scaled" }, - { - "name": "Disease", - "path": "obs/disease" + "obsSets": [ + { + "name": "Spot Type", + "path": "obs/cell_type" + }, + { + "name": "Development Stage", + "path": "obs/development_stage" + }, + { + "name": "Disease", + "path": "obs/disease" + }, + { + "name": "Sex", + "path": "obs/sex" + } + ], + "obsFeatureMatrix": { + "path": "layers/X_uint8" }, - { - "name": "Sex", - "path": "obs/sex" + "featureLabels": { + "path": "var/feature_name" } - ] + }, + "coordinationValues": { + "obsType": "spot", + "featureType": "gene", + "featureValueType": "detection count" + } + }, + { + "fileType": "image.ome-zarr", + "url": "{{ base_url_gcp }}/kuppe_2022_nature.visium.ome.zarr" } - }, - { - "fileType": "image.ome-zarr", - "url": "{{ base_url_gcp }}/kuppe_2022_nature.visium.ome.zarr" - } - ] - }], - "initStrategy": "auto", + ] + } + ], "coordinationSpace": { + "dataset": { + "A": "kuppe_2022_nature" + }, "embeddingType": { - "RNA_UMAP": "snRNA UMAP", - "RNA_PCA": "snRNA PCA", - "ATAC_UMAP": "snATAC UMAP" + "A": "snRNA UMAP", + "B": "snATAC UMAP" }, "obsType": { "A": "cell", "B": "spot" }, - "featureType": { - "A": "gene" - }, - "featureValueType": { - "A": "transcript count", - "B": "mapped peak count", - "C": "detection count" - }, - "featureSelection": { - "A": null - }, - "obsColorEncoding": { - "A": "cellSetSelection" - }, "obsSetSelection": { "A": null, "B": null @@ -161,13 +164,32 @@ "A": null, "B": null }, - "featureValueColormapRange": { - "A": [0, 0.1], - "B": [0, 0.1] - }, "embeddingObsSetLabelsVisible": { "A": true }, + "featureValueType": { + "A": "transcript count", + "B": "mapped peak count", + "C": "detection count" + }, + "featureValueColormapRange": { + "A": [ + 0, + 0.1 + ], + "B": [ + 0, + 0.1 + ] + }, + "spatialSegmentationLayer": { + "A": { + "radius": 65, + "stroked": true, + "visible": true, + "opacity": 1 + } + }, "spatialImageLayer": { "A": [ { @@ -179,7 +201,9 @@ "domainType": "Min/Max", "channels": [ { - "selection": { "c": 0 }, + "selection": { + "c": 0 + }, "color": [ 255, 0, @@ -192,7 +216,9 @@ ] }, { - "selection": { "c": 1 }, + "selection": { + "c": 1 + }, "color": [ 0, 255, @@ -205,7 +231,9 @@ ] }, { - "selection": { "c": 2 }, + "selection": { + "c": 2 + }, "color": [ 0, 0, @@ -221,134 +249,151 @@ } ] }, - "spatialSegmentationLayer": { - "A": { "radius": 65, "stroked": true, "visible": true, "opacity": 1 } + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "featureType": { + "A": "gene" + }, + "featureSelection": { + "A": null } }, "layout": [ { "component": "obsSets", - "h": 2, - "w": 3, - "x": 3, - "y": 4, "coordinationScopes": { + "dataset": "A", "obsType": "A", - "obsColorEncoding": "A", "obsSetSelection": "A", - "obsSetColor": "A" + "obsSetColor": "A", + "obsColorEncoding": "A" }, + "x": 3, + "y": 4, + "w": 3, + "h": 2, "uid": "A-cell" }, { "component": "obsSets", - "h": 2, - "w": 3, - "x": 3, - "y": 6, "coordinationScopes": { + "dataset": "A", "obsType": "B", - "obsColorEncoding": "A", "obsSetSelection": "B", - "obsSetColor": "B" + "obsSetColor": "B", + "obsColorEncoding": "A" }, + "x": 3, + "y": 6, + "w": 3, + "h": 2, "uid": "A-spot" }, { "component": "spatial", - "h": 4, - "w": 4, - "x": 8, - "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "B", - "obsColorEncoding": "A", - "obsSetColor": "B", "obsSetSelection": "B", - "featureType": "A", + "obsSetColor": "B", "featureValueType": "C", "spatialSegmentationLayer": "A", "spatialImageLayer": "A", + "obsColorEncoding": "A", + "featureType": "A", "featureSelection": "A" }, + "x": 8, + "y": 0, + "w": 4, + "h": 4, "uid": "B" }, { "component": "scatterplot", - "h": 4, - "w": 4, - "x": 0, - "y": 0, "coordinationScopes": { - "embeddingType": "RNA_UMAP", + "dataset": "A", + "embeddingType": "A", "obsType": "A", - "featureType": "A", - "featureValueType": "A", - "featureSelection": "A", - "obsColorEncoding": "A", - "obsSetColor": "A", "obsSetSelection": "A", + "obsSetColor": "A", + "embeddingObsSetLabelsVisible": "A", + "featureValueType": "A", "featureValueColormapRange": "A", - "embeddingObsSetLabelsVisible": "A" + "obsColorEncoding": "A", + "featureType": "A", + "featureSelection": "A" }, + "x": 0, + "y": 0, + "w": 4, + "h": 4, "uid": "C" }, { "component": "scatterplot", - "h": 4, - "w": 4, - "x": 4, - "y": 0, "coordinationScopes": { - "embeddingType": "ATAC_UMAP", + "dataset": "A", + "embeddingType": "B", "obsType": "A", - "featureType": "A", - "featureValueType": "B", - "featureSelection": "A", - "obsColorEncoding": "A", - "obsSetColor": "A", "obsSetSelection": "A", + "obsSetColor": "A", + "embeddingObsSetLabelsVisible": "A", + "featureValueType": "B", "featureValueColormapRange": "B", - "embeddingObsSetLabelsVisible": "A" + "obsColorEncoding": "A", + "featureType": "A", + "featureSelection": "A" }, + "x": 4, + "y": 0, + "w": 4, + "h": 4, "uid": "D" }, { "component": "featureList", - "h": 4, - "w": 3, - "x": 6, - "y": 4, "coordinationScopes": { + "dataset": "A", + "obsColorEncoding": "A", "featureType": "A", - "featureSelection": "A", - "obsColorEncoding": "A" + "featureSelection": "A" }, + "x": 6, + "y": 4, + "w": 3, + "h": 4, "uid": "E" }, { "component": "description", - "h": 4, - "w": 3, + "coordinationScopes": { + "dataset": "A" + }, "x": 0, "y": 4, + "w": 3, + "h": 4, "uid": "H" }, { "component": "layerController", "coordinationScopes": { + "dataset": "A", "obsType": "B", "spatialSegmentationLayer": "A", "spatialImageLayer": "A" }, - "props": { - "disableChannelsIfRgbDetected": true - }, - "h": 4, - "w": 3, "x": 9, "y": 4, - "uid": "I" + "w": 3, + "h": 4, + "uid": "I", + "props": { + "disableChannelsIfRgbDetected": true + } } - ] -} \ No newline at end of file + ], + "initStrategy": "auto" +} diff --git a/demos/marshall-2022/Snakefile b/demos/marshall-2022/Snakefile index 4da84f41..adecec0a 100644 --- a/demos/marshall-2022/Snakefile +++ b/demos/marshall-2022/Snakefile @@ -18,7 +18,8 @@ H5AD_URL = "https://datasets.cellxgene.cziscience.com/69ecc4ce-5bb2-4f2c-9ce7-15 rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" rule convert_to_zarr: input: @@ -44,3 +45,17 @@ rule download_adata: ''' curl -L -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/marshall-2022/src/vitessce_config.py b/demos/marshall-2022/src/vitessce_config.py new file mode 100644 index 00000000..8e174531 --- /dev/null +++ b/demos/marshall-2022/src/vitessce_config.py @@ -0,0 +1,74 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="Marshall et al., 2022 iScience", + description="Spatial transcriptomics (Slide-seqV2) in the healthy human kidney (Puck_200903_13)", + ) + dataset = vc.add_dataset(name="marshall_2022", uid="marshall_2022").add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/marshall_2022_iscience.h5ad.zarr", + obs_feature_matrix_path="X", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["UMAP"], + obs_locations_path="obsm/X_spatial", + obs_segmentations_path="obsm/X_segmentations", + obs_set_paths=["obs/cell_type"], + obs_set_names=["Bead Type"], + feature_labels_path="var/feature_name", + coordination_values={ + "obsType": "bead", + "featureType": "gene", + "featureValueType": "expression", + }, + )) + + obs_sets = vc.add_view("obsSets", dataset=dataset, x=4, y=0, w=4, h=4) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=0, w=4, h=4) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=4, h=4) + spatial = vc.add_view("spatial", dataset=dataset, x=0, y=4, w=4, h=4) + layer_controller = vc.add_view("layerController", dataset=dataset, x=4, y=4, w=4, h=4) + feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=2, h=4) + vc.add_view("description", dataset=dataset, x=10, y=4, w=2, h=4) + + vc.link_views([obs_sets, obs_set_sizes, scatterplot, spatial, layer_controller, feature_list], ["obsType"], ["bead"]) + vc.link_views([scatterplot, spatial, layer_controller, feature_list], ["featureType"], ["gene"]) + vc.link_views([scatterplot, spatial, layer_controller], ["featureValueType"], ["expression"]) + vc.link_views([scatterplot, spatial], ["featureValueColormapRange"], [[0.0, 0.1]]) + vc.link_views( + [spatial, layer_controller], + ["spatialSegmentationLayer"], + [{"opacity": 1, "radius": 50, "visible": True, "stroked": False}], + ) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/marshall-2022/vitessce.template.json b/demos/marshall-2022/vitessce.template.json index 33c63549..bdecc3e6 100644 --- a/demos/marshall-2022/vitessce.template.json +++ b/demos/marshall-2022/vitessce.template.json @@ -2,47 +2,59 @@ "version": "1.0.15", "name": "Marshall et al., 2022 iScience", "description": "Spatial transcriptomics (Slide-seqV2) in the healthy human kidney (Puck_200903_13)", - "datasets": [{ - "uid": "marshall_2022", - "name": "marshall_2022", - "files": [{ - "fileType": "anndata.zarr", - "url": "{{ base_url }}/marshall_2022_iscience.h5ad.zarr", - "coordinationValues": { - "obsType": "bead", - "featureType": "gene", - "featureValueType": "expression", - "embeddingType": "UMAP" - }, - "options": { - "obsFeatureMatrix": { - "path": "X" - }, - "obsEmbedding": { - "path": "obsm/X_umap" - }, - "obsLocations": { - "path": "obsm/X_spatial" - }, - "obsSegmentations": { - "path": "obsm/X_segmentations" - }, - "obsSets": [ - { - "name": "Bead Type", - "path": "obs/cell_type" + "datasets": [ + { + "uid": "marshall_2022", + "name": "marshall_2022", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/marshall_2022_iscience.h5ad.zarr", + "options": { + "obsLocations": { + "path": "obsm/X_spatial" + }, + "obsSegmentations": { + "path": "obsm/X_segmentations" + }, + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ], + "obsSets": [ + { + "name": "Bead Type", + "path": "obs/cell_type" + } + ], + "obsFeatureMatrix": { + "path": "X" + }, + "featureLabels": { + "path": "var/feature_name" + } + }, + "coordinationValues": { + "obsType": "bead", + "featureType": "gene", + "featureValueType": "expression" } - ], - "featureLabels": { - "path": "var/feature_name" } - } - }] - }], - "initStrategy": "auto", + ] + } + ], "coordinationSpace": { + "dataset": { + "A": "marshall_2022" + }, "embeddingType": { - "UMAP": "UMAP" + "A": "UMAP" }, "obsType": { "A": "bead" @@ -54,99 +66,109 @@ "A": "expression" }, "featureValueColormapRange": { - "A": [0.0, 0.1] + "A": [ + 0.0, + 0.1 + ] }, "spatialSegmentationLayer": { "A": { - "opacity": 1, "radius": 50, "visible": true, "stroked": false + "opacity": 1, + "radius": 50, + "visible": true, + "stroked": false } } }, - "layout": [{ + "layout": [ + { "component": "obsSets", - "h": 4, - "w": 4, - "x": 4, - "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "A" + "x": 4, + "y": 0, + "w": 4, + "h": 4 }, { "component": "obsSetSizes", - "h": 4, - "w": 4, - "x": 8, - "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "B" + "x": 8, + "y": 0, + "w": 4, + "h": 4 }, { "component": "scatterplot", - "h": 4, - "w": 4, - "x": 0, - "y": 0, "coordinationScopes": { - "embeddingType": "UMAP", + "dataset": "A", + "embeddingType": "A", "obsType": "A", "featureType": "A", "featureValueType": "A", "featureValueColormapRange": "A" }, - "uid": "C" + "x": 0, + "y": 0, + "w": 4, + "h": 4 }, { "component": "spatial", - "h": 4, - "w": 4, - "x": 0, - "y": 4, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A", "featureValueType": "A", - "spatialSegmentationLayer": "A", - "featureValueColormapRange": "A" + "featureValueColormapRange": "A", + "spatialSegmentationLayer": "A" }, - "uid": "E" + "x": 0, + "y": 4, + "w": 4, + "h": 4 }, { "component": "layerController", - "h": 4, - "w": 4, - "x": 4, - "y": 4, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A", "featureValueType": "A", "spatialSegmentationLayer": "A" }, - "uid": "F" + "x": 4, + "y": 4, + "w": 4, + "h": 4 }, { "component": "featureList", - "h": 4, - "w": 2, - "x": 8, - "y": 4, "coordinationScopes": { + "dataset": "A", "obsType": "A", "featureType": "A" }, - "uid": "G" + "x": 8, + "y": 4, + "w": 2, + "h": 4 }, { "component": "description", - "h": 4, - "w": 2, + "coordinationScopes": { + "dataset": "A" + }, "x": 10, "y": 4, - "uid": "H" + "w": 2, + "h": 4 } - ] -} \ No newline at end of file + ], + "initStrategy": "auto" +} diff --git a/demos/meta-2022-azimuth/Snakefile b/demos/meta-2022-azimuth/Snakefile index 2289e02e..263199af 100644 --- a/demos/meta-2022-azimuth/Snakefile +++ b/demos/meta-2022-azimuth/Snakefile @@ -18,7 +18,8 @@ H5AD_URL = "https://datasets.cellxgene.cziscience.com/d084f1e1-42f1-4f65-8e5a-3a rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" rule convert_to_zarr: input: @@ -44,3 +45,17 @@ rule download_adata: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/meta-2022-azimuth/src/vitessce_config.py b/demos/meta-2022-azimuth/src/vitessce_config.py new file mode 100644 index 00000000..450d02a0 --- /dev/null +++ b/demos/meta-2022-azimuth/src/vitessce_config.py @@ -0,0 +1,84 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="Meta-analysis, Azimuth 2022", + description="Meta-analysis of 10 datasets of healthy and diseased human lung", + ) + dataset = vc.add_dataset(name="azimuth_2022_meta", uid="azimuth_2022_meta").add_object(AnnDataWrapper( + adata_url=f"{BASE_URL}/meta_2022_azimuth.h5ad.zarr", + obs_feature_matrix_path="X", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["UMAP"], + feature_labels_path="var/feature_name", + obs_set_paths=[ + "obs/cell_type", + ["obs/annotation.l2", "obs/annotation.l1"], + "obs/assay", + "obs/disease", + "obs/organism", + "obs/sex", + "obs/tissue", + "obs/self_reported_ethnicity", + "obs/development_stage", + ], + obs_set_names=[ + "Cell Type", + "Cell Type Annotation", + "Assay", + "Disease", + "Organism", + "Sex", + "Tissue", + "Ethnicity", + "Development Stage", + ], + coordination_values={ + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression", + }, + )) + + obs_sets = vc.add_view("obsSets", dataset=dataset, x=10, y=6, w=2, h=6) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=1, w=4, h=5) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=8, h=12) + feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=6, w=2, h=6) + vc.add_view("description", dataset=dataset, x=8, y=0, w=4, h=1) + + vc.link_views([obs_sets, obs_set_sizes, scatterplot], ["obsType"], ["cell"]) + vc.link_views([scatterplot, feature_list], ["featureType"], ["gene"]) + vc.link_views([scatterplot], ["featureValueType"], ["expression"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/meta-2022-azimuth/vitessce.template.json b/demos/meta-2022-azimuth/vitessce.template.json index 496f1b8b..ae13efe0 100644 --- a/demos/meta-2022-azimuth/vitessce.template.json +++ b/demos/meta-2022-azimuth/vitessce.template.json @@ -2,73 +2,88 @@ "version": "1.0.15", "name": "Meta-analysis, Azimuth 2022", "description": "Meta-analysis of 10 datasets of healthy and diseased human lung", - "datasets": [{ - "uid": "azimuth_2022_meta", - "name": "azimuth_2022_meta", - "files": [{ - "fileType": "anndata.zarr", - "url": "{{ base_url }}/meta_2022_azimuth.h5ad.zarr", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression", - "embeddingType": "UMAP" - }, - "options": { - "obsFeatureMatrix": { - "path": "X" - }, - "obsEmbedding": { - "path": "obsm/X_umap" - }, - "featureLabels": { - "path": "var/feature_name" - }, - "obsSets": [ - { - "name": "Cell Type", - "path": "obs/cell_type" - }, - { - "name": "Cell Type Annotation", - "path": ["obs/annotation.l2", "obs/annotation.l1"] - }, - { - "name": "Assay", - "path": "obs/assay" - }, - { - "name": "Disease", - "path": "obs/disease" - }, - { - "name": "Organism", - "path": "obs/organism" - }, - { - "name": "Sex", - "path": "obs/sex" - }, - { - "name": "Tissue", - "path": "obs/tissue" - }, - { - "name": "Ethnicity", - "path": "obs/self_reported_ethnicity" + "datasets": [ + { + "uid": "azimuth_2022_meta", + "name": "azimuth_2022_meta", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/meta_2022_azimuth.h5ad.zarr", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ], + "obsSets": [ + { + "name": "Cell Type", + "path": "obs/cell_type" + }, + { + "name": "Cell Type Annotation", + "path": [ + "obs/annotation.l2", + "obs/annotation.l1" + ] + }, + { + "name": "Assay", + "path": "obs/assay" + }, + { + "name": "Disease", + "path": "obs/disease" + }, + { + "name": "Organism", + "path": "obs/organism" + }, + { + "name": "Sex", + "path": "obs/sex" + }, + { + "name": "Tissue", + "path": "obs/tissue" + }, + { + "name": "Ethnicity", + "path": "obs/self_reported_ethnicity" + }, + { + "name": "Development Stage", + "path": "obs/development_stage" + } + ], + "obsFeatureMatrix": { + "path": "X" + }, + "featureLabels": { + "path": "var/feature_name" + } }, - { - "name": "Development Stage", - "path": "obs/development_stage" + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression" } - ] - } - }] - }], - "initStrategy": "auto", + } + ] + } + ], "coordinationSpace": { + "dataset": { + "A": "azimuth_2022_meta" + }, "embeddingType": { - "UMAP": "UMAP" + "A": "UMAP" }, "obsType": { "A": "cell" @@ -80,61 +95,64 @@ "A": "expression" } }, - "layout": [{ + "layout": [ + { "component": "obsSets", - "h": 6, - "w": 2, - "x": 10, - "y": 6, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "A" + "x": 10, + "y": 6, + "w": 2, + "h": 6 }, { "component": "obsSetSizes", - "h": 5, - "w": 4, - "x": 8, - "y": 1, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "B" + "x": 8, + "y": 1, + "w": 4, + "h": 5 }, { "component": "scatterplot", - "h": 12, - "w": 8, - "x": 0, - "y": 0, "coordinationScopes": { - "embeddingType": "UMAP", + "dataset": "A", + "embeddingType": "A", "obsType": "A", "featureType": "A", "featureValueType": "A" }, - "uid": "C" + "x": 0, + "y": 0, + "w": 8, + "h": 12 }, - { "component": "featureList", - "h": 6, - "w": 2, - "x": 8, - "y": 6, "coordinationScopes": { + "dataset": "A", "featureType": "A" }, - "uid": "E" + "x": 8, + "y": 6, + "w": 2, + "h": 6 }, { "component": "description", - "h": 1, - "w": 4, + "coordinationScopes": { + "dataset": "A" + }, "x": 8, "y": 0, - "uid": "F" + "w": 4, + "h": 1 } - ] -} \ No newline at end of file + ], + "initStrategy": "auto" +} diff --git a/demos/mudata-cite-seq-pbmc/Snakefile b/demos/mudata-cite-seq-pbmc/Snakefile index a9cf11df..c30f988e 100644 --- a/demos/mudata-cite-seq-pbmc/Snakefile +++ b/demos/mudata-cite-seq-pbmc/Snakefile @@ -23,7 +23,8 @@ H5_URL = "https://cf.10xgenomics.com/samples/cell-exp/10.0.0/16k_Human_PBMCs_Tot rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Split into RNA and protein modalities, process each, and write MuData-Zarr. rule process: @@ -50,3 +51,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/mudata-cite-seq-pbmc/src/vitessce_config.py b/demos/mudata-cite-seq-pbmc/src/vitessce_config.py new file mode 100644 index 00000000..104039bd --- /dev/null +++ b/demos/mudata-cite-seq-pbmc/src/vitessce_config.py @@ -0,0 +1,87 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper + +BASE_URL = "{{ base_url }}" +MUDATA_URL = f"{BASE_URL}/flex_pbmc_cite_seq.h5mu.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.15", + name="10x Flex v2 PBMC CITE-seq (TotalSeq-C)", + description=( + "Paired gene expression and surface protein (184 TotalSeq-C antibodies) of ~12k human PBMCs " + "from four samples, profiled with 10x GEM-X Flex v2. Stored as MuData-Zarr; each modality " + "(mod/rna, mod/prot) is loaded as AnnData-Zarr. Leiden clusters and UMAP computed from RNA; " + "protein values are CLR-normalized." + ), + ) + dataset = vc.add_dataset(name="Flex CITE-seq PBMC", uid="flex-cite-seq-pbmc") + # Each MuData modality is an AnnData object within the MuData-Zarr store. + dataset.add_object(AnnDataWrapper( + adata_url=f"{MUDATA_URL}/mod/rna", + obs_feature_matrix_path="X", + obs_embedding_paths=["obsm/X_umap", "obsm/X_umap_prot"], + obs_embedding_names=["UMAP", "UMAP (protein)"], + obs_set_paths=["obs/leiden", "obs/sample"], + obs_set_names=["Leiden Cluster (RNA)", "Sample"], + coordination_values={"obsType": "cell", "featureType": "gene", "featureValueType": "expression"}, + )) + dataset.add_object(AnnDataWrapper( + adata_url=f"{MUDATA_URL}/mod/prot", + obs_feature_matrix_path="X", + feature_labels_path="var/target", + coordination_values={"obsType": "cell", "featureType": "protein", "featureValueType": "abundance"}, + )) + + gene_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=4, h=5).set_props(title="UMAP (RNA), colored by gene") + protein_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=4, y=0, w=4, h=5).set_props(title="UMAP (RNA), colored by protein") + obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=0, w=4, h=5) + gene_list = vc.add_view("featureList", dataset=dataset, x=0, y=5, w=2, h=4).set_props(title="Genes") + protein_list = vc.add_view("featureList", dataset=dataset, x=2, y=5, w=2, h=4).set_props(title="Proteins") + heatmap = vc.add_view("heatmap", dataset=dataset, x=4, y=5, w=8, h=4).set_props(transpose=True) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=0, y=9, w=6, h=3) + vc.add_view("description", dataset=dataset, x=6, y=9, w=6, h=3) + + vc.link_views([gene_scatterplot, protein_scatterplot], ["embeddingType"], ["UMAP"]) + vc.link_views([gene_scatterplot, protein_scatterplot, obs_sets, heatmap, obs_set_sizes], ["obsType"], ["cell"]) + vc.link_views( + [gene_scatterplot, gene_list], + ["featureType", "featureSelection", "obsColorEncoding"], + ["gene", None, "cellSetSelection"], + ) + vc.link_views([gene_scatterplot], ["featureValueType"], ["expression"]) + vc.link_views( + [protein_scatterplot, protein_list, heatmap], + ["featureType", "featureSelection", "obsColorEncoding"], + ["protein", None, "cellSetSelection"], + ) + vc.link_views([protein_scatterplot, heatmap], ["featureValueType"], ["abundance"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/mudata-cite-seq-pbmc/vitessce.template.json b/demos/mudata-cite-seq-pbmc/vitessce.template.json index 0e95e2cf..7964541f 100644 --- a/demos/mudata-cite-seq-pbmc/vitessce.template.json +++ b/demos/mudata-cite-seq-pbmc/vitessce.template.json @@ -2,184 +2,221 @@ "version": "1.0.15", "name": "10x Flex v2 PBMC CITE-seq (TotalSeq-C)", "description": "Paired gene expression and surface protein (184 TotalSeq-C antibodies) of ~12k human PBMCs from four samples, profiled with 10x GEM-X Flex v2. Stored as MuData-Zarr; each modality (mod/rna, mod/prot) is loaded as AnnData-Zarr. Leiden clusters and UMAP computed from RNA; protein values are CLR-normalized.", - "datasets": [{ - "uid": "flex-cite-seq-pbmc", - "name": "Flex CITE-seq PBMC", - "files": [ - { - "fileType": "anndata.zarr", - "url": "{{ base_url }}/flex_pbmc_cite_seq.h5mu.zarr/mod/rna", - "coordinationValues": { - "obsType": "cell", - "featureType": "gene", - "featureValueType": "expression", - "embeddingType": "UMAP" - }, - "options": { - "obsFeatureMatrix": { - "path": "X" - }, - "obsEmbedding": [ - { - "path": "obsm/X_umap", - "embeddingType": "UMAP" - }, - { - "path": "obsm/X_umap_prot", - "embeddingType": "UMAP (protein)" + "datasets": [ + { + "uid": "flex-cite-seq-pbmc", + "name": "Flex CITE-seq PBMC", + "files": [ + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/flex_pbmc_cite_seq.h5mu.zarr/mod/rna", + "options": { + "obsEmbedding": [ + { + "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + }, + { + "path": "obsm/X_umap_prot", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP (protein)" + } + ], + "obsSets": [ + { + "name": "Leiden Cluster (RNA)", + "path": "obs/leiden" + }, + { + "name": "Sample", + "path": "obs/sample" + } + ], + "obsFeatureMatrix": { + "path": "X" } - ], - "obsSets": [ - { - "name": "Leiden Cluster (RNA)", - "path": "obs/leiden" + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "featureValueType": "expression" + } + }, + { + "fileType": "anndata.zarr", + "url": "{{ base_url }}/flex_pbmc_cite_seq.h5mu.zarr/mod/prot", + "options": { + "obsFeatureMatrix": { + "path": "X" }, - { - "name": "Sample", - "path": "obs/sample" + "featureLabels": { + "path": "var/target" } - ] - } - }, - { - "fileType": "anndata.zarr", - "url": "{{ base_url }}/flex_pbmc_cite_seq.h5mu.zarr/mod/prot", - "coordinationValues": { - "obsType": "cell", - "featureType": "protein", - "featureValueType": "abundance" - }, - "options": { - "obsFeatureMatrix": { - "path": "X" }, - "featureLabels": { - "path": "var/target" + "coordinationValues": { + "obsType": "cell", + "featureType": "protein", + "featureValueType": "abundance" } } - } - ] - }], - "initStrategy": "auto", + ] + } + ], "coordinationSpace": { + "dataset": { + "A": "flex-cite-seq-pbmc" + }, "embeddingType": { - "RNA": "UMAP", - "PROT": "UMAP (protein)" + "A": "UMAP" }, "obsType": { "A": "cell" }, "featureType": { - "RNA": "gene", - "PROT": "protein" - }, - "featureValueType": { - "RNA": "expression", - "PROT": "abundance" + "A": "gene", + "B": "protein" }, "featureSelection": { - "RNA": null, - "PROT": null + "A": null, + "B": null }, "obsColorEncoding": { - "RNA": "cellSetSelection", - "PROT": "cellSetSelection" + "A": "cellSetSelection", + "B": "cellSetSelection" + }, + "featureValueType": { + "A": "expression", + "B": "abundance" } }, "layout": [ { "component": "scatterplot", - "h": 5, "w": 4, "x": 0, "y": 0, "coordinationScopes": { - "embeddingType": "RNA", + "dataset": "A", + "embeddingType": "A", "obsType": "A", - "featureType": "RNA", - "featureValueType": "RNA", - "featureSelection": "RNA", - "obsColorEncoding": "RNA" + "featureType": "A", + "featureSelection": "A", + "obsColorEncoding": "A", + "featureValueType": "A" }, + "x": 0, + "y": 0, + "w": 4, + "h": 5, "props": { "title": "UMAP (RNA), colored by gene" - }, - "uid": "A" + } }, { "component": "scatterplot", - "h": 5, "w": 4, "x": 4, "y": 0, "coordinationScopes": { - "embeddingType": "RNA", + "dataset": "A", + "embeddingType": "A", "obsType": "A", - "featureType": "PROT", - "featureValueType": "PROT", - "featureSelection": "PROT", - "obsColorEncoding": "PROT" + "featureType": "B", + "featureSelection": "B", + "obsColorEncoding": "B", + "featureValueType": "B" }, + "x": 4, + "y": 0, + "w": 4, + "h": 5, "props": { "title": "UMAP (RNA), colored by protein" - }, - "uid": "B" + } }, { "component": "obsSets", - "h": 5, "w": 4, "x": 8, "y": 0, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "C" + "x": 8, + "y": 0, + "w": 4, + "h": 5 }, { "component": "featureList", - "h": 4, "w": 2, "x": 0, "y": 5, "coordinationScopes": { - "featureType": "RNA", - "featureSelection": "RNA", - "obsColorEncoding": "RNA" + "dataset": "A", + "featureType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" }, + "x": 0, + "y": 5, + "w": 2, + "h": 4, "props": { "title": "Genes" - }, - "uid": "D" + } }, { "component": "featureList", - "h": 4, "w": 2, "x": 2, "y": 5, "coordinationScopes": { - "featureType": "PROT", - "featureSelection": "PROT", - "obsColorEncoding": "PROT" + "dataset": "A", + "featureType": "B", + "featureSelection": "B", + "obsColorEncoding": "B" }, + "x": 2, + "y": 5, + "w": 2, + "h": 4, "props": { "title": "Proteins" - }, - "uid": "E" + } }, { "component": "heatmap", - "h": 4, "w": 8, "x": 4, "y": 5, "coordinationScopes": { + "dataset": "A", "obsType": "A", - "featureType": "PROT", - "featureValueType": "PROT", - "featureSelection": "PROT", - "obsColorEncoding": "PROT" + "featureType": "B", + "featureSelection": "B", + "obsColorEncoding": "B", + "featureValueType": "B" }, + "x": 4, + "y": 5, + "w": 8, + "h": 4, "props": { "transpose": true - }, - "uid": "F" + } }, { "component": "obsSetSizes", - "h": 3, "w": 6, "x": 0, "y": 9, "coordinationScopes": { + "dataset": "A", "obsType": "A" }, - "uid": "G" + "x": 0, + "y": 9, + "w": 6, + "h": 3 }, { "component": "description", - "h": 3, "w": 6, "x": 6, "y": 9, - "uid": "H" + "coordinationScopes": { + "dataset": "A" + }, + "x": 6, + "y": 9, + "w": 6, + "h": 3 } - ] + ], + "initStrategy": "auto" } diff --git a/demos/mudata-pbmc-multiome-10x/Snakefile b/demos/mudata-pbmc-multiome-10x/Snakefile index 56c7db81..5aad49fa 100644 --- a/demos/mudata-pbmc-multiome-10x/Snakefile +++ b/demos/mudata-pbmc-multiome-10x/Snakefile @@ -26,7 +26,8 @@ RAW_FILES = [ rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # RNA + ATAC processing, to a MuData-Zarr store and a genomic-profiles (multivec) Zarr store. rule process_multiome: @@ -60,3 +61,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py b/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py new file mode 100644 index 00000000..3780314f --- /dev/null +++ b/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py @@ -0,0 +1,88 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper, MultivecZarrWrapper + +BASE_URL = "{{ base_url }}" +MUDATA_URL = f"{BASE_URL}/pbmc_multiome_10x.h5mu.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="10x Multiome PBMC (granulocytes removed, 10k)", + description=( + "10x Genomics Single Cell Multiome ATAC + Gene Expression of human PBMCs (Cell Ranger ARC 2.0.0); " + "RNA expression, ATAC gene activity, and pseudobulk ATAC profiles per cell type" + ), + ) + dataset = vc.add_dataset(name="10x Multiome") + # Each MuData modality is an AnnData object within the MuData-Zarr store. + dataset.add_object(AnnDataWrapper( + adata_url=f"{MUDATA_URL}/mod/rna", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["RNA UMAP"], + obs_set_paths=["obs/cell_type", "obs/leiden", "obs/leiden_atac"], + obs_set_names=["Cell Type", "RNA Leiden", "ATAC Leiden"], + obs_feature_matrix_path="X", + coordination_values={"obsType": "cell", "featureType": "gene", "featureValueType": "expression"}, + )) + dataset.add_object(AnnDataWrapper( + adata_url=f"{MUDATA_URL}/mod/atac", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["ATAC UMAP"], + obs_feature_matrix_path="X", + coordination_values={"obsType": "cell", "featureType": "gene activity", "featureValueType": "accessibility"}, + )) + # Pseudobulk ATAC profiles per cell type. + dataset.add_object(MultivecZarrWrapper( + zarr_url=f"{BASE_URL}/pbmc_multiome_10x.genomic-profiles.zarr", + )) + + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=6, h=4) + atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=6, y=0, w=6, h=4) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=0, y=4, w=4, h=4) + gene_list = vc.add_view("featureList", dataset=dataset, x=4, y=4, w=4, h=4) + gene_activity_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=4, h=4) + vc.add_view("genomicProfiles", dataset=dataset, x=0, y=8, w=8, h=4).set_props(assembly="hg38") + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=8, w=4, h=4) + + vc.link_views([rna_scatterplot, atac_scatterplot, obs_sets, gene_list, gene_activity_list, obs_set_sizes], ["obsType"], ["cell"]) + vc.link_views( + [rna_scatterplot, gene_list], + ["featureType", "featureValueType", "featureSelection", "obsColorEncoding"], + ["gene", "expression", None, "cellSetSelection"], + ) + vc.link_views( + [atac_scatterplot, gene_activity_list], + ["featureType", "featureValueType", "featureSelection", "obsColorEncoding"], + ["gene activity", "accessibility", None, "cellSetSelection"], + ) + vc.link_views([rna_scatterplot], ["embeddingType"], ["RNA UMAP"]) + vc.link_views([atac_scatterplot], ["embeddingType"], ["ATAC UMAP"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/mudata-pbmc-multiome-10x/vitessce.template.json b/demos/mudata-pbmc-multiome-10x/vitessce.template.json index c6f7bbce..701b02b4 100644 --- a/demos/mudata-pbmc-multiome-10x/vitessce.template.json +++ b/demos/mudata-pbmc-multiome-10x/vitessce.template.json @@ -14,6 +14,10 @@ "obsEmbedding": [ { "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], "embeddingType": "RNA UMAP" } ], @@ -48,6 +52,10 @@ "obsEmbedding": [ { "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], "embeddingType": "ATAC UMAP" } ], @@ -75,25 +83,25 @@ "obsType": { "A": "cell" }, - "embeddingType": { - "RNA": "RNA UMAP", - "ATAC": "ATAC UMAP" - }, "featureType": { - "RNA": "gene", - "ATAC": "gene activity" + "A": "gene", + "B": "gene activity" }, "featureValueType": { - "RNA": "expression", - "ATAC": "accessibility" + "A": "expression", + "B": "accessibility" }, "featureSelection": { - "RNA": null, - "ATAC": null + "A": null, + "B": null }, "obsColorEncoding": { - "RNA": "cellSetSelection", - "ATAC": "cellSetSelection" + "A": "cellSetSelection", + "B": "cellSetSelection" + }, + "embeddingType": { + "A": "RNA UMAP", + "B": "ATAC UMAP" } }, "layout": [ @@ -102,11 +110,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "embeddingType": "RNA", - "featureType": "RNA", - "featureValueType": "RNA", - "featureSelection": "RNA", - "obsColorEncoding": "RNA" + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A", + "embeddingType": "A" }, "x": 0, "y": 0, @@ -118,11 +126,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "embeddingType": "ATAC", - "featureType": "ATAC", - "featureValueType": "ATAC", - "featureSelection": "ATAC", - "obsColorEncoding": "ATAC" + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "B", + "embeddingType": "B" }, "x": 6, "y": 0, @@ -145,10 +153,10 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "RNA", - "featureValueType": "RNA", - "featureSelection": "RNA", - "obsColorEncoding": "RNA" + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" }, "x": 4, "y": 4, @@ -160,10 +168,10 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "ATAC", - "featureValueType": "ATAC", - "featureSelection": "ATAC", - "obsColorEncoding": "ATAC" + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "B" }, "x": 8, "y": 4, @@ -175,13 +183,13 @@ "coordinationScopes": { "dataset": "A" }, - "props": { - "assembly": "hg38" - }, "x": 0, "y": 8, "w": 8, - "h": 4 + "h": 4, + "props": { + "assembly": "hg38" + } }, { "component": "obsSetSizes", @@ -196,4 +204,4 @@ } ], "initStrategy": "auto" -} \ No newline at end of file +} diff --git a/demos/mudata-snareseq2-lung-hubmap/Snakefile b/demos/mudata-snareseq2-lung-hubmap/Snakefile index ff9ab24b..def82ab3 100644 --- a/demos/mudata-snareseq2-lung-hubmap/Snakefile +++ b/demos/mudata-snareseq2-lung-hubmap/Snakefile @@ -23,7 +23,8 @@ H5MU_URL = f"https://assets.hubmapconsortium.org/{HUBMAP_UUID}/secondary_analysi rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Convert the HuBMAP secondary analysis MuData to a MuData-Zarr store and a genomic-profiles (multivec) Zarr store. rule process_snareseq2: @@ -54,3 +55,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -A "vitessce-demos" -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/mudata-snareseq2-lung-hubmap/src/vitessce_config.py b/demos/mudata-snareseq2-lung-hubmap/src/vitessce_config.py new file mode 100644 index 00000000..43bd8021 --- /dev/null +++ b/demos/mudata-snareseq2-lung-hubmap/src/vitessce_config.py @@ -0,0 +1,99 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import VitessceConfig, AnnDataWrapper, MultivecZarrWrapper + +BASE_URL = "{{ base_url }}" +MUDATA_URL = f"{BASE_URL}/snareseq2_lung.h5mu.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="SNARE-seq2 human lung (HuBMAP HBM582.RKVK.974)", + description="Joint single-nucleus RNA + ATAC (SNARE-seq2) of human lung, processed by the HuBMAP Salmon + ArchR + Muon pipeline", + ) + dataset = vc.add_dataset(name="SNARE-seq2") + # Each MuData modality is an AnnData object within the MuData-Zarr store. + dataset.add_object(AnnDataWrapper( + adata_url=f"{MUDATA_URL}/mod/rna", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["RNA UMAP"], + obs_set_paths=["obs/cell_type", "obs/leiden_wnn", "obs/leiden_rna", "obs/leiden_atac"], + obs_set_names=["Cell Type", "Joint (WNN) Leiden", "RNA Leiden", "ATAC Leiden"], + obs_feature_matrix_path="X", + feature_labels_path="var/hugo_symbol", + coordination_values={"obsType": "cell", "featureType": "gene", "featureValueType": "expression"}, + )) + dataset.add_object(AnnDataWrapper( + adata_url=f"{MUDATA_URL}/mod/atac", + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["ATAC UMAP"], + obs_feature_matrix_path="X", + coordination_values={"obsType": "cell", "featureType": "gene score", "featureValueType": "accessibility"}, + )) + # The joint (WNN) UMAP is stored at the root of the MuData object. + dataset.add_object(AnnDataWrapper( + adata_url=MUDATA_URL, + obs_embedding_paths=["obsm/X_umap"], + obs_embedding_names=["Joint (WNN) UMAP"], + coordination_values={"obsType": "cell"}, + )) + # Pseudobulk ATAC profiles per cell type. + dataset.add_object(MultivecZarrWrapper( + zarr_url=f"{BASE_URL}/snareseq2_lung.genomic-profiles.zarr", + )) + + wnn_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=4, h=4) + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=4, y=0, w=4, h=4) + atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=8, y=0, w=4, h=4) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=0, y=4, w=4, h=4) + gene_list = vc.add_view("featureList", dataset=dataset, x=4, y=4, w=4, h=4) + gene_score_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=4, h=4) + vc.add_view("genomicProfiles", dataset=dataset, x=0, y=8, w=8, h=4).set_props(assembly="hg38") + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=8, w=4, h=4) + + vc.link_views( + [wnn_scatterplot, rna_scatterplot, atac_scatterplot, obs_sets, gene_list, gene_score_list, obs_set_sizes], + ["obsType"], + ["cell"], + ) + vc.link_views([wnn_scatterplot], ["embeddingType"], ["Joint (WNN) UMAP"]) + vc.link_views([rna_scatterplot], ["embeddingType"], ["RNA UMAP"]) + vc.link_views([atac_scatterplot], ["embeddingType"], ["ATAC UMAP"]) + vc.link_views( + [rna_scatterplot, gene_list], + ["featureType", "featureValueType", "featureSelection", "obsColorEncoding"], + ["gene", "expression", None, "cellSetSelection"], + ) + vc.link_views( + [atac_scatterplot, gene_score_list], + ["featureType", "featureValueType", "featureSelection", "obsColorEncoding"], + ["gene score", "accessibility", None, "cellSetSelection"], + ) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/mudata-snareseq2-lung-hubmap/vitessce.template.json b/demos/mudata-snareseq2-lung-hubmap/vitessce.template.json index ab993606..58cb4191 100644 --- a/demos/mudata-snareseq2-lung-hubmap/vitessce.template.json +++ b/demos/mudata-snareseq2-lung-hubmap/vitessce.template.json @@ -14,6 +14,10 @@ "obsEmbedding": [ { "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], "embeddingType": "RNA UMAP" } ], @@ -55,6 +59,10 @@ "obsEmbedding": [ { "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], "embeddingType": "ATAC UMAP" } ], @@ -75,6 +83,10 @@ "obsEmbedding": [ { "path": "obsm/X_umap", + "dims": [ + 0, + 1 + ], "embeddingType": "Joint (WNN) UMAP" } ] @@ -98,25 +110,25 @@ "A": "cell" }, "embeddingType": { - "RNA": "RNA UMAP", - "ATAC": "ATAC UMAP", - "WNN": "Joint (WNN) UMAP" + "A": "Joint (WNN) UMAP", + "B": "RNA UMAP", + "C": "ATAC UMAP" }, "featureType": { - "RNA": "gene", - "ATAC": "gene score" + "A": "gene", + "B": "gene score" }, "featureValueType": { - "RNA": "expression", - "ATAC": "accessibility" + "A": "expression", + "B": "accessibility" }, "featureSelection": { - "RNA": null, - "ATAC": null + "A": null, + "B": null }, "obsColorEncoding": { - "RNA": "cellSetSelection", - "ATAC": "cellSetSelection" + "A": "cellSetSelection", + "B": "cellSetSelection" } }, "layout": [ @@ -125,7 +137,7 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "embeddingType": "WNN" + "embeddingType": "A" }, "x": 0, "y": 0, @@ -137,11 +149,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "embeddingType": "RNA", - "featureType": "RNA", - "featureValueType": "RNA", - "featureSelection": "RNA", - "obsColorEncoding": "RNA" + "embeddingType": "B", + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" }, "x": 4, "y": 0, @@ -153,11 +165,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "embeddingType": "ATAC", - "featureType": "ATAC", - "featureValueType": "ATAC", - "featureSelection": "ATAC", - "obsColorEncoding": "ATAC" + "embeddingType": "C", + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "B" }, "x": 8, "y": 0, @@ -180,10 +192,10 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "RNA", - "featureValueType": "RNA", - "featureSelection": "RNA", - "obsColorEncoding": "RNA" + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" }, "x": 4, "y": 4, @@ -195,10 +207,10 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "ATAC", - "featureValueType": "ATAC", - "featureSelection": "ATAC", - "obsColorEncoding": "ATAC" + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "B" }, "x": 8, "y": 4, @@ -210,13 +222,13 @@ "coordinationScopes": { "dataset": "A" }, - "props": { - "assembly": "hg38" - }, "x": 0, "y": 8, "w": 8, - "h": 4 + "h": 4, + "props": { + "assembly": "hg38" + } }, { "component": "obsSetSizes", diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/Snakefile b/demos/ome-zarr-lightsheet-hubmap-spleen/Snakefile index f6f4e23f..93310f94 100644 --- a/demos/ome-zarr-lightsheet-hubmap-spleen/Snakefile +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/Snakefile @@ -31,7 +31,8 @@ OME_TIFF_URL = f"https://assets.hubmapconsortium.org/{HUBMAP_UUID}/ometiff-pyram rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Convert the OME-TIFF to a multiscale (Z, Y, X downsampled) OME-Zarr. rule convert_to_ome_zarr: @@ -60,3 +61,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -A "vitessce-demos" -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py b/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py new file mode 100644 index 00000000..7890bf72 --- /dev/null +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py @@ -0,0 +1,69 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + ImageOmeZarrWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +# OME-Zarr outputs are uploaded to GCS. +BASE_URL_GCP = "{{ base_url_gcp }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Light-sheet human spleen (HuBMAP HBM759.DQHR.327)", + description=( + "3D light-sheet fluorescence microscopy (Zeiss LightSheet Z.1) of cleared human spleen stained for Iba1, " + "from HuBMAP (University of Florida TMC). Multiscale 3D OME-Zarr." + ), + ) + dataset = vc.add_dataset(name="Light-sheet human spleen (HuBMAP HBM759.DQHR.327)").add_object(ImageOmeZarrWrapper( + img_url=f"{BASE_URL_GCP}/lightsheet_hubmap_spleen.ome.zarr", + )) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=9, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=9, y=0, w=3, h=12) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "BlackIsZero", + "spatialLayerOpacity": 1.0, + "imageChannel": CL([{ + "spatialTargetC": 0, + "spatialChannelColor": [255, 255, 255], + # Contrast limits for the Iba1 channel. + "spatialChannelWindow": [292, 1363], + "spatialChannelVisible": True, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-atera-kidney/Snakefile b/demos/spatialdata-atera-kidney/Snakefile index c4511ce2..b8885a75 100644 --- a/demos/spatialdata-atera-kidney/Snakefile +++ b/demos/spatialdata-atera-kidney/Snakefile @@ -36,7 +36,8 @@ wildcard_constraints: rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Convert the output bundle to SpatialData, and add a morton-sorted copy of the # transcripts (with quality value >= 20) for tiled access in Vitessce. @@ -72,3 +73,17 @@ rule download_bundle: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-atera-kidney/src/vitessce_config.py b/demos/spatialdata-atera-kidney/src/vitessce_config.py new file mode 100644 index 00000000..0619a9be --- /dev/null +++ b/demos/spatialdata-atera-kidney/src/vitessce_config.py @@ -0,0 +1,133 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" +SDATA_URL = f"{BASE_URL}/Atera_v1_WTA_Kidney_non_diseased_FFPE.spatialdata.zarr" + +# Morphology image channels: (index, color). +IMAGE_CHANNELS = [ + (0, [0, 0, 255]), + (1, [0, 255, 0]), + (2, [255, 255, 0]), + (3, [255, 0, 0]), +] + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Atera WTA non-diseased human kidney (FFPE)", + description="10x Genomics Atera whole-transcriptome in situ dataset, with Azimuth cell type annotations", + ) + cells = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/morphology", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="shapes/cell_boundaries", + obs_set_paths=[ + "tables/table/obs/azimuth_broad", + "tables/table/obs/azimuth_coarse", + "tables/table/obs/azimuth_fine", + "tables/table/obs/leiden_res_1.0", + ], + obs_set_names=["Azimuth broad", "Azimuth coarse", "Azimuth fine", "Leiden (resolution 1.0)"], + obs_embedding_paths=["tables/table/obsm/X_umap"], + obs_embedding_names=["UMAP"], + coordinate_system="global", + coordination_values={"obsType": "cell", "fileUid": "cells"}, + ) + points = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/table", + obs_points_path="points/transcripts_with_morton_codes", + obs_points_feature_index_column="feature_name_codes", + obs_points_morton_code_column="morton_code_2d", + coordinate_system="global", + coordination_values={"obsType": "point", "featureType": "gene", "fileUid": "points"}, + ) + dataset = vc.add_dataset(name="Atera WTA non-diseased human kidney (FFPE)").add_object(cells).add_object(points) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=0, w=3, h=6) + feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=6, w=3, h=6) + scatterplot = vc.add_view("scatterplot", dataset=dataset, x=9, y=6, w=3, h=6) + + vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "fileUid": "cells", + "photometricInterpretation": "BlackIsZero", + "spatialLayerOpacity": 1.0, + "spatialLayerVisible": True, + "imageChannel": CL([ + { + "spatialTargetC": c, + "spatialChannelColor": color, + "spatialChannelVisible": True, + "spatialChannelOpacity": 1.0, + } + for c, color in IMAGE_CHANNELS + ]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "fileUid": "cells", + "spatialLayerOpacity": 1.0, + "spatialLayerVisible": True, + "segmentationChannel": CL([{ + "obsType": "cell", + "spatialChannelVisible": True, + "spatialChannelOpacity": 0.75, + "spatialChannelColor": [255, 255, 255], + "obsColorEncoding": "cellSetSelection", + "spatialSegmentationFilled": True, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + # The transcripts layer (~1 billion points) is hidden initially. + vc.link_views_by_dict([spatial, layer_controller], { + "pointLayer": CL([{ + "fileUid": "points", + "obsType": "point", + "spatialLayerOpacity": 1.0, + "spatialLayerVisible": False, + "obsColorEncoding": "geneSelection", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) + vc.link_views([spatial, layer_controller, obs_sets, feature_list, scatterplot], ["obsType"], ["cell"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/Snakefile b/demos/spatialdata-aviti24-teton-hela-tnfa/Snakefile index 98b37d89..50964367 100644 --- a/demos/spatialdata-aviti24-teton-hela-tnfa/Snakefile +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/Snakefile @@ -23,7 +23,8 @@ ZIP_MEMBER = "GEO_submission/Teton/RawCellStats_ACE_3678.parquet" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Convert the RawCellStats table to SpatialData (cells as circles, counts and morphology tables). rule convert_to_spatialdata: @@ -54,3 +55,17 @@ rule download_data: -m "{params.zip_member}" \ -o {output} ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/src/vitessce_config.py b/demos/spatialdata-aviti24-teton-hela-tnfa/src/vitessce_config.py new file mode 100644 index 00000000..1150f7fd --- /dev/null +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/src/vitessce_config.py @@ -0,0 +1,91 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="AVITI24 Teton CytoProfiling of TNF-alpha-stimulated HeLa cells", + description=( + "Element Biosciences AVITI24 RawCellStats from Zenodo 10.5281/zenodo.17394327 (Lopez et al.). " + "Cells are circles at their centroids, with tiles laid out on the flow cell grid." + ), + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/aviti24_teton_hela_tnfa.spatialdata.zarr", + table_path="tables/counts", + obs_feature_matrix_path="tables/counts/X", + obs_spots_path="shapes/cells", + obs_set_paths=[ + "tables/counts/obs/leiden", + "tables/counts/obs/treatment", + "tables/counts/obs/time_min", + "tables/counts/obs/well_label", + ], + obs_set_names=["Leiden clusters", "Treatment", "Time (minutes)", "Well label"], + obs_embedding_paths=["tables/counts/obsm/X_umap"], + obs_embedding_names=["UMAP"], + coordinate_system="global", + coordination_values={"obsType": "cell", "featureType": "target"}, + ) + dataset = vc.add_dataset(name="AVITI24 Teton").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=4) + feature_list = vc.add_view("featureList", dataset=dataset, x=9, y=0, w=3, h=4) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=4, w=3, h=8) + scatterplot = vc.add_view("scatterplot", dataset=dataset, x=9, y=4, w=3, h=8) + + obs_type, feature_type, obs_color_encoding = vc.add_coordination("obsType", "featureType", "obsColorEncoding") + obs_type.set_value("cell") + feature_type.set_value("target") + obs_color_encoding.set_value("cellSetSelection") + vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) + + # The spot layer shares obsType, featureType, and color encoding with the other views. + vc.link_views_by_dict([spatial, layer_controller], { + "spotLayer": CL([{ + "obsType": obs_type, + "featureType": feature_type, + "obsColorEncoding": obs_color_encoding, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) + for view in [spatial, layer_controller]: + view.use_coordination(obs_type, feature_type) + for view in [feature_list, obs_sets, scatterplot]: + view.use_coordination(obs_type, feature_type, obs_color_encoding) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/vitessce.template.json b/demos/spatialdata-aviti24-teton-hela-tnfa/vitessce.template.json index 15d90f99..5535e08d 100644 --- a/demos/spatialdata-aviti24-teton-hela-tnfa/vitessce.template.json +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/vitessce.template.json @@ -14,13 +14,7 @@ "obsFeatureMatrix": { "path": "tables/counts/X" }, - "obsSpots": { - "path": "shapes/cells", - "tablePath": "tables/counts", - "coordinateSystem": "global" - }, "obsSets": { - "tablePath": "tables/counts", "obsSets": [ { "name": "Leiden clusters", @@ -38,12 +32,21 @@ "name": "Well label", "path": "tables/counts/obs/well_label" } - ] + ], + "tablePath": "tables/counts" + }, + "obsSpots": { + "path": "shapes/cells", + "tablePath": "tables/counts", + "coordinateSystem": "global" }, "obsEmbedding": [ { "path": "tables/counts/obsm/X_umap", - "dims": [0, 1], + "dims": [ + 0, + 1 + ], "embeddingType": "UMAP" } ] @@ -66,12 +69,12 @@ "featureType": { "A": "target" }, - "embeddingType": { - "A": "UMAP" - }, "obsColorEncoding": { "A": "cellSetSelection" }, + "embeddingType": { + "A": "UMAP" + }, "spotLayer": { "init_A_obsSpots_0": "__dummy__" }, @@ -165,9 +168,9 @@ "component": "scatterplot", "coordinationScopes": { "dataset": "A", + "embeddingType": "A", "obsType": "A", "featureType": "A", - "embeddingType": "A", "obsColorEncoding": "A" }, "x": 9, diff --git a/demos/spatialdata-codex-hubmap-large-intestine/Snakefile b/demos/spatialdata-codex-hubmap-large-intestine/Snakefile index 4fe3b237..eca6387b 100644 --- a/demos/spatialdata-codex-hubmap-large-intestine/Snakefile +++ b/demos/spatialdata-codex-hubmap-large-intestine/Snakefile @@ -38,7 +38,8 @@ FILES = { rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Combine image, segmentation mask, and SPRM table into one SpatialData store. rule convert_to_spatialdata: @@ -70,3 +71,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -A "vitessce-demos" -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py b/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py new file mode 100644 index 00000000..710b7909 --- /dev/null +++ b/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py @@ -0,0 +1,124 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + +NAME = "CODEX human large intestine (HuBMAP HBM996.CGFD.228)" +DESCRIPTION = ( + "Akoya CODEX 54-channel image of human large intestine (Hickey et al. 2023) " + "with Cytokit segmentation and SPRM cell-by-marker table, from HuBMAP" +) +SDATA_URL = f"{BASE_URL}/codex_hubmap_large_intestine.spatialdata.zarr" +# Initially-visible image channels: (channel index, color, contrast window). +IMAGE_CHANNELS = [ + (0, [0, 0, 255], [0, 8000]), + (50, [0, 255, 0], [0, 4000]), + (7, [255, 0, 0], [0, 6000]), + (46, [255, 255, 0], [0, 1500]), + (25, [255, 0, 255], [0, 8000]), +] + + +def create_config(): + vc = VitessceConfig(schema_version="1.0.18", name=NAME, description=DESCRIPTION) + wrapper = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/image", + table_path="tables/table", + region="cell_labels", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="labels/cell_labels", + obs_set_paths=[ + "tables/table/obs/k_means_mean_expression", + "tables/table/obs/k_means_covariance_expression", + "tables/table/obs/k_means_total_expression", + "tables/table/obs/k_means_umap_all_features", + ], + obs_set_names=[ + "SPRM K-Means [Mean] Expression", + "SPRM K-Means [Covariance] Expression", + "SPRM K-Means [Total] Expression", + "SPRM K-Means [UMAP All Features]", + ], + obs_embedding_paths=["tables/table/obsm/X_tsne"], + obs_embedding_names=["t-SNE"], + coordinate_system="global", + coordination_values={"obsType": "cell", "featureType": "marker"}, + ) + dataset = vc.add_dataset(name=NAME).add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=6) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) + feature_list = vc.add_view("featureList", dataset=dataset, x=9, y=0, w=3, h=3) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=3, w=3, h=3) + scatterplot = vc.add_view("scatterplot", dataset=dataset, x=6, y=6, w=6, h=6) + heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=6, h=6) + + vc.link_views([scatterplot], ["embeddingType"], ["t-SNE"]) + # The segmentation outlines, feature list, cell sets, t-SNE, and heatmap share one color encoding. + [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + obs_color_encoding.set_value("cellSetSelection") + for view in [feature_list, obs_sets, scatterplot, heatmap]: + view.use_coordination(obs_color_encoding) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "BlackIsZero", + "spatialLayerOpacity": 1.0, + "imageChannel": CL([ + { + "spatialTargetC": c, + "spatialChannelColor": color, + "spatialChannelWindow": window, + "spatialChannelVisible": True, + } + for c, color, window in IMAGE_CHANNELS + ]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "spatialLayerVisible": True, + "spatialLayerOpacity": 1.0, + "segmentationChannel": CL([{ + "obsColorEncoding": obs_color_encoding, + "spatialChannelVisible": True, + "spatialSegmentationFilled": False, + "spatialSegmentationStrokeWidth": 1.0, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets, scatterplot, heatmap], ["obsType"], ["cell"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json b/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json index e90864ed..973bf3c7 100644 --- a/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json +++ b/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json @@ -310,54 +310,50 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 9, "y": 0, "w": 3, - "h": 3, - "coordinationScopesBy": {} + "h": 3 }, { "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 9, "y": 3, "w": 3, - "h": 3, - "coordinationScopesBy": {} + "h": 3 }, { "component": "scatterplot", "coordinationScopes": { "dataset": "A", "embeddingType": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 6, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "heatmap", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 0, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/spatialdata-cosmx-nsclc/Snakefile b/demos/spatialdata-cosmx-nsclc/Snakefile index 187a8f1d..11dc3fad 100644 --- a/demos/spatialdata-cosmx-nsclc/Snakefile +++ b/demos/spatialdata-cosmx-nsclc/Snakefile @@ -26,7 +26,8 @@ TAR_URL = f"https://nanostring-public-share.s3.us-west-2.amazonaws.com/SMI-Compr rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Stitch the per-FOV images, trace the cell boundaries from the label masks, # build the cell-by-gene table, and add the morton-sorted transcripts. @@ -63,3 +64,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py b/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py new file mode 100644 index 00000000..fe2c62a7 --- /dev/null +++ b/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py @@ -0,0 +1,106 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" +SDATA_URL = f"{BASE_URL}/cosmx_nsclc_lung9_rep1.spatialdata.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="CosMx SMI NSCLC (Lung9_Rep1)", + description=( + "NanoString CosMx non-small-cell lung cancer FFPE dataset (He et al. 2022), section Lung9_Rep1: " + "stitched CellComposite image, cell boundaries, Leiden clusters, and morton-sorted transcripts" + ), + ) + cells = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/composite", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="shapes/cell_boundaries", + obs_set_paths=["tables/table/obs/leiden", "tables/table/obs/fov"], + obs_set_names=["Leiden", "FOV"], + coordinate_system="global", + coordination_values={"obsType": "cell"}, + ) + points = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + # The transcripts are morton-sorted in place by src/convert_to_spatialdata.py. + obs_points_path="points/transcripts", + coordinate_system="global", + coordination_values={"obsType": "point", "featureType": "gene"}, + ) + dataset = vc.add_dataset(name="CosMx").add_object(cells).add_object(points) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=6, h=3) + feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=3, w=6, h=3) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=6, w=6, h=6) + + # The cell segmentations, feature list, and cell sets share one color encoding. + [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + obs_color_encoding.set_value("cellSetSelection") + for view in [feature_list, obs_sets]: + view.use_coordination(obs_color_encoding) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + "spatialLayerOpacity": 1.0, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "segmentationChannel": CL([{ + "obsType": "cell", + "obsColorEncoding": obs_color_encoding, + "spatialChannelOpacity": 0.5, + "spatialSegmentationFilled": False, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + # The transcripts layer is hidden initially. + vc.link_views_by_dict([spatial, layer_controller], { + "pointLayer": CL([{ + "obsType": "point", + "spatialLayerVisible": False, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets], ["obsType"], ["cell"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-cosmx-nsclc/vitessce.template.json b/demos/spatialdata-cosmx-nsclc/vitessce.template.json index ef1caeb4..6b6e9aa4 100644 --- a/demos/spatialdata-cosmx-nsclc/vitessce.template.json +++ b/demos/spatialdata-cosmx-nsclc/vitessce.template.json @@ -211,27 +211,25 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 6, "y": 3, "w": 6, - "h": 3, - "coordinationScopesBy": {} + "h": 3 }, { "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 6, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile b/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile index 59281910..e4642f16 100644 --- a/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile +++ b/demos/spatialdata-dbit-seq-mouse-embryo/Snakefile @@ -31,7 +31,8 @@ FILES = { rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Build a SpatialData object with the tissue image, the pixels as square polygon Shapes, # and one table per modality ("rna" and "protein"), both annotating the pixels. @@ -64,3 +65,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py b/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py new file mode 100644 index 00000000..d68fde27 --- /dev/null +++ b/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py @@ -0,0 +1,120 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, +) + +BASE_URL = "{{ base_url }}" +SDATA_URL = f"{BASE_URL}/dbit_seq_mouse_embryo_e10.spatialdata.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="DBiT-seq E10 mouse embryo (Liu et al. 2020)", + description="DBiT-seq 50 um pixels with co-profiled mRNA and protein (GEO GSE137986, samples GSM4189613 and GSM4202307)", + ) + # Both tables annotate the same `pixels` shapes element. + rna = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/tissue_image", + table_path="tables/rna", + region="pixels", + obs_feature_matrix_path="tables/rna/X", + obs_segmentations_path="shapes/pixels", + obs_set_paths=["tables/rna/obs/leiden"], + obs_set_names=["Leiden (RNA)"], + obs_embedding_paths=["tables/rna/obsm/X_umap"], + obs_embedding_names=["UMAP"], + coordinate_system="global", + coordination_values={"obsType": "pixel", "featureType": "gene", "featureValueType": "expression"}, + ) + protein = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/protein", + region="pixels", + obs_feature_matrix_path="tables/protein/X", + coordination_values={"obsType": "pixel", "featureType": "protein", "featureValueType": "expression"}, + ) + dataset = vc.add_dataset(name="DBiT-seq E10 mouse embryo (Liu et al. 2020)").add_object(rna).add_object(protein) + + rna_spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=3, h=6).set_props(title="Spatial (mRNA)") + rna_layers = vc.add_view("layerControllerBeta", dataset=dataset, x=3, y=0, w=3, h=3).set_props(title="Layers (mRNA)") + rna_features = vc.add_view("featureList", dataset=dataset, x=3, y=3, w=3, h=3).set_props(title="mRNA features") + protein_spatial = vc.add_view("spatialBeta", dataset=dataset, x=6, y=0, w=3, h=6).set_props(title="Spatial (Protein)") + protein_layers = vc.add_view("layerControllerBeta", dataset=dataset, x=9, y=0, w=3, h=3).set_props(title="Layers (Protein)") + protein_features = vc.add_view("featureList", dataset=dataset, x=9, y=3, w=3, h=3).set_props(title="Protein features") + obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=6, w=6, h=6) + scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=6, w=6, h=6) + + # The two spatial views share zoom and target. + vc.link_views([rna_spatial, protein_spatial], ["spatialZoom", "spatialTargetX", "spatialTargetY"], [None, None, None]) + vc.link_views( + [rna_spatial, rna_layers, rna_features, protein_spatial, protein_layers, protein_features, obs_sets, scatterplot], + ["obsType"], + ["pixel"], + ) + vc.link_views([obs_sets, scatterplot], ["obsColorEncoding"], ["cellSetSelection"]) + vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) + + # Each spatial view shows the tissue image and the pixels colored by one modality. + for modality, spatial, layers, features, feature_type, feature in [ + ("rna", rna_spatial, rna_layers, rna_features, "gene", "Hbb-y"), + ("protein", protein_spatial, protein_layers, protein_features, "protein", "CD326-Ep-CAM"), + ]: + f_type, f_value_type, f_selection, color_encoding = vc.add_coordination( + "featureType", "featureValueType", "featureSelection", "obsColorEncoding", + ) + f_type.set_value(feature_type) + f_value_type.set_value("expression") + f_selection.set_value([feature]) + color_encoding.set_value("geneSelection") + features.use_coordination(f_type, f_value_type, f_selection, color_encoding) + vc.link_views_by_dict([spatial, layers], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + "spatialLayerOpacity": 1.0, + }]), + "segmentationLayer": CL([{ + "spatialLayerOpacity": 1.0, + "segmentationChannel": CL([{ + "obsType": "pixel", + "featureType": f_type, + "featureValueType": f_value_type, + "featureSelection": f_selection, + "obsColorEncoding": color_encoding, + "spatialChannelOpacity": 0.8, + "spatialSegmentationFilled": True, + "spatialChannelVisible": True, + }]), + }]), + }, scope_prefix=f"init_{modality}_") + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json b/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json index 2121d7df..0e39dca8 100644 --- a/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json +++ b/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json @@ -82,23 +82,18 @@ "spatialTargetY": { "A": null }, - "imageLayer": { - "A": null, - "init_rna_0": "__dummy__", - "init_protein_0": "__dummy__" + "obsType": { + "A": "pixel", + "init_rna_0": "pixel", + "init_protein_0": "pixel" }, "obsColorEncoding": { - "A": "geneSelection", + "A": "cellSetSelection", "B": "geneSelection", - "C": "cellSetSelection" + "C": "geneSelection" }, - "featureSelection": { - "A": [ - "Hbb-y" - ], - "B": [ - "CD326-Ep-CAM" - ] + "embeddingType": { + "A": "UMAP" }, "featureType": { "A": "gene", @@ -108,6 +103,18 @@ "A": "expression", "B": "expression" }, + "featureSelection": { + "A": [ + "Hbb-y" + ], + "B": [ + "CD326-Ep-CAM" + ] + }, + "imageLayer": { + "init_rna_0": "__dummy__", + "init_protein_0": "__dummy__" + }, "photometricInterpretation": { "init_rna_0": "RGB", "init_protein_0": "RGB" @@ -126,11 +133,6 @@ "init_rna_0": "__dummy__", "init_protein_0": "__dummy__" }, - "obsType": { - "init_rna_0": "pixel", - "init_protein_0": "pixel", - "A": "pixel" - }, "spatialChannelOpacity": { "init_rna_0": 0.8, "init_protein_0": 0.8 @@ -195,7 +197,7 @@ "init_rna_0": "A" }, "obsColorEncoding": { - "init_rna_0": "A" + "init_rna_0": "B" }, "spatialChannelOpacity": { "init_rna_0": "init_rna_0" @@ -241,7 +243,7 @@ "init_protein_0": "B" }, "obsColorEncoding": { - "init_protein_0": "B" + "init_protein_0": "C" }, "spatialChannelOpacity": { "init_protein_0": "init_protein_0" @@ -254,9 +256,6 @@ } } } - }, - "embeddingType": { - "A": "UMAP" } }, "layout": [ @@ -264,16 +263,16 @@ "component": "spatialBeta", "coordinationScopes": { "dataset": "A", + "spatialZoom": "A", + "spatialTargetX": "A", + "spatialTargetY": "A", + "obsType": "A", "metaCoordinationScopes": [ "init_rna_0" ], "metaCoordinationScopesBy": [ "init_rna_0" - ], - "spatialZoom": "A", - "spatialTargetX": "A", - "spatialTargetY": "A", - "obsType": "A" + ] }, "x": 0, "y": 0, @@ -287,13 +286,13 @@ "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", + "obsType": "A", "metaCoordinationScopes": [ "init_rna_0" ], "metaCoordinationScopesBy": [ "init_rna_0" - ], - "obsType": "A" + ] }, "x": 3, "y": 0, @@ -307,11 +306,11 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", + "obsType": "A", "featureType": "A", "featureValueType": "A", "featureSelection": "A", - "obsColorEncoding": "A", - "obsType": "A" + "obsColorEncoding": "B" }, "x": 3, "y": 3, @@ -319,23 +318,22 @@ "h": 3, "props": { "title": "mRNA features" - }, - "coordinationScopesBy": {} + } }, { "component": "spatialBeta", "coordinationScopes": { "dataset": "A", + "spatialZoom": "A", + "spatialTargetX": "A", + "spatialTargetY": "A", + "obsType": "A", "metaCoordinationScopes": [ "init_protein_0" ], "metaCoordinationScopesBy": [ "init_protein_0" - ], - "spatialZoom": "A", - "spatialTargetX": "A", - "spatialTargetY": "A", - "obsType": "A" + ] }, "x": 6, "y": 0, @@ -349,13 +347,13 @@ "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", + "obsType": "A", "metaCoordinationScopes": [ "init_protein_0" ], "metaCoordinationScopesBy": [ "init_protein_0" - ], - "obsType": "A" + ] }, "x": 9, "y": 0, @@ -369,11 +367,11 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", + "obsType": "A", "featureType": "B", "featureValueType": "B", "featureSelection": "B", - "obsColorEncoding": "B", - "obsType": "A" + "obsColorEncoding": "C" }, "x": 9, "y": 3, @@ -381,35 +379,32 @@ "h": 3, "props": { "title": "Protein features" - }, - "coordinationScopesBy": {} + } }, { "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsColorEncoding": "C", - "obsType": "A" + "obsType": "A", + "obsColorEncoding": "A" }, "x": 6, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "scatterplot", "coordinationScopes": { "dataset": "A", - "embeddingType": "A", - "obsColorEncoding": "C", - "obsType": "A" + "obsType": "A", + "obsColorEncoding": "A", + "embeddingType": "A" }, "x": 0, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/spatialdata-geomx-mouse-embryo/Snakefile b/demos/spatialdata-geomx-mouse-embryo/Snakefile index 7ac5d165..b9481c3f 100644 --- a/demos/spatialdata-geomx-mouse-embryo/Snakefile +++ b/demos/spatialdata-geomx-mouse-embryo/Snakefile @@ -25,7 +25,8 @@ CHANNEL_NAMES = "DNA (SYTO 13),Autofluorescence (Cy3),beta3-tubulin (Alexa 594), rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" rule convert_to_spatialdata: input: @@ -77,3 +78,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-geomx-mouse-embryo/src/vitessce_config.py b/demos/spatialdata-geomx-mouse-embryo/src/vitessce_config.py new file mode 100644 index 00000000..d41a0584 --- /dev/null +++ b/demos/spatialdata-geomx-mouse-embryo/src/vitessce_config.py @@ -0,0 +1,113 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + +# Image channels: (channel index, color, contrast window, visible). +# Marker names (from the dataset README): DNA, autofluorescence, beta3-tubulin, p63. +IMAGE_CHANNELS = [ + (0, [0, 0, 255], [0, 3000], True), + (1, [255, 255, 255], [0, 500], False), + (2, [0, 255, 0], [0, 400], True), + (3, [255, 0, 0], [0, 1100], True), +] + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="GeoMx DSP mouse embryo (E11)", + description=( + "NanoString Spatial Organ Atlas, mouse embryonic development, scan mu_dev_E11_004: " + "AOI polygons with Q3-normalized whole-transcriptome counts" + ), + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/geomx_mouse_embryo_e11.spatialdata.zarr", + image_path="images/image", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + # Areas of illumination (AOIs) as polygons. + obs_segmentations_path="shapes/aois", + obs_set_paths=[ + "tables/table/obs/Tissue", + "tables/table/obs/Tissue_annotation", + "tables/table/obs/Tissue_substructure", + "tables/table/obs/Tissue_type", + "tables/table/obs/p63_expression", + ], + obs_set_names=["Tissue", "Tissue annotation", "Tissue substructure", "Tissue type", "p63 expression"], + coordinate_system="global", + coordination_values={"obsType": "AOI"}, + ) + dataset = vc.add_dataset(name="GeoMx").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=6) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=6, h=6) + feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=6, w=3, h=6) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=6, w=3, h=6) + heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=6, h=6) + + # The AOI polygons, feature list, AOI sets, and heatmap share one color encoding. + [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + obs_color_encoding.set_value("cellSetSelection") + for view in [feature_list, obs_sets, heatmap]: + view.use_coordination(obs_color_encoding) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "BlackIsZero", + "imageChannel": CL([ + { + "spatialTargetC": c, + "spatialChannelColor": color, + "spatialChannelWindow": window, + "spatialChannelVisible": visible, + } + for c, color, window, visible in IMAGE_CHANNELS + ]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "segmentationChannel": CL([{ + "obsColorEncoding": obs_color_encoding, + "spatialChannelOpacity": 0.6, + "spatialSegmentationFilled": True, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets, heatmap], ["obsType"], ["AOI"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-geomx-mouse-embryo/vitessce.template.json b/demos/spatialdata-geomx-mouse-embryo/vitessce.template.json index 6a719da5..e1d068e9 100644 --- a/demos/spatialdata-geomx-mouse-embryo/vitessce.template.json +++ b/demos/spatialdata-geomx-mouse-embryo/vitessce.template.json @@ -261,40 +261,37 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 6, "y": 6, "w": 3, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 9, "y": 6, "w": 3, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "heatmap", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 0, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/Snakefile b/demos/spatialdata-illumina-stratamap-mouse-kidney/Snakefile index 2b90a109..78e3a606 100644 --- a/demos/spatialdata-illumina-stratamap-mouse-kidney/Snakefile +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/Snakefile @@ -27,7 +27,8 @@ SAMPLE_ID = "mouse_kidney" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" rule convert_to_spatialdata: input: @@ -54,3 +55,17 @@ rule manual_download: echo "Place the DRAGEN StrataMap results folder for the sample at {output} (see the comments in this Snakefile)." >&2 exit 1 ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/src/vitessce_config.py b/demos/spatialdata-illumina-stratamap-mouse-kidney/src/vitessce_config.py new file mode 100644 index 00000000..bb08c2a5 --- /dev/null +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/src/vitessce_config.py @@ -0,0 +1,87 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Illumina StrataMap Spatial (mouse kidney demo)", + description=( + "Illumina StrataMap Spatial Transcriptome demo dataset (DRAGEN StrataMap outputs): " + "registered H&E, 5 um-expanded cell contours, cell-binned counts, Leiden clusters" + ), + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/stratamap_mouse_kidney.spatialdata.zarr", + image_path="images/he", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="shapes/cell_boundaries", + obs_set_paths=["tables/table/obs/leiden"], + obs_set_names=["Leiden"], + coordinate_system="global", + coordination_values={"obsType": "cell"}, + ) + dataset = vc.add_dataset(name="StrataMap").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=6, h=3) + feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=3, w=6, h=3) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=6, w=6, h=6) + + # The cell outlines, feature list, and cell sets share one color encoding. + [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + obs_color_encoding.set_value("cellSetSelection") + for view in [feature_list, obs_sets]: + view.use_coordination(obs_color_encoding) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "segmentationChannel": CL([{ + "obsColorEncoding": obs_color_encoding, + "spatialChannelOpacity": 0.5, + "spatialSegmentationFilled": False, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets], ["obsType"], ["cell"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/vitessce.template.json b/demos/spatialdata-illumina-stratamap-mouse-kidney/vitessce.template.json index 6625efde..ef09053d 100644 --- a/demos/spatialdata-illumina-stratamap-mouse-kidney/vitessce.template.json +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/vitessce.template.json @@ -153,27 +153,25 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 6, "y": 3, "w": 6, - "h": 3, - "coordinationScopesBy": {} + "h": 3 }, { "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 6, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/Snakefile b/demos/spatialdata-maldi-msi-timstof-mouse-brain/Snakefile index b5198c41..7d07cd85 100644 --- a/demos/spatialdata-maldi-msi-timstof-mouse-brain/Snakefile +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/Snakefile @@ -26,7 +26,8 @@ D_DIR_NAME = "20240826_Xenium_0041899.d" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Select the most intense peaks of the average spectrum, rasterize the MSI pixels # to a Labels element annotated by a (pixels x peaks) table, cluster the pixels, @@ -92,3 +93,17 @@ rule download_data: curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" python3 -c "import hashlib, sys; h = hashlib.md5(); f = open(sys.argv[1], 'rb'); [h.update(b) for b in iter(lambda: f.read(1 << 24), b'')]; sys.exit(0 if h.hexdigest() == sys.argv[2] else 'MD5 mismatch for ' + sys.argv[1])" {output} {params.md5} ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/vitessce_config.py b/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/vitessce_config.py new file mode 100644 index 00000000..dc58985e --- /dev/null +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/vitessce_config.py @@ -0,0 +1,95 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="MALDI-MSI sagittal mouse brain (Bruker timsTOF)", + description=( + "MALDI mass spectrometry imaging from Zenodo 10.5281/zenodo.18326569, converted with Thyra, " + "with the 100 most intense peaks of the average spectrum and k-means clusters of pixels" + ), + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/maldi_msi_mouse_brain.spatialdata.zarr", + # The aligned optical image if Thyra provides one, otherwise the TIC image. + image_path="images/background_image", + table_path="tables/msi_peaks", + obs_feature_matrix_path="tables/msi_peaks/X", + # MSI pixels, rasterized to a Labels element. + obs_segmentations_path="labels/pixel_labels", + obs_set_paths=["tables/msi_peaks/obs/kmeans"], + obs_set_names=["K-means clusters"], + coordinate_system="global", + coordination_values={"obsType": "pixel", "featureType": "peak", "featureValueType": "intensity"}, + ) + dataset = vc.add_dataset(name="MALDI-MSI").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=8, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=8, y=0, w=4, h=4) + feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=4, h=4) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=8, w=4, h=4) + + obs_type, feature_type, feature_value_type, obs_color_encoding = vc.add_coordination( + "obsType", "featureType", "featureValueType", "obsColorEncoding", + ) + obs_type.set_value("pixel") + feature_type.set_value("peak") + feature_value_type.set_value("intensity") + obs_color_encoding.set_value("cellSetSelection") + for view in [spatial, layer_controller]: + view.use_coordination(obs_type, feature_type, feature_value_type) + for view in [feature_list, obs_sets]: + view.use_coordination(obs_type, feature_type, feature_value_type, obs_color_encoding) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{}]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + # The pixel labels share obsType, feature, and color encoding scopes with the other views. + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "segmentationChannel": CL([{ + "obsType": obs_type, + "featureType": feature_type, + "featureValueType": feature_value_type, + "spatialChannelOpacity": 0.75, + "obsColorEncoding": obs_color_encoding, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/vitessce.template.json b/demos/spatialdata-maldi-msi-timstof-mouse-brain/vitessce.template.json index 3d6b0248..fef903cb 100644 --- a/demos/spatialdata-maldi-msi-timstof-mouse-brain/vitessce.template.json +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/vitessce.template.json @@ -14,6 +14,15 @@ "obsFeatureMatrix": { "path": "tables/msi_peaks/X" }, + "obsSets": { + "obsSets": [ + { + "name": "K-means clusters", + "path": "tables/msi_peaks/obs/kmeans" + } + ], + "tablePath": "tables/msi_peaks" + }, "image": { "path": "images/background_image", "coordinateSystem": "global" @@ -22,15 +31,6 @@ "path": "labels/pixel_labels", "tablePath": "tables/msi_peaks", "coordinateSystem": "global" - }, - "obsSets": { - "tablePath": "tables/msi_peaks", - "obsSets": [ - { - "name": "K-means clusters", - "path": "tables/msi_peaks/obs/kmeans" - } - ] } }, "coordinationValues": { @@ -55,21 +55,12 @@ "featureValueType": { "A": "intensity" }, - "imageLayer": { - "init_A_image_0": "__dummy__" - }, - "segmentationLayer": { - "init_A_obsSegmentations_0": "__dummy__" - }, - "segmentationChannel": { - "init_A_obsSegmentations_0": "__dummy__" - }, - "spatialChannelOpacity": { - "init_A_obsSegmentations_0": 0.75 - }, "obsColorEncoding": { "A": "cellSetSelection" }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, "metaCoordinationScopes": { "init_A_image_0": { "imageLayer": [ @@ -110,6 +101,15 @@ } } } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.75 } }, "layout": [ @@ -117,6 +117,9 @@ "component": "spatialBeta", "coordinationScopes": { "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureValueType": "A", "metaCoordinationScopes": [ "init_A_image_0", "init_A_obsSegmentations_0" @@ -124,10 +127,7 @@ "metaCoordinationScopesBy": [ "init_A_image_0", "init_A_obsSegmentations_0" - ], - "obsType": "A", - "featureType": "A", - "featureValueType": "A" + ] }, "x": 0, "y": 0, @@ -138,6 +138,9 @@ "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureValueType": "A", "metaCoordinationScopes": [ "init_A_image_0", "init_A_obsSegmentations_0" @@ -145,10 +148,7 @@ "metaCoordinationScopesBy": [ "init_A_image_0", "init_A_obsSegmentations_0" - ], - "obsType": "A", - "featureType": "A", - "featureValueType": "A" + ] }, "x": 8, "y": 0, diff --git a/demos/spatialdata-merfish-zhuang-abca-4/Snakefile b/demos/spatialdata-merfish-zhuang-abca-4/Snakefile index 3b025ef2..2b84af5f 100644 --- a/demos/spatialdata-merfish-zhuang-abca-4/Snakefile +++ b/demos/spatialdata-merfish-zhuang-abca-4/Snakefile @@ -30,7 +30,8 @@ METADATA_URL = f"{ABC_ATLAS_URL}/metadata/Zhuang-ABCA-4/20241115/views/cell_meta rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" rule to_spatialdata: input: @@ -67,3 +68,17 @@ rule download_metadata: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py b/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py new file mode 100644 index 00000000..3826389d --- /dev/null +++ b/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py @@ -0,0 +1,78 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="MERFISH whole mouse brain (Zhuang-ABCA-4)", + description=( + "Zhuang lab MERFISH (Zhang et al. 2023), three sagittal sections laid out side by side, " + "with ABC atlas cell type labels" + ), + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/zhuang_abca_4.spatialdata.zarr", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + # The source data has no segmentations, so each cell is a circle. + obs_spots_path="shapes/cell_circles", + obs_set_paths=[ + "tables/table/obs/class", + "tables/table/obs/subclass", + "tables/table/obs/supertype", + "tables/table/obs/neurotransmitter", + "tables/table/obs/brain_section_label", + ], + obs_set_names=["Class", "Subclass", "Supertype", "Neurotransmitter", "Brain section"], + coordinate_system="global", + coordination_values={"obsType": "cell"}, + ) + dataset = vc.add_dataset(name="Zhuang-ABCA-4").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=8, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=8, y=0, w=4, h=3) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=3, w=4, h=5) + feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=8, w=4, h=4) + + vc.link_views_by_dict([spatial, layer_controller], { + "spotLayer": CL([{ + "obsColorEncoding": "cellSetSelection", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) + vc.link_views([spatial, layer_controller, obs_sets, feature_list], ["obsType"], ["cell"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json b/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json index 0cdf86b8..8c1ed217 100644 --- a/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json +++ b/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json @@ -14,13 +14,7 @@ "obsFeatureMatrix": { "path": "tables/table/X" }, - "obsSpots": { - "path": "shapes/cell_circles", - "tablePath": "tables/table", - "coordinateSystem": "global" - }, "obsSets": { - "tablePath": "tables/table", "obsSets": [ { "name": "Class", @@ -42,7 +36,13 @@ "name": "Brain section", "path": "tables/table/obs/brain_section_label" } - ] + ], + "tablePath": "tables/table" + }, + "obsSpots": { + "path": "shapes/cell_circles", + "tablePath": "tables/table", + "coordinateSystem": "global" } }, "coordinationValues": { @@ -56,6 +56,12 @@ "dataset": { "A": "A" }, + "spotLayer": { + "init_A_obsSpots_0": "__dummy__" + }, + "obsColorEncoding": { + "init_A_obsSpots_0": "cellSetSelection" + }, "metaCoordinationScopes": { "init_A_obsSpots_0": { "spotLayer": [ @@ -72,12 +78,6 @@ } } }, - "spotLayer": { - "init_A_obsSpots_0": "__dummy__" - }, - "obsColorEncoding": { - "init_A_obsSpots_0": "cellSetSelection" - }, "obsType": { "A": "cell" } diff --git a/demos/spatialdata-merscope-mouse-brain/Snakefile b/demos/spatialdata-merscope-mouse-brain/Snakefile index 625446aa..df6354fd 100644 --- a/demos/spatialdata-merscope-mouse-brain/Snakefile +++ b/demos/spatialdata-merscope-mouse-brain/Snakefile @@ -39,7 +39,8 @@ INTERMEDIATE_DIR = DATA_DIR / "intermediate" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" rule to_spatialdata: input: @@ -126,3 +127,17 @@ rule download_csv: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-merscope-mouse-brain/src/vitessce_config.py b/demos/spatialdata-merscope-mouse-brain/src/vitessce_config.py new file mode 100644 index 00000000..14c0b660 --- /dev/null +++ b/demos/spatialdata-merscope-mouse-brain/src/vitessce_config.py @@ -0,0 +1,126 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" +SDATA_URL = f"{BASE_URL}/merscope_mouse_brain_slice2_replicate1.spatialdata.zarr" + +# Mosaic image channels (DAPI, PolyT): (index, color). +IMAGE_CHANNELS = [ + (0, [0, 0, 255]), + (1, [0, 255, 0]), +] + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="MERSCOPE mouse brain receptor map (slice 2, replicate 1)", + description="Vizgen MERFISH Mouse Brain Receptor Map (483 genes), with Leiden clusters computed in the processing script", + ) + cells = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/mouse_brain_slice2_replicate1_z3", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="shapes/mouse_brain_slice2_replicate1_polygons", + obs_set_paths=["tables/table/obs/leiden"], + obs_set_names=["Leiden"], + obs_embedding_paths=["tables/table/obsm/X_umap"], + obs_embedding_names=["UMAP"], + coordinate_system="global", + coordination_values={"obsType": "cell", "fileUid": "cells"}, + ) + points = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/table", + obs_points_path="points/transcripts_with_morton_codes", + obs_points_feature_index_column="gene_codes", + obs_points_morton_code_column="morton_code_2d", + coordinate_system="global", + coordination_values={"obsType": "point", "featureType": "gene", "fileUid": "points"}, + ) + dataset = vc.add_dataset(name="MERSCOPE mouse brain receptor map (slice 2, replicate 1)").add_object(cells).add_object(points) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=0, w=3, h=6) + feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=6, w=3, h=6) + scatterplot = vc.add_view("scatterplot", dataset=dataset, x=9, y=6, w=3, h=6) + + vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "fileUid": "cells", + "photometricInterpretation": "BlackIsZero", + "spatialLayerOpacity": 1.0, + "spatialLayerVisible": True, + "imageChannel": CL([ + { + "spatialTargetC": c, + "spatialChannelColor": color, + "spatialChannelVisible": True, + "spatialChannelOpacity": 1.0, + } + for c, color in IMAGE_CHANNELS + ]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "fileUid": "cells", + "spatialLayerOpacity": 1.0, + "spatialLayerVisible": True, + "segmentationChannel": CL([{ + "obsType": "cell", + "spatialChannelVisible": True, + "spatialChannelOpacity": 0.75, + "spatialChannelColor": [255, 255, 255], + "obsColorEncoding": "cellSetSelection", + "spatialSegmentationFilled": True, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + # The transcripts layer is hidden initially. + vc.link_views_by_dict([spatial, layer_controller], { + "pointLayer": CL([{ + "fileUid": "points", + "obsType": "point", + "spatialLayerOpacity": 1.0, + "spatialLayerVisible": False, + "obsColorEncoding": "geneSelection", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) + vc.link_views([spatial, layer_controller, obs_sets, feature_list, scatterplot], ["obsType"], ["cell"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-mibi-hubmap-uterus/Snakefile b/demos/spatialdata-mibi-hubmap-uterus/Snakefile index 85eca2f1..4aa9e85c 100644 --- a/demos/spatialdata-mibi-hubmap-uterus/Snakefile +++ b/demos/spatialdata-mibi-hubmap-uterus/Snakefile @@ -36,7 +36,8 @@ FILES = { rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Combine image, segmentation mask, and SPRM table into one SpatialData store. rule convert_to_spatialdata: @@ -68,3 +69,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -A "vitessce-demos" -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py b/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py new file mode 100644 index 00000000..1eae8cf5 --- /dev/null +++ b/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py @@ -0,0 +1,124 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + +NAME = "MIBI maternal-fetal interface (HuBMAP HBM957.GCWC.626)" +DESCRIPTION = ( + "Ionpath MIBIscope image of human decidua (Greenbaum et al. 2023) " + "with DeepCell segmentation and SPRM cell-by-marker table, from HuBMAP" +) +SDATA_URL = f"{BASE_URL}/mibi_hubmap_uterus.spatialdata.zarr" +# Initially-visible image channels: (channel index, color, contrast window). +IMAGE_CHANNELS = [ + (26, [0, 0, 255], [0, 40]), + (44, [0, 255, 0], [0, 20]), + (28, [255, 0, 0], [0, 8]), + (2, [255, 255, 0], [0, 15]), + (37, [255, 0, 255], [0, 10]), +] + + +def create_config(): + vc = VitessceConfig(schema_version="1.0.18", name=NAME, description=DESCRIPTION) + wrapper = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/image", + table_path="tables/table", + region="cell_labels", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="labels/cell_labels", + obs_set_paths=[ + "tables/table/obs/k_means_mean_expression", + "tables/table/obs/k_means_covariance_expression", + "tables/table/obs/k_means_total_expression", + "tables/table/obs/k_means_umap_all_features", + ], + obs_set_names=[ + "SPRM K-Means [Mean] Expression", + "SPRM K-Means [Covariance] Expression", + "SPRM K-Means [Total] Expression", + "SPRM K-Means [UMAP All Features]", + ], + obs_embedding_paths=["tables/table/obsm/X_tsne"], + obs_embedding_names=["t-SNE"], + coordinate_system="global", + coordination_values={"obsType": "cell", "featureType": "marker"}, + ) + dataset = vc.add_dataset(name=NAME).add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=6) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) + feature_list = vc.add_view("featureList", dataset=dataset, x=9, y=0, w=3, h=3) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=3, w=3, h=3) + scatterplot = vc.add_view("scatterplot", dataset=dataset, x=6, y=6, w=6, h=6) + heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=6, h=6) + + vc.link_views([scatterplot], ["embeddingType"], ["t-SNE"]) + # The segmentation outlines, feature list, cell sets, t-SNE, and heatmap share one color encoding. + [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + obs_color_encoding.set_value("cellSetSelection") + for view in [feature_list, obs_sets, scatterplot, heatmap]: + view.use_coordination(obs_color_encoding) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "BlackIsZero", + "spatialLayerOpacity": 1.0, + "imageChannel": CL([ + { + "spatialTargetC": c, + "spatialChannelColor": color, + "spatialChannelWindow": window, + "spatialChannelVisible": True, + } + for c, color, window in IMAGE_CHANNELS + ]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "spatialLayerVisible": True, + "spatialLayerOpacity": 1.0, + "segmentationChannel": CL([{ + "obsColorEncoding": obs_color_encoding, + "spatialChannelVisible": True, + "spatialSegmentationFilled": False, + "spatialSegmentationStrokeWidth": 1.0, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets, scatterplot, heatmap], ["obsType"], ["cell"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json b/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json index 69bf4da7..0781fda3 100644 --- a/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json +++ b/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json @@ -310,54 +310,50 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 9, "y": 0, "w": 3, - "h": 3, - "coordinationScopesBy": {} + "h": 3 }, { "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 9, "y": 3, "w": 3, - "h": 3, - "coordinationScopesBy": {} + "h": 3 }, { "component": "scatterplot", "coordinationScopes": { "dataset": "A", "embeddingType": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 6, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "heatmap", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 0, "y": 6, "w": 6, - "h": 6, - "coordinationScopesBy": {} + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/Snakefile b/demos/spatialdata-slide-seq-hubmap-kidney/Snakefile index 807ca6c0..1dd7011c 100644 --- a/demos/spatialdata-slide-seq-hubmap-kidney/Snakefile +++ b/demos/spatialdata-slide-seq-hubmap-kidney/Snakefile @@ -25,7 +25,8 @@ H5AD_URL = "https://assets.hubmapconsortium.org/17fb6d5db17936acc8fb613ce98ab808 rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Convert the HuBMAP AnnData object to a SpatialData object, # with beads as circle Shapes annotated by the table. @@ -52,3 +53,17 @@ rule download_data: ''' curl -L -A "vitessce-demos" --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/src/vitessce_config.py b/demos/spatialdata-slide-seq-hubmap-kidney/src/vitessce_config.py new file mode 100644 index 00000000..ada69245 --- /dev/null +++ b/demos/spatialdata-slide-seq-hubmap-kidney/src/vitessce_config.py @@ -0,0 +1,79 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Slide-seq human kidney (HuBMAP HBM537.GVTL.683)", + description=( + "Slide-seqV2 beads from HuBMAP dataset HBM537.GVTL.683, with Leiden clusters, UMAP, " + "and Azimuth cell type predictions from the HuBMAP Salmon pipeline" + ), + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/hubmap_slide_seq_kidney.spatialdata.zarr", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + obs_spots_path="shapes/beads", + obs_set_paths=["tables/table/obs/leiden", "tables/table/obs/predicted_ASCT_celltype"], + obs_set_names=["Leiden", "Predicted cell type (Azimuth)"], + obs_embedding_paths=["tables/table/obsm/X_umap"], + obs_embedding_names=["UMAP"], + coordinate_system="global", + coordination_values={"obsType": "bead"}, + ) + dataset = vc.add_dataset(name="Slide-seq").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=4, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=4, y=0, w=4, h=6) + feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=0, w=4, h=6) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=6, w=4, h=6) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=4, y=6, w=4, h=6) + + # The spot layer, feature list, cell sets, and UMAP share one color encoding. + [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + obs_color_encoding.set_value("cellSetSelection") + vc.link_views_by_dict([spatial, layer_controller], { + "spotLayer": CL([{ + "obsColorEncoding": obs_color_encoding, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) + for view in [feature_list, obs_sets, scatterplot]: + view.use_coordination(obs_color_encoding) + vc.link_views([spatial, layer_controller, feature_list, obs_sets, scatterplot], ["obsType"], ["bead"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/vitessce.template.json b/demos/spatialdata-slide-seq-hubmap-kidney/vitessce.template.json index 39cc8260..94e07f85 100644 --- a/demos/spatialdata-slide-seq-hubmap-kidney/vitessce.template.json +++ b/demos/spatialdata-slide-seq-hubmap-kidney/vitessce.template.json @@ -12,8 +12,7 @@ "url": "{{ base_url }}/hubmap_slide_seq_kidney.spatialdata.zarr", "options": { "obsFeatureMatrix": { - "path": "tables/table/X", - "region": "beads" + "path": "tables/table/X" }, "obsSets": { "obsSets": [ @@ -26,8 +25,7 @@ "path": "tables/table/obs/predicted_ASCT_celltype" } ], - "tablePath": "tables/table", - "region": "beads" + "tablePath": "tables/table" }, "obsSpots": { "path": "shapes/beads", @@ -124,41 +122,38 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 8, "y": 0, "w": 4, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 8, "y": 6, "w": 4, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "scatterplot", "coordinationScopes": { "dataset": "A", "embeddingType": "A", - "obsType": "A", - "obsColorEncoding": "A" + "obsColorEncoding": "A", + "obsType": "A" }, "x": 4, "y": 6, "w": 4, - "h": 6, - "coordinationScopesBy": {} + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/Snakefile b/demos/spatialdata-spatial-atac-rna-mouse-brain/Snakefile index ca7c2fcb..6158744c 100644 --- a/demos/spatialdata-spatial-atac-rna-mouse-brain/Snakefile +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/Snakefile @@ -27,7 +27,8 @@ FILE_URLS = { rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # RNA + ATAC + image -> SpatialData-Zarr store, and pseudobulk ATAC tracks -> genomic-profiles Zarr store. rule process_spatial_atac_rna: @@ -75,3 +76,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py b/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py new file mode 100644 index 00000000..f01fbea1 --- /dev/null +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py @@ -0,0 +1,123 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + MultivecZarrWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" +SDATA_URL = f"{BASE_URL}/spatial_atac_rna_mouse_brain.spatialdata.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Spatial ATAC-RNA-seq mouse brain (Zhang et al. 2023)", + description=( + "Spatial co-profiling of chromatin accessibility and gene expression (20 um pixels) " + "in a P21/22 mouse brain section, GEO GSE205055" + ), + ) + rna = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/tissue_image", + table_path="tables/rna", + obs_spots_path="shapes/pixels", + obs_feature_matrix_path="tables/rna/X", + obs_set_paths=["tables/rna/obs/rna_cluster", "tables/rna/obs/atac_cluster"], + obs_set_names=["RNA Cluster", "ATAC Cluster"], + obs_embedding_paths=["tables/rna/obsm/X_umap"], + obs_embedding_names=["RNA UMAP"], + coordinate_system="global", + coordination_values={"obsType": "spot", "featureType": "gene", "featureValueType": "expression"}, + ) + # ATAC gene activity, annotating the same pixels. + atac = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/atac", + obs_feature_matrix_path="tables/atac/X", + obs_embedding_paths=["tables/atac/obsm/X_umap"], + obs_embedding_names=["ATAC UMAP"], + coordination_values={"obsType": "spot", "featureType": "gene activity", "featureValueType": "accessibility"}, + ) + dataset = vc.add_dataset(name="Spatial ATAC-RNA-seq").add_object(rna).add_object(atac) + # Pseudobulk ATAC profiles per RNA cluster. + dataset.add_object(MultivecZarrWrapper( + zarr_url=f"{BASE_URL}/spatial_atac_rna_mouse_brain.genomic-profiles.zarr", + )) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=5, h=8) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=5, y=0, w=3, h=4) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=5, y=4, w=3, h=4) + gene_list = vc.add_view("featureList", dataset=dataset, x=8, y=0, w=4, h=4) + gene_activity_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=4, h=4) + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=8, w=3, h=4) + atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=3, y=8, w=3, h=4) + vc.add_view("genomicProfiles", dataset=dataset, x=6, y=8, w=6, h=4).set_props(assembly="mm10") + + vc.link_views( + [spatial, layer_controller, obs_sets, gene_list, gene_activity_list, rna_scatterplot, atac_scatterplot], + ["obsType"], + ["spot"], + ) + vc.link_views([rna_scatterplot], ["embeddingType"], ["RNA UMAP"]) + vc.link_views([atac_scatterplot], ["embeddingType"], ["ATAC UMAP"]) + + # RNA: the spot layer, gene list, and RNA UMAP share feature and color encoding scopes. + rna_scopes = vc.add_coordination("featureType", "featureValueType", "featureSelection", "obsColorEncoding") + for scope, value in zip(rna_scopes, ["gene", "expression", None, "cellSetSelection"]): + scope.set_value(value) + rna_type, rna_value_type, rna_selection, rna_encoding = rna_scopes + for view in [gene_list, rna_scatterplot]: + view.use_coordination(*rna_scopes) + # ATAC gene activity: gene activity list and ATAC UMAP. + vc.link_views( + [gene_activity_list, atac_scatterplot], + ["featureType", "featureValueType", "featureSelection", "obsColorEncoding"], + ["gene activity", "accessibility", None, "cellSetSelection"], + ) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "spotLayer": CL([{ + "obsType": "spot", + "featureType": rna_type, + "featureValueType": rna_value_type, + "featureSelection": rna_selection, + "obsColorEncoding": rna_encoding, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json b/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json index 4c7710c7..fbb522a8 100644 --- a/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json @@ -11,20 +11,10 @@ "fileType": "spatialdata.zarr", "url": "{{ base_url }}/spatial_atac_rna_mouse_brain.spatialdata.zarr", "options": { - "image": { - "path": "images/tissue_image", - "coordinateSystem": "global" - }, - "obsSpots": { - "path": "shapes/pixels", - "tablePath": "tables/rna", - "coordinateSystem": "global" - }, "obsFeatureMatrix": { "path": "tables/rna/X" }, "obsSets": { - "tablePath": "tables/rna", "obsSets": [ { "name": "RNA Cluster", @@ -34,11 +24,25 @@ "name": "ATAC Cluster", "path": "tables/rna/obs/atac_cluster" } - ] + ], + "tablePath": "tables/rna" + }, + "obsSpots": { + "path": "shapes/pixels", + "tablePath": "tables/rna", + "coordinateSystem": "global" + }, + "image": { + "path": "images/tissue_image", + "coordinateSystem": "global" }, "obsEmbedding": [ { "path": "tables/rna/obsm/X_umap", + "dims": [ + 0, + 1 + ], "embeddingType": "RNA UMAP" } ] @@ -59,6 +63,10 @@ "obsEmbedding": [ { "path": "tables/atac/obsm/X_umap", + "dims": [ + 0, + 1 + ], "embeddingType": "ATAC UMAP" } ] @@ -85,24 +93,24 @@ "init_A_obsSpots_0": "spot" }, "embeddingType": { - "RNA": "RNA UMAP", - "ATAC": "ATAC UMAP" + "A": "RNA UMAP", + "B": "ATAC UMAP" }, "featureType": { - "RNA": "gene", - "ATAC": "gene activity" + "A": "gene", + "B": "gene activity" }, "featureValueType": { - "RNA": "expression", - "ATAC": "accessibility" + "A": "expression", + "B": "accessibility" }, "featureSelection": { - "RNA": null, - "ATAC": null + "A": null, + "B": null }, "obsColorEncoding": { - "RNA": "cellSetSelection", - "ATAC": "cellSetSelection" + "A": "cellSetSelection", + "B": "cellSetSelection" }, "imageLayer": { "init_A_image_0": "__dummy__" @@ -110,9 +118,6 @@ "photometricInterpretation": { "init_A_image_0": "RGB" }, - "spotLayer": { - "init_A_obsSpots_0": "__dummy__" - }, "metaCoordinationScopes": { "init_A_image_0": { "imageLayer": [ @@ -139,19 +144,22 @@ "init_A_obsSpots_0": "init_A_obsSpots_0" }, "featureType": { - "init_A_obsSpots_0": "RNA" + "init_A_obsSpots_0": "A" }, "featureValueType": { - "init_A_obsSpots_0": "RNA" + "init_A_obsSpots_0": "A" }, "featureSelection": { - "init_A_obsSpots_0": "RNA" + "init_A_obsSpots_0": "A" }, "obsColorEncoding": { - "init_A_obsSpots_0": "RNA" + "init_A_obsSpots_0": "A" } } } + }, + "spotLayer": { + "init_A_obsSpots_0": "__dummy__" } }, "layout": [ @@ -209,10 +217,10 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "RNA", - "featureValueType": "RNA", - "featureSelection": "RNA", - "obsColorEncoding": "RNA" + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" }, "x": 8, "y": 0, @@ -224,10 +232,10 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "ATAC", - "featureValueType": "ATAC", - "featureSelection": "ATAC", - "obsColorEncoding": "ATAC" + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "B" }, "x": 8, "y": 4, @@ -239,11 +247,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "embeddingType": "RNA", - "featureType": "RNA", - "featureValueType": "RNA", - "featureSelection": "RNA", - "obsColorEncoding": "RNA" + "embeddingType": "A", + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" }, "x": 0, "y": 8, @@ -255,11 +263,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "embeddingType": "ATAC", - "featureType": "ATAC", - "featureValueType": "ATAC", - "featureSelection": "ATAC", - "obsColorEncoding": "ATAC" + "embeddingType": "B", + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "B" }, "x": 3, "y": 8, @@ -271,13 +279,13 @@ "coordinationScopes": { "dataset": "A" }, - "props": { - "assembly": "mm10" - }, "x": 6, "y": 8, "w": 6, - "h": 4 + "h": 4, + "props": { + "assembly": "mm10" + } } ], "initStrategy": "auto" diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile index 677d46cb..04412e74 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/Snakefile @@ -36,7 +36,8 @@ SPATIAL_DIR = INTERIM_DIR / "MouseBrain_20um_100barcodes_H3K27me3_spatial" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Build a SpatialData object with the tissue image, the pixels as square polygon Shapes, # and one table per modality ("rna" and "cut_and_tag"), both annotating the pixels. @@ -103,3 +104,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py new file mode 100644 index 00000000..1e6005f7 --- /dev/null +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py @@ -0,0 +1,125 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, +) + +BASE_URL = "{{ base_url }}" +SDATA_URL = f"{BASE_URL}/spatial_cut_and_tag_rna_mouse_brain_h3k27me3.spatialdata.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Spatial CUT&Tag-RNA-seq mouse brain, H3K27me3 (Zhang et al. 2023)", + description=( + "H3K27me3 CUT&Tag gene scores and RNA co-profiled in 20 um pixels of P22 mouse brain " + "(GEO GSE205055, samples GSM6704978 and GSM6753044)" + ), + ) + # Both tables annotate the same `pixels` shapes element. + rna = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/tissue_image", + table_path="tables/rna", + region="pixels", + obs_feature_matrix_path="tables/rna/X", + obs_segmentations_path="shapes/pixels", + obs_set_paths=["tables/rna/obs/rna_leiden", "tables/rna/obs/cut_and_tag_leiden"], + obs_set_names=["Leiden (RNA)", "Leiden (H3K27me3)"], + obs_embedding_paths=["tables/rna/obsm/X_umap_rna", "tables/rna/obsm/X_umap_cut_and_tag"], + obs_embedding_names=["UMAP (RNA)", "UMAP (H3K27me3)"], + coordinate_system="global", + coordination_values={"obsType": "pixel", "featureType": "gene", "featureValueType": "expression"}, + ) + cut_and_tag = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/cut_and_tag", + region="pixels", + obs_feature_matrix_path="tables/cut_and_tag/X", + coordination_values={"obsType": "pixel", "featureType": "geneScore", "featureValueType": "score"}, + ) + dataset = vc.add_dataset(name="Spatial CUT&Tag-RNA-seq mouse brain, H3K27me3 (Zhang et al. 2023)").add_object(rna).add_object(cut_and_tag) + + rna_spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=3, h=6).set_props(title="Spatial (RNA)") + rna_layers = vc.add_view("layerControllerBeta", dataset=dataset, x=3, y=0, w=3, h=3).set_props(title="Layers (RNA)") + rna_features = vc.add_view("featureList", dataset=dataset, x=3, y=3, w=3, h=3).set_props(title="RNA features") + ct_spatial = vc.add_view("spatialBeta", dataset=dataset, x=6, y=0, w=3, h=6).set_props(title="Spatial (H3K27me3 gene score)") + ct_layers = vc.add_view("layerControllerBeta", dataset=dataset, x=9, y=0, w=3, h=3).set_props(title="Layers (H3K27me3 gene score)") + ct_features = vc.add_view("featureList", dataset=dataset, x=9, y=3, w=3, h=3).set_props(title="H3K27me3 gene score features") + obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=6, w=4, h=6) + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=6, w=4, h=6) + ct_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=4, y=6, w=4, h=6) + + # The two spatial views share zoom and target. + vc.link_views([rna_spatial, ct_spatial], ["spatialZoom", "spatialTargetX", "spatialTargetY"], [None, None, None]) + vc.link_views( + [rna_spatial, rna_layers, rna_features, ct_spatial, ct_layers, ct_features, obs_sets, rna_scatterplot, ct_scatterplot], + ["obsType"], + ["pixel"], + ) + vc.link_views([obs_sets, rna_scatterplot, ct_scatterplot], ["obsColorEncoding"], ["cellSetSelection"]) + vc.link_views([rna_scatterplot], ["embeddingType"], ["UMAP (RNA)"]) + vc.link_views([ct_scatterplot], ["embeddingType"], ["UMAP (H3K27me3)"]) + + # Each spatial view shows the tissue image and the pixels colored by one modality. + for modality, spatial, layers, features, feature_type, feature_value_type, feature in [ + ("rna", rna_spatial, rna_layers, rna_features, "gene", "expression", "Mbp"), + ("cut_and_tag", ct_spatial, ct_layers, ct_features, "geneScore", "score", "Hoxa9"), + ]: + f_type, f_value_type, f_selection, color_encoding = vc.add_coordination( + "featureType", "featureValueType", "featureSelection", "obsColorEncoding", + ) + f_type.set_value(feature_type) + f_value_type.set_value(feature_value_type) + f_selection.set_value([feature]) + color_encoding.set_value("geneSelection") + features.use_coordination(f_type, f_value_type, f_selection, color_encoding) + vc.link_views_by_dict([spatial, layers], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + "spatialLayerOpacity": 1.0, + }]), + "segmentationLayer": CL([{ + "spatialLayerOpacity": 1.0, + "segmentationChannel": CL([{ + "obsType": "pixel", + "featureType": f_type, + "featureValueType": f_value_type, + "featureSelection": f_selection, + "obsColorEncoding": color_encoding, + "spatialChannelOpacity": 0.8, + "spatialSegmentationFilled": True, + "spatialChannelVisible": True, + }]), + }]), + }, scope_prefix=f"init_{modality}_") + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json index 600b03ce..56b229c2 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json @@ -94,23 +94,19 @@ "spatialTargetY": { "A": null }, - "imageLayer": { - "A": null, - "init_rna_0": "__dummy__", - "init_cut_and_tag_0": "__dummy__" + "obsType": { + "A": "pixel", + "init_rna_0": "pixel", + "init_cut_and_tag_0": "pixel" }, "obsColorEncoding": { - "A": "geneSelection", + "A": "cellSetSelection", "B": "geneSelection", - "C": "cellSetSelection" + "C": "geneSelection" }, - "featureSelection": { - "A": [ - "Mbp" - ], - "B": [ - "Hoxa9" - ] + "embeddingType": { + "A": "UMAP (RNA)", + "B": "UMAP (H3K27me3)" }, "featureType": { "A": "gene", @@ -120,6 +116,18 @@ "A": "expression", "B": "score" }, + "featureSelection": { + "A": [ + "Mbp" + ], + "B": [ + "Hoxa9" + ] + }, + "imageLayer": { + "init_rna_0": "__dummy__", + "init_cut_and_tag_0": "__dummy__" + }, "photometricInterpretation": { "init_rna_0": "RGB", "init_cut_and_tag_0": "RGB" @@ -138,11 +146,6 @@ "init_rna_0": "__dummy__", "init_cut_and_tag_0": "__dummy__" }, - "obsType": { - "init_rna_0": "pixel", - "init_cut_and_tag_0": "pixel", - "A": "pixel" - }, "spatialChannelOpacity": { "init_rna_0": 0.8, "init_cut_and_tag_0": 0.8 @@ -207,7 +210,7 @@ "init_rna_0": "A" }, "obsColorEncoding": { - "init_rna_0": "A" + "init_rna_0": "B" }, "spatialChannelOpacity": { "init_rna_0": "init_rna_0" @@ -253,7 +256,7 @@ "init_cut_and_tag_0": "B" }, "obsColorEncoding": { - "init_cut_and_tag_0": "B" + "init_cut_and_tag_0": "C" }, "spatialChannelOpacity": { "init_cut_and_tag_0": "init_cut_and_tag_0" @@ -266,10 +269,6 @@ } } } - }, - "embeddingType": { - "A": "UMAP (RNA)", - "B": "UMAP (H3K27me3)" } }, "layout": [ @@ -277,16 +276,16 @@ "component": "spatialBeta", "coordinationScopes": { "dataset": "A", + "spatialZoom": "A", + "spatialTargetX": "A", + "spatialTargetY": "A", + "obsType": "A", "metaCoordinationScopes": [ "init_rna_0" ], "metaCoordinationScopesBy": [ "init_rna_0" - ], - "spatialZoom": "A", - "spatialTargetX": "A", - "spatialTargetY": "A", - "obsType": "A" + ] }, "x": 0, "y": 0, @@ -300,13 +299,13 @@ "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", + "obsType": "A", "metaCoordinationScopes": [ "init_rna_0" ], "metaCoordinationScopesBy": [ "init_rna_0" - ], - "obsType": "A" + ] }, "x": 3, "y": 0, @@ -320,11 +319,11 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", + "obsType": "A", "featureType": "A", "featureValueType": "A", "featureSelection": "A", - "obsColorEncoding": "A", - "obsType": "A" + "obsColorEncoding": "B" }, "x": 3, "y": 3, @@ -332,23 +331,22 @@ "h": 3, "props": { "title": "RNA features" - }, - "coordinationScopesBy": {} + } }, { "component": "spatialBeta", "coordinationScopes": { "dataset": "A", + "spatialZoom": "A", + "spatialTargetX": "A", + "spatialTargetY": "A", + "obsType": "A", "metaCoordinationScopes": [ "init_cut_and_tag_0" ], "metaCoordinationScopesBy": [ "init_cut_and_tag_0" - ], - "spatialZoom": "A", - "spatialTargetX": "A", - "spatialTargetY": "A", - "obsType": "A" + ] }, "x": 6, "y": 0, @@ -362,13 +360,13 @@ "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", + "obsType": "A", "metaCoordinationScopes": [ "init_cut_and_tag_0" ], "metaCoordinationScopesBy": [ "init_cut_and_tag_0" - ], - "obsType": "A" + ] }, "x": 9, "y": 0, @@ -382,11 +380,11 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", + "obsType": "A", "featureType": "B", "featureValueType": "B", "featureSelection": "B", - "obsColorEncoding": "B", - "obsType": "A" + "obsColorEncoding": "C" }, "x": 9, "y": 3, @@ -394,49 +392,45 @@ "h": 3, "props": { "title": "H3K27me3 gene score features" - }, - "coordinationScopesBy": {} + } }, { "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsColorEncoding": "C", - "obsType": "A" + "obsType": "A", + "obsColorEncoding": "A" }, "x": 8, "y": 6, "w": 4, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "scatterplot", "coordinationScopes": { "dataset": "A", - "embeddingType": "A", - "obsColorEncoding": "C", - "obsType": "A" + "obsType": "A", + "obsColorEncoding": "A", + "embeddingType": "A" }, "x": 0, "y": 6, "w": 4, - "h": 6, - "coordinationScopesBy": {} + "h": 6 }, { "component": "scatterplot", "coordinationScopes": { "dataset": "A", - "embeddingType": "B", - "obsColorEncoding": "C", - "obsType": "A" + "obsType": "A", + "obsColorEncoding": "A", + "embeddingType": "B" }, "x": 4, "y": 6, "w": 4, - "h": 6, - "coordinationScopesBy": {} + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/spatialdata-stellaromics-pyxa-small/Snakefile b/demos/spatialdata-stellaromics-pyxa-small/Snakefile index 2dde41a7..b24e7393 100644 --- a/demos/spatialdata-stellaromics-pyxa-small/Snakefile +++ b/demos/spatialdata-stellaromics-pyxa-small/Snakefile @@ -29,7 +29,8 @@ PYXA_RAW_DIR = RAW_DIR / "pyxa_small" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Read the Pyxa output files into a SpatialData object (3D image, 3D transcripts, # 2D cell footprints and per-z-plane cell polygons, and the cell x gene table), @@ -60,3 +61,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py b/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py new file mode 100644 index 00000000..b19d5e36 --- /dev/null +++ b/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py @@ -0,0 +1,98 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" +SDATA_URL = f"{BASE_URL}/stellaromics_pyxa_small.spatialdata.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Stellaromics Pyxa (small demo region)", + description=( + "3D in situ transcriptomics from the Stellaromics/demo Hugging Face dataset (small/), " + "read with the spatialdata-io pyxa reader, with Leiden clusters and morton-sorted transcripts" + ), + ) + cells = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/mosaic_image", + table_path="tables/rna", + obs_feature_matrix_path="tables/rna/X", + obs_segmentations_path="shapes/cell_boundaries", + obs_set_paths=["tables/rna/obs/leiden"], + obs_set_names=["Leiden clusters"], + obs_embedding_paths=["tables/rna/obsm/X_umap"], + obs_embedding_names=["UMAP"], + coordinate_system="global", + coordination_values={"obsType": "cell", "featureType": "gene"}, + ) + points = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/rna", + obs_feature_matrix_path="tables/rna/X", + obs_points_path="points/transcripts_with_morton_codes", + coordinate_system="global", + coordination_values={"obsType": "point", "featureType": "gene"}, + ) + dataset = vc.add_dataset(name="Stellaromics Pyxa").add_object(cells).add_object(points) + + spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) + feature_list = vc.add_view("featureList", dataset=dataset, x=9, y=0, w=3, h=6) + obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=6, w=3, h=6) + scatterplot = vc.add_view("scatterplot", dataset=dataset, x=9, y=6, w=3, h=6) + + vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{}]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "segmentationChannel": CL([{ + "obsType": "cell", + "spatialChannelOpacity": 0.5, + "obsColorEncoding": "cellSetSelection", + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views_by_dict([spatial, layer_controller], { + "pointLayer": CL([{ + "obsType": "point", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets, scatterplot], ["obsType"], ["cell"]) + vc.link_views([feature_list, obs_sets, scatterplot], ["obsColorEncoding"], ["cellSetSelection"]) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json b/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json index 363d5c75..3df17312 100644 --- a/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json +++ b/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json @@ -14,6 +14,15 @@ "obsFeatureMatrix": { "path": "tables/rna/X" }, + "obsSets": { + "obsSets": [ + { + "name": "Leiden clusters", + "path": "tables/rna/obs/leiden" + } + ], + "tablePath": "tables/rna" + }, "image": { "path": "images/mosaic_image", "coordinateSystem": "global" @@ -23,19 +32,13 @@ "tablePath": "tables/rna", "coordinateSystem": "global" }, - "obsSets": { - "tablePath": "tables/rna", - "obsSets": [ - { - "name": "Leiden clusters", - "path": "tables/rna/obs/leiden" - } - ] - }, "obsEmbedding": [ { "path": "tables/rna/obsm/X_umap", - "dims": [0, 1], + "dims": [ + 0, + 1 + ], "embeddingType": "UMAP" } ] @@ -73,30 +76,9 @@ "embeddingType": { "A": "UMAP" }, - "obsType": { - "init_A_obsSegmentations_0": "cell", - "init_A_obsPoints_0": "point", - "A": "cell" - }, "imageLayer": { "init_A_image_0": "__dummy__" }, - "segmentationLayer": { - "init_A_obsSegmentations_0": "__dummy__" - }, - "segmentationChannel": { - "init_A_obsSegmentations_0": "__dummy__" - }, - "pointLayer": { - "init_A_obsPoints_0": "__dummy__" - }, - "spatialChannelOpacity": { - "init_A_obsSegmentations_0": 0.5 - }, - "obsColorEncoding": { - "init_A_obsSegmentations_0": "cellSetSelection", - "A": "cellSetSelection" - }, "metaCoordinationScopes": { "init_A_image_0": { "imageLayer": [ @@ -143,6 +125,27 @@ } } } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "init_A_obsPoints_0": "point", + "A": "cell" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.5 + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "cellSetSelection", + "A": "cellSetSelection" + }, + "pointLayer": { + "init_A_obsPoints_0": "__dummy__" } }, "layout": [ @@ -216,8 +219,8 @@ "component": "scatterplot", "coordinationScopes": { "dataset": "A", - "obsType": "A", "embeddingType": "A", + "obsType": "A", "obsColorEncoding": "A" }, "x": 9, diff --git a/demos/spatialdata-visium-hd-3.0.0/Snakefile b/demos/spatialdata-visium-hd-3.0.0/Snakefile index 3f166bde..f2f2cd9d 100644 --- a/demos/spatialdata-visium-hd-3.0.0/Snakefile +++ b/demos/spatialdata-visium-hd-3.0.0/Snakefile @@ -12,7 +12,8 @@ ZIP_URL = f"{SPATIALDATA_SANDBOX_URL}/visium_hd_3.0.0_io_spatialdata_0.7.1.zip" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Unzip the SpatialData store (the zip file contains a single # top-level data.zarr directory) and then, in place, rasterize the bins @@ -42,3 +43,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-visium-hd-3.0.0/src/vitessce_config.py b/demos/spatialdata-visium-hd-3.0.0/src/vitessce_config.py new file mode 100644 index 00000000..a6ee96c3 --- /dev/null +++ b/demos/spatialdata-visium-hd-3.0.0/src/vitessce_config.py @@ -0,0 +1,79 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Visium HD (Space Ranger 3.0.0) mouse small intestine", + description="SpatialData sandbox dataset visium_hd_3.0.0_io, with bins rasterized to Labels elements", + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/visium_hd_3.0.0_io.spatialdata.zarr", + image_path="images/Visium_HD_Mouse_Small_Intestine_full_image", + table_path="tables/square_016um", + obs_feature_matrix_path="tables/square_016um/X", + # 16um bins, rasterized to a Labels element by src/rasterize_bins.py. + obs_segmentations_path="labels/rasterized_016um", + coordinate_system="Visium_HD_Mouse_Small_Intestine", + coordination_values={"obsType": "bin"}, + ) + dataset = vc.add_dataset(name="Visium HD").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "segmentationChannel": CL([{ + "spatialChannelOpacity": 0.5, + "obsColorEncoding": "geneSelection", + "featureValueColormapRange": [0, 0.5], + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets], ["obsType", "featureSelection"], ["bin", ["AA986860"]]) + + vc.layout(spatial | (feature_list / layer_controller / obs_sets)) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-visium-hd-4.0.1/Snakefile b/demos/spatialdata-visium-hd-4.0.1/Snakefile index 71f18bc2..02e07e77 100644 --- a/demos/spatialdata-visium-hd-4.0.1/Snakefile +++ b/demos/spatialdata-visium-hd-4.0.1/Snakefile @@ -12,7 +12,8 @@ ZIP_URL = f"{SPATIALDATA_SANDBOX_URL}/visium_hd_4.0.1_io_spatialdata_0.7.1.zip" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # No processing is needed beyond unzipping: this dataset contains cell and nucleus segmentation # Shapes (polygons) with annotating tables, but no square bins to rasterize. @@ -39,3 +40,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-visium-hd-4.0.1/src/vitessce_config.py b/demos/spatialdata-visium-hd-4.0.1/src/vitessce_config.py new file mode 100644 index 00000000..3fe0a1f9 --- /dev/null +++ b/demos/spatialdata-visium-hd-4.0.1/src/vitessce_config.py @@ -0,0 +1,76 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Visium HD (Space Ranger 4.0.1) 3' mouse brain", + description="SpatialData sandbox dataset visium_hd_4.0.1_io, with cell segmentations", + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/visium_hd_4.0.1_io.spatialdata.zarr", + image_path="images/Visium_HD_3prime_Mouse_Brain_hires_image", + table_path="tables/cell_segmentations", + obs_feature_matrix_path="tables/cell_segmentations/X", + obs_segmentations_path="shapes/Visium_HD_3prime_Mouse_Brain_cell_segmentations", + coordinate_system="Visium_HD_3prime_Mouse_Brain", + coordination_values={"obsType": "cell"}, + ) + dataset = vc.add_dataset(name="Visium HD").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "segmentationChannel": CL([{ + "spatialChannelOpacity": 0.5, + "obsColorEncoding": "geneSelection", + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views([spatial, layer_controller, feature_list], ["obsType"], ["cell"]) + + vc.layout(spatial | (feature_list / layer_controller)) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-visium/Snakefile b/demos/spatialdata-visium/Snakefile index 59133731..78cb662d 100644 --- a/demos/spatialdata-visium/Snakefile +++ b/demos/spatialdata-visium/Snakefile @@ -12,7 +12,8 @@ ZIP_URL = f"{SPATIALDATA_SANDBOX_URL}/visium_spatialdata_0.7.1.zip" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # No processing is needed beyond unzipping: the spots are Shapes (circles) annotated by the table. # The zip file contains a single top-level data.zarr directory. @@ -38,3 +39,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-visium/src/vitessce_config.py b/demos/spatialdata-visium/src/vitessce_config.py new file mode 100644 index 00000000..fb1672b8 --- /dev/null +++ b/demos/spatialdata-visium/src/vitessce_config.py @@ -0,0 +1,75 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Visium mouse brain", + description="SpatialData sandbox dataset visium, section ST8059048", + ) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/visium.spatialdata.zarr", + image_path="images/ST8059048_hires_image", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + obs_spots_path="shapes/ST8059048", + # The table annotates the spots of two sections (ST8059048 and ST8059050). + region="ST8059048", + coordinate_system="ST8059048", + coordination_values={"obsType": "spot"}, + ) + dataset = vc.add_dataset(name="Visium").add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "spotLayer": CL([{ + "obsColorEncoding": "geneSelection", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) + vc.link_views([spatial, layer_controller, feature_list], ["obsType"], ["spot"]) + + vc.layout(spatial | (feature_list / layer_controller)) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-xenium-rep1/Snakefile b/demos/spatialdata-xenium-rep1/Snakefile index 85da79d7..85870da2 100644 --- a/demos/spatialdata-xenium-rep1/Snakefile +++ b/demos/spatialdata-xenium-rep1/Snakefile @@ -12,7 +12,8 @@ ZIP_URL = f"{SPATIALDATA_SANDBOX_URL}/xenium_rep1_io_spatialdata_0.7.1.zip" rule all: input: - [ (PROCESSED_DIR / f) for f in OUTPUTS ] + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" # Unzip the SpatialData store (the zip file contains a single # top-level data.zarr directory) and then, in place, add a morton-sorted @@ -42,3 +43,17 @@ rule download_data: ''' curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-xenium-rep1/src/vitessce_config.py b/demos/spatialdata-xenium-rep1/src/vitessce_config.py new file mode 100644 index 00000000..03396e02 --- /dev/null +++ b/demos/spatialdata-xenium-rep1/src/vitessce_config.py @@ -0,0 +1,85 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, +) + +BASE_URL = "{{ base_url }}" +SDATA_URL = f"{BASE_URL}/xenium_rep1_io.spatialdata.zarr" + + +def create_config(): + vc = VitessceConfig( + schema_version="1.0.18", + name="Xenium human breast cancer (replicate 1)", + description="SpatialData sandbox dataset xenium_rep1_io, with morton-sorted transcripts", + ) + cells = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/morphology_focus", + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="shapes/cell_boundaries", + coordinate_system="global", + coordination_values={"obsType": "cell"}, + ) + points = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/table", + obs_feature_matrix_path="tables/table/X", + obs_points_path="points/transcripts_with_morton_codes", + coordinate_system="global", + coordination_values={"obsType": "point", "featureType": "gene"}, + ) + dataset = vc.add_dataset(name="Xenium").add_object(cells).add_object(points) + + spatial = vc.add_view("spatialBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "segmentationChannel": CL([{ + "obsType": "cell", + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views_by_dict([spatial, layer_controller], { + "pointLayer": CL([{ + "obsType": "point", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets], ["obsType"], ["cell"]) + + vc.layout(spatial | (feature_list / layer_controller / obs_sets)) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") From 4cd50665c1aedf38b9c2539955af78e5ceade72d Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:12:18 -0500 Subject: [PATCH 6/9] Use vc.layout rather than xywh in add_view --- .../src/vitessce_config.py | 39 ++++++++++++++---- .../vitessce.template.json | 18 ++++---- .../anndata-parse-pbmc/src/vitessce_config.py | 39 ++++++++++++++---- .../anndata-parse-pbmc/vitessce.template.json | 18 ++++---- demos/combat-2022/src/vitessce_config.py | 36 ++++++++++++---- demos/combat-2022/vitessce.template.json | 20 ++++----- demos/habib-2017/src/vitessce_config.py | 32 +++++++++++---- demos/habib-2017/vitessce.template.json | 18 ++++---- .../src/vitessce_config.py | 29 +++++++++---- demos/kuppe-2022/src/vitessce_config.py | 35 ++++++++++++---- demos/kuppe-2022/vitessce.template.json | 26 ++++++------ demos/marshall-2022/src/vitessce_config.py | 34 +++++++++++---- demos/marshall-2022/vitessce.template.json | 22 +++++----- .../meta-2022-azimuth/src/vitessce_config.py | 26 +++++++++--- .../src/vitessce_config.py | 37 +++++++++++++---- .../src/vitessce_config.py | 33 +++++++++++---- .../src/vitessce_config.py | 38 +++++++++++++---- .../src/vitessce_config.py | 11 ++++- .../src/vitessce_config.py | 25 ++++++++--- .../src/vitessce_config.py | 27 +++++++++--- .../src/vitessce_config.py | 31 +++++++++++--- .../src/vitessce_config.py | 20 +++++++-- .../src/vitessce_config.py | 41 +++++++++++++++---- .../src/vitessce_config.py | 26 +++++++++--- .../src/vitessce_config.py | 20 +++++++-- .../src/vitessce_config.py | 20 +++++++-- .../src/vitessce_config.py | 21 ++++++++-- .../src/vitessce_config.py | 25 ++++++++--- .../src/vitessce_config.py | 31 +++++++++++--- .../src/vitessce_config.py | 24 ++++++++--- .../src/vitessce_config.py | 40 ++++++++++++++---- .../src/vitessce_config.py | 40 ++++++++++++++---- .../src/vitessce_config.py | 25 ++++++++--- .../src/vitessce_config.py | 12 +++++- .../src/vitessce_config.py | 10 ++++- .../spatialdata-visium/src/vitessce_config.py | 10 ++++- .../src/vitessce_config.py | 12 +++++- 37 files changed, 734 insertions(+), 237 deletions(-) diff --git a/demos/anndata-chromium-pbmc/src/vitessce_config.py b/demos/anndata-chromium-pbmc/src/vitessce_config.py index 9afd3b1e..ba5bb530 100644 --- a/demos/anndata-chromium-pbmc/src/vitessce_config.py +++ b/demos/anndata-chromium-pbmc/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper +from vitessce import VitessceConfig, AnnDataWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" @@ -44,17 +44,40 @@ def create_config(): }, )) - scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=5, h=6) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=5, y=0, w=3, h=3) - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=0, w=4, h=3) - feature_list = vc.add_view("featureList", dataset=dataset, x=5, y=3, w=3, h=3) - violin = vc.add_view("obsSetFeatureValueDistribution", dataset=dataset, x=8, y=3, w=4, h=3) - heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=9, h=4).set_props(transpose=True) - vc.add_view("description", dataset=dataset, x=9, y=6, w=3, h=4) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP") + obs_sets = vc.add_view("obsSets", dataset=dataset) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + violin = vc.add_view("obsSetFeatureValueDistribution", dataset=dataset) + heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) + description = vc.add_view("description", dataset=dataset) vc.link_views([scatterplot, obs_sets, obs_set_sizes, violin, heatmap], ["obsType"], ["cell"]) vc.link_views([scatterplot, feature_list, violin, heatmap], ["featureType"], ["gene"]) vc.link_views([scatterplot, violin, heatmap], ["featureValueType"], ["expression"]) + + vc.layout(vconcat( + hconcat( + scatterplot, + vconcat( + obs_sets, + feature_list, + split=[4, 3], + ), + vconcat( + obs_set_sizes, + violin, + split=[4, 3], + ), + split=[5, 3, 4], + ), + hconcat( + heatmap, + description, + split=[9, 3], + ), + split=[7, 5], + )) return vc diff --git a/demos/anndata-chromium-pbmc/vitessce.template.json b/demos/anndata-chromium-pbmc/vitessce.template.json index b578d617..6b400cce 100644 --- a/demos/anndata-chromium-pbmc/vitessce.template.json +++ b/demos/anndata-chromium-pbmc/vitessce.template.json @@ -70,7 +70,7 @@ "x": 0, "y": 0, "w": 5, - "h": 6 + "h": 7 }, { "component": "obsSets", @@ -81,7 +81,7 @@ "x": 5, "y": 0, "w": 3, - "h": 3 + "h": 4 }, { "component": "obsSetSizes", @@ -92,7 +92,7 @@ "x": 8, "y": 0, "w": 4, - "h": 3 + "h": 4 }, { "component": "featureList", @@ -101,7 +101,7 @@ "featureType": "A" }, "x": 5, - "y": 3, + "y": 4, "w": 3, "h": 3 }, @@ -114,7 +114,7 @@ "featureValueType": "A" }, "x": 8, - "y": 3, + "y": 4, "w": 4, "h": 3 }, @@ -127,9 +127,9 @@ "featureValueType": "A" }, "x": 0, - "y": 6, + "y": 7, "w": 9, - "h": 4, + "h": 5, "props": { "transpose": true } @@ -140,9 +140,9 @@ "dataset": "A" }, "x": 9, - "y": 6, + "y": 7, "w": 3, - "h": 4 + "h": 5 } ], "initStrategy": "auto" diff --git a/demos/anndata-parse-pbmc/src/vitessce_config.py b/demos/anndata-parse-pbmc/src/vitessce_config.py index d6a0a34b..b0536bf1 100644 --- a/demos/anndata-parse-pbmc/src/vitessce_config.py +++ b/demos/anndata-parse-pbmc/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper +from vitessce import VitessceConfig, AnnDataWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" @@ -45,17 +45,40 @@ def create_config(): }, )) - scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=5, h=6) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=5, y=0, w=3, h=3) - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=0, w=4, h=3) - feature_list = vc.add_view("featureList", dataset=dataset, x=5, y=3, w=3, h=3) - violin = vc.add_view("obsSetFeatureValueDistribution", dataset=dataset, x=8, y=3, w=4, h=3) - heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=9, h=4).set_props(transpose=True) - vc.add_view("description", dataset=dataset, x=9, y=6, w=3, h=4) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP") + obs_sets = vc.add_view("obsSets", dataset=dataset) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + violin = vc.add_view("obsSetFeatureValueDistribution", dataset=dataset) + heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) + description = vc.add_view("description", dataset=dataset) vc.link_views([scatterplot, obs_sets, obs_set_sizes, violin, heatmap], ["obsType"], ["cell"]) vc.link_views([scatterplot, feature_list, violin, heatmap], ["featureType"], ["gene"]) vc.link_views([scatterplot, violin, heatmap], ["featureValueType"], ["expression"]) + + vc.layout(vconcat( + hconcat( + scatterplot, + vconcat( + obs_sets, + feature_list, + split=[4, 3], + ), + vconcat( + obs_set_sizes, + violin, + split=[4, 3], + ), + split=[5, 3, 4], + ), + hconcat( + heatmap, + description, + split=[9, 3], + ), + split=[7, 5], + )) return vc diff --git a/demos/anndata-parse-pbmc/vitessce.template.json b/demos/anndata-parse-pbmc/vitessce.template.json index 8a6e3037..fce2f557 100644 --- a/demos/anndata-parse-pbmc/vitessce.template.json +++ b/demos/anndata-parse-pbmc/vitessce.template.json @@ -74,7 +74,7 @@ "x": 0, "y": 0, "w": 5, - "h": 6 + "h": 7 }, { "component": "obsSets", @@ -85,7 +85,7 @@ "x": 5, "y": 0, "w": 3, - "h": 3 + "h": 4 }, { "component": "obsSetSizes", @@ -96,7 +96,7 @@ "x": 8, "y": 0, "w": 4, - "h": 3 + "h": 4 }, { "component": "featureList", @@ -105,7 +105,7 @@ "featureType": "A" }, "x": 5, - "y": 3, + "y": 4, "w": 3, "h": 3 }, @@ -118,7 +118,7 @@ "featureValueType": "A" }, "x": 8, - "y": 3, + "y": 4, "w": 4, "h": 3 }, @@ -131,9 +131,9 @@ "featureValueType": "A" }, "x": 0, - "y": 6, + "y": 7, "w": 9, - "h": 4, + "h": 5, "props": { "transpose": true } @@ -144,9 +144,9 @@ "dataset": "A" }, "x": 9, - "y": 6, + "y": 7, "w": 3, - "h": 4 + "h": 5 } ], "initStrategy": "auto" diff --git a/demos/combat-2022/src/vitessce_config.py b/demos/combat-2022/src/vitessce_config.py index 8ed04116..10ada12a 100644 --- a/demos/combat-2022/src/vitessce_config.py +++ b/demos/combat-2022/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper +from vitessce import VitessceConfig, AnnDataWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" ADATA_URL = f"{BASE_URL}/combat_2022_cell.h5ad.zarr" @@ -56,13 +56,13 @@ def create_config(): }, )) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=7, y=0, w=3, h=4) - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=7, y=4, w=5, h=4) - gene_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=4, h=4) - antibody_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=4, w=4, h=4) - vc.add_view("description", dataset=dataset, x=10, y=0, w=2, h=4) - gene_list = vc.add_view("featureList", dataset=dataset, x=4, y=0, w=3, h=4) - antibody_list = vc.add_view("featureList", dataset=dataset, x=4, y=4, w=3, h=4) + obs_sets = vc.add_view("obsSets", dataset=dataset) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) + gene_scatterplot = vc.add_view("scatterplot", dataset=dataset) + antibody_scatterplot = vc.add_view("scatterplot", dataset=dataset) + description = vc.add_view("description", dataset=dataset) + gene_list = vc.add_view("featureList", dataset=dataset) + antibody_list = vc.add_view("featureList", dataset=dataset) # Both scatterplots share the same embedding, camera, and obsType. vc.link_views( @@ -84,6 +84,26 @@ def create_config(): ) vc.link_views([gene_scatterplot], ["featureValueType", "featureValueColormapRange"], ["expression", [0, 0.05]]) vc.link_views([antibody_scatterplot], ["featureValueType", "featureValueColormapRange"], ["capture", [0, 0.05]]) + + vc.layout(hconcat( + vconcat( + gene_scatterplot, + antibody_scatterplot, + ), + vconcat( + gene_list, + antibody_list, + ), + vconcat( + hconcat( + obs_sets, + description, + split=[3, 2], + ), + obs_set_sizes, + ), + split=[4, 3, 5], + )) return vc diff --git a/demos/combat-2022/vitessce.template.json b/demos/combat-2022/vitessce.template.json index 3489f9f7..69f9d53d 100644 --- a/demos/combat-2022/vitessce.template.json +++ b/demos/combat-2022/vitessce.template.json @@ -119,7 +119,7 @@ "x": 7, "y": 0, "w": 3, - "h": 4 + "h": 6 }, { "component": "obsSetSizes", @@ -128,9 +128,9 @@ "obsType": "A" }, "x": 7, - "y": 4, + "y": 6, "w": 5, - "h": 4 + "h": 6 }, { "component": "scatterplot", @@ -151,7 +151,7 @@ "x": 0, "y": 0, "w": 4, - "h": 4 + "h": 6 }, { "component": "scatterplot", @@ -170,9 +170,9 @@ "featureValueColormapRange": "B" }, "x": 0, - "y": 4, + "y": 6, "w": 4, - "h": 4 + "h": 6 }, { "component": "description", @@ -182,7 +182,7 @@ "x": 10, "y": 0, "w": 2, - "h": 4 + "h": 6 }, { "component": "featureList", @@ -196,7 +196,7 @@ "x": 4, "y": 0, "w": 3, - "h": 4 + "h": 6 }, { "component": "featureList", @@ -208,9 +208,9 @@ "featureSelection": "B" }, "x": 4, - "y": 4, + "y": 6, "w": 3, - "h": 4 + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/habib-2017/src/vitessce_config.py b/demos/habib-2017/src/vitessce_config.py index a8676592..362126a3 100644 --- a/demos/habib-2017/src/vitessce_config.py +++ b/demos/habib-2017/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper +from vitessce import VitessceConfig, AnnDataWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" @@ -41,16 +41,34 @@ def create_config(): }, )) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=4, y=0, w=4, h=4) - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=0, w=4, h=4) - scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=4, h=4) - heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=4, w=8, h=4).set_props(transpose=True) - feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=2, h=4) - vc.add_view("description", dataset=dataset, x=10, y=4, w=2, h=4) + obs_sets = vc.add_view("obsSets", dataset=dataset) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP") + heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) + feature_list = vc.add_view("featureList", dataset=dataset) + description = vc.add_view("description", dataset=dataset) vc.link_views([obs_sets, obs_set_sizes, scatterplot, heatmap], ["obsType"], ["cell"]) vc.link_views([scatterplot, heatmap, feature_list], ["featureType"], ["gene"]) vc.link_views([scatterplot, heatmap], ["featureValueType", "featureValueColormapRange"], ["expression", [0.0, 0.35]]) + + vc.layout(hconcat( + vconcat( + hconcat( + scatterplot, + obs_sets, + ), + heatmap, + ), + vconcat( + obs_set_sizes, + hconcat( + feature_list, + description, + ), + ), + split=[8, 4], + )) return vc diff --git a/demos/habib-2017/vitessce.template.json b/demos/habib-2017/vitessce.template.json index d56a233a..1cef72b1 100644 --- a/demos/habib-2017/vitessce.template.json +++ b/demos/habib-2017/vitessce.template.json @@ -73,7 +73,7 @@ "x": 4, "y": 0, "w": 4, - "h": 4 + "h": 6 }, { "component": "obsSetSizes", @@ -84,7 +84,7 @@ "x": 8, "y": 0, "w": 4, - "h": 4 + "h": 6 }, { "component": "scatterplot", @@ -99,7 +99,7 @@ "x": 0, "y": 0, "w": 4, - "h": 4 + "h": 6 }, { "component": "heatmap", @@ -111,9 +111,9 @@ "featureValueColormapRange": "A" }, "x": 0, - "y": 4, + "y": 6, "w": 8, - "h": 4, + "h": 6, "props": { "transpose": true } @@ -125,9 +125,9 @@ "featureType": "A" }, "x": 8, - "y": 4, + "y": 6, "w": 2, - "h": 4 + "h": 6 }, { "component": "description", @@ -135,9 +135,9 @@ "dataset": "A" }, "x": 10, - "y": 4, + "y": 6, "w": 2, - "h": 4 + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/human-lymph-node-10x-visium/src/vitessce_config.py b/demos/human-lymph-node-10x-visium/src/vitessce_config.py index 5f8a68f9..9cf0694b 100644 --- a/demos/human-lymph-node-10x-visium/src/vitessce_config.py +++ b/demos/human-lymph-node-10x-visium/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper, ImageOmeZarrWrapper +from vitessce import VitessceConfig, AnnDataWrapper, ImageOmeZarrWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" # OME-Zarr outputs are uploaded to GCS. @@ -50,12 +50,12 @@ def create_config(): img_url=f"{BASE_URL_GCP}/human_lymph_node_10x_visium.ome.zarr", )) - spatial_sets = vc.add_view("spatial", dataset=dataset, x=0, y=0, w=6, h=6) - spatial_genes = vc.add_view("spatial", dataset=dataset, x=6, y=0, w=6, h=6) - heatmap = vc.add_view("heatmap", dataset=dataset, x=6, y=6, w=6, h=6).set_props(transpose=True) - layer_controller = vc.add_view("layerController", dataset=dataset, x=0, y=6, w=2, h=6).set_props(disableChannelsIfRgbDetected=True) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=2, y=6, w=2, h=6) - feature_list = vc.add_view("featureList", dataset=dataset, x=4, y=6, w=2, h=6) + spatial_sets = vc.add_view("spatial", dataset=dataset) + spatial_genes = vc.add_view("spatial", dataset=dataset) + heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) + layer_controller = vc.add_view("layerController", dataset=dataset).set_props(disableChannelsIfRgbDetected=True) + obs_sets = vc.add_view("obsSets", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) vc.link_views([spatial_sets, spatial_genes, heatmap, layer_controller, obs_sets, feature_list], ["obsType"], ["spot"]) vc.link_views( @@ -86,6 +86,21 @@ def create_config(): # Left spatial view: colored by cell set. Right spatial view: colored by gene. vc.link_views([spatial_sets, heatmap, obs_sets], ["obsColorEncoding"], ["cellSetSelection"]) vc.link_views([spatial_genes, feature_list], ["obsColorEncoding", "featureSelection"], ["geneSelection", ["CR2"]]) + + vc.layout(hconcat( + vconcat( + spatial_sets, + hconcat( + layer_controller, + obs_sets, + feature_list, + ), + ), + vconcat( + spatial_genes, + heatmap, + ), + )) return vc diff --git a/demos/kuppe-2022/src/vitessce_config.py b/demos/kuppe-2022/src/vitessce_config.py index 7ca2f004..376294f3 100644 --- a/demos/kuppe-2022/src/vitessce_config.py +++ b/demos/kuppe-2022/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper, ImageOmeZarrWrapper +from vitessce import VitessceConfig, AnnDataWrapper, ImageOmeZarrWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" # OME-Zarr outputs are uploaded to GCS. @@ -81,15 +81,15 @@ def create_config(): img_url=f"{BASE_URL_GCP}/kuppe_2022_nature.visium.ome.zarr", )) - cell_sets = vc.add_view("obsSets", dataset=dataset, x=3, y=4, w=3, h=2, uid="A-cell") - spot_sets = vc.add_view("obsSets", dataset=dataset, x=3, y=6, w=3, h=2, uid="A-spot") - spatial = vc.add_view("spatial", dataset=dataset, x=8, y=0, w=4, h=4, uid="B") - rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=4, h=4, uid="C") - atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=4, y=0, w=4, h=4, uid="D") - feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=4, w=3, h=4, uid="E") - vc.add_view("description", dataset=dataset, x=0, y=4, w=3, h=4, uid="H") + cell_sets = vc.add_view("obsSets", dataset=dataset, uid="A-cell") + spot_sets = vc.add_view("obsSets", dataset=dataset, uid="A-spot") + spatial = vc.add_view("spatial", dataset=dataset, uid="B") + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, uid="C") + atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, uid="D") + feature_list = vc.add_view("featureList", dataset=dataset, uid="E") + description = vc.add_view("description", dataset=dataset, uid="H") layer_controller = vc.add_view( - "layerController", dataset=dataset, x=9, y=4, w=3, h=4, uid="I", + "layerController", dataset=dataset, uid="I", ).set_props(disableChannelsIfRgbDetected=True) vc.link_views([rna_scatterplot], ["embeddingType"], ["snRNA UMAP"]) @@ -130,6 +130,23 @@ def create_config(): ["featureType", "featureSelection"], ["gene", None], ) + + vc.layout(vconcat( + hconcat( + rna_scatterplot, + atac_scatterplot, + spatial, + ), + hconcat( + description, + vconcat( + cell_sets, + spot_sets, + ), + feature_list, + layer_controller, + ), + )) return vc diff --git a/demos/kuppe-2022/vitessce.template.json b/demos/kuppe-2022/vitessce.template.json index 79772119..0cc446a2 100644 --- a/demos/kuppe-2022/vitessce.template.json +++ b/demos/kuppe-2022/vitessce.template.json @@ -270,9 +270,9 @@ "obsColorEncoding": "A" }, "x": 3, - "y": 4, + "y": 6, "w": 3, - "h": 2, + "h": 3, "uid": "A-cell" }, { @@ -285,9 +285,9 @@ "obsColorEncoding": "A" }, "x": 3, - "y": 6, + "y": 9, "w": 3, - "h": 2, + "h": 3, "uid": "A-spot" }, { @@ -307,7 +307,7 @@ "x": 8, "y": 0, "w": 4, - "h": 4, + "h": 6, "uid": "B" }, { @@ -328,7 +328,7 @@ "x": 0, "y": 0, "w": 4, - "h": 4, + "h": 6, "uid": "C" }, { @@ -349,7 +349,7 @@ "x": 4, "y": 0, "w": 4, - "h": 4, + "h": 6, "uid": "D" }, { @@ -361,9 +361,9 @@ "featureSelection": "A" }, "x": 6, - "y": 4, + "y": 6, "w": 3, - "h": 4, + "h": 6, "uid": "E" }, { @@ -372,9 +372,9 @@ "dataset": "A" }, "x": 0, - "y": 4, + "y": 6, "w": 3, - "h": 4, + "h": 6, "uid": "H" }, { @@ -386,9 +386,9 @@ "spatialImageLayer": "A" }, "x": 9, - "y": 4, + "y": 6, "w": 3, - "h": 4, + "h": 6, "uid": "I", "props": { "disableChannelsIfRgbDetected": true diff --git a/demos/marshall-2022/src/vitessce_config.py b/demos/marshall-2022/src/vitessce_config.py index 8e174531..31836b13 100644 --- a/demos/marshall-2022/src/vitessce_config.py +++ b/demos/marshall-2022/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper +from vitessce import VitessceConfig, AnnDataWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" @@ -44,13 +44,13 @@ def create_config(): }, )) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=4, y=0, w=4, h=4) - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=0, w=4, h=4) - scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=4, h=4) - spatial = vc.add_view("spatial", dataset=dataset, x=0, y=4, w=4, h=4) - layer_controller = vc.add_view("layerController", dataset=dataset, x=4, y=4, w=4, h=4) - feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=2, h=4) - vc.add_view("description", dataset=dataset, x=10, y=4, w=2, h=4) + obs_sets = vc.add_view("obsSets", dataset=dataset) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP") + spatial = vc.add_view("spatial", dataset=dataset) + layer_controller = vc.add_view("layerController", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + description = vc.add_view("description", dataset=dataset) vc.link_views([obs_sets, obs_set_sizes, scatterplot, spatial, layer_controller, feature_list], ["obsType"], ["bead"]) vc.link_views([scatterplot, spatial, layer_controller, feature_list], ["featureType"], ["gene"]) @@ -61,6 +61,24 @@ def create_config(): ["spatialSegmentationLayer"], [{"opacity": 1, "radius": 50, "visible": True, "stroked": False}], ) + + vc.layout(hconcat( + vconcat( + scatterplot, + spatial, + ), + vconcat( + obs_sets, + layer_controller, + ), + vconcat( + obs_set_sizes, + hconcat( + feature_list, + description, + ), + ), + )) return vc diff --git a/demos/marshall-2022/vitessce.template.json b/demos/marshall-2022/vitessce.template.json index bdecc3e6..a523a9c8 100644 --- a/demos/marshall-2022/vitessce.template.json +++ b/demos/marshall-2022/vitessce.template.json @@ -90,7 +90,7 @@ "x": 4, "y": 0, "w": 4, - "h": 4 + "h": 6 }, { "component": "obsSetSizes", @@ -101,7 +101,7 @@ "x": 8, "y": 0, "w": 4, - "h": 4 + "h": 6 }, { "component": "scatterplot", @@ -116,7 +116,7 @@ "x": 0, "y": 0, "w": 4, - "h": 4 + "h": 6 }, { "component": "spatial", @@ -129,9 +129,9 @@ "spatialSegmentationLayer": "A" }, "x": 0, - "y": 4, + "y": 6, "w": 4, - "h": 4 + "h": 6 }, { "component": "layerController", @@ -143,9 +143,9 @@ "spatialSegmentationLayer": "A" }, "x": 4, - "y": 4, + "y": 6, "w": 4, - "h": 4 + "h": 6 }, { "component": "featureList", @@ -155,9 +155,9 @@ "featureType": "A" }, "x": 8, - "y": 4, + "y": 6, "w": 2, - "h": 4 + "h": 6 }, { "component": "description", @@ -165,9 +165,9 @@ "dataset": "A" }, "x": 10, - "y": 4, + "y": 6, "w": 2, - "h": 4 + "h": 6 } ], "initStrategy": "auto" diff --git a/demos/meta-2022-azimuth/src/vitessce_config.py b/demos/meta-2022-azimuth/src/vitessce_config.py index 450d02a0..dac8def9 100644 --- a/demos/meta-2022-azimuth/src/vitessce_config.py +++ b/demos/meta-2022-azimuth/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper +from vitessce import VitessceConfig, AnnDataWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" @@ -62,15 +62,29 @@ def create_config(): }, )) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=10, y=6, w=2, h=6) - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=1, w=4, h=5) - scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=0, y=0, w=8, h=12) - feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=6, w=2, h=6) - vc.add_view("description", dataset=dataset, x=8, y=0, w=4, h=1) + obs_sets = vc.add_view("obsSets", dataset=dataset) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP") + feature_list = vc.add_view("featureList", dataset=dataset) + description = vc.add_view("description", dataset=dataset) vc.link_views([obs_sets, obs_set_sizes, scatterplot], ["obsType"], ["cell"]) vc.link_views([scatterplot, feature_list], ["featureType"], ["gene"]) vc.link_views([scatterplot], ["featureValueType"], ["expression"]) + + vc.layout(hconcat( + scatterplot, + vconcat( + description, + obs_set_sizes, + hconcat( + feature_list, + obs_sets, + ), + split=[1, 5, 6], + ), + split=[8, 4], + )) return vc diff --git a/demos/mudata-cite-seq-pbmc/src/vitessce_config.py b/demos/mudata-cite-seq-pbmc/src/vitessce_config.py index 104039bd..f4ca8bf3 100644 --- a/demos/mudata-cite-seq-pbmc/src/vitessce_config.py +++ b/demos/mudata-cite-seq-pbmc/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper +from vitessce import VitessceConfig, AnnDataWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" MUDATA_URL = f"{BASE_URL}/flex_pbmc_cite_seq.h5mu.zarr" @@ -51,14 +51,14 @@ def create_config(): coordination_values={"obsType": "cell", "featureType": "protein", "featureValueType": "abundance"}, )) - gene_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=4, h=5).set_props(title="UMAP (RNA), colored by gene") - protein_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=4, y=0, w=4, h=5).set_props(title="UMAP (RNA), colored by protein") - obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=0, w=4, h=5) - gene_list = vc.add_view("featureList", dataset=dataset, x=0, y=5, w=2, h=4).set_props(title="Genes") - protein_list = vc.add_view("featureList", dataset=dataset, x=2, y=5, w=2, h=4).set_props(title="Proteins") - heatmap = vc.add_view("heatmap", dataset=dataset, x=4, y=5, w=8, h=4).set_props(transpose=True) - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=0, y=9, w=6, h=3) - vc.add_view("description", dataset=dataset, x=6, y=9, w=6, h=3) + gene_scatterplot = vc.add_view("scatterplot", dataset=dataset).set_props(title="UMAP (RNA), colored by gene") + protein_scatterplot = vc.add_view("scatterplot", dataset=dataset).set_props(title="UMAP (RNA), colored by protein") + obs_sets = vc.add_view("obsSets", dataset=dataset) + gene_list = vc.add_view("featureList", dataset=dataset).set_props(title="Genes") + protein_list = vc.add_view("featureList", dataset=dataset).set_props(title="Proteins") + heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) + description = vc.add_view("description", dataset=dataset) vc.link_views([gene_scatterplot, protein_scatterplot], ["embeddingType"], ["UMAP"]) vc.link_views([gene_scatterplot, protein_scatterplot, obs_sets, heatmap, obs_set_sizes], ["obsType"], ["cell"]) @@ -74,6 +74,25 @@ def create_config(): ["protein", None, "cellSetSelection"], ) vc.link_views([protein_scatterplot, heatmap], ["featureValueType"], ["abundance"]) + + vc.layout(vconcat( + hconcat( + gene_scatterplot, + protein_scatterplot, + obs_sets, + ), + hconcat( + gene_list, + protein_list, + heatmap, + split=[2, 2, 8], + ), + hconcat( + obs_set_sizes, + description, + ), + split=[5, 4, 3], + )) return vc diff --git a/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py b/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py index 3780314f..7e083b3c 100644 --- a/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py +++ b/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper, MultivecZarrWrapper +from vitessce import VitessceConfig, AnnDataWrapper, MultivecZarrWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" MUDATA_URL = f"{BASE_URL}/pbmc_multiome_10x.h5mu.zarr" @@ -54,13 +54,13 @@ def create_config(): zarr_url=f"{BASE_URL}/pbmc_multiome_10x.genomic-profiles.zarr", )) - rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=6, h=4) - atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=6, y=0, w=6, h=4) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=0, y=4, w=4, h=4) - gene_list = vc.add_view("featureList", dataset=dataset, x=4, y=4, w=4, h=4) - gene_activity_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=4, h=4) - vc.add_view("genomicProfiles", dataset=dataset, x=0, y=8, w=8, h=4).set_props(assembly="hg38") - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=8, w=4, h=4) + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset) + atac_scatterplot = vc.add_view("scatterplot", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + gene_list = vc.add_view("featureList", dataset=dataset) + gene_activity_list = vc.add_view("featureList", dataset=dataset) + genomicprofiles = vc.add_view("genomicProfiles", dataset=dataset).set_props(assembly="hg38") + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) vc.link_views([rna_scatterplot, atac_scatterplot, obs_sets, gene_list, gene_activity_list, obs_set_sizes], ["obsType"], ["cell"]) vc.link_views( @@ -75,6 +75,23 @@ def create_config(): ) vc.link_views([rna_scatterplot], ["embeddingType"], ["RNA UMAP"]) vc.link_views([atac_scatterplot], ["embeddingType"], ["ATAC UMAP"]) + + vc.layout(vconcat( + hconcat( + rna_scatterplot, + atac_scatterplot, + ), + hconcat( + obs_sets, + gene_list, + gene_activity_list, + ), + hconcat( + genomicprofiles, + obs_set_sizes, + split=[8, 4], + ), + )) return vc diff --git a/demos/mudata-snareseq2-lung-hubmap/src/vitessce_config.py b/demos/mudata-snareseq2-lung-hubmap/src/vitessce_config.py index 43bd8021..2efa726f 100644 --- a/demos/mudata-snareseq2-lung-hubmap/src/vitessce_config.py +++ b/demos/mudata-snareseq2-lung-hubmap/src/vitessce_config.py @@ -16,7 +16,7 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper, MultivecZarrWrapper +from vitessce import VitessceConfig, AnnDataWrapper, MultivecZarrWrapper, hconcat, vconcat BASE_URL = "{{ base_url }}" MUDATA_URL = f"{BASE_URL}/snareseq2_lung.h5mu.zarr" @@ -59,14 +59,14 @@ def create_config(): zarr_url=f"{BASE_URL}/snareseq2_lung.genomic-profiles.zarr", )) - wnn_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=0, w=4, h=4) - rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=4, y=0, w=4, h=4) - atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=8, y=0, w=4, h=4) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=0, y=4, w=4, h=4) - gene_list = vc.add_view("featureList", dataset=dataset, x=4, y=4, w=4, h=4) - gene_score_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=4, h=4) - vc.add_view("genomicProfiles", dataset=dataset, x=0, y=8, w=8, h=4).set_props(assembly="hg38") - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset, x=8, y=8, w=4, h=4) + wnn_scatterplot = vc.add_view("scatterplot", dataset=dataset) + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset) + atac_scatterplot = vc.add_view("scatterplot", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + gene_list = vc.add_view("featureList", dataset=dataset) + gene_score_list = vc.add_view("featureList", dataset=dataset) + genomicprofiles = vc.add_view("genomicProfiles", dataset=dataset).set_props(assembly="hg38") + obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) vc.link_views( [wnn_scatterplot, rna_scatterplot, atac_scatterplot, obs_sets, gene_list, gene_score_list, obs_set_sizes], @@ -86,6 +86,26 @@ def create_config(): ["featureType", "featureValueType", "featureSelection", "obsColorEncoding"], ["gene score", "accessibility", None, "cellSetSelection"], ) + + vc.layout(hconcat( + vconcat( + hconcat( + wnn_scatterplot, + rna_scatterplot, + ), + hconcat( + obs_sets, + gene_list, + ), + genomicprofiles, + ), + vconcat( + atac_scatterplot, + gene_score_list, + obs_set_sizes, + ), + split=[8, 4], + )) return vc diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py b/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py index 7890bf72..eab74a6b 100644 --- a/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py @@ -21,6 +21,7 @@ ImageOmeZarrWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, ) # OME-Zarr outputs are uploaded to GCS. @@ -40,8 +41,8 @@ def create_config(): img_url=f"{BASE_URL_GCP}/lightsheet_hubmap_spleen.ome.zarr", )) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=9, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=9, y=0, w=3, h=12) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) vc.link_views_by_dict([spatial, layer_controller], { "imageLayer": CL([{ @@ -56,6 +57,12 @@ def create_config(): }]), }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + + vc.layout(hconcat( + spatial, + layer_controller, + split=[9, 3], + )) return vc diff --git a/demos/spatialdata-atera-kidney/src/vitessce_config.py b/demos/spatialdata-atera-kidney/src/vitessce_config.py index 0619a9be..ae15ba24 100644 --- a/demos/spatialdata-atera-kidney/src/vitessce_config.py +++ b/demos/spatialdata-atera-kidney/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -70,11 +72,11 @@ def create_config(): ) dataset = vc.add_dataset(name="Atera WTA non-diseased human kidney (FFPE)").add_object(cells).add_object(points) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=0, w=3, h=6) - feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=6, w=3, h=6) - scatterplot = vc.add_view("scatterplot", dataset=dataset, x=9, y=6, w=3, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset) vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) vc.link_views_by_dict([spatial, layer_controller], { @@ -120,6 +122,19 @@ def create_config(): }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) vc.link_views([spatial, layer_controller, obs_sets, feature_list, scatterplot], ["obsType"], ["cell"]) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + feature_list, + ), + vconcat( + obs_sets, + scatterplot, + ), + split=[6, 3, 3], + )) return vc diff --git a/demos/spatialdata-aviti24-teton-hela-tnfa/src/vitessce_config.py b/demos/spatialdata-aviti24-teton-hela-tnfa/src/vitessce_config.py index 1150f7fd..1c87044d 100644 --- a/demos/spatialdata-aviti24-teton-hela-tnfa/src/vitessce_config.py +++ b/demos/spatialdata-aviti24-teton-hela-tnfa/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -54,11 +56,11 @@ def create_config(): ) dataset = vc.add_dataset(name="AVITI24 Teton").add_object(wrapper) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=4) - feature_list = vc.add_view("featureList", dataset=dataset, x=9, y=0, w=3, h=4) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=4, w=3, h=8) - scatterplot = vc.add_view("scatterplot", dataset=dataset, x=9, y=4, w=3, h=8) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset) obs_type, feature_type, obs_color_encoding = vc.add_coordination("obsType", "featureType", "obsColorEncoding") obs_type.set_value("cell") @@ -78,6 +80,21 @@ def create_config(): view.use_coordination(obs_type, feature_type) for view in [feature_list, obs_sets, scatterplot]: view.use_coordination(obs_type, feature_type, obs_color_encoding) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + obs_sets, + split=[4, 8], + ), + vconcat( + feature_list, + scatterplot, + split=[4, 8], + ), + split=[6, 3, 3], + )) return vc diff --git a/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py b/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py index 710b7909..13f94daa 100644 --- a/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py +++ b/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -69,12 +71,12 @@ def create_config(): ) dataset = vc.add_dataset(name=NAME).add_object(wrapper) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=6) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) - feature_list = vc.add_view("featureList", dataset=dataset, x=9, y=0, w=3, h=3) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=3, w=3, h=3) - scatterplot = vc.add_view("scatterplot", dataset=dataset, x=6, y=6, w=6, h=6) - heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=6, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset) + heatmap = vc.add_view("heatmap", dataset=dataset) vc.link_views([scatterplot], ["embeddingType"], ["t-SNE"]) # The segmentation outlines, feature list, cell sets, t-SNE, and heatmap share one color encoding. @@ -111,6 +113,23 @@ def create_config(): }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) vc.link_views([spatial, layer_controller, feature_list, obs_sets, scatterplot, heatmap], ["obsType"], ["cell"]) + + vc.layout(hconcat( + vconcat( + spatial, + heatmap, + ), + vconcat( + hconcat( + layer_controller, + vconcat( + feature_list, + obs_sets, + ), + ), + scatterplot, + ), + )) return vc diff --git a/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py b/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py index fe2c62a7..8794cf69 100644 --- a/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py +++ b/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -58,10 +60,10 @@ def create_config(): ) dataset = vc.add_dataset(name="CosMx").add_object(cells).add_object(points) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=6, h=3) - feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=3, w=6, h=3) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=6, w=6, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) # The cell segmentations, feature list, and cell sets share one color encoding. [obs_color_encoding] = vc.add_coordination("obsColorEncoding") @@ -93,6 +95,16 @@ def create_config(): }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) vc.link_views([spatial, layer_controller, feature_list, obs_sets], ["obsType"], ["cell"]) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + feature_list, + obs_sets, + split=[3, 3, 6], + ), + )) return vc diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py b/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py index d68fde27..a1db39d4 100644 --- a/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py +++ b/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py @@ -20,6 +20,8 @@ VitessceConfig, SpatialDataWrapper, CoordinationLevel as CL, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -56,14 +58,14 @@ def create_config(): ) dataset = vc.add_dataset(name="DBiT-seq E10 mouse embryo (Liu et al. 2020)").add_object(rna).add_object(protein) - rna_spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=3, h=6).set_props(title="Spatial (mRNA)") - rna_layers = vc.add_view("layerControllerBeta", dataset=dataset, x=3, y=0, w=3, h=3).set_props(title="Layers (mRNA)") - rna_features = vc.add_view("featureList", dataset=dataset, x=3, y=3, w=3, h=3).set_props(title="mRNA features") - protein_spatial = vc.add_view("spatialBeta", dataset=dataset, x=6, y=0, w=3, h=6).set_props(title="Spatial (Protein)") - protein_layers = vc.add_view("layerControllerBeta", dataset=dataset, x=9, y=0, w=3, h=3).set_props(title="Layers (Protein)") - protein_features = vc.add_view("featureList", dataset=dataset, x=9, y=3, w=3, h=3).set_props(title="Protein features") - obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=6, w=6, h=6) - scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=6, w=6, h=6) + rna_spatial = vc.add_view("spatialBeta", dataset=dataset).set_props(title="Spatial (mRNA)") + rna_layers = vc.add_view("layerControllerBeta", dataset=dataset).set_props(title="Layers (mRNA)") + rna_features = vc.add_view("featureList", dataset=dataset).set_props(title="mRNA features") + protein_spatial = vc.add_view("spatialBeta", dataset=dataset).set_props(title="Spatial (Protein)") + protein_layers = vc.add_view("layerControllerBeta", dataset=dataset).set_props(title="Layers (Protein)") + protein_features = vc.add_view("featureList", dataset=dataset).set_props(title="Protein features") + obs_sets = vc.add_view("obsSets", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset) # The two spatial views share zoom and target. vc.link_views([rna_spatial, protein_spatial], ["spatialZoom", "spatialTargetX", "spatialTargetY"], [None, None, None]) @@ -107,6 +109,29 @@ def create_config(): }]), }]), }, scope_prefix=f"init_{modality}_") + + vc.layout(hconcat( + vconcat( + hconcat( + rna_spatial, + vconcat( + rna_layers, + rna_features, + ), + ), + scatterplot, + ), + vconcat( + hconcat( + protein_spatial, + vconcat( + protein_layers, + protein_features, + ), + ), + obs_sets, + ), + )) return vc diff --git a/demos/spatialdata-geomx-mouse-embryo/src/vitessce_config.py b/demos/spatialdata-geomx-mouse-embryo/src/vitessce_config.py index d41a0584..6a2132b9 100644 --- a/demos/spatialdata-geomx-mouse-embryo/src/vitessce_config.py +++ b/demos/spatialdata-geomx-mouse-embryo/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -64,11 +66,11 @@ def create_config(): ) dataset = vc.add_dataset(name="GeoMx").add_object(wrapper) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=6) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=6, h=6) - feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=6, w=3, h=6) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=6, w=3, h=6) - heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=6, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + heatmap = vc.add_view("heatmap", dataset=dataset) # The AOI polygons, feature list, AOI sets, and heatmap share one color encoding. [obs_color_encoding] = vc.add_coordination("obsColorEncoding") @@ -100,6 +102,20 @@ def create_config(): }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) vc.link_views([spatial, layer_controller, feature_list, obs_sets, heatmap], ["obsType"], ["AOI"]) + + vc.layout(hconcat( + vconcat( + spatial, + heatmap, + ), + vconcat( + layer_controller, + hconcat( + feature_list, + obs_sets, + ), + ), + )) return vc diff --git a/demos/spatialdata-illumina-stratamap-mouse-kidney/src/vitessce_config.py b/demos/spatialdata-illumina-stratamap-mouse-kidney/src/vitessce_config.py index bb08c2a5..78882c4d 100644 --- a/demos/spatialdata-illumina-stratamap-mouse-kidney/src/vitessce_config.py +++ b/demos/spatialdata-illumina-stratamap-mouse-kidney/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -48,10 +50,10 @@ def create_config(): ) dataset = vc.add_dataset(name="StrataMap").add_object(wrapper) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=6, h=3) - feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=3, w=6, h=3) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=6, w=6, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) # The cell outlines, feature list, and cell sets share one color encoding. [obs_color_encoding] = vc.add_coordination("obsColorEncoding") @@ -74,6 +76,16 @@ def create_config(): }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) vc.link_views([spatial, layer_controller, feature_list, obs_sets], ["obsType"], ["cell"]) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + feature_list, + obs_sets, + split=[3, 3, 6], + ), + )) return vc diff --git a/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/vitessce_config.py b/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/vitessce_config.py index dc58985e..5b10dc13 100644 --- a/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/vitessce_config.py +++ b/demos/spatialdata-maldi-msi-timstof-mouse-brain/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -50,10 +52,10 @@ def create_config(): ) dataset = vc.add_dataset(name="MALDI-MSI").add_object(wrapper) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=8, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=8, y=0, w=4, h=4) - feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=4, h=4) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=8, w=4, h=4) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) obs_type, feature_type, feature_value_type, obs_color_encoding = vc.add_coordination( "obsType", "featureType", "featureValueType", "obsColorEncoding", @@ -82,6 +84,16 @@ def create_config(): }]), }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + feature_list, + obs_sets, + ), + split=[8, 4], + )) return vc diff --git a/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py b/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py index 3826389d..37298872 100644 --- a/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py +++ b/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -54,10 +56,10 @@ def create_config(): ) dataset = vc.add_dataset(name="Zhuang-ABCA-4").add_object(wrapper) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=8, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=8, y=0, w=4, h=3) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=3, w=4, h=5) - feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=8, w=4, h=4) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) vc.link_views_by_dict([spatial, layer_controller], { "spotLayer": CL([{ @@ -65,6 +67,17 @@ def create_config(): }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) vc.link_views([spatial, layer_controller, obs_sets, feature_list], ["obsType"], ["cell"]) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + obs_sets, + feature_list, + split=[3, 5, 4], + ), + split=[8, 4], + )) return vc diff --git a/demos/spatialdata-merscope-mouse-brain/src/vitessce_config.py b/demos/spatialdata-merscope-mouse-brain/src/vitessce_config.py index 14c0b660..211b389a 100644 --- a/demos/spatialdata-merscope-mouse-brain/src/vitessce_config.py +++ b/demos/spatialdata-merscope-mouse-brain/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -63,11 +65,11 @@ def create_config(): ) dataset = vc.add_dataset(name="MERSCOPE mouse brain receptor map (slice 2, replicate 1)").add_object(cells).add_object(points) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=0, w=3, h=6) - feature_list = vc.add_view("featureList", dataset=dataset, x=6, y=6, w=3, h=6) - scatterplot = vc.add_view("scatterplot", dataset=dataset, x=9, y=6, w=3, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset) vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) vc.link_views_by_dict([spatial, layer_controller], { @@ -113,6 +115,19 @@ def create_config(): }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) vc.link_views([spatial, layer_controller, obs_sets, feature_list, scatterplot], ["obsType"], ["cell"]) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + feature_list, + ), + vconcat( + obs_sets, + scatterplot, + ), + split=[6, 3, 3], + )) return vc diff --git a/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py b/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py index 1eae8cf5..8e6e72c6 100644 --- a/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py +++ b/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -69,12 +71,12 @@ def create_config(): ) dataset = vc.add_dataset(name=NAME).add_object(wrapper) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=6) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) - feature_list = vc.add_view("featureList", dataset=dataset, x=9, y=0, w=3, h=3) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=9, y=3, w=3, h=3) - scatterplot = vc.add_view("scatterplot", dataset=dataset, x=6, y=6, w=6, h=6) - heatmap = vc.add_view("heatmap", dataset=dataset, x=0, y=6, w=6, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset) + heatmap = vc.add_view("heatmap", dataset=dataset) vc.link_views([scatterplot], ["embeddingType"], ["t-SNE"]) # The segmentation outlines, feature list, cell sets, t-SNE, and heatmap share one color encoding. @@ -111,6 +113,23 @@ def create_config(): }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) vc.link_views([spatial, layer_controller, feature_list, obs_sets, scatterplot, heatmap], ["obsType"], ["cell"]) + + vc.layout(hconcat( + vconcat( + spatial, + heatmap, + ), + vconcat( + hconcat( + layer_controller, + vconcat( + feature_list, + obs_sets, + ), + ), + scatterplot, + ), + )) return vc diff --git a/demos/spatialdata-slide-seq-hubmap-kidney/src/vitessce_config.py b/demos/spatialdata-slide-seq-hubmap-kidney/src/vitessce_config.py index ada69245..57470254 100644 --- a/demos/spatialdata-slide-seq-hubmap-kidney/src/vitessce_config.py +++ b/demos/spatialdata-slide-seq-hubmap-kidney/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -49,11 +51,11 @@ def create_config(): ) dataset = vc.add_dataset(name="Slide-seq").add_object(wrapper) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=4, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=4, y=0, w=4, h=6) - feature_list = vc.add_view("featureList", dataset=dataset, x=8, y=0, w=4, h=6) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=6, w=4, h=6) - scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP", x=4, y=6, w=4, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP") # The spot layer, feature list, cell sets, and UMAP share one color encoding. [obs_color_encoding] = vc.add_coordination("obsColorEncoding") @@ -66,6 +68,18 @@ def create_config(): for view in [feature_list, obs_sets, scatterplot]: view.use_coordination(obs_color_encoding) vc.link_views([spatial, layer_controller, feature_list, obs_sets, scatterplot], ["obsType"], ["bead"]) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + scatterplot, + ), + vconcat( + feature_list, + obs_sets, + ), + )) return vc diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py b/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py index f01fbea1..c484b0b9 100644 --- a/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py @@ -22,6 +22,8 @@ MultivecZarrWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -65,14 +67,14 @@ def create_config(): zarr_url=f"{BASE_URL}/spatial_atac_rna_mouse_brain.genomic-profiles.zarr", )) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=5, h=8) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=5, y=0, w=3, h=4) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=5, y=4, w=3, h=4) - gene_list = vc.add_view("featureList", dataset=dataset, x=8, y=0, w=4, h=4) - gene_activity_list = vc.add_view("featureList", dataset=dataset, x=8, y=4, w=4, h=4) - rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=8, w=3, h=4) - atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=3, y=8, w=3, h=4) - vc.add_view("genomicProfiles", dataset=dataset, x=6, y=8, w=6, h=4).set_props(assembly="mm10") + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + gene_list = vc.add_view("featureList", dataset=dataset) + gene_activity_list = vc.add_view("featureList", dataset=dataset) + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset) + atac_scatterplot = vc.add_view("scatterplot", dataset=dataset) + genomicprofiles = vc.add_view("genomicProfiles", dataset=dataset).set_props(assembly="mm10") vc.link_views( [spatial, layer_controller, obs_sets, gene_list, gene_activity_list, rna_scatterplot, atac_scatterplot], @@ -110,6 +112,28 @@ def create_config(): "obsColorEncoding": rna_encoding, }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) + + vc.layout(vconcat( + hconcat( + spatial, + vconcat( + layer_controller, + obs_sets, + ), + vconcat( + gene_list, + gene_activity_list, + ), + split=[5, 3, 4], + ), + hconcat( + rna_scatterplot, + atac_scatterplot, + genomicprofiles, + split=[3, 3, 6], + ), + split=[8, 4], + )) return vc diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py index 1e6005f7..76f64b1c 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py @@ -20,6 +20,8 @@ VitessceConfig, SpatialDataWrapper, CoordinationLevel as CL, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -59,15 +61,15 @@ def create_config(): ) dataset = vc.add_dataset(name="Spatial CUT&Tag-RNA-seq mouse brain, H3K27me3 (Zhang et al. 2023)").add_object(rna).add_object(cut_and_tag) - rna_spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=3, h=6).set_props(title="Spatial (RNA)") - rna_layers = vc.add_view("layerControllerBeta", dataset=dataset, x=3, y=0, w=3, h=3).set_props(title="Layers (RNA)") - rna_features = vc.add_view("featureList", dataset=dataset, x=3, y=3, w=3, h=3).set_props(title="RNA features") - ct_spatial = vc.add_view("spatialBeta", dataset=dataset, x=6, y=0, w=3, h=6).set_props(title="Spatial (H3K27me3 gene score)") - ct_layers = vc.add_view("layerControllerBeta", dataset=dataset, x=9, y=0, w=3, h=3).set_props(title="Layers (H3K27me3 gene score)") - ct_features = vc.add_view("featureList", dataset=dataset, x=9, y=3, w=3, h=3).set_props(title="H3K27me3 gene score features") - obs_sets = vc.add_view("obsSets", dataset=dataset, x=8, y=6, w=4, h=6) - rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=0, y=6, w=4, h=6) - ct_scatterplot = vc.add_view("scatterplot", dataset=dataset, x=4, y=6, w=4, h=6) + rna_spatial = vc.add_view("spatialBeta", dataset=dataset).set_props(title="Spatial (RNA)") + rna_layers = vc.add_view("layerControllerBeta", dataset=dataset).set_props(title="Layers (RNA)") + rna_features = vc.add_view("featureList", dataset=dataset).set_props(title="RNA features") + ct_spatial = vc.add_view("spatialBeta", dataset=dataset).set_props(title="Spatial (H3K27me3 gene score)") + ct_layers = vc.add_view("layerControllerBeta", dataset=dataset).set_props(title="Layers (H3K27me3 gene score)") + ct_features = vc.add_view("featureList", dataset=dataset).set_props(title="H3K27me3 gene score features") + obs_sets = vc.add_view("obsSets", dataset=dataset) + rna_scatterplot = vc.add_view("scatterplot", dataset=dataset) + ct_scatterplot = vc.add_view("scatterplot", dataset=dataset) # The two spatial views share zoom and target. vc.link_views([rna_spatial, ct_spatial], ["spatialZoom", "spatialTargetX", "spatialTargetY"], [None, None, None]) @@ -112,6 +114,26 @@ def create_config(): }]), }]), }, scope_prefix=f"init_{modality}_") + + vc.layout(vconcat( + hconcat( + rna_spatial, + vconcat( + rna_layers, + rna_features, + ), + ct_spatial, + vconcat( + ct_layers, + ct_features, + ), + ), + hconcat( + rna_scatterplot, + ct_scatterplot, + obs_sets, + ), + )) return vc diff --git a/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py b/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py index b19d5e36..f2714e94 100644 --- a/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py +++ b/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -59,11 +61,11 @@ def create_config(): ) dataset = vc.add_dataset(name="Stellaromics Pyxa").add_object(cells).add_object(points) - spatial = vc.add_view("spatialBeta", dataset=dataset, x=0, y=0, w=6, h=12) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, x=6, y=0, w=3, h=6) - feature_list = vc.add_view("featureList", dataset=dataset, x=9, y=0, w=3, h=6) - obs_sets = vc.add_view("obsSets", dataset=dataset, x=6, y=6, w=3, h=6) - scatterplot = vc.add_view("scatterplot", dataset=dataset, x=9, y=6, w=3, h=6) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + scatterplot = vc.add_view("scatterplot", dataset=dataset) vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) vc.link_views_by_dict([spatial, layer_controller], { @@ -85,6 +87,19 @@ def create_config(): }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) vc.link_views([spatial, layer_controller, feature_list, obs_sets, scatterplot], ["obsType"], ["cell"]) vc.link_views([feature_list, obs_sets, scatterplot], ["obsColorEncoding"], ["cellSetSelection"]) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + obs_sets, + ), + vconcat( + feature_list, + scatterplot, + ), + split=[6, 3, 3], + )) return vc diff --git a/demos/spatialdata-visium-hd-3.0.0/src/vitessce_config.py b/demos/spatialdata-visium-hd-3.0.0/src/vitessce_config.py index a6ee96c3..2ad5578e 100644 --- a/demos/spatialdata-visium-hd-3.0.0/src/vitessce_config.py +++ b/demos/spatialdata-visium-hd-3.0.0/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -65,7 +67,15 @@ def create_config(): }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) vc.link_views([spatial, layer_controller, feature_list, obs_sets], ["obsType", "featureSelection"], ["bin", ["AA986860"]]) - vc.layout(spatial | (feature_list / layer_controller / obs_sets)) + vc.layout(hconcat( + spatial, + vconcat( + feature_list, + layer_controller, + obs_sets, + split=[3, 3, 6], + ), + )) return vc diff --git a/demos/spatialdata-visium-hd-4.0.1/src/vitessce_config.py b/demos/spatialdata-visium-hd-4.0.1/src/vitessce_config.py index 3fe0a1f9..c369a302 100644 --- a/demos/spatialdata-visium-hd-4.0.1/src/vitessce_config.py +++ b/demos/spatialdata-visium-hd-4.0.1/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -62,7 +64,13 @@ def create_config(): }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) vc.link_views([spatial, layer_controller, feature_list], ["obsType"], ["cell"]) - vc.layout(spatial | (feature_list / layer_controller)) + vc.layout(hconcat( + spatial, + vconcat( + feature_list, + layer_controller, + ), + )) return vc diff --git a/demos/spatialdata-visium/src/vitessce_config.py b/demos/spatialdata-visium/src/vitessce_config.py index fb1672b8..2c353846 100644 --- a/demos/spatialdata-visium/src/vitessce_config.py +++ b/demos/spatialdata-visium/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -61,7 +63,13 @@ def create_config(): }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) vc.link_views([spatial, layer_controller, feature_list], ["obsType"], ["spot"]) - vc.layout(spatial | (feature_list / layer_controller)) + vc.layout(hconcat( + spatial, + vconcat( + feature_list, + layer_controller, + ), + )) return vc diff --git a/demos/spatialdata-xenium-rep1/src/vitessce_config.py b/demos/spatialdata-xenium-rep1/src/vitessce_config.py index 03396e02..733b3c8e 100644 --- a/demos/spatialdata-xenium-rep1/src/vitessce_config.py +++ b/demos/spatialdata-xenium-rep1/src/vitessce_config.py @@ -21,6 +21,8 @@ SpatialDataWrapper, CoordinationLevel as CL, get_initial_coordination_scope_prefix, + hconcat, + vconcat, ) BASE_URL = "{{ base_url }}" @@ -71,7 +73,15 @@ def create_config(): }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsPoints")) vc.link_views([spatial, layer_controller, feature_list, obs_sets], ["obsType"], ["cell"]) - vc.layout(spatial | (feature_list / layer_controller / obs_sets)) + vc.layout(hconcat( + spatial, + vconcat( + feature_list, + layer_controller, + obs_sets, + split=[3, 3, 6], + ), + )) return vc From 8e7d90c7f558cd1ba643bb9f06417e337d4b36d2 Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:59:37 -0500 Subject: [PATCH 7/9] Fix config bugs. Add openst and opendvp pipelines --- demos/Snakefile | 14 + .../src/vitessce_config.py | 71 +- .../vitessce.template.json | 201 +++--- demos/kuppe-2022/src/vitessce_config.py | 93 +-- demos/kuppe-2022/vitessce.template.json | 174 +++-- demos/marshall-2022/src/vitessce_config.py | 45 +- demos/marshall-2022/vitessce.template.json | 84 ++- .../src/sprm_to_spatialdata.py | 35 +- .../src/vitessce_config.py | 25 +- .../vitessce.template.json | 42 +- .../src/convert_to_spatialdata.py | 2 +- .../src/vitessce_config.py | 28 +- .../vitessce.template.json | 41 +- .../src/vitessce_config.py | 11 +- .../vitessce.template.json | 25 +- .../src/sprm_to_spatialdata.py | 35 +- .../src/vitessce_config.py | 25 +- .../vitessce.template.json | 42 +- demos/spatialdata-opendvp-tnbc/README.md | 12 + demos/spatialdata-opendvp-tnbc/Snakefile | 81 +++ demos/spatialdata-opendvp-tnbc/config.yml | 2 + .../src/convert_to_spatialdata.py | 222 +++++++ .../src/vitessce_config.py | 244 +++++++ .../vitessce.template.json | 629 ++++++++++++++++++ .../README.md | 11 + .../Snakefile | 80 +++ .../config.yml | 2 + .../src/convert_to_spatialdata.py | 136 ++++ .../src/vitessce_config.py | 117 ++++ .../vitessce.template.json | 263 ++++++++ .../src/vitessce_config.py | 30 +- .../vitessce.template.json | 14 +- .../src/vitessce_config.py | 32 +- .../vitessce.template.json | 48 +- .../src/convert_to_spatialdata.py | 21 +- .../src/vitessce_config.py | 12 +- .../vitessce.template.json | 58 +- 37 files changed, 2600 insertions(+), 407 deletions(-) create mode 100644 demos/spatialdata-opendvp-tnbc/README.md create mode 100644 demos/spatialdata-opendvp-tnbc/Snakefile create mode 100644 demos/spatialdata-opendvp-tnbc/config.yml create mode 100644 demos/spatialdata-opendvp-tnbc/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-opendvp-tnbc/src/vitessce_config.py create mode 100644 demos/spatialdata-opendvp-tnbc/vitessce.template.json create mode 100644 demos/spatialdata-openst-mouse-hippocampus/README.md create mode 100644 demos/spatialdata-openst-mouse-hippocampus/Snakefile create mode 100644 demos/spatialdata-openst-mouse-hippocampus/config.yml create mode 100644 demos/spatialdata-openst-mouse-hippocampus/src/convert_to_spatialdata.py create mode 100644 demos/spatialdata-openst-mouse-hippocampus/src/vitessce_config.py create mode 100644 demos/spatialdata-openst-mouse-hippocampus/vitessce.template.json diff --git a/demos/Snakefile b/demos/Snakefile index 275e781a..bc96d60e 100644 --- a/demos/Snakefile +++ b/demos/Snakefile @@ -35,6 +35,8 @@ DEMO_DIRS = [ "spatialdata-merfish-zhuang-abca-4", "spatialdata-merscope-mouse-brain", "spatialdata-mibi-hubmap-uterus", + "spatialdata-opendvp-tnbc", + "spatialdata-openst-mouse-hippocampus", "spatialdata-slide-seq-hubmap-kidney", "spatialdata-spatial-atac-rna-mouse-brain", "spatialdata-spatial-cut-and-tag-rna-mouse-brain", @@ -218,6 +220,18 @@ module spatialdata_mibi_hubmap_uterus: use rule * from spatialdata_mibi_hubmap_uterus as spatialdata_mibi_hubmap_uterus_* +module spatialdata_opendvp_tnbc: + snakefile: "spatialdata-opendvp-tnbc/Snakefile" + prefix: "spatialdata-opendvp-tnbc" + +use rule * from spatialdata_opendvp_tnbc as spatialdata_opendvp_tnbc_* + +module spatialdata_openst_mouse_hippocampus: + snakefile: "spatialdata-openst-mouse-hippocampus/Snakefile" + prefix: "spatialdata-openst-mouse-hippocampus" + +use rule * from spatialdata_openst_mouse_hippocampus as spatialdata_openst_mouse_hippocampus_* + module spatialdata_slide_seq_hubmap_kidney: snakefile: "spatialdata-slide-seq-hubmap-kidney/Snakefile" prefix: "spatialdata-slide-seq-hubmap-kidney" diff --git a/demos/human-lymph-node-10x-visium/src/vitessce_config.py b/demos/human-lymph-node-10x-visium/src/vitessce_config.py index 9cf0694b..d4635705 100644 --- a/demos/human-lymph-node-10x-visium/src/vitessce_config.py +++ b/demos/human-lymph-node-10x-visium/src/vitessce_config.py @@ -16,11 +16,21 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper, ImageOmeZarrWrapper, hconcat, vconcat +from vitessce import ( + VitessceConfig, + AnnDataWrapper, + ImageOmeZarrWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, + hconcat, + vconcat, +) BASE_URL = "{{ base_url }}" # OME-Zarr outputs are uploaded to GCS. BASE_URL_GCP = "{{ base_url_gcp }}" +# Spot radius, in the units of obsm/spatial (matches the diamonds drawn by src/create_zarr.py). +SPOT_RADIUS = 10 def create_config(): @@ -34,8 +44,7 @@ def create_config(): adata_url=f"{BASE_URL}/human_lymph_node_10x_visium.h5ad.zarr", obs_feature_matrix_path="X", initial_feature_filter_path="var/highly_variable", - obs_locations_path="obsm/spatial", - obs_segmentations_path="obsm/segmentations", + obs_spots_path="obsm/spatial", obs_embedding_paths=["obsm/X_umap", "obsm/X_pca"], obs_embedding_names=["UMAP", "PCA"], obs_set_paths=["obs/clusters"], @@ -50,42 +59,48 @@ def create_config(): img_url=f"{BASE_URL_GCP}/human_lymph_node_10x_visium.ome.zarr", )) - spatial_sets = vc.add_view("spatial", dataset=dataset) - spatial_genes = vc.add_view("spatial", dataset=dataset) + spatial_sets = vc.add_view("spatialBeta", dataset=dataset).set_props(title="Spatial (cell sets)") + spatial_genes = vc.add_view("spatialBeta", dataset=dataset).set_props(title="Spatial (CR2)") heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) - layer_controller = vc.add_view("layerController", dataset=dataset).set_props(disableChannelsIfRgbDetected=True) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) obs_sets = vc.add_view("obsSets", dataset=dataset) feature_list = vc.add_view("featureList", dataset=dataset) vc.link_views([spatial_sets, spatial_genes, heatmap, layer_controller, obs_sets, feature_list], ["obsType"], ["spot"]) - vc.link_views( - [spatial_sets, spatial_genes, layer_controller], - ["spatialImageLayer", "spatialSegmentationLayer"], - [ - [{ - "type": "raster", - "index": 0, - "colormap": None, - "transparentColor": None, - "opacity": 1, - "domainType": "Min/Max", - "channels": [ - {"selection": {"c": 0}, "color": [255, 0, 0], "visible": True, "slider": [0, 255]}, - {"selection": {"c": 1}, "color": [0, 255, 0], "visible": True, "slider": [0, 255]}, - {"selection": {"c": 2}, "color": [0, 0, 255], "visible": True, "slider": [0, 255]}, - ], - }], - {"radius": 65, "stroked": True, "visible": True, "opacity": 1}, - ], - ) + # The two spatial views share zoom and target. vc.link_views( [spatial_sets, spatial_genes], ["spatialZoom", "spatialTargetX", "spatialTargetY"], [-2.598, 1008.88, 1004.69], ) # Left spatial view: colored by cell set. Right spatial view: colored by gene. - vc.link_views([spatial_sets, heatmap, obs_sets], ["obsColorEncoding"], ["cellSetSelection"]) - vc.link_views([spatial_genes, feature_list], ["obsColorEncoding", "featureSelection"], ["geneSelection", ["CR2"]]) + [set_encoding] = vc.add_coordination("obsColorEncoding") + set_encoding.set_value("cellSetSelection") + gene_encoding, gene_selection = vc.add_coordination("obsColorEncoding", "featureSelection") + gene_encoding.set_value("geneSelection") + gene_selection.set_value(["CR2"]) + for view in [heatmap, obs_sets]: + view.use_coordination(set_encoding) + feature_list.use_coordination(gene_encoding, gene_selection) + + # Both spatial views show the H&E image. + vc.link_views_by_dict([spatial_sets, spatial_genes, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("visium", "image")) + # Each spatial view has its own spot layer (with its own color encoding). + for spatial, spot_scopes in [ + (spatial_sets, {"obsColorEncoding": set_encoding}), + (spatial_genes, {"obsColorEncoding": gene_encoding, "featureSelection": gene_selection}), + ]: + vc.link_views_by_dict([spatial, layer_controller], { + "spotLayer": CL([{ + "obsType": "spot", + "spatialSpotRadius": SPOT_RADIUS, + **spot_scopes, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("visium", "obsSpots")) vc.layout(hconcat( vconcat( diff --git a/demos/human-lymph-node-10x-visium/vitessce.template.json b/demos/human-lymph-node-10x-visium/vitessce.template.json index 572d7b46..69c0aa6c 100644 --- a/demos/human-lymph-node-10x-visium/vitessce.template.json +++ b/demos/human-lymph-node-10x-visium/vitessce.template.json @@ -11,12 +11,9 @@ "fileType": "anndata.zarr", "url": "{{ base_url }}/human_lymph_node_10x_visium.h5ad.zarr", "options": { - "obsLocations": { + "obsSpots": { "path": "obsm/spatial" }, - "obsSegmentations": { - "path": "obsm/segmentations" - }, "obsEmbedding": [ { "path": "obsm/X_umap", @@ -64,74 +61,9 @@ "A": "visium" }, "obsType": { - "A": "spot" - }, - "spatialImageLayer": { - "A": [ - { - "type": "raster", - "index": 0, - "colormap": null, - "transparentColor": null, - "opacity": 1, - "domainType": "Min/Max", - "channels": [ - { - "selection": { - "c": 0 - }, - "color": [ - 255, - 0, - 0 - ], - "visible": true, - "slider": [ - 0, - 255 - ] - }, - { - "selection": { - "c": 1 - }, - "color": [ - 0, - 255, - 0 - ], - "visible": true, - "slider": [ - 0, - 255 - ] - }, - { - "selection": { - "c": 2 - }, - "color": [ - 0, - 0, - 255 - ], - "visible": true, - "slider": [ - 0, - 255 - ] - } - ] - } - ] - }, - "spatialSegmentationLayer": { - "A": { - "radius": 65, - "stroked": true, - "visible": true, - "opacity": 1 - } + "A": "spot", + "init_visium_obsSpots_0": "spot", + "init_visium_obsSpots_1": "spot" }, "spatialZoom": { "A": -2.598 @@ -150,43 +82,127 @@ "A": [ "CR2" ] + }, + "imageLayer": { + "init_visium_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_visium_image_0": "RGB" + }, + "metaCoordinationScopes": { + "init_visium_image_0": { + "imageLayer": [ + "init_visium_image_0" + ] + }, + "init_visium_obsSpots_0": { + "spotLayer": [ + "init_visium_obsSpots_0" + ] + }, + "init_visium_obsSpots_1": { + "spotLayer": [ + "init_visium_obsSpots_1" + ] + } + }, + "metaCoordinationScopesBy": { + "init_visium_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_visium_image_0": "init_visium_image_0" + } + } + }, + "init_visium_obsSpots_0": { + "spotLayer": { + "obsType": { + "init_visium_obsSpots_0": "init_visium_obsSpots_0" + }, + "spatialSpotRadius": { + "init_visium_obsSpots_0": "init_visium_obsSpots_0" + }, + "obsColorEncoding": { + "init_visium_obsSpots_0": "A" + } + } + }, + "init_visium_obsSpots_1": { + "spotLayer": { + "obsType": { + "init_visium_obsSpots_1": "init_visium_obsSpots_1" + }, + "spatialSpotRadius": { + "init_visium_obsSpots_1": "init_visium_obsSpots_1" + }, + "obsColorEncoding": { + "init_visium_obsSpots_1": "B" + }, + "featureSelection": { + "init_visium_obsSpots_1": "A" + } + } + } + }, + "spotLayer": { + "init_visium_obsSpots_0": "__dummy__", + "init_visium_obsSpots_1": "__dummy__" + }, + "spatialSpotRadius": { + "init_visium_obsSpots_0": 10, + "init_visium_obsSpots_1": 10 } }, "layout": [ { - "component": "spatial", + "component": "spatialBeta", "coordinationScopes": { "dataset": "A", "obsType": "A", - "spatialImageLayer": "A", - "spatialSegmentationLayer": "A", "spatialZoom": "A", "spatialTargetX": "A", "spatialTargetY": "A", - "obsColorEncoding": "A" + "metaCoordinationScopes": [ + "init_visium_image_0", + "init_visium_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_visium_image_0", + "init_visium_obsSpots_0" + ] }, "x": 0, "y": 0, "w": 6, - "h": 6 + "h": 6, + "props": { + "title": "Spatial (cell sets)" + } }, { - "component": "spatial", + "component": "spatialBeta", "coordinationScopes": { "dataset": "A", "obsType": "A", - "spatialImageLayer": "A", - "spatialSegmentationLayer": "A", "spatialZoom": "A", "spatialTargetX": "A", "spatialTargetY": "A", - "obsColorEncoding": "B", - "featureSelection": "A" + "metaCoordinationScopes": [ + "init_visium_image_0", + "init_visium_obsSpots_1" + ], + "metaCoordinationScopesBy": [ + "init_visium_image_0", + "init_visium_obsSpots_1" + ] }, "x": 6, "y": 0, "w": 6, - "h": 6 + "h": 6, + "props": { + "title": "Spatial (CR2)" + } }, { "component": "heatmap", @@ -204,20 +220,25 @@ } }, { - "component": "layerController", + "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", "obsType": "A", - "spatialImageLayer": "A", - "spatialSegmentationLayer": "A" + "metaCoordinationScopes": [ + "init_visium_image_0", + "init_visium_obsSpots_0", + "init_visium_obsSpots_1" + ], + "metaCoordinationScopesBy": [ + "init_visium_image_0", + "init_visium_obsSpots_0", + "init_visium_obsSpots_1" + ] }, "x": 0, "y": 6, "w": 2, - "h": 6, - "props": { - "disableChannelsIfRgbDetected": true - } + "h": 6 }, { "component": "obsSets", diff --git a/demos/kuppe-2022/src/vitessce_config.py b/demos/kuppe-2022/src/vitessce_config.py index 376294f3..ab307e56 100644 --- a/demos/kuppe-2022/src/vitessce_config.py +++ b/demos/kuppe-2022/src/vitessce_config.py @@ -16,25 +16,23 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper, ImageOmeZarrWrapper, hconcat, vconcat +from vitessce import ( + VitessceConfig, + AnnDataWrapper, + ImageOmeZarrWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, + hconcat, + vconcat, +) BASE_URL = "{{ base_url }}" # OME-Zarr outputs are uploaded to GCS. BASE_URL_GCP = "{{ base_url_gcp }}" -SPATIAL_IMAGE_LAYER = [{ - "type": "raster", - "index": 0, - "colormap": None, - "transparentColor": None, - "opacity": 1, - "domainType": "Min/Max", - "channels": [ - {"selection": {"c": 0}, "color": [255, 0, 0], "visible": True, "slider": [0, 255]}, - {"selection": {"c": 1}, "color": [0, 255, 0], "visible": True, "slider": [0, 255]}, - {"selection": {"c": 2}, "color": [0, 0, 255], "visible": True, "slider": [0, 255]}, - ], -}] +# Visium spot radius in the hires image coordinates of obsm/xy_scaled: +# spot_diameter_fullres (76.31) / 2 * tissue_hires_scalef (0.2032), from the Visium scalefactors. +SPOT_RADIUS = 7.75 def create_config(): @@ -69,8 +67,7 @@ def create_config(): )) dataset.add_object(AnnDataWrapper( adata_url=f"{BASE_URL}/kuppe_2022_nature.visium.h5ad.zarr", - obs_locations_path="obsm/xy_scaled", - obs_segmentations_path="obsm/xy_segmentations_scaled", + obs_spots_path="obsm/xy_scaled", obs_feature_matrix_path="layers/X_uint8", feature_labels_path="var/feature_name", obs_set_paths=["obs/cell_type", "obs/development_stage", "obs/disease", "obs/sex"], @@ -83,14 +80,12 @@ def create_config(): cell_sets = vc.add_view("obsSets", dataset=dataset, uid="A-cell") spot_sets = vc.add_view("obsSets", dataset=dataset, uid="A-spot") - spatial = vc.add_view("spatial", dataset=dataset, uid="B") + spatial = vc.add_view("spatialBeta", dataset=dataset, uid="B") rna_scatterplot = vc.add_view("scatterplot", dataset=dataset, uid="C") atac_scatterplot = vc.add_view("scatterplot", dataset=dataset, uid="D") feature_list = vc.add_view("featureList", dataset=dataset, uid="E") description = vc.add_view("description", dataset=dataset, uid="H") - layer_controller = vc.add_view( - "layerController", dataset=dataset, uid="I", - ).set_props(disableChannelsIfRgbDetected=True) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset, uid="I") vc.link_views([rna_scatterplot], ["embeddingType"], ["snRNA UMAP"]) vc.link_views([atac_scatterplot], ["embeddingType"], ["snATAC UMAP"]) @@ -105,31 +100,43 @@ def create_config(): vc.link_views([rna_scatterplot], ["featureValueType", "featureValueColormapRange"], ["transcript count", [0, 0.1]]) vc.link_views([atac_scatterplot], ["featureValueType", "featureValueColormapRange"], ["mapped peak count", [0, 0.1]]) - # Visium spots. - vc.link_views( - [spot_sets, spatial, layer_controller], - ["obsType"], - ["spot"], - ) - vc.link_views([spot_sets, spatial], ["obsSetSelection", "obsSetColor"], [None, None]) - vc.link_views([spatial], ["featureValueType"], ["detection count"]) - vc.link_views( - [spatial, layer_controller], - ["spatialSegmentationLayer", "spatialImageLayer"], - [{"radius": 65, "stroked": True, "visible": True, "opacity": 1}, SPATIAL_IMAGE_LAYER], - ) - # Shared gene selection and color encoding. - vc.link_views( - [cell_sets, spot_sets, spatial, rna_scatterplot, atac_scatterplot, feature_list], - ["obsColorEncoding"], - ["cellSetSelection"], - ) - vc.link_views( - [spatial, rna_scatterplot, atac_scatterplot, feature_list], - ["featureType", "featureSelection"], - ["gene", None], + obs_color_encoding, feature_type, feature_selection = vc.add_coordination( + "obsColorEncoding", "featureType", "featureSelection", ) + obs_color_encoding.set_value("cellSetSelection") + feature_type.set_value("gene") + feature_selection.set_value(None) + for view in [cell_sets, spot_sets, rna_scatterplot, atac_scatterplot, feature_list]: + view.use_coordination(obs_color_encoding) + for view in [rna_scatterplot, atac_scatterplot, feature_list]: + view.use_coordination(feature_type, feature_selection) + + # Visium spots: spot sets, the spatial spot layer, and the layer controller. + spot_obs_type, spot_set_selection, spot_set_color = vc.add_coordination("obsType", "obsSetSelection", "obsSetColor") + spot_obs_type.set_value("spot") + spot_set_selection.set_value(None) + spot_set_color.set_value(None) + spot_sets.use_coordination(spot_obs_type, spot_set_selection, spot_set_color) + for view in [spatial, layer_controller]: + view.use_coordination(spot_obs_type) + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("kuppe_2022_nature", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "spotLayer": CL([{ + "obsType": spot_obs_type, + "spatialSpotRadius": SPOT_RADIUS, + "featureType": feature_type, + "featureValueType": "detection count", + "featureSelection": feature_selection, + "obsColorEncoding": obs_color_encoding, + "obsSetSelection": spot_set_selection, + "obsSetColor": spot_set_color, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("kuppe_2022_nature", "obsSpots")) vc.layout(vconcat( hconcat( diff --git a/demos/kuppe-2022/vitessce.template.json b/demos/kuppe-2022/vitessce.template.json index 0cc446a2..f8314bc0 100644 --- a/demos/kuppe-2022/vitessce.template.json +++ b/demos/kuppe-2022/vitessce.template.json @@ -100,12 +100,9 @@ "fileType": "anndata.zarr", "url": "{{ base_url }}/kuppe_2022_nature.visium.h5ad.zarr", "options": { - "obsLocations": { + "obsSpots": { "path": "obsm/xy_scaled" }, - "obsSegmentations": { - "path": "obsm/xy_segmentations_scaled" - }, "obsSets": [ { "name": "Spot Type", @@ -170,7 +167,7 @@ "featureValueType": { "A": "transcript count", "B": "mapped peak count", - "C": "detection count" + "init_kuppe_2022_nature_obsSpots_0": "detection count" }, "featureValueColormapRange": { "A": [ @@ -182,73 +179,6 @@ 0.1 ] }, - "spatialSegmentationLayer": { - "A": { - "radius": 65, - "stroked": true, - "visible": true, - "opacity": 1 - } - }, - "spatialImageLayer": { - "A": [ - { - "type": "raster", - "index": 0, - "colormap": null, - "transparentColor": null, - "opacity": 1, - "domainType": "Min/Max", - "channels": [ - { - "selection": { - "c": 0 - }, - "color": [ - 255, - 0, - 0 - ], - "visible": true, - "slider": [ - 0, - 255 - ] - }, - { - "selection": { - "c": 1 - }, - "color": [ - 0, - 255, - 0 - ], - "visible": true, - "slider": [ - 0, - 255 - ] - }, - { - "selection": { - "c": 2 - }, - "color": [ - 0, - 0, - 255 - ], - "visible": true, - "slider": [ - 0, - 255 - ] - } - ] - } - ] - }, "obsColorEncoding": { "A": "cellSetSelection" }, @@ -257,6 +187,67 @@ }, "featureSelection": { "A": null + }, + "imageLayer": { + "init_kuppe_2022_nature_image_0": "__dummy__" + }, + "photometricInterpretation": { + "init_kuppe_2022_nature_image_0": "RGB" + }, + "metaCoordinationScopes": { + "init_kuppe_2022_nature_image_0": { + "imageLayer": [ + "init_kuppe_2022_nature_image_0" + ] + }, + "init_kuppe_2022_nature_obsSpots_0": { + "spotLayer": [ + "init_kuppe_2022_nature_obsSpots_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_kuppe_2022_nature_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_kuppe_2022_nature_image_0": "init_kuppe_2022_nature_image_0" + } + } + }, + "init_kuppe_2022_nature_obsSpots_0": { + "spotLayer": { + "obsType": { + "init_kuppe_2022_nature_obsSpots_0": "B" + }, + "spatialSpotRadius": { + "init_kuppe_2022_nature_obsSpots_0": "init_kuppe_2022_nature_obsSpots_0" + }, + "featureType": { + "init_kuppe_2022_nature_obsSpots_0": "A" + }, + "featureValueType": { + "init_kuppe_2022_nature_obsSpots_0": "init_kuppe_2022_nature_obsSpots_0" + }, + "featureSelection": { + "init_kuppe_2022_nature_obsSpots_0": "A" + }, + "obsColorEncoding": { + "init_kuppe_2022_nature_obsSpots_0": "A" + }, + "obsSetSelection": { + "init_kuppe_2022_nature_obsSpots_0": "B" + }, + "obsSetColor": { + "init_kuppe_2022_nature_obsSpots_0": "B" + } + } + } + }, + "spotLayer": { + "init_kuppe_2022_nature_obsSpots_0": "__dummy__" + }, + "spatialSpotRadius": { + "init_kuppe_2022_nature_obsSpots_0": 7.75 } }, "layout": [ @@ -279,10 +270,10 @@ "component": "obsSets", "coordinationScopes": { "dataset": "A", + "obsColorEncoding": "A", "obsType": "B", "obsSetSelection": "B", - "obsSetColor": "B", - "obsColorEncoding": "A" + "obsSetColor": "B" }, "x": 3, "y": 9, @@ -291,18 +282,18 @@ "uid": "A-spot" }, { - "component": "spatial", + "component": "spatialBeta", "coordinationScopes": { "dataset": "A", "obsType": "B", - "obsSetSelection": "B", - "obsSetColor": "B", - "featureValueType": "C", - "spatialSegmentationLayer": "A", - "spatialImageLayer": "A", - "obsColorEncoding": "A", - "featureType": "A", - "featureSelection": "A" + "metaCoordinationScopes": [ + "init_kuppe_2022_nature_image_0", + "init_kuppe_2022_nature_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_kuppe_2022_nature_image_0", + "init_kuppe_2022_nature_obsSpots_0" + ] }, "x": 8, "y": 0, @@ -378,21 +369,24 @@ "uid": "H" }, { - "component": "layerController", + "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", "obsType": "B", - "spatialSegmentationLayer": "A", - "spatialImageLayer": "A" + "metaCoordinationScopes": [ + "init_kuppe_2022_nature_image_0", + "init_kuppe_2022_nature_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_kuppe_2022_nature_image_0", + "init_kuppe_2022_nature_obsSpots_0" + ] }, "x": 9, "y": 6, "w": 3, "h": 6, - "uid": "I", - "props": { - "disableChannelsIfRgbDetected": true - } + "uid": "I" } ], "initStrategy": "auto" diff --git a/demos/marshall-2022/src/vitessce_config.py b/demos/marshall-2022/src/vitessce_config.py index 31836b13..48026535 100644 --- a/demos/marshall-2022/src/vitessce_config.py +++ b/demos/marshall-2022/src/vitessce_config.py @@ -16,9 +16,18 @@ import argparse import json -from vitessce import VitessceConfig, AnnDataWrapper, hconcat, vconcat +from vitessce import ( + VitessceConfig, + AnnDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, + hconcat, + vconcat, +) BASE_URL = "{{ base_url }}" +# Bead radius, in the units of obsm/X_spatial (matches the diamonds drawn by src/convert_to_zarr.py). +SPOT_RADIUS = 10 def create_config(): @@ -32,8 +41,7 @@ def create_config(): obs_feature_matrix_path="X", obs_embedding_paths=["obsm/X_umap"], obs_embedding_names=["UMAP"], - obs_locations_path="obsm/X_spatial", - obs_segmentations_path="obsm/X_segmentations", + obs_spots_path="obsm/X_spatial", obs_set_paths=["obs/cell_type"], obs_set_names=["Bead Type"], feature_labels_path="var/feature_name", @@ -47,20 +55,33 @@ def create_config(): obs_sets = vc.add_view("obsSets", dataset=dataset) obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP") - spatial = vc.add_view("spatial", dataset=dataset) - layer_controller = vc.add_view("layerController", dataset=dataset) + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) feature_list = vc.add_view("featureList", dataset=dataset) description = vc.add_view("description", dataset=dataset) vc.link_views([obs_sets, obs_set_sizes, scatterplot, spatial, layer_controller, feature_list], ["obsType"], ["bead"]) - vc.link_views([scatterplot, spatial, layer_controller, feature_list], ["featureType"], ["gene"]) - vc.link_views([scatterplot, spatial, layer_controller], ["featureValueType"], ["expression"]) - vc.link_views([scatterplot, spatial], ["featureValueColormapRange"], [[0.0, 0.1]]) - vc.link_views( - [spatial, layer_controller], - ["spatialSegmentationLayer"], - [{"opacity": 1, "radius": 50, "visible": True, "stroked": False}], + # The bead spot layer shares its feature and color scopes with the UMAP, feature list, and bead sets. + feature_type, feature_value_type, colormap_range, obs_color_encoding = vc.add_coordination( + "featureType", "featureValueType", "featureValueColormapRange", "obsColorEncoding", ) + feature_type.set_value("gene") + feature_value_type.set_value("expression") + colormap_range.set_value([0.0, 0.1]) + obs_color_encoding.set_value("cellSetSelection") + scatterplot.use_coordination(feature_type, feature_value_type, colormap_range, obs_color_encoding) + feature_list.use_coordination(feature_type, obs_color_encoding) + obs_sets.use_coordination(obs_color_encoding) + vc.link_views_by_dict([spatial, layer_controller], { + "spotLayer": CL([{ + "obsType": "bead", + "spatialSpotRadius": SPOT_RADIUS, + "featureType": feature_type, + "featureValueType": feature_value_type, + "featureValueColormapRange": colormap_range, + "obsColorEncoding": obs_color_encoding, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("marshall_2022", "obsSpots")) vc.layout(hconcat( vconcat( diff --git a/demos/marshall-2022/vitessce.template.json b/demos/marshall-2022/vitessce.template.json index a523a9c8..ea79f57e 100644 --- a/demos/marshall-2022/vitessce.template.json +++ b/demos/marshall-2022/vitessce.template.json @@ -11,12 +11,9 @@ "fileType": "anndata.zarr", "url": "{{ base_url }}/marshall_2022_iscience.h5ad.zarr", "options": { - "obsLocations": { + "obsSpots": { "path": "obsm/X_spatial" }, - "obsSegmentations": { - "path": "obsm/X_segmentations" - }, "obsEmbedding": [ { "path": "obsm/X_umap", @@ -57,7 +54,8 @@ "A": "UMAP" }, "obsType": { - "A": "bead" + "A": "bead", + "init_marshall_2022_obsSpots_0": "bead" }, "featureType": { "A": "gene" @@ -71,12 +69,44 @@ 0.1 ] }, - "spatialSegmentationLayer": { - "A": { - "opacity": 1, - "radius": 50, - "visible": true, - "stroked": false + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "spotLayer": { + "init_marshall_2022_obsSpots_0": "__dummy__" + }, + "spatialSpotRadius": { + "init_marshall_2022_obsSpots_0": 10 + }, + "metaCoordinationScopes": { + "init_marshall_2022_obsSpots_0": { + "spotLayer": [ + "init_marshall_2022_obsSpots_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_marshall_2022_obsSpots_0": { + "spotLayer": { + "obsType": { + "init_marshall_2022_obsSpots_0": "init_marshall_2022_obsSpots_0" + }, + "spatialSpotRadius": { + "init_marshall_2022_obsSpots_0": "init_marshall_2022_obsSpots_0" + }, + "featureType": { + "init_marshall_2022_obsSpots_0": "A" + }, + "featureValueType": { + "init_marshall_2022_obsSpots_0": "A" + }, + "featureValueColormapRange": { + "init_marshall_2022_obsSpots_0": "A" + }, + "obsColorEncoding": { + "init_marshall_2022_obsSpots_0": "A" + } + } } } }, @@ -85,7 +115,8 @@ "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsType": "A" + "obsType": "A", + "obsColorEncoding": "A" }, "x": 4, "y": 0, @@ -111,7 +142,8 @@ "obsType": "A", "featureType": "A", "featureValueType": "A", - "featureValueColormapRange": "A" + "featureValueColormapRange": "A", + "obsColorEncoding": "A" }, "x": 0, "y": 0, @@ -119,14 +151,16 @@ "h": 6 }, { - "component": "spatial", + "component": "spatialBeta", "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "A", - "featureValueType": "A", - "featureValueColormapRange": "A", - "spatialSegmentationLayer": "A" + "metaCoordinationScopes": [ + "init_marshall_2022_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_marshall_2022_obsSpots_0" + ] }, "x": 0, "y": 6, @@ -134,13 +168,16 @@ "h": 6 }, { - "component": "layerController", + "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "A", - "featureValueType": "A", - "spatialSegmentationLayer": "A" + "metaCoordinationScopes": [ + "init_marshall_2022_obsSpots_0" + ], + "metaCoordinationScopesBy": [ + "init_marshall_2022_obsSpots_0" + ] }, "x": 4, "y": 6, @@ -152,7 +189,8 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "featureType": "A" + "featureType": "A", + "obsColorEncoding": "A" }, "x": 8, "y": 6, diff --git a/demos/spatialdata-codex-hubmap-large-intestine/src/sprm_to_spatialdata.py b/demos/spatialdata-codex-hubmap-large-intestine/src/sprm_to_spatialdata.py index a950163e..9a778e38 100644 --- a/demos/spatialdata-codex-hubmap-large-intestine/src/sprm_to_spatialdata.py +++ b/demos/spatialdata-codex-hubmap-large-intestine/src/sprm_to_spatialdata.py @@ -8,6 +8,7 @@ # "tifffile>=2025.5.10", # "imagecodecs", # "dask", +# "scanpy[leiden]==1.12.6", # ] # # [tool.uv.sources] @@ -22,7 +23,8 @@ - images/image: multiscale (pyramidal) multiplexed image (c, y, x) - labels/cell_labels: multiscale cell segmentation bitmask - tables/table: cell-by-marker mean intensities, annotating labels/cell_labels, - with SPRM K-Means cluster assignments in obs and t-SNE in obsm. + with SPRM K-Means cluster assignments in obs, plus Leiden clusters and a UMAP + computed here from the marker intensities. (SPRM's own t-SNE is not used.) """ import argparse import re @@ -33,6 +35,7 @@ import dask.array as da import numpy as np import pandas as pd +import scanpy as sc import tifffile import zarr from spatialdata import SpatialData @@ -113,6 +116,34 @@ def slugify(name): return re.sub(r"[^0-9a-zA-Z]+", "_", name).strip("_").lower() +# Channels that are not cell-type markers: nuclear stains (Hoechst, DRAQ5, Ir, H3) and, +# for MIBI, elemental/background mass channels. These are excluded from the embedding. +NON_MARKER_CHANNELS = { + "Hoechst1", "DRAQ5", + "Au", "Ca", "Co", "Fe", "Ir", "H3", "Na", "Sc", "Si", "Ta", "background", +} + + +def compute_embedding(adata): + """Compute Leiden clusters and a UMAP from the per-cell mean marker intensities.""" + markers = [v for v in adata.var_names if v not in NON_MARKER_CHANNELS] + x = np.asarray(adata[:, markers].X, dtype=np.float64) + # arcsinh transform with a per-marker cofactor (median of the positive values), + # since marker intensity ranges differ widely within and across panels. + cofactors = np.array([np.median(col[col > 0]) if np.any(col > 0) else 1.0 for col in x.T]) + emb = ad.AnnData(X=np.arcsinh(x / cofactors)) + sc.pp.scale(emb, max_value=10) + sc.pp.pca(emb, n_comps=min(20, len(markers) - 1)) + sc.pp.neighbors(emb, n_neighbors=15) + sc.tl.umap(emb, random_state=0) + sc.tl.leiden(emb, resolution=1.0, flavor="igraph", n_iterations=2, random_state=0) + leiden = pd.Categorical( + [f"Cluster {v}" for v in emb.obs["leiden"]], + categories=[f"Cluster {v}" for v in sorted(emb.obs["leiden"].unique(), key=int)], + ) + return leiden, np.asarray(emb.obsm["X_umap"], dtype=np.float32) + + def read_sprm_table(anndata_zip_path, tmp_dir): # The HuBMAP anndata-zarr zip contains the contents of an AnnData Zarr store at its root. with zipfile.ZipFile(anndata_zip_path) as zf: @@ -139,9 +170,9 @@ def read_sprm_table(anndata_zip_path, tmp_dir): }, obsm={ "spatial": np.asarray(adata.obsm["xy"], dtype=np.float32), - "X_tsne": np.asarray(adata.obsm["tsne"], dtype=np.float32), }, ) + new_adata.obs["leiden"], new_adata.obsm["X_umap"] = compute_embedding(new_adata) return TableModel.parse(new_adata, region=LABELS_KEY, region_key="region", instance_key="cell_id") diff --git a/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py b/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py index 13f94daa..00cc6529 100644 --- a/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py +++ b/demos/spatialdata-codex-hubmap-large-intestine/src/vitessce_config.py @@ -53,19 +53,22 @@ def create_config(): obs_feature_matrix_path="tables/table/X", obs_segmentations_path="labels/cell_labels", obs_set_paths=[ + "tables/table/obs/leiden", "tables/table/obs/k_means_mean_expression", "tables/table/obs/k_means_covariance_expression", "tables/table/obs/k_means_total_expression", "tables/table/obs/k_means_umap_all_features", ], obs_set_names=[ + "Leiden", "SPRM K-Means [Mean] Expression", "SPRM K-Means [Covariance] Expression", "SPRM K-Means [Total] Expression", "SPRM K-Means [UMAP All Features]", ], - obs_embedding_paths=["tables/table/obsm/X_tsne"], - obs_embedding_names=["t-SNE"], + # UMAP computed from the marker intensities by src/sprm_to_spatialdata.py. + obs_embedding_paths=["tables/table/obsm/X_umap"], + obs_embedding_names=["UMAP"], coordinate_system="global", coordination_values={"obsType": "cell", "featureType": "marker"}, ) @@ -78,12 +81,19 @@ def create_config(): scatterplot = vc.add_view("scatterplot", dataset=dataset) heatmap = vc.add_view("heatmap", dataset=dataset) - vc.link_views([scatterplot], ["embeddingType"], ["t-SNE"]) - # The segmentation outlines, feature list, cell sets, t-SNE, and heatmap share one color encoding. - [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) + # The segmentations, feature list, cell sets, UMAP, and heatmap share the feature type + # (the table's features are markers, not genes), feature selection, and color encoding. + feature_type, feature_selection, obs_color_encoding = vc.add_coordination( + "featureType", "featureSelection", "obsColorEncoding", + ) + feature_type.set_value("marker") + feature_selection.set_value(None) obs_color_encoding.set_value("cellSetSelection") + for view in [spatial, layer_controller]: + view.use_coordination(feature_type) for view in [feature_list, obs_sets, scatterplot, heatmap]: - view.use_coordination(obs_color_encoding) + view.use_coordination(feature_type, feature_selection, obs_color_encoding) vc.link_views_by_dict([spatial, layer_controller], { "imageLayer": CL([{ @@ -105,6 +115,9 @@ def create_config(): "spatialLayerVisible": True, "spatialLayerOpacity": 1.0, "segmentationChannel": CL([{ + "obsType": "cell", + "featureType": feature_type, + "featureSelection": feature_selection, "obsColorEncoding": obs_color_encoding, "spatialChannelVisible": True, "spatialSegmentationFilled": False, diff --git a/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json b/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json index 973bf3c7..b52146be 100644 --- a/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json +++ b/demos/spatialdata-codex-hubmap-large-intestine/vitessce.template.json @@ -17,6 +17,10 @@ }, "obsSets": { "obsSets": [ + { + "name": "Leiden", + "path": "tables/table/obs/leiden" + }, { "name": "SPRM K-Means [Mean] Expression", "path": "tables/table/obs/k_means_mean_expression" @@ -48,12 +52,12 @@ }, "obsEmbedding": [ { - "path": "tables/table/obsm/X_tsne", + "path": "tables/table/obsm/X_umap", "dims": [ 0, 1 ], - "embeddingType": "t-SNE" + "embeddingType": "UMAP" } ] }, @@ -70,7 +74,13 @@ "A": "A" }, "embeddingType": { - "A": "t-SNE" + "A": "UMAP" + }, + "featureType": { + "A": "marker" + }, + "featureSelection": { + "A": null }, "obsColorEncoding": { "A": "cellSetSelection" @@ -233,6 +243,15 @@ } }, "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "featureType": { + "init_A_obsSegmentations_0": "A" + }, + "featureSelection": { + "init_A_obsSegmentations_0": "A" + }, "obsColorEncoding": { "init_A_obsSegmentations_0": "A" }, @@ -257,14 +276,15 @@ "segmentationChannel": { "init_A_obsSegmentations_0": "__dummy__" }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "A": "cell" + }, "spatialSegmentationFilled": { "init_A_obsSegmentations_0": false }, "spatialSegmentationStrokeWidth": { "init_A_obsSegmentations_0": 1.0 - }, - "obsType": { - "A": "cell" } }, "layout": [ @@ -272,6 +292,7 @@ "component": "spatialBeta", "coordinationScopes": { "dataset": "A", + "featureType": "A", "metaCoordinationScopes": [ "init_A_image_0", "init_A_obsSegmentations_0" @@ -291,6 +312,7 @@ "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", + "featureType": "A", "metaCoordinationScopes": [ "init_A_image_0", "init_A_obsSegmentations_0" @@ -310,6 +332,8 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", + "featureType": "A", + "featureSelection": "A", "obsColorEncoding": "A", "obsType": "A" }, @@ -322,6 +346,8 @@ "component": "obsSets", "coordinationScopes": { "dataset": "A", + "featureType": "A", + "featureSelection": "A", "obsColorEncoding": "A", "obsType": "A" }, @@ -335,6 +361,8 @@ "coordinationScopes": { "dataset": "A", "embeddingType": "A", + "featureType": "A", + "featureSelection": "A", "obsColorEncoding": "A", "obsType": "A" }, @@ -347,6 +375,8 @@ "component": "heatmap", "coordinationScopes": { "dataset": "A", + "featureType": "A", + "featureSelection": "A", "obsColorEncoding": "A", "obsType": "A" }, diff --git a/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py b/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py index 981f8d49..c6791f28 100644 --- a/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py +++ b/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py @@ -229,7 +229,7 @@ def process(flat_dir, section, output_path): images={ "composite": Image2DModel.parse( image, dims=("c", "y", "x"), c_coords=["r", "g", "b"], - scale_factors=[2, 2, 2, 2], chunks=(3, 1024, 1024), transformations=identity, + scale_factors=[2, 2, 2, 2, 2], chunks=(3, 1024, 1024), transformations=identity, ), }, shapes={"cell_boundaries": ShapesModel.parse(boundaries, transformations=identity)}, diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py b/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py index a1db39d4..3d7b837b 100644 --- a/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py +++ b/demos/spatialdata-dbit-seq-mouse-embryo/src/vitessce_config.py @@ -74,35 +74,47 @@ def create_config(): ["obsType"], ["pixel"], ) - vc.link_views([obs_sets, scatterplot], ["obsColorEncoding"], ["cellSetSelection"]) vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) + # One color encoding for the pixel segmentations in both spatial views, both feature lists, + # the cell sets, and the UMAP: selecting a set or a feature updates all of them. + # Image and segmentation layer opacities are also shared across the two modalities. + obs_color_encoding, image_opacity, segmentation_opacity = vc.add_coordination( + "obsColorEncoding", "spatialLayerOpacity", "spatialLayerOpacity", + ) + obs_color_encoding.set_value("geneSelection") + image_opacity.set_value(1.0) + segmentation_opacity.set_value(1.0) + obs_sets.use_coordination(obs_color_encoding) + # Each spatial view shows the tissue image and the pixels colored by one modality. for modality, spatial, layers, features, feature_type, feature in [ ("rna", rna_spatial, rna_layers, rna_features, "gene", "Hbb-y"), ("protein", protein_spatial, protein_layers, protein_features, "protein", "CD326-Ep-CAM"), ]: - f_type, f_value_type, f_selection, color_encoding = vc.add_coordination( - "featureType", "featureValueType", "featureSelection", "obsColorEncoding", + f_type, f_value_type, f_selection = vc.add_coordination( + "featureType", "featureValueType", "featureSelection", ) f_type.set_value(feature_type) f_value_type.set_value("expression") f_selection.set_value([feature]) - color_encoding.set_value("geneSelection") - features.use_coordination(f_type, f_value_type, f_selection, color_encoding) + features.use_coordination(f_type, f_value_type, f_selection, obs_color_encoding) + if modality == "rna": + # The UMAP is computed from RNA, so color it by the RNA feature selection. + scatterplot.use_coordination(f_type, f_value_type, f_selection, obs_color_encoding) vc.link_views_by_dict([spatial, layers], { "imageLayer": CL([{ "photometricInterpretation": "RGB", - "spatialLayerOpacity": 1.0, + "spatialLayerOpacity": image_opacity, }]), "segmentationLayer": CL([{ - "spatialLayerOpacity": 1.0, + "spatialLayerOpacity": segmentation_opacity, "segmentationChannel": CL([{ "obsType": "pixel", "featureType": f_type, "featureValueType": f_value_type, "featureSelection": f_selection, - "obsColorEncoding": color_encoding, + "obsColorEncoding": obs_color_encoding, "spatialChannelOpacity": 0.8, "spatialSegmentationFilled": True, "spatialChannelVisible": True, diff --git a/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json b/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json index 0e39dca8..24ffcd6b 100644 --- a/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json +++ b/demos/spatialdata-dbit-seq-mouse-embryo/vitessce.template.json @@ -87,14 +87,16 @@ "init_rna_0": "pixel", "init_protein_0": "pixel" }, - "obsColorEncoding": { - "A": "cellSetSelection", - "B": "geneSelection", - "C": "geneSelection" - }, "embeddingType": { "A": "UMAP" }, + "obsColorEncoding": { + "A": "geneSelection" + }, + "spatialLayerOpacity": { + "A": 1.0, + "B": 1.0 + }, "featureType": { "A": "gene", "B": "protein" @@ -119,12 +121,6 @@ "init_rna_0": "RGB", "init_protein_0": "RGB" }, - "spatialLayerOpacity": { - "init_rna_0": 1.0, - "init_rna_1": 1.0, - "init_protein_0": 1.0, - "init_protein_1": 1.0 - }, "segmentationLayer": { "init_rna_0": "__dummy__", "init_protein_0": "__dummy__" @@ -170,12 +166,12 @@ "init_rna_0": "init_rna_0" }, "spatialLayerOpacity": { - "init_rna_0": "init_rna_0" + "init_rna_0": "A" } }, "segmentationLayer": { "spatialLayerOpacity": { - "init_rna_0": "init_rna_1" + "init_rna_0": "B" }, "segmentationChannel": { "init_rna_0": [ @@ -197,7 +193,7 @@ "init_rna_0": "A" }, "obsColorEncoding": { - "init_rna_0": "B" + "init_rna_0": "A" }, "spatialChannelOpacity": { "init_rna_0": "init_rna_0" @@ -216,12 +212,12 @@ "init_protein_0": "init_protein_0" }, "spatialLayerOpacity": { - "init_protein_0": "init_protein_0" + "init_protein_0": "A" } }, "segmentationLayer": { "spatialLayerOpacity": { - "init_protein_0": "init_protein_1" + "init_protein_0": "B" }, "segmentationChannel": { "init_protein_0": [ @@ -243,7 +239,7 @@ "init_protein_0": "B" }, "obsColorEncoding": { - "init_protein_0": "C" + "init_protein_0": "A" }, "spatialChannelOpacity": { "init_protein_0": "init_protein_0" @@ -310,7 +306,7 @@ "featureType": "A", "featureValueType": "A", "featureSelection": "A", - "obsColorEncoding": "B" + "obsColorEncoding": "A" }, "x": 3, "y": 3, @@ -371,7 +367,7 @@ "featureType": "B", "featureValueType": "B", "featureSelection": "B", - "obsColorEncoding": "C" + "obsColorEncoding": "A" }, "x": 9, "y": 3, @@ -398,8 +394,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "obsColorEncoding": "A", - "embeddingType": "A" + "embeddingType": "A", + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" }, "x": 0, "y": 6, diff --git a/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py b/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py index 37298872..8af93e33 100644 --- a/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py +++ b/demos/spatialdata-merfish-zhuang-abca-4/src/vitessce_config.py @@ -61,9 +61,18 @@ def create_config(): obs_sets = vc.add_view("obsSets", dataset=dataset) feature_list = vc.add_view("featureList", dataset=dataset) + # The cell spot layer, cell sets, and feature list share one color encoding + # (and feature selection), so selecting a set or a gene recolors the cells. + obs_color_encoding, feature_selection = vc.add_coordination("obsColorEncoding", "featureSelection") + obs_color_encoding.set_value("cellSetSelection") + feature_selection.set_value(None) + obs_sets.use_coordination(obs_color_encoding) + feature_list.use_coordination(obs_color_encoding, feature_selection) vc.link_views_by_dict([spatial, layer_controller], { "spotLayer": CL([{ - "obsColorEncoding": "cellSetSelection", + "obsType": "cell", + "obsColorEncoding": obs_color_encoding, + "featureSelection": feature_selection, }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) vc.link_views([spatial, layer_controller, obs_sets, feature_list], ["obsType"], ["cell"]) diff --git a/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json b/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json index 8c1ed217..47105b09 100644 --- a/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json +++ b/demos/spatialdata-merfish-zhuang-abca-4/vitessce.template.json @@ -56,11 +56,18 @@ "dataset": { "A": "A" }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "featureSelection": { + "A": null + }, "spotLayer": { "init_A_obsSpots_0": "__dummy__" }, - "obsColorEncoding": { - "init_A_obsSpots_0": "cellSetSelection" + "obsType": { + "init_A_obsSpots_0": "cell", + "A": "cell" }, "metaCoordinationScopes": { "init_A_obsSpots_0": { @@ -72,14 +79,17 @@ "metaCoordinationScopesBy": { "init_A_obsSpots_0": { "spotLayer": { - "obsColorEncoding": { + "obsType": { "init_A_obsSpots_0": "init_A_obsSpots_0" + }, + "obsColorEncoding": { + "init_A_obsSpots_0": "A" + }, + "featureSelection": { + "init_A_obsSpots_0": "A" } } } - }, - "obsType": { - "A": "cell" } }, "layout": [ @@ -121,6 +131,7 @@ "component": "obsSets", "coordinationScopes": { "dataset": "A", + "obsColorEncoding": "A", "obsType": "A" }, "x": 8, @@ -132,6 +143,8 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", + "obsColorEncoding": "A", + "featureSelection": "A", "obsType": "A" }, "x": 8, diff --git a/demos/spatialdata-mibi-hubmap-uterus/src/sprm_to_spatialdata.py b/demos/spatialdata-mibi-hubmap-uterus/src/sprm_to_spatialdata.py index a950163e..9a778e38 100644 --- a/demos/spatialdata-mibi-hubmap-uterus/src/sprm_to_spatialdata.py +++ b/demos/spatialdata-mibi-hubmap-uterus/src/sprm_to_spatialdata.py @@ -8,6 +8,7 @@ # "tifffile>=2025.5.10", # "imagecodecs", # "dask", +# "scanpy[leiden]==1.12.6", # ] # # [tool.uv.sources] @@ -22,7 +23,8 @@ - images/image: multiscale (pyramidal) multiplexed image (c, y, x) - labels/cell_labels: multiscale cell segmentation bitmask - tables/table: cell-by-marker mean intensities, annotating labels/cell_labels, - with SPRM K-Means cluster assignments in obs and t-SNE in obsm. + with SPRM K-Means cluster assignments in obs, plus Leiden clusters and a UMAP + computed here from the marker intensities. (SPRM's own t-SNE is not used.) """ import argparse import re @@ -33,6 +35,7 @@ import dask.array as da import numpy as np import pandas as pd +import scanpy as sc import tifffile import zarr from spatialdata import SpatialData @@ -113,6 +116,34 @@ def slugify(name): return re.sub(r"[^0-9a-zA-Z]+", "_", name).strip("_").lower() +# Channels that are not cell-type markers: nuclear stains (Hoechst, DRAQ5, Ir, H3) and, +# for MIBI, elemental/background mass channels. These are excluded from the embedding. +NON_MARKER_CHANNELS = { + "Hoechst1", "DRAQ5", + "Au", "Ca", "Co", "Fe", "Ir", "H3", "Na", "Sc", "Si", "Ta", "background", +} + + +def compute_embedding(adata): + """Compute Leiden clusters and a UMAP from the per-cell mean marker intensities.""" + markers = [v for v in adata.var_names if v not in NON_MARKER_CHANNELS] + x = np.asarray(adata[:, markers].X, dtype=np.float64) + # arcsinh transform with a per-marker cofactor (median of the positive values), + # since marker intensity ranges differ widely within and across panels. + cofactors = np.array([np.median(col[col > 0]) if np.any(col > 0) else 1.0 for col in x.T]) + emb = ad.AnnData(X=np.arcsinh(x / cofactors)) + sc.pp.scale(emb, max_value=10) + sc.pp.pca(emb, n_comps=min(20, len(markers) - 1)) + sc.pp.neighbors(emb, n_neighbors=15) + sc.tl.umap(emb, random_state=0) + sc.tl.leiden(emb, resolution=1.0, flavor="igraph", n_iterations=2, random_state=0) + leiden = pd.Categorical( + [f"Cluster {v}" for v in emb.obs["leiden"]], + categories=[f"Cluster {v}" for v in sorted(emb.obs["leiden"].unique(), key=int)], + ) + return leiden, np.asarray(emb.obsm["X_umap"], dtype=np.float32) + + def read_sprm_table(anndata_zip_path, tmp_dir): # The HuBMAP anndata-zarr zip contains the contents of an AnnData Zarr store at its root. with zipfile.ZipFile(anndata_zip_path) as zf: @@ -139,9 +170,9 @@ def read_sprm_table(anndata_zip_path, tmp_dir): }, obsm={ "spatial": np.asarray(adata.obsm["xy"], dtype=np.float32), - "X_tsne": np.asarray(adata.obsm["tsne"], dtype=np.float32), }, ) + new_adata.obs["leiden"], new_adata.obsm["X_umap"] = compute_embedding(new_adata) return TableModel.parse(new_adata, region=LABELS_KEY, region_key="region", instance_key="cell_id") diff --git a/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py b/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py index 8e6e72c6..fffd1bfb 100644 --- a/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py +++ b/demos/spatialdata-mibi-hubmap-uterus/src/vitessce_config.py @@ -53,19 +53,22 @@ def create_config(): obs_feature_matrix_path="tables/table/X", obs_segmentations_path="labels/cell_labels", obs_set_paths=[ + "tables/table/obs/leiden", "tables/table/obs/k_means_mean_expression", "tables/table/obs/k_means_covariance_expression", "tables/table/obs/k_means_total_expression", "tables/table/obs/k_means_umap_all_features", ], obs_set_names=[ + "Leiden", "SPRM K-Means [Mean] Expression", "SPRM K-Means [Covariance] Expression", "SPRM K-Means [Total] Expression", "SPRM K-Means [UMAP All Features]", ], - obs_embedding_paths=["tables/table/obsm/X_tsne"], - obs_embedding_names=["t-SNE"], + # UMAP computed from the marker intensities by src/sprm_to_spatialdata.py. + obs_embedding_paths=["tables/table/obsm/X_umap"], + obs_embedding_names=["UMAP"], coordinate_system="global", coordination_values={"obsType": "cell", "featureType": "marker"}, ) @@ -78,12 +81,19 @@ def create_config(): scatterplot = vc.add_view("scatterplot", dataset=dataset) heatmap = vc.add_view("heatmap", dataset=dataset) - vc.link_views([scatterplot], ["embeddingType"], ["t-SNE"]) - # The segmentation outlines, feature list, cell sets, t-SNE, and heatmap share one color encoding. - [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) + # The segmentations, feature list, cell sets, UMAP, and heatmap share the feature type + # (the table's features are markers, not genes), feature selection, and color encoding. + feature_type, feature_selection, obs_color_encoding = vc.add_coordination( + "featureType", "featureSelection", "obsColorEncoding", + ) + feature_type.set_value("marker") + feature_selection.set_value(None) obs_color_encoding.set_value("cellSetSelection") + for view in [spatial, layer_controller]: + view.use_coordination(feature_type) for view in [feature_list, obs_sets, scatterplot, heatmap]: - view.use_coordination(obs_color_encoding) + view.use_coordination(feature_type, feature_selection, obs_color_encoding) vc.link_views_by_dict([spatial, layer_controller], { "imageLayer": CL([{ @@ -105,6 +115,9 @@ def create_config(): "spatialLayerVisible": True, "spatialLayerOpacity": 1.0, "segmentationChannel": CL([{ + "obsType": "cell", + "featureType": feature_type, + "featureSelection": feature_selection, "obsColorEncoding": obs_color_encoding, "spatialChannelVisible": True, "spatialSegmentationFilled": False, diff --git a/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json b/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json index 0781fda3..5dc95fbb 100644 --- a/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json +++ b/demos/spatialdata-mibi-hubmap-uterus/vitessce.template.json @@ -17,6 +17,10 @@ }, "obsSets": { "obsSets": [ + { + "name": "Leiden", + "path": "tables/table/obs/leiden" + }, { "name": "SPRM K-Means [Mean] Expression", "path": "tables/table/obs/k_means_mean_expression" @@ -48,12 +52,12 @@ }, "obsEmbedding": [ { - "path": "tables/table/obsm/X_tsne", + "path": "tables/table/obsm/X_umap", "dims": [ 0, 1 ], - "embeddingType": "t-SNE" + "embeddingType": "UMAP" } ] }, @@ -70,7 +74,13 @@ "A": "A" }, "embeddingType": { - "A": "t-SNE" + "A": "UMAP" + }, + "featureType": { + "A": "marker" + }, + "featureSelection": { + "A": null }, "obsColorEncoding": { "A": "cellSetSelection" @@ -233,6 +243,15 @@ } }, "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "featureType": { + "init_A_obsSegmentations_0": "A" + }, + "featureSelection": { + "init_A_obsSegmentations_0": "A" + }, "obsColorEncoding": { "init_A_obsSegmentations_0": "A" }, @@ -257,14 +276,15 @@ "segmentationChannel": { "init_A_obsSegmentations_0": "__dummy__" }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "A": "cell" + }, "spatialSegmentationFilled": { "init_A_obsSegmentations_0": false }, "spatialSegmentationStrokeWidth": { "init_A_obsSegmentations_0": 1.0 - }, - "obsType": { - "A": "cell" } }, "layout": [ @@ -272,6 +292,7 @@ "component": "spatialBeta", "coordinationScopes": { "dataset": "A", + "featureType": "A", "metaCoordinationScopes": [ "init_A_image_0", "init_A_obsSegmentations_0" @@ -291,6 +312,7 @@ "component": "layerControllerBeta", "coordinationScopes": { "dataset": "A", + "featureType": "A", "metaCoordinationScopes": [ "init_A_image_0", "init_A_obsSegmentations_0" @@ -310,6 +332,8 @@ "component": "featureList", "coordinationScopes": { "dataset": "A", + "featureType": "A", + "featureSelection": "A", "obsColorEncoding": "A", "obsType": "A" }, @@ -322,6 +346,8 @@ "component": "obsSets", "coordinationScopes": { "dataset": "A", + "featureType": "A", + "featureSelection": "A", "obsColorEncoding": "A", "obsType": "A" }, @@ -335,6 +361,8 @@ "coordinationScopes": { "dataset": "A", "embeddingType": "A", + "featureType": "A", + "featureSelection": "A", "obsColorEncoding": "A", "obsType": "A" }, @@ -347,6 +375,8 @@ "component": "heatmap", "coordinationScopes": { "dataset": "A", + "featureType": "A", + "featureSelection": "A", "obsColorEncoding": "A", "obsType": "A" }, diff --git a/demos/spatialdata-opendvp-tnbc/README.md b/demos/spatialdata-opendvp-tnbc/README.md new file mode 100644 index 00000000..ed3adbad --- /dev/null +++ b/demos/spatialdata-opendvp-tnbc/README.md @@ -0,0 +1,12 @@ +# openDVP tutorial dataset (TNBC, Deep Visual Proteomics) + +Deep Visual Proteomics (DVP) pairs multiplexed imaging with laser microdissection (LMD) and mass-spectrometry proteomics. This demo uses the openDVP tutorial dataset: a multiplexed immunofluorescence (mIF) image of a triple-negative breast cancer (TNBC) subset, its cell segmentation and per-cell marker quantification, and the LMD regions that were collected for proteomics with their DIA-NN protein matrix. The data is converted to a SpatialData object. + +## Data source +- Zenodo: Fritzsche, S. & Nimo, J. "openDVP tutorial dataset." https://doi.org/10.5281/zenodo.15830141 + - File downloaded by this pipeline: `https://zenodo.org/api/records/15830141/files/data.tar.gz/content` (133 MB, MD5 `a767c99a32ab0138e7d4ad3577e170c2`) +- openDVP: https://github.com/CosciaLab/openDVP (docs: https://coscialab.github.io/openDVP/). The dataset is the one returned by `opendvp.datasets.tutorial_data()`. +- DVP method: Mund, A. et al. "Deep Visual Proteomics defines single-cell identity and heterogeneity." *Nature Biotechnology* 40, 1231–1240 (2022). https://doi.org/10.1038/s41587-022-01302-5 + +## Data sharing policy +CC-BY 4.0 diff --git a/demos/spatialdata-opendvp-tnbc/Snakefile b/demos/spatialdata-opendvp-tnbc/Snakefile new file mode 100644 index 00000000..108a61c9 --- /dev/null +++ b/demos/spatialdata-opendvp-tnbc/Snakefile @@ -0,0 +1,81 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# openDVP (academic; Deep Visual Proteomics) tutorial dataset. +# +# - openDVP: https://github.com/CosciaLab/openDVP, docs https://coscialab.github.io/openDVP/ +# (dataset loader: opendvp.datasets.tutorial_data, https://coscialab.github.io/openDVP/api/datasets.html) +# - Zenodo record "openDVP tutorial dataset" (Fritzsche, S. & Nimo, J.), https://doi.org/10.5281/zenodo.15830141, CC-BY 4.0. +# A single 133 MB data.tar.gz (~1 GB extracted): a 15-channel mIF OME-TIFF of a triple-negative +# breast cancer subset (TD_15_TNBC_subset), a Cellpose segmentation mask, per-cell quantification, +# gates and a phenotype matrix, manual artefact annotations, and laser microdissection (LMD) +# collection shapes with the DIA-NN protein matrix of the collected regions. +ZENODO_URL = "https://zenodo.org/api/records/15830141/files/data.tar.gz/content" +ZENODO_MD5 = "a767c99a32ab0138e7d4ad3577e170c2" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" + +# Combine the image, mask, cell table (with openDVP phenotyping), LMD regions and their proteomics +# into one SpatialData store. +rule convert_to_spatialdata: + input: + (RAW_DIR / "data" / "quantification" / "quant.csv") + output: + directory(PROCESSED_DIR / "opendvp_tnbc.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py"), + data_dir=(RAW_DIR / "data") + shell: + ''' + uv run --script {params.script} \ + -i {params.data_dir} \ + -o {output} + ''' + +# The archive extracts to a `data/` directory. +rule extract_data: + input: + (RAW_DIR / "data.tar.gz") + output: + (RAW_DIR / "data" / "quantification" / "quant.csv") + params: + raw_dir=RAW_DIR + shell: + ''' + tar -xzf {input} -C {params.raw_dir} + touch {output} + ''' + +rule download_data: + output: + (RAW_DIR / "data.tar.gz") + params: + file_url=ZENODO_URL, + md5=ZENODO_MD5 + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + python3 -c "import hashlib, sys; h = hashlib.md5(open('{output}', 'rb').read()).hexdigest(); sys.exit(0 if h == '{params.md5}' else f'MD5 mismatch: {{h}}')" + ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-opendvp-tnbc/config.yml b/demos/spatialdata-opendvp-tnbc/config.yml new file mode 100644 index 00000000..34ce02ca --- /dev/null +++ b/demos/spatialdata-opendvp-tnbc/config.yml @@ -0,0 +1,2 @@ +output: +- opendvp_tnbc.spatialdata.zarr diff --git a/demos/spatialdata-opendvp-tnbc/src/convert_to_spatialdata.py b/demos/spatialdata-opendvp-tnbc/src/convert_to_spatialdata.py new file mode 100644 index 00000000..e2aaf8e6 --- /dev/null +++ b/demos/spatialdata-opendvp-tnbc/src/convert_to_spatialdata.py @@ -0,0 +1,222 @@ +# /// script +# requires-python = ">=3.12,<3.14" +# dependencies = [ +# "opendvp==0.8.0", +# "spatialdata==0.8.0", +# "anndata==0.13.4", +# "scanpy", +# "igraph", +# "leidenalg", +# "geopandas", +# "tifffile", +# "dask", +# "numpy", +# "pandas", +# ] +# /// +"""Convert the openDVP tutorial dataset to a SpatialData store. + +The openDVP tutorial dataset (Zenodo 10.5281/zenodo.15830141) is a subset of a triple-negative +breast cancer (TNBC) sample (TD_15_TNBC_subset) processed with Deep Visual Proteomics (DVP): +a multiplexed immunofluorescence (mIF) image, its cell segmentation, per-cell marker +quantification, and the laser microdissection (LMD) regions that were cut out for +mass-spectrometry proteomics, with the DIA-NN protein matrix of those regions. + +The cell table is processed with openDVP's own functions, following its tutorials: +- dvp.io.quant_to_adata: quant.csv to AnnData (CellID made 1-based to match the mask labels), +- dvp.tl.filter_by_annotation: flag cells inside the manual artefact annotations, +- dvp.pp.scimap_rescale + dvp.tl.scimap_phenotype: gate-based rescaling and phenotyping + with the provided gates.csv and celltype_matrix.csv. +We also compute a UMAP and Leiden clusters from the (non-background, non-DAPI) markers. + +The proteomics table is processed with dvp.io.DIANN_to_adata, log2-transformed, +filtered to proteins with >= 70% valid values (dvp.tl.filter_features_byNaNs), +and imputed (dvp.tl.impute_gaussian). + +Output elements (all in the "global" coordinate system, in microns; the image is 1 um/pixel): +- images/image: 15-channel mIF image (multiscale). +- labels/cell_labels: cell segmentation mask (multiscale), annotated by tables/table. +- shapes/lmd_regions: LMD collection polygons, annotated by tables/proteomics + (several polygons are pooled into one proteomics sample, so each polygon row + repeats its sample's protein values). +- shapes/artefacts: manual artefact annotation polygons, annotated by tables/artefact_annotations. +""" +import argparse +from pathlib import Path + +import anndata as ad +import dask.array as da +import geopandas as gpd +import numpy as np +import opendvp as dvp +import pandas as pd +import scanpy as sc +import tifffile +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, Labels2DModel, ShapesModel, TableModel +from spatialdata.transformations import Identity + +SAMPLE_ID = "TD_15_TNBC_subset" +# Channels that are not used for the UMAP / Leiden clustering. +NON_BIOLOGICAL_MARKERS = {"750_bg", "647_bg", "555_bg", "488_bg", "DAPI_bg", "DAPI_1", "DAPI_2"} +SCALE_FACTORS = [2, 2, 2, 2] + + +def classification_name(value): + """QuPath GeoJSON features store the class as {"name": ..., "color": ...}.""" + if isinstance(value, dict): + return value.get("name") + if isinstance(value, str): + import json + try: + return json.loads(value).get("name") + except (ValueError, AttributeError): + return value + return None + + +def read_qupath_geojson(path): + gdf = gpd.read_file(path) + gdf["class_name"] = [classification_name(v) for v in gdf["classification"]] + gdf = gdf[["class_name", "geometry"]].reset_index(drop=True) + gdf.index = gdf.index.astype(str) + return gdf + + +def make_cell_table(data_dir, cell_ids_in_mask): + adata = dvp.io.quant_to_adata(data_dir / "quantification" / "quant.csv") + adata.var_names = [v.removeprefix("mean_") for v in adata.var_names] + adata = dvp.tl.filter_by_annotation(adata, str(data_dir / "manual_artefact_annotations" / "artefacts.geojson")) + + gates = dvp.io.import_thresholds(data_dir / "phenotyping" / "gates.csv", sample_id=SAMPLE_ID) + gates["markers"] = gates["markers"].str.removeprefix("mean_") + adata.obs["imageid"] = SAMPLE_ID + raw = adata.X.copy() + adata = dvp.pp.scimap_rescale(adata, gate=gates, log=True, imageid="imageid", verbose=False) + phenotypes = pd.read_csv(data_dir / "phenotyping" / "celltype_matrix.csv") + adata = dvp.tl.scimap_phenotype(adata, phenotypes, label="phenotype", imageid="imageid", verbose=False) + + obs = pd.DataFrame(index=adata.obs_names.astype(str)) + obs["cell_id"] = adata.obs["CellID"].astype(np.int64).to_numpy() + obs["phenotype"] = pd.Categorical(adata.obs["phenotype"].astype(str).to_numpy()) + obs["artefact"] = pd.Categorical(adata.obs["annotation"].astype(str).to_numpy()) + for col in ["Area", "Eccentricity", "Solidity"]: + obs[col.lower()] = adata.obs[col].astype(np.float32).to_numpy() + + table = ad.AnnData( + # Gate-rescaled intensities (0-1; values above 0.5 are positive), from scimap_rescale. + X=np.asarray(adata.X, dtype=np.float32), + obs=obs, + var=pd.DataFrame(index=pd.Index(adata.var_names.astype(str))), + layers={"mean_intensity": np.asarray(raw, dtype=np.float32)}, + obsm={"spatial": adata.obs[["X_centroid", "Y_centroid"]].to_numpy(dtype=np.float32)}, + ) + + # UMAP and Leiden from the arcsinh-transformed, z-scored biological markers. + markers = [v for v in table.var_names if v not in NON_BIOLOGICAL_MARKERS] + embed = ad.AnnData(X=np.arcsinh(table[:, markers].layers["mean_intensity"] / 5.0), obs=pd.DataFrame(index=table.obs_names)) + sc.pp.scale(embed, max_value=10) + sc.pp.neighbors(embed, n_neighbors=15, use_rep="X", random_state=0) + sc.tl.umap(embed, random_state=0) + sc.tl.leiden(embed, resolution=0.5, flavor="igraph", n_iterations=2, random_state=0) + table.obsm["X_umap"] = embed.obsm["X_umap"].astype(np.float32) + table.obs["leiden"] = embed.obs["leiden"].astype("category") + + missing = set(table.obs["cell_id"]) - cell_ids_in_mask + assert not missing, f"{len(missing)} cells are not in the segmentation mask" + table.obs["region"] = pd.Categorical(["cell_labels"] * table.n_obs) + return TableModel.parse(table, region="cell_labels", region_key="region", instance_key="cell_id") + + +def make_proteomics_table(data_dir, lmd_regions): + prot = dvp.io.DIANN_to_adata( + str(data_dir / "proteomics" / "DIANN_pg_matrix.csv"), + metadata_path=str(data_dir / "proteomics" / "DIANN_metadata.csv"), + metadata_sep=";", + ) + prot.X = np.log2(np.asarray(prot.X, dtype=np.float64)) + prot = dvp.tl.filter_features_byNaNs(prot, threshold=0.7) + prot = dvp.tl.impute_gaussian(prot) + prot.obs_names = prot.obs["QuPath_class"].astype(str).to_numpy() + prot.var_names_make_unique() + + # One row per LMD polygon, with the values of the proteomics sample that the polygon was pooled into. + samples = lmd_regions["class_name"].to_numpy() + unknown = set(samples) - set(prot.obs_names) + assert not unknown, f"LMD polygons without a proteomics sample: {unknown}" + X = np.asarray(prot[samples].X, dtype=np.float32) + obs = pd.DataFrame(index=lmd_regions.index.astype(str)) + obs["lmd_region_id"] = lmd_regions.index.astype(str).to_numpy() + obs["sample"] = pd.Categorical(samples) + obs["recurrent_cellular_neighborhood"] = pd.Categorical(prot.obs.loc[samples, "RCN_long"].astype(str).to_numpy()) + obs["proteins_identified"] = prot.obs.loc[samples, "Proteins.Identified"].astype(np.int64).to_numpy() + var = pd.DataFrame(index=pd.Index(prot.var_names.astype(str))) + var["protein_group"] = prot.var["Protein.Group"].astype(str).to_numpy() + var["description"] = prot.var["First.Protein.Description"].astype(str).to_numpy() + table = ad.AnnData(X=X, obs=obs, var=var) + table.obs["region"] = pd.Categorical(["lmd_regions"] * table.n_obs) + return TableModel.parse(table, region="lmd_regions", region_key="region", instance_key="lmd_region_id") + + +def make_artefacts_table(artefacts): + obs = pd.DataFrame(index=artefacts.index.astype(str)) + obs["artefact_id"] = artefacts.index.astype(str).to_numpy() + obs["artefact_class"] = pd.Categorical(artefacts["class_name"].astype(str).to_numpy()) + obs["region"] = pd.Categorical(["artefacts"] * len(obs)) + table = ad.AnnData(obs=obs) + return TableModel.parse(table, region="artefacts", region_key="region", instance_key="artefact_id") + + +def convert(data_dir, output_path): + data_dir = Path(data_dir) + identity = {"global": Identity()} + + with tifffile.TiffFile(data_dir / "image" / "mIF.ome.tif") as tif: + image = tif.asarray() # (c, y, x) uint8, ~1 GB + # The OME-XML has generic channel names; the channels are in the same order as the quant.csv markers. + quant_columns = pd.read_csv(data_dir / "quantification" / "quant.csv", nrows=0).columns + channel_names = [c.removeprefix("mean_") for c in quant_columns if c.startswith("mean_")] + assert len(channel_names) == image.shape[0], (channel_names, image.shape) + + mask = tifffile.imread(data_dir / "segmentation" / "segmentation_mask.tif").astype(np.uint32) + assert mask.shape == image.shape[1:], (mask.shape, image.shape) + cell_ids_in_mask = set(np.unique(mask).tolist()) - {0} + + lmd_regions = read_qupath_geojson(data_dir / "proteomics" / "collection_shapes.geojson") + artefacts = read_qupath_geojson(data_dir / "manual_artefact_annotations" / "artefacts.geojson") + + sdata = SpatialData( + images={ + "image": Image2DModel.parse( + da.from_array(image, chunks=(1, 1024, 1024)), dims=("c", "y", "x"), c_coords=channel_names, + scale_factors=SCALE_FACTORS, chunks=(1, 1024, 1024), transformations=identity, + ), + }, + labels={ + "cell_labels": Labels2DModel.parse( + da.from_array(mask, chunks=(1024, 1024)), dims=("y", "x"), + scale_factors=SCALE_FACTORS, chunks=(1024, 1024), transformations=identity, + ), + }, + shapes={ + "lmd_regions": ShapesModel.parse(lmd_regions[["geometry"]], transformations=identity), + "artefacts": ShapesModel.parse(artefacts[["geometry"]], transformations=identity), + }, + tables={ + "table": make_cell_table(data_dir, cell_ids_in_mask), + "proteomics": make_proteomics_table(data_dir, lmd_regions), + "artefact_annotations": make_artefacts_table(artefacts), + }, + ) + sdata.write(output_path, overwrite=True) + print(sdata) + for key, table in sdata.tables.items(): + print(key, table) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-i", "--input", type=str, required=True, help="Extracted openDVP tutorial `data` directory") + parser.add_argument("-o", "--output", type=str, required=True, help="Output SpatialData .zarr store") + args = parser.parse_args() + convert(args.input, args.output) diff --git a/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py b/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py new file mode 100644 index 00000000..eff6d45b --- /dev/null +++ b/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py @@ -0,0 +1,244 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, + hconcat, + vconcat, +) + +BASE_URL = "{{ base_url }}" + +NAME = "openDVP tutorial dataset (TNBC, Deep Visual Proteomics)" +DESCRIPTION = ( + "Multiplexed immunofluorescence image of a triple-negative breast cancer subset with cell segmentation, " + "openDVP gating-based phenotypes, and laser microdissection regions with their DIA-NN proteomics " + "(Zenodo 10.5281/zenodo.15830141)" +) +SDATA_URL = f"{BASE_URL}/opendvp_tnbc.spatialdata.zarr" + +# Initially-visible image channels: (channel index, color, contrast window). +# Channel names (from quant.csv): 750_bg, 647_bg, 555_bg, 488_bg, DAPI_bg, Vimentin, CD3e, panCK, +# CD8, DAPI_1, COL1A1, CD20, CD68, Ki67, DAPI_2. +IMAGE_CHANNELS = [ + (9, [0, 0, 255], [0, 60]), # DAPI_1 + (7, [255, 255, 0], [0, 70]), # panCK + (6, [255, 0, 0], [0, 30]), # CD3e + (10, [0, 255, 0], [10, 50]), # COL1A1 + (11, [255, 0, 255], [0, 40]), # CD20 +] +RCN_SET_NAME = "Recurrent cellular neighborhood" +RCN_COLORS = [ + ("Tumor enriched", [255, 0, 0]), + ("Immune enriched", [0, 255, 255]), +] + + +def create_config(): + vc = VitessceConfig(schema_version="1.0.18", name=NAME, description=DESCRIPTION) + cells = SpatialDataWrapper( + sdata_url=SDATA_URL, + image_path="images/image", + table_path="tables/table", + region="cell_labels", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="labels/cell_labels", + obs_set_paths=["tables/table/obs/phenotype", "tables/table/obs/leiden", "tables/table/obs/artefact"], + obs_set_names=["Phenotype (openDVP gating)", "Leiden", "Artefact annotation"], + obs_embedding_paths=["tables/table/obsm/X_umap"], + obs_embedding_names=["UMAP"], + coordinate_system="global", + coordination_values={"obsType": "cell", "featureType": "marker", "fileUid": "cells"}, + ) + lmd_regions = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/proteomics", + region="lmd_regions", + obs_feature_matrix_path="tables/proteomics/X", + obs_segmentations_path="shapes/lmd_regions", + obs_set_paths=["tables/proteomics/obs/recurrent_cellular_neighborhood", "tables/proteomics/obs/sample"], + obs_set_names=[RCN_SET_NAME, "Proteomics sample"], + coordinate_system="global", + coordination_values={"obsType": "LMD region", "featureType": "protein", "fileUid": "lmd_regions"}, + ) + artefacts = SpatialDataWrapper( + sdata_url=SDATA_URL, + table_path="tables/artefact_annotations", + region="artefacts", + obs_segmentations_path="shapes/artefacts", + obs_set_paths=["tables/artefact_annotations/obs/artefact_class"], + obs_set_names=["Artefact class"], + coordinate_system="global", + coordination_values={"obsType": "artefact", "fileUid": "artefacts"}, + ) + dataset = vc.add_dataset(name=NAME).add_object(cells).add_object(lmd_regions).add_object(artefacts) + + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + cell_features = vc.add_view("featureList", dataset=dataset).set_props(title="Markers") + cell_sets = vc.add_view("obsSets", dataset=dataset).set_props(title="Cell sets") + umap = vc.add_view("scatterplot", dataset=dataset) + cell_heatmap = vc.add_view("heatmap", dataset=dataset).set_props(title="Cells (gate-rescaled marker intensity)") + protein_features = vc.add_view("featureList", dataset=dataset).set_props(title="Proteins") + region_sets = vc.add_view("obsSets", dataset=dataset).set_props(title="LMD regions") + protein_heatmap = vc.add_view("heatmap", dataset=dataset).set_props(title="LMD regions (log2 protein intensity)") + + vc.link_views([umap], ["embeddingType"], ["UMAP"]) + + # Cells: the segmentation channel, marker list, cell sets, UMAP, and heatmap share the + # feature type (markers, not genes), the feature selection, and the color encoding. + cell_obs_type, cell_feature_type, cell_feature_selection, cell_color = vc.add_coordination( + "obsType", "featureType", "featureSelection", "obsColorEncoding", + ) + cell_obs_type.set_value("cell") + cell_feature_type.set_value("marker") + cell_feature_selection.set_value(None) + cell_color.set_value("cellSetSelection") + for view in [cell_features, cell_sets, umap, cell_heatmap]: + view.use_coordination(cell_obs_type, cell_feature_type, cell_feature_selection, cell_color) + + # LMD regions: likewise, for the proteomics of the microdissected regions. + # The LMD regions are initially colored by their recurrent cellular neighborhood + # (with the colors of the QuPath classes in collection_shapes.geojson). + ( + region_obs_type, protein_feature_type, protein_feature_selection, region_color, + region_set_selection, region_set_color, + ) = vc.add_coordination( + "obsType", "featureType", "featureSelection", "obsColorEncoding", "obsSetSelection", "obsSetColor", + ) + region_obs_type.set_value("LMD region") + protein_feature_type.set_value("protein") + protein_feature_selection.set_value(None) + region_color.set_value("cellSetSelection") + region_set_selection.set_value([[RCN_SET_NAME, name] for name, _ in RCN_COLORS]) + region_set_color.set_value([{"path": [RCN_SET_NAME, name], "color": color} for name, color in RCN_COLORS]) + for view in [protein_features, region_sets, protein_heatmap]: + view.use_coordination( + region_obs_type, protein_feature_type, protein_feature_selection, region_color, + region_set_selection, region_set_color, + ) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "fileUid": "cells", + "photometricInterpretation": "BlackIsZero", + "spatialLayerOpacity": 1.0, + "spatialLayerVisible": True, + "imageChannel": CL([ + { + "spatialTargetC": c, + "spatialChannelColor": color, + "spatialChannelWindow": window, + "spatialChannelVisible": True, + "spatialChannelOpacity": 1.0, + } + for c, color, window in IMAGE_CHANNELS + ]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([ + { + "fileUid": "cells", + "spatialLayerVisible": True, + "spatialLayerOpacity": 1.0, + "segmentationChannel": CL([{ + "obsType": cell_obs_type, + "featureType": cell_feature_type, + "featureSelection": cell_feature_selection, + "obsColorEncoding": cell_color, + "spatialChannelVisible": True, + "spatialChannelOpacity": 1.0, + "spatialSegmentationFilled": False, + "spatialSegmentationStrokeWidth": 1.0, + }]), + }, + { + "fileUid": "lmd_regions", + "spatialLayerVisible": True, + "spatialLayerOpacity": 1.0, + "segmentationChannel": CL([{ + "obsType": region_obs_type, + "featureType": protein_feature_type, + "featureSelection": protein_feature_selection, + "obsColorEncoding": region_color, + "obsSetSelection": region_set_selection, + "obsSetColor": region_set_color, + "spatialChannelVisible": True, + "spatialChannelOpacity": 0.5, + "spatialSegmentationFilled": True, + }]), + }, + { + # The manual artefact annotations are hidden initially. + "fileUid": "artefacts", + "spatialLayerVisible": False, + "spatialLayerOpacity": 1.0, + "segmentationChannel": CL([{ + "obsType": "artefact", + "obsColorEncoding": "cellSetSelection", + "spatialChannelVisible": True, + "spatialChannelOpacity": 1.0, + "spatialSegmentationFilled": False, + "spatialSegmentationStrokeWidth": 3.0, + }]), + }, + ]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + + vc.layout(hconcat( + vconcat( + spatial, + hconcat( + cell_heatmap, + protein_heatmap, + ), + split=[2, 1], + ), + vconcat( + hconcat( + layer_controller, + vconcat( + cell_features, + cell_sets, + ), + ), + hconcat( + umap, + vconcat( + protein_features, + region_sets, + ), + ), + ), + split=[7, 5], + )) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-opendvp-tnbc/vitessce.template.json b/demos/spatialdata-opendvp-tnbc/vitessce.template.json new file mode 100644 index 00000000..bbc4c9e1 --- /dev/null +++ b/demos/spatialdata-opendvp-tnbc/vitessce.template.json @@ -0,0 +1,629 @@ +{ + "version": "1.0.18", + "name": "openDVP tutorial dataset (TNBC, Deep Visual Proteomics)", + "description": "Multiplexed immunofluorescence image of a triple-negative breast cancer subset with cell segmentation, openDVP gating-based phenotypes, and laser microdissection regions with their DIA-NN proteomics (Zenodo 10.5281/zenodo.15830141)", + "datasets": [ + { + "uid": "A", + "name": "openDVP tutorial dataset (TNBC, Deep Visual Proteomics)", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/opendvp_tnbc.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X", + "region": "cell_labels" + }, + "obsSets": { + "obsSets": [ + { + "name": "Phenotype (openDVP gating)", + "path": "tables/table/obs/phenotype" + }, + { + "name": "Leiden", + "path": "tables/table/obs/leiden" + }, + { + "name": "Artefact annotation", + "path": "tables/table/obs/artefact" + } + ], + "tablePath": "tables/table", + "region": "cell_labels" + }, + "image": { + "path": "images/image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "labels/cell_labels", + "tablePath": "tables/table", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/table/obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "marker", + "fileUid": "cells" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/opendvp_tnbc.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/proteomics/X", + "region": "lmd_regions" + }, + "obsSets": { + "obsSets": [ + { + "name": "Recurrent cellular neighborhood", + "path": "tables/proteomics/obs/recurrent_cellular_neighborhood" + }, + { + "name": "Proteomics sample", + "path": "tables/proteomics/obs/sample" + } + ], + "tablePath": "tables/proteomics", + "region": "lmd_regions" + }, + "obsSegmentations": { + "path": "shapes/lmd_regions", + "tablePath": "tables/proteomics", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "LMD region", + "featureType": "protein", + "fileUid": "lmd_regions" + } + }, + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/opendvp_tnbc.spatialdata.zarr", + "options": { + "obsSets": { + "obsSets": [ + { + "name": "Artefact class", + "path": "tables/artefact_annotations/obs/artefact_class" + } + ], + "tablePath": "tables/artefact_annotations", + "region": "artefacts" + }, + "obsSegmentations": { + "path": "shapes/artefacts", + "tablePath": "tables/artefact_annotations", + "coordinateSystem": "global" + } + }, + "coordinationValues": { + "obsType": "artefact", + "fileUid": "artefacts" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "embeddingType": { + "A": "UMAP" + }, + "obsType": { + "A": "cell", + "B": "LMD region", + "init_A_obsSegmentations_0": "artefact" + }, + "featureType": { + "A": "marker", + "B": "protein" + }, + "featureSelection": { + "A": null, + "B": null + }, + "obsColorEncoding": { + "A": "cellSetSelection", + "B": "cellSetSelection", + "init_A_obsSegmentations_0": "cellSetSelection" + }, + "obsSetSelection": { + "A": [ + [ + "Recurrent cellular neighborhood", + "Tumor enriched" + ], + [ + "Recurrent cellular neighborhood", + "Immune enriched" + ] + ] + }, + "obsSetColor": { + "A": [ + { + "path": [ + "Recurrent cellular neighborhood", + "Tumor enriched" + ], + "color": [ + 255, + 0, + 0 + ] + }, + { + "path": [ + "Recurrent cellular neighborhood", + "Immune enriched" + ], + "color": [ + 0, + 255, + 255 + ] + } + ] + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "fileUid": { + "init_A_image_0": "cells", + "init_A_obsSegmentations_0": "cells", + "init_A_obsSegmentations_1": "lmd_regions", + "init_A_obsSegmentations_2": "artefacts" + }, + "photometricInterpretation": { + "init_A_image_0": "BlackIsZero" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0, + "init_A_obsSegmentations_0": 1.0, + "init_A_obsSegmentations_1": 1.0, + "init_A_obsSegmentations_2": 1.0 + }, + "spatialLayerVisible": { + "init_A_image_0": true, + "init_A_obsSegmentations_0": true, + "init_A_obsSegmentations_1": true, + "init_A_obsSegmentations_2": false + }, + "imageChannel": { + "init_A_image_0": "__dummy__", + "init_A_image_1": "__dummy__", + "init_A_image_2": "__dummy__", + "init_A_image_3": "__dummy__", + "init_A_image_4": "__dummy__" + }, + "spatialTargetC": { + "init_A_image_0": 9, + "init_A_image_1": 7, + "init_A_image_2": 6, + "init_A_image_3": 10, + "init_A_image_4": 11 + }, + "spatialChannelColor": { + "init_A_image_0": [ + 0, + 0, + 255 + ], + "init_A_image_1": [ + 255, + 255, + 0 + ], + "init_A_image_2": [ + 255, + 0, + 0 + ], + "init_A_image_3": [ + 0, + 255, + 0 + ], + "init_A_image_4": [ + 255, + 0, + 255 + ] + }, + "spatialChannelWindow": { + "init_A_image_0": [ + 0, + 60 + ], + "init_A_image_1": [ + 0, + 70 + ], + "init_A_image_2": [ + 0, + 30 + ], + "init_A_image_3": [ + 10, + 50 + ], + "init_A_image_4": [ + 0, + 40 + ] + }, + "spatialChannelVisible": { + "init_A_image_0": true, + "init_A_image_1": true, + "init_A_image_2": true, + "init_A_image_3": true, + "init_A_image_4": true, + "init_A_obsSegmentations_0": true, + "init_A_obsSegmentations_1": true, + "init_A_obsSegmentations_2": true + }, + "spatialChannelOpacity": { + "init_A_image_0": 1.0, + "init_A_image_1": 1.0, + "init_A_image_2": 1.0, + "init_A_image_3": 1.0, + "init_A_image_4": 1.0, + "init_A_obsSegmentations_0": 1.0, + "init_A_obsSegmentations_1": 0.5, + "init_A_obsSegmentations_2": 1.0 + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0", + "init_A_obsSegmentations_1", + "init_A_obsSegmentations_2" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "fileUid": { + "init_A_image_0": "init_A_image_0" + }, + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerVisible": { + "init_A_image_0": "init_A_image_0" + }, + "imageChannel": { + "init_A_image_0": [ + "init_A_image_0", + "init_A_image_1", + "init_A_image_2", + "init_A_image_3", + "init_A_image_4" + ] + } + }, + "imageChannel": { + "spatialTargetC": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelColor": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelWindow": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelVisible": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + }, + "spatialChannelOpacity": { + "init_A_image_0": "init_A_image_0", + "init_A_image_1": "init_A_image_1", + "init_A_image_2": "init_A_image_2", + "init_A_image_3": "init_A_image_3", + "init_A_image_4": "init_A_image_4" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "fileUid": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + }, + "spatialLayerVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + }, + "spatialLayerOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ], + "init_A_obsSegmentations_1": [ + "init_A_obsSegmentations_1" + ], + "init_A_obsSegmentations_2": [ + "init_A_obsSegmentations_2" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "A", + "init_A_obsSegmentations_1": "B", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_0" + }, + "featureType": { + "init_A_obsSegmentations_0": "A", + "init_A_obsSegmentations_1": "B" + }, + "featureSelection": { + "init_A_obsSegmentations_0": "A", + "init_A_obsSegmentations_1": "B" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "A", + "init_A_obsSegmentations_1": "B", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_0" + }, + "spatialChannelVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + }, + "spatialSegmentationStrokeWidth": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", + "init_A_obsSegmentations_2": "init_A_obsSegmentations_1" + }, + "obsSetSelection": { + "init_A_obsSegmentations_1": "A" + }, + "obsSetColor": { + "init_A_obsSegmentations_1": "A" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__", + "init_A_obsSegmentations_1": "__dummy__", + "init_A_obsSegmentations_2": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__", + "init_A_obsSegmentations_1": "__dummy__", + "init_A_obsSegmentations_2": "__dummy__" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": false, + "init_A_obsSegmentations_1": true, + "init_A_obsSegmentations_2": false + }, + "spatialSegmentationStrokeWidth": { + "init_A_obsSegmentations_0": 1.0, + "init_A_obsSegmentations_1": 3.0 + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ] + }, + "x": 0, + "y": 0, + "w": 7, + "h": 8 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ] + }, + "x": 7, + "y": 0, + "w": 2, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 0, + "w": 2, + "h": 3, + "props": { + "title": "Markers" + } + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" + }, + "x": 9, + "y": 3, + "w": 2, + "h": 3, + "props": { + "title": "Cell sets" + } + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "obsType": "A", + "featureType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" + }, + "x": 7, + "y": 6, + "w": 2, + "h": 6 + }, + { + "component": "heatmap", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" + }, + "x": 0, + "y": 8, + "w": 3, + "h": 4, + "props": { + "title": "Cells (gate-rescaled marker intensity)" + } + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "obsType": "B", + "featureType": "B", + "featureSelection": "B", + "obsColorEncoding": "B", + "obsSetSelection": "A", + "obsSetColor": "A" + }, + "x": 9, + "y": 6, + "w": 2, + "h": 3, + "props": { + "title": "Proteins" + } + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "obsType": "B", + "featureType": "B", + "featureSelection": "B", + "obsColorEncoding": "B", + "obsSetSelection": "A", + "obsSetColor": "A" + }, + "x": 9, + "y": 9, + "w": 2, + "h": 3, + "props": { + "title": "LMD regions" + } + }, + { + "component": "heatmap", + "coordinationScopes": { + "dataset": "A", + "obsType": "B", + "featureType": "B", + "featureSelection": "B", + "obsColorEncoding": "B", + "obsSetSelection": "A", + "obsSetColor": "A" + }, + "x": 3, + "y": 8, + "w": 3, + "h": 4, + "props": { + "title": "LMD regions (log2 protein intensity)" + } + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-openst-mouse-hippocampus/README.md b/demos/spatialdata-openst-mouse-hippocampus/README.md new file mode 100644 index 00000000..4b5eeef5 --- /dev/null +++ b/demos/spatialdata-openst-mouse-hippocampus/README.md @@ -0,0 +1,11 @@ +# Open-ST adult mouse hippocampus (Schott et al. 2024) + +Open-ST is a sequencing-based spatial transcriptomics method with 0.6 µm capture spots. It aggregates transcripts into cells using a segmentation of a paired H&E image. This demo uses the Open-ST example dataset of an adult mouse hippocampus section: the "by cell" h5ad that the Open-ST tutorial produces, which also stores the aligned H&E image and its segmentation mask in `uns/spatial`. The data is converted to a SpatialData object. + +## Data source +- Open-ST example datasets: https://github.com/rajewsky-lab/openst/blob/main/docs/examples/datasets.md + - File downloaded by this pipeline: `http://bimsbstatic.mdc-berlin.de/rajewsky/openst-public-data/adult_mouse_by_cell.h5ad.tar.gz` (683 MB, MD5 `c837f3184d25fb4842a0e27bde1b3941`). It is listed on the datasets page as `adult_mouse_hippocampus_by_cell.h5ad.tar.gz`. + - Tutorial that produces this file: https://rajewsky-lab.github.io/openst/latest/examples/adult_mouse/ + - Pixel size (1 pixel = 0.345 µm): https://rajewsky-lab.github.io/openst/latest/examples/adult_mouse/pairwise_alignment/ +- Processed data in GEO: [GSE251926](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE251926). Raw reads in SRA: PRJNA1055947. +- Publication: Schott, M. et al. "Open-ST: High-resolution spatial transcriptomics in 3D." *Cell* 187, 3953–3972 (2024). https://doi.org/10.1016/j.cell.2024.05.055 diff --git a/demos/spatialdata-openst-mouse-hippocampus/Snakefile b/demos/spatialdata-openst-mouse-hippocampus/Snakefile new file mode 100644 index 00000000..87a0d5ea --- /dev/null +++ b/demos/spatialdata-openst-mouse-hippocampus/Snakefile @@ -0,0 +1,80 @@ +include: "../common.smk" + +# Absolute paths, so that this Snakefile works both standalone +# (from within this directory) and as a module of ../Snakefile. +DEMO_DIR = Path(workflow.current_basedir) +SRC_DIR = DEMO_DIR / "src" +OUTPUTS = load_demo_outputs(DEMO_DIR) + +# Open-ST (academic; Rajewsky lab) adult mouse hippocampus example dataset. +# +# - Datasets page: https://github.com/rajewsky-lab/openst/blob/main/docs/examples/datasets.md +# ("adult_mouse_hippocampus_by_cell.h5ad.tar.gz", MD5 c837f3184d25fb4842a0e27bde1b3941, 683 MB; +# it extracts to openst_demo_adult_mouse_by_cell.h5ad, 3.3 GB). +# This is the output of the Open-ST tutorial (https://rajewsky-lab.github.io/openst/latest/examples/adult_mouse/), +# with the transcripts aggregated by image-based cell segmentation and the aligned H&E image and mask in `uns/spatial`. +# - Publication: Schott, M. et al. "Open-ST: High-resolution spatial transcriptomics in 3D." Cell 187, 3953-3972 (2024). +# https://doi.org/10.1016/j.cell.2024.05.055 +# - The processed data are also in GEO (GSE251926) and the raw reads in SRA (PRJNA1055947). +OPENST_URL = "http://bimsbstatic.mdc-berlin.de/rajewsky/openst-public-data/adult_mouse_by_cell.h5ad.tar.gz" +OPENST_MD5 = "c837f3184d25fb4842a0e27bde1b3941" + +rule all: + input: + [ (PROCESSED_DIR / f) for f in OUTPUTS ], + "vitessce.template.json" + +# Convert the h5ad (with the H&E image and segmentation mask in uns/spatial) to SpatialData, +# and compute Leiden clusters and a UMAP. +rule convert_to_spatialdata: + input: + (RAW_DIR / "openst_demo_adult_mouse_by_cell.h5ad") + output: + directory(PROCESSED_DIR / "openst_mouse_hippocampus.spatialdata.zarr") + params: + script=(SRC_DIR / "convert_to_spatialdata.py") + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + -o {output} + ''' + +rule extract_data: + input: + (RAW_DIR / "adult_mouse_by_cell.h5ad.tar.gz") + output: + (RAW_DIR / "openst_demo_adult_mouse_by_cell.h5ad") + params: + raw_dir=RAW_DIR + shell: + ''' + tar -xzf {input} -C {params.raw_dir} + touch {output} + ''' + +rule download_data: + output: + (RAW_DIR / "adult_mouse_by_cell.h5ad.tar.gz") + params: + file_url=OPENST_URL, + md5=OPENST_MD5 + shell: + ''' + curl -L --retry 999 --retry-delay 3 -C - -o {output} "{params.file_url}" + python3 -c "import hashlib, sys; h = hashlib.md5(open('{output}', 'rb').read()).hexdigest(); sys.exit(0 if h == '{params.md5}' else f'MD5 mismatch: {{h}}')" + ''' + +# Generate the Vitessce configuration template from src/vitessce_config.py, +# which builds the configuration with the VitessceConfig and wrapper class APIs. +# File URLs in the template contain the `{{ base_url }}` placeholder +# (rendered by the top-level `fill_templates` rule). +rule vitessce_config: + input: + (SRC_DIR / "vitessce_config.py") + output: + "vitessce.template.json" + shell: + ''' + uv run --script {input} -o {output} + ''' diff --git a/demos/spatialdata-openst-mouse-hippocampus/config.yml b/demos/spatialdata-openst-mouse-hippocampus/config.yml new file mode 100644 index 00000000..2cfdd9d6 --- /dev/null +++ b/demos/spatialdata-openst-mouse-hippocampus/config.yml @@ -0,0 +1,2 @@ +output: +- openst_mouse_hippocampus.spatialdata.zarr diff --git a/demos/spatialdata-openst-mouse-hippocampus/src/convert_to_spatialdata.py b/demos/spatialdata-openst-mouse-hippocampus/src/convert_to_spatialdata.py new file mode 100644 index 00000000..e1ac56e0 --- /dev/null +++ b/demos/spatialdata-openst-mouse-hippocampus/src/convert_to_spatialdata.py @@ -0,0 +1,136 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "spatialdata==0.7.3", +# "anndata==0.12.19", # anndata 0.13 exposes X as layers[None], which spatialdata 0.7.3 TableModel.parse rejects. +# "scanpy", +# "scikit-misc", +# "igraph", +# "leidenalg", +# "h5py", +# "dask", +# "numpy", +# "pandas", +# "scipy", +# ] +# /// +"""Convert the Open-ST adult mouse hippocampus "by cell" h5ad to a SpatialData store. + +The Open-ST pipeline (`openst segment` + `openst transcript_assign`) writes one h5ad with +the cell-by-gene counts of the image-segmented cells, plus the aligned H&E staining image +and its segmentation mask in `uns/spatial`: +- uns/spatial/staining_image: (y, x, 3) uint8 H&E image, +- uns/spatial/staining_image_mask: (y, x) int64 segmentation mask; its labels are obs/cell_ID_mask, +- obsm/spatial: cell centroids as (row, column) in staining image pixels. +Cell ID 0 is the background (all transcripts not assigned to any cell) and is dropped. +1 image pixel = 0.345 um +(https://rajewsky-lab.github.io/openst/latest/examples/adult_mouse/pairwise_alignment/). + +We read only these elements with h5py, which skips the per-spot mapping in `uns` +(`indices_joined_spatial_units`, `spatial_units_obs_names`; ~20 million spots). + +Output elements (the "global" coordinate system is in microns): +- images/image: H&E image (multiscale, RGB). +- labels/cell_labels: segmentation mask (multiscale), annotated by tables/table. +- tables/table: log-normalized expression (X) and raw counts (layers/counts), + with QC metrics, Leiden clusters, and UMAP computed here with Scanpy. +""" +import argparse + +import anndata as ad +import dask.array as da +import h5py +import numpy as np +import pandas as pd +import scanpy as sc +from anndata.io import read_elem +from scipy import sparse +from spatialdata import SpatialData +from spatialdata.models import Image2DModel, Labels2DModel, TableModel +from spatialdata.transformations import Scale + +MICRONS_PER_PIXEL = 0.345 +SCALE_FACTORS = [2, 2, 2, 2, 2] +OBS_COLUMNS = ["n_genes_by_counts", "total_counts", "pct_counts_mt", "n_reads"] + + +def make_table(h5): + obs = read_elem(h5["obs"]) + var = read_elem(h5["var"]) + X = read_elem(h5["X"]) + centroids_rc = h5["obsm/spatial"][:] + + keep = obs["cell_ID_mask"].to_numpy() != 0 + obs = obs.loc[keep, ["cell_ID_mask"] + OBS_COLUMNS].copy() + obs.index = obs.index.astype(str) + adata = ad.AnnData( + X=sparse.csr_matrix(X[keep], dtype=np.float32), + obs=obs, + var=pd.DataFrame(index=var.index.astype(str)), + obsm={"spatial": (centroids_rc[keep][:, ::-1] * MICRONS_PER_PIXEL).astype(np.float32)}, + ) + adata.var_names_make_unique() + sc.pp.filter_genes(adata, min_cells=10) + sc.pp.filter_cells(adata, min_counts=1) + print(f"Table after filtering: {adata}") + + adata.layers["counts"] = adata.X.copy() + sc.pp.normalize_total(adata, target_sum=1e4) + sc.pp.log1p(adata) + sc.pp.highly_variable_genes(adata, n_top_genes=2000, flavor="seurat_v3", layer="counts") + sc.tl.pca(adata, n_comps=50, mask_var="highly_variable", random_state=0) + sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30, random_state=0) + sc.tl.umap(adata, random_state=0) + sc.tl.leiden(adata, resolution=1.0, flavor="igraph", n_iterations=2, random_state=0) + + table = ad.AnnData( + # Column-oriented, so that Vitessce can load a single gene's values efficiently. + X=sparse.csc_matrix(adata.X, dtype=np.float32), + obs=adata.obs[["cell_ID_mask", "leiden"] + OBS_COLUMNS].rename(columns={"cell_ID_mask": "cell_id"}), + var=adata.var[["highly_variable", "n_cells"]].copy(), + layers={"counts": sparse.csc_matrix(adata.layers["counts"], dtype=np.float32)}, + obsm={"spatial": adata.obsm["spatial"], "X_umap": adata.obsm["X_umap"].astype(np.float32)}, + ) + table.obs["cell_id"] = table.obs["cell_id"].astype(np.int64) + table.obs["region"] = pd.Categorical(["cell_labels"] * table.n_obs) + return TableModel.parse(table, region="cell_labels", region_key="region", instance_key="cell_id") + + +def convert(input_path, output_path): + scale = {"global": Scale([MICRONS_PER_PIXEL, MICRONS_PER_PIXEL], axes=("x", "y"))} + with h5py.File(input_path, "r") as h5: + table = make_table(h5) + image = h5["uns/spatial/staining_image"][:] # (y, x, 3) uint8 + mask = h5["uns/spatial/staining_image_mask"][:] # (y, x) int64 + assert image.shape[:2] == mask.shape, (image.shape, mask.shape) + assert mask.max() < np.iinfo(np.uint32).max + mask = mask.astype(np.uint32) + missing = set(table.obs["cell_id"]) - set(np.unique(mask).tolist()) + assert not missing, f"{len(missing)} cells are not in the segmentation mask" + + sdata = SpatialData( + images={ + "image": Image2DModel.parse( + da.from_array(np.moveaxis(image, -1, 0), chunks=(3, 1024, 1024)), dims=("c", "y", "x"), + c_coords=["r", "g", "b"], scale_factors=SCALE_FACTORS, chunks=(3, 1024, 1024), transformations=scale, + ), + }, + labels={ + "cell_labels": Labels2DModel.parse( + da.from_array(mask, chunks=(1024, 1024)), dims=("y", "x"), + scale_factors=SCALE_FACTORS, chunks=(1024, 1024), transformations=scale, + ), + }, + tables={"table": table}, + ) + sdata.write(output_path, overwrite=True) + print(sdata) + print(sdata["table"]) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-i", "--input", type=str, required=True, help="Input Open-ST by-cell .h5ad file") + parser.add_argument("-o", "--output", type=str, required=True, help="Output SpatialData .zarr store") + args = parser.parse_args() + convert(args.input, args.output) diff --git a/demos/spatialdata-openst-mouse-hippocampus/src/vitessce_config.py b/demos/spatialdata-openst-mouse-hippocampus/src/vitessce_config.py new file mode 100644 index 00000000..43d39836 --- /dev/null +++ b/demos/spatialdata-openst-mouse-hippocampus/src/vitessce_config.py @@ -0,0 +1,117 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "vitessce[all]", +# ] +# +# [tool.uv.sources] +# # Use the local (repository) version of vitessce. +# vitessce = { path = "../../..", editable = true } +# /// +"""Build the Vitessce configuration template for this demo. + +Writes vitessce.template.json, in which file URLs contain the `{{ base_url }}` +Jinja2 placeholder that ../../fill_template.py later replaces. +""" +import argparse +import json + +from vitessce import ( + VitessceConfig, + SpatialDataWrapper, + CoordinationLevel as CL, + get_initial_coordination_scope_prefix, + hconcat, + vconcat, +) + +BASE_URL = "{{ base_url }}" + +NAME = "Open-ST adult mouse hippocampus (Schott et al. 2024)" +DESCRIPTION = ( + "Open-ST spatial transcriptomics of an adult mouse hippocampus section: H&E image, " + "image-based cell segmentation, and cell-by-gene counts, with Leiden clusters and UMAP" +) + + +def create_config(): + vc = VitessceConfig(schema_version="1.0.18", name=NAME, description=DESCRIPTION) + wrapper = SpatialDataWrapper( + sdata_url=f"{BASE_URL}/openst_mouse_hippocampus.spatialdata.zarr", + image_path="images/image", + table_path="tables/table", + region="cell_labels", + obs_feature_matrix_path="tables/table/X", + obs_segmentations_path="labels/cell_labels", + obs_set_paths=["tables/table/obs/leiden"], + obs_set_names=["Leiden"], + obs_embedding_paths=["tables/table/obsm/X_umap"], + obs_embedding_names=["UMAP"], + coordinate_system="global", + coordination_values={"obsType": "cell", "featureType": "gene", "fileUid": "cells"}, + ) + dataset = vc.add_dataset(name=NAME).add_object(wrapper) + + spatial = vc.add_view("spatialBeta", dataset=dataset) + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + feature_list = vc.add_view("featureList", dataset=dataset) + obs_sets = vc.add_view("obsSets", dataset=dataset) + umap = vc.add_view("scatterplot", dataset=dataset) + + vc.link_views([umap], ["embeddingType"], ["UMAP"]) + # The segmentations, gene list, cell sets, and UMAP share the gene selection and color encoding. + feature_selection, obs_color_encoding = vc.add_coordination("featureSelection", "obsColorEncoding") + feature_selection.set_value(None) + obs_color_encoding.set_value("cellSetSelection") + for view in [feature_list, obs_sets, umap]: + view.use_coordination(feature_selection, obs_color_encoding) + + vc.link_views_by_dict([spatial, layer_controller], { + "imageLayer": CL([{ + "fileUid": "cells", + "photometricInterpretation": "RGB", + "spatialLayerOpacity": 1.0, + "spatialLayerVisible": True, + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) + vc.link_views_by_dict([spatial, layer_controller], { + "segmentationLayer": CL([{ + "fileUid": "cells", + "spatialLayerVisible": True, + "spatialLayerOpacity": 1.0, + "segmentationChannel": CL([{ + "obsType": "cell", + "featureType": "gene", + "featureSelection": feature_selection, + "obsColorEncoding": obs_color_encoding, + "spatialChannelVisible": True, + "spatialChannelOpacity": 0.7, + "spatialSegmentationFilled": True, + }]), + }]), + }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) + vc.link_views([spatial, layer_controller, feature_list, obs_sets, umap], ["obsType"], ["cell"]) + + vc.layout(hconcat( + spatial, + vconcat( + layer_controller, + umap, + ), + vconcat( + feature_list, + obs_sets, + ), + split=[6, 3, 3], + )) + return vc + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-o", "--output", type=str, required=True, help="Output vitessce.template.json") + args = parser.parse_args() + config = create_config().to_dict() + with open(args.output, "w") as f: + json.dump(config, f, indent=2) + f.write("\n") diff --git a/demos/spatialdata-openst-mouse-hippocampus/vitessce.template.json b/demos/spatialdata-openst-mouse-hippocampus/vitessce.template.json new file mode 100644 index 00000000..a1a08758 --- /dev/null +++ b/demos/spatialdata-openst-mouse-hippocampus/vitessce.template.json @@ -0,0 +1,263 @@ +{ + "version": "1.0.18", + "name": "Open-ST adult mouse hippocampus (Schott et al. 2024)", + "description": "Open-ST spatial transcriptomics of an adult mouse hippocampus section: H&E image, image-based cell segmentation, and cell-by-gene counts, with Leiden clusters and UMAP", + "datasets": [ + { + "uid": "A", + "name": "Open-ST adult mouse hippocampus (Schott et al. 2024)", + "files": [ + { + "fileType": "spatialdata.zarr", + "url": "{{ base_url }}/openst_mouse_hippocampus.spatialdata.zarr", + "options": { + "obsFeatureMatrix": { + "path": "tables/table/X", + "region": "cell_labels" + }, + "obsSets": { + "obsSets": [ + { + "name": "Leiden", + "path": "tables/table/obs/leiden" + } + ], + "tablePath": "tables/table", + "region": "cell_labels" + }, + "image": { + "path": "images/image", + "coordinateSystem": "global" + }, + "obsSegmentations": { + "path": "labels/cell_labels", + "tablePath": "tables/table", + "coordinateSystem": "global" + }, + "obsEmbedding": [ + { + "path": "tables/table/obsm/X_umap", + "dims": [ + 0, + 1 + ], + "embeddingType": "UMAP" + } + ] + }, + "coordinationValues": { + "obsType": "cell", + "featureType": "gene", + "fileUid": "cells" + } + } + ] + } + ], + "coordinationSpace": { + "dataset": { + "A": "A" + }, + "embeddingType": { + "A": "UMAP" + }, + "featureSelection": { + "A": null + }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, + "imageLayer": { + "init_A_image_0": "__dummy__" + }, + "fileUid": { + "init_A_image_0": "cells", + "init_A_obsSegmentations_0": "cells" + }, + "photometricInterpretation": { + "init_A_image_0": "RGB" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0, + "init_A_obsSegmentations_0": 1.0 + }, + "spatialLayerVisible": { + "init_A_image_0": true, + "init_A_obsSegmentations_0": true + }, + "metaCoordinationScopes": { + "init_A_image_0": { + "imageLayer": [ + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": [ + "init_A_obsSegmentations_0" + ] + } + }, + "metaCoordinationScopesBy": { + "init_A_image_0": { + "imageLayer": { + "fileUid": { + "init_A_image_0": "init_A_image_0" + }, + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerVisible": { + "init_A_image_0": "init_A_image_0" + } + } + }, + "init_A_obsSegmentations_0": { + "segmentationLayer": { + "fileUid": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialLayerVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialLayerOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" + ] + } + }, + "segmentationChannel": { + "obsType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "featureType": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "featureSelection": { + "init_A_obsSegmentations_0": "A" + }, + "obsColorEncoding": { + "init_A_obsSegmentations_0": "A" + }, + "spatialChannelVisible": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" + } + } + } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__" + }, + "obsType": { + "init_A_obsSegmentations_0": "cell", + "A": "cell" + }, + "featureType": { + "init_A_obsSegmentations_0": "gene" + }, + "spatialChannelVisible": { + "init_A_obsSegmentations_0": true + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.7 + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": true + } + }, + "layout": [ + { + "component": "spatialBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 0, + "y": 0, + "w": 6, + "h": 12 + }, + { + "component": "layerControllerBeta", + "coordinationScopes": { + "dataset": "A", + "metaCoordinationScopes": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "metaCoordinationScopesBy": [ + "init_A_image_0", + "init_A_obsSegmentations_0" + ], + "obsType": "A" + }, + "x": 6, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "featureList", + "coordinationScopes": { + "dataset": "A", + "featureSelection": "A", + "obsColorEncoding": "A", + "obsType": "A" + }, + "x": 9, + "y": 0, + "w": 3, + "h": 6 + }, + { + "component": "obsSets", + "coordinationScopes": { + "dataset": "A", + "featureSelection": "A", + "obsColorEncoding": "A", + "obsType": "A" + }, + "x": 9, + "y": 6, + "w": 3, + "h": 6 + }, + { + "component": "scatterplot", + "coordinationScopes": { + "dataset": "A", + "embeddingType": "A", + "featureSelection": "A", + "obsColorEncoding": "A", + "obsType": "A" + }, + "x": 6, + "y": 6, + "w": 3, + "h": 6 + } + ], + "initStrategy": "auto" +} diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py b/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py index c484b0b9..243927d1 100644 --- a/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/src/vitessce_config.py @@ -84,19 +84,25 @@ def create_config(): vc.link_views([rna_scatterplot], ["embeddingType"], ["RNA UMAP"]) vc.link_views([atac_scatterplot], ["embeddingType"], ["ATAC UMAP"]) - # RNA: the spot layer, gene list, and RNA UMAP share feature and color encoding scopes. - rna_scopes = vc.add_coordination("featureType", "featureValueType", "featureSelection", "obsColorEncoding") - for scope, value in zip(rna_scopes, ["gene", "expression", None, "cellSetSelection"]): - scope.set_value(value) - rna_type, rna_value_type, rna_selection, rna_encoding = rna_scopes + # One color encoding for the spot layer, cell sets, both feature lists, and both UMAPs: + # selecting a set or a feature updates all of them. + [obs_color_encoding] = vc.add_coordination("obsColorEncoding") + obs_color_encoding.set_value("cellSetSelection") + obs_sets.use_coordination(obs_color_encoding) + # RNA: the spot layer, gene list, and RNA UMAP share feature scopes. + rna_type, rna_value_type, rna_selection = vc.add_coordination("featureType", "featureValueType", "featureSelection") + rna_type.set_value("gene") + rna_value_type.set_value("expression") + rna_selection.set_value(None) for view in [gene_list, rna_scatterplot]: - view.use_coordination(*rna_scopes) + view.use_coordination(rna_type, rna_value_type, rna_selection, obs_color_encoding) # ATAC gene activity: gene activity list and ATAC UMAP. - vc.link_views( - [gene_activity_list, atac_scatterplot], - ["featureType", "featureValueType", "featureSelection", "obsColorEncoding"], - ["gene activity", "accessibility", None, "cellSetSelection"], - ) + atac_type, atac_value_type, atac_selection = vc.add_coordination("featureType", "featureValueType", "featureSelection") + atac_type.set_value("gene activity") + atac_value_type.set_value("accessibility") + atac_selection.set_value(None) + for view in [gene_activity_list, atac_scatterplot]: + view.use_coordination(atac_type, atac_value_type, atac_selection, obs_color_encoding) vc.link_views_by_dict([spatial, layer_controller], { "imageLayer": CL([{ @@ -109,7 +115,7 @@ def create_config(): "featureType": rna_type, "featureValueType": rna_value_type, "featureSelection": rna_selection, - "obsColorEncoding": rna_encoding, + "obsColorEncoding": obs_color_encoding, }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) diff --git a/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json b/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json index fbb522a8..c59c94d1 100644 --- a/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json +++ b/demos/spatialdata-spatial-atac-rna-mouse-brain/vitessce.template.json @@ -96,6 +96,9 @@ "A": "RNA UMAP", "B": "ATAC UMAP" }, + "obsColorEncoding": { + "A": "cellSetSelection" + }, "featureType": { "A": "gene", "B": "gene activity" @@ -108,10 +111,6 @@ "A": null, "B": null }, - "obsColorEncoding": { - "A": "cellSetSelection", - "B": "cellSetSelection" - }, "imageLayer": { "init_A_image_0": "__dummy__" }, @@ -205,7 +204,8 @@ "component": "obsSets", "coordinationScopes": { "dataset": "A", - "obsType": "A" + "obsType": "A", + "obsColorEncoding": "A" }, "x": 5, "y": 4, @@ -235,7 +235,7 @@ "featureType": "B", "featureValueType": "B", "featureSelection": "B", - "obsColorEncoding": "B" + "obsColorEncoding": "A" }, "x": 8, "y": 4, @@ -267,7 +267,7 @@ "featureType": "B", "featureValueType": "B", "featureSelection": "B", - "obsColorEncoding": "B" + "obsColorEncoding": "A" }, "x": 3, "y": 8, diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py index 76f64b1c..c5d44c80 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py @@ -78,36 +78,46 @@ def create_config(): ["obsType"], ["pixel"], ) - vc.link_views([obs_sets, rna_scatterplot, ct_scatterplot], ["obsColorEncoding"], ["cellSetSelection"]) vc.link_views([rna_scatterplot], ["embeddingType"], ["UMAP (RNA)"]) vc.link_views([ct_scatterplot], ["embeddingType"], ["UMAP (H3K27me3)"]) + # One color encoding for the pixel segmentations in both spatial views, both feature lists, + # the cell sets, and both UMAPs: selecting a set or a feature updates all of them. + # Image and segmentation layer opacities are also shared across the two modalities. + obs_color_encoding, image_opacity, segmentation_opacity = vc.add_coordination( + "obsColorEncoding", "spatialLayerOpacity", "spatialLayerOpacity", + ) + obs_color_encoding.set_value("geneSelection") + image_opacity.set_value(1.0) + segmentation_opacity.set_value(1.0) + obs_sets.use_coordination(obs_color_encoding) + # Each spatial view shows the tissue image and the pixels colored by one modality. - for modality, spatial, layers, features, feature_type, feature_value_type, feature in [ - ("rna", rna_spatial, rna_layers, rna_features, "gene", "expression", "Mbp"), - ("cut_and_tag", ct_spatial, ct_layers, ct_features, "geneScore", "score", "Hoxa9"), + for modality, spatial, layers, features, scatterplot, feature_type, feature_value_type, feature in [ + ("rna", rna_spatial, rna_layers, rna_features, rna_scatterplot, "gene", "expression", "Mbp"), + ("cut_and_tag", ct_spatial, ct_layers, ct_features, ct_scatterplot, "geneScore", "score", "Hoxa9"), ]: - f_type, f_value_type, f_selection, color_encoding = vc.add_coordination( - "featureType", "featureValueType", "featureSelection", "obsColorEncoding", + f_type, f_value_type, f_selection = vc.add_coordination( + "featureType", "featureValueType", "featureSelection", ) f_type.set_value(feature_type) f_value_type.set_value(feature_value_type) f_selection.set_value([feature]) - color_encoding.set_value("geneSelection") - features.use_coordination(f_type, f_value_type, f_selection, color_encoding) + for view in [features, scatterplot]: + view.use_coordination(f_type, f_value_type, f_selection, obs_color_encoding) vc.link_views_by_dict([spatial, layers], { "imageLayer": CL([{ "photometricInterpretation": "RGB", - "spatialLayerOpacity": 1.0, + "spatialLayerOpacity": image_opacity, }]), "segmentationLayer": CL([{ - "spatialLayerOpacity": 1.0, + "spatialLayerOpacity": segmentation_opacity, "segmentationChannel": CL([{ "obsType": "pixel", "featureType": f_type, "featureValueType": f_value_type, "featureSelection": f_selection, - "obsColorEncoding": color_encoding, + "obsColorEncoding": obs_color_encoding, "spatialChannelOpacity": 0.8, "spatialSegmentationFilled": True, "spatialChannelVisible": True, diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json index 56b229c2..44a49150 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json @@ -99,15 +99,17 @@ "init_rna_0": "pixel", "init_cut_and_tag_0": "pixel" }, - "obsColorEncoding": { - "A": "cellSetSelection", - "B": "geneSelection", - "C": "geneSelection" - }, "embeddingType": { "A": "UMAP (RNA)", "B": "UMAP (H3K27me3)" }, + "obsColorEncoding": { + "A": "geneSelection" + }, + "spatialLayerOpacity": { + "A": 1.0, + "B": 1.0 + }, "featureType": { "A": "gene", "B": "geneScore" @@ -132,12 +134,6 @@ "init_rna_0": "RGB", "init_cut_and_tag_0": "RGB" }, - "spatialLayerOpacity": { - "init_rna_0": 1.0, - "init_rna_1": 1.0, - "init_cut_and_tag_0": 1.0, - "init_cut_and_tag_1": 1.0 - }, "segmentationLayer": { "init_rna_0": "__dummy__", "init_cut_and_tag_0": "__dummy__" @@ -183,12 +179,12 @@ "init_rna_0": "init_rna_0" }, "spatialLayerOpacity": { - "init_rna_0": "init_rna_0" + "init_rna_0": "A" } }, "segmentationLayer": { "spatialLayerOpacity": { - "init_rna_0": "init_rna_1" + "init_rna_0": "B" }, "segmentationChannel": { "init_rna_0": [ @@ -210,7 +206,7 @@ "init_rna_0": "A" }, "obsColorEncoding": { - "init_rna_0": "B" + "init_rna_0": "A" }, "spatialChannelOpacity": { "init_rna_0": "init_rna_0" @@ -229,12 +225,12 @@ "init_cut_and_tag_0": "init_cut_and_tag_0" }, "spatialLayerOpacity": { - "init_cut_and_tag_0": "init_cut_and_tag_0" + "init_cut_and_tag_0": "A" } }, "segmentationLayer": { "spatialLayerOpacity": { - "init_cut_and_tag_0": "init_cut_and_tag_1" + "init_cut_and_tag_0": "B" }, "segmentationChannel": { "init_cut_and_tag_0": [ @@ -256,7 +252,7 @@ "init_cut_and_tag_0": "B" }, "obsColorEncoding": { - "init_cut_and_tag_0": "C" + "init_cut_and_tag_0": "A" }, "spatialChannelOpacity": { "init_cut_and_tag_0": "init_cut_and_tag_0" @@ -323,7 +319,7 @@ "featureType": "A", "featureValueType": "A", "featureSelection": "A", - "obsColorEncoding": "B" + "obsColorEncoding": "A" }, "x": 3, "y": 3, @@ -384,7 +380,7 @@ "featureType": "B", "featureValueType": "B", "featureSelection": "B", - "obsColorEncoding": "C" + "obsColorEncoding": "A" }, "x": 9, "y": 3, @@ -411,8 +407,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "obsColorEncoding": "A", - "embeddingType": "A" + "embeddingType": "A", + "featureType": "A", + "featureValueType": "A", + "featureSelection": "A", + "obsColorEncoding": "A" }, "x": 0, "y": 6, @@ -424,8 +423,11 @@ "coordinationScopes": { "dataset": "A", "obsType": "A", - "obsColorEncoding": "A", - "embeddingType": "B" + "embeddingType": "B", + "featureType": "B", + "featureValueType": "B", + "featureSelection": "B", + "obsColorEncoding": "A" }, "x": 4, "y": 6, diff --git a/demos/spatialdata-stellaromics-pyxa-small/src/convert_to_spatialdata.py b/demos/spatialdata-stellaromics-pyxa-small/src/convert_to_spatialdata.py index 9ce84bd5..2a1d4c7c 100644 --- a/demos/spatialdata-stellaromics-pyxa-small/src/convert_to_spatialdata.py +++ b/demos/spatialdata-stellaromics-pyxa-small/src/convert_to_spatialdata.py @@ -24,7 +24,8 @@ import numpy as np import scanpy as sc from spatialdata import read_zarr -from spatialdata.models import PointsModel +from spatialdata.models import Image3DModel, PointsModel +from spatialdata.transformations import get_transformation from spatialdata_io.experimental import pyxa from vitessce.data_utils import ( sdata_morton_sort_points, @@ -34,6 +35,7 @@ TABLE = "rna" POINTS = "transcripts" +IMAGE = "mosaic_image" def add_clusters(adata): @@ -56,12 +58,29 @@ def add_clusters(adata): adata.obsm["X_umap"] = umap +def rebuild_image_pyramid(sdata): + # The reader's pyramid downsamples z along with y/x (and chunks 32 z-planes together). + # Vitessce renders one z-plane at a time from each resolution level, so every level + # needs all of the z-planes: downsample only y/x, and chunk one z-plane at a time. + image = sdata.images[IMAGE] + full_res = image["scale0"]["image"] if "scale0" in image else image + sdata.images[IMAGE] = Image3DModel.parse( + full_res.data, + dims=("c", "z", "y", "x"), + c_coords=full_res.coords["c"].values, + transformations=get_transformation(full_res, get_all=True), + scale_factors=[{"z": 1, "y": 2, "x": 2}] * 4, + chunks=(1, 1, 1024, 1024), + ) + + def process(input_dir, output_path): # Shapes: cell_boundaries (2D footprint per cell, annotated by the table) and # cell_boundaries_z (per-cell, per-z-plane polygons, with a Z_um column). # Image: mosaic_image (3D, multiscale DAPI). # Points: transcripts (3D, x/y/z in um). sdata = pyxa(input_dir, labels=False) + rebuild_image_pyramid(sdata) add_clusters(sdata.tables[TABLE]) # Store X as CSC, so that Vitessce can read one gene (column) at a time. sdata.tables[TABLE].X = sdata.tables[TABLE].X.tocsc() diff --git a/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py b/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py index f2714e94..fc7864ff 100644 --- a/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py +++ b/demos/spatialdata-stellaromics-pyxa-small/src/vitessce_config.py @@ -69,7 +69,17 @@ def create_config(): vc.link_views([scatterplot], ["embeddingType"], ["UMAP"]) vc.link_views_by_dict([spatial, layer_controller], { - "imageLayer": CL([{}]), + "imageLayer": CL([{ + "photometricInterpretation": "BlackIsZero", + "spatialLayerOpacity": 1.0, + # The 3D image has a single DAPI channel (uint8). + "imageChannel": CL([{ + "spatialTargetC": 0, + "spatialChannelColor": [255, 255, 255], + "spatialChannelWindow": [0, 160], + "spatialChannelVisible": True, + }]), + }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "image")) vc.link_views_by_dict([spatial, layer_controller], { "segmentationLayer": CL([{ diff --git a/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json b/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json index 3df17312..b3ee5617 100644 --- a/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json +++ b/demos/spatialdata-stellaromics-pyxa-small/vitessce.template.json @@ -79,6 +79,34 @@ "imageLayer": { "init_A_image_0": "__dummy__" }, + "photometricInterpretation": { + "init_A_image_0": "BlackIsZero" + }, + "spatialLayerOpacity": { + "init_A_image_0": 1.0 + }, + "imageChannel": { + "init_A_image_0": "__dummy__" + }, + "spatialTargetC": { + "init_A_image_0": 0 + }, + "spatialChannelColor": { + "init_A_image_0": [ + 255, + 255, + 255 + ] + }, + "spatialChannelWindow": { + "init_A_image_0": [ + 0, + 160 + ] + }, + "spatialChannelVisible": { + "init_A_image_0": true + }, "metaCoordinationScopes": { "init_A_image_0": { "imageLayer": [ @@ -97,7 +125,35 @@ } }, "metaCoordinationScopesBy": { - "init_A_image_0": {}, + "init_A_image_0": { + "imageLayer": { + "photometricInterpretation": { + "init_A_image_0": "init_A_image_0" + }, + "spatialLayerOpacity": { + "init_A_image_0": "init_A_image_0" + }, + "imageChannel": { + "init_A_image_0": [ + "init_A_image_0" + ] + } + }, + "imageChannel": { + "spatialTargetC": { + "init_A_image_0": "init_A_image_0" + }, + "spatialChannelColor": { + "init_A_image_0": "init_A_image_0" + }, + "spatialChannelWindow": { + "init_A_image_0": "init_A_image_0" + }, + "spatialChannelVisible": { + "init_A_image_0": "init_A_image_0" + } + } + }, "init_A_obsSegmentations_0": { "segmentationLayer": { "segmentationChannel": { From 7f1be16ce02dc1b6cf85f74e09c8025d95954f04 Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:48:07 -0500 Subject: [PATCH 8/9] Config improvements and todo comments --- demos/mudata-cite-seq-pbmc/src/vitessce_config.py | 2 ++ demos/mudata-pbmc-multiome-10x/src/vitessce_config.py | 2 ++ demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py | 3 ++- demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py | 1 + demos/spatialdata-cosmx-nsclc/src/vitessce_config.py | 3 ++- .../src/convert_to_spatialdata.py | 3 +++ demos/spatialdata-opendvp-tnbc/src/vitessce_config.py | 2 ++ .../src/vitessce_config.py | 2 ++ 8 files changed, 16 insertions(+), 2 deletions(-) diff --git a/demos/mudata-cite-seq-pbmc/src/vitessce_config.py b/demos/mudata-cite-seq-pbmc/src/vitessce_config.py index f4ca8bf3..d153c323 100644 --- a/demos/mudata-cite-seq-pbmc/src/vitessce_config.py +++ b/demos/mudata-cite-seq-pbmc/src/vitessce_config.py @@ -60,6 +60,8 @@ def create_config(): obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) description = vc.add_view("description", dataset=dataset) + + # TODO: sync the zoom/pan of these two scatterplots also vc.link_views([gene_scatterplot, protein_scatterplot], ["embeddingType"], ["UMAP"]) vc.link_views([gene_scatterplot, protein_scatterplot, obs_sets, heatmap, obs_set_sizes], ["obsType"], ["cell"]) vc.link_views( diff --git a/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py b/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py index 7e083b3c..40475110 100644 --- a/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py +++ b/demos/mudata-pbmc-multiome-10x/src/vitessce_config.py @@ -63,6 +63,8 @@ def create_config(): obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) vc.link_views([rna_scatterplot, atac_scatterplot, obs_sets, gene_list, gene_activity_list, obs_set_sizes], ["obsType"], ["cell"]) + + # TODO: all views should share obsColorEncoding and obsSetSelection? vc.link_views( [rna_scatterplot, gene_list], ["featureType", "featureValueType", "featureSelection", "obsColorEncoding"], diff --git a/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py b/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py index eab74a6b..c9753f25 100644 --- a/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py +++ b/demos/ome-zarr-lightsheet-hubmap-spleen/src/vitessce_config.py @@ -41,10 +41,11 @@ def create_config(): img_url=f"{BASE_URL_GCP}/lightsheet_hubmap_spleen.ome.zarr", )) - spatial = vc.add_view("spatialBeta", dataset=dataset) + spatial = vc.add_view("spatialBeta", dataset=dataset).set_props(three=True, accelerated=True) layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) vc.link_views_by_dict([spatial, layer_controller], { + # TODO: begin in 3D rendering mode "imageLayer": CL([{ "photometricInterpretation": "BlackIsZero", "spatialLayerOpacity": 1.0, diff --git a/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py b/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py index c6791f28..6c0153cc 100644 --- a/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py +++ b/demos/spatialdata-cosmx-nsclc/src/convert_to_spatialdata.py @@ -232,6 +232,7 @@ def process(flat_dir, section, output_path): scale_factors=[2, 2, 2, 2, 2], chunks=(3, 1024, 1024), transformations=identity, ), }, + # TODO: store the cell masks (filled) as a label image shapes={"cell_boundaries": ShapesModel.parse(boundaries, transformations=identity)}, tables={"table": TableModel.parse(adata, region="cell_boundaries", region_key="region", instance_key="cell_id")}, ) diff --git a/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py b/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py index 8794cf69..4d081831 100644 --- a/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py +++ b/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py @@ -61,7 +61,8 @@ def create_config(): dataset = vc.add_dataset(name="CosMx").add_object(cells).add_object(points) spatial = vc.add_view("spatialBeta", dataset=dataset) - layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + + layer_controller = vc.add_view("layerControllerBeta", dataset=dataset).set_props(layerPerFeatureForPoints=True) feature_list = vc.add_view("featureList", dataset=dataset) obs_sets = vc.add_view("obsSets", dataset=dataset) diff --git a/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py b/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py index a825b969..08677d09 100644 --- a/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py +++ b/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py @@ -140,9 +140,12 @@ def load_table(xlsx_path, scan_label): var = var[[c for c in ["HUGOSymbol", "TargetGroup", "CodeClass"] if c in var.columns]].astype(str) var.index.name = None + # TODO: use vitessce's sort_var_axis to ensure the var axis has a more meaningful ordering (e.g., to improve how the heatmap looks) + q3 = counts.T.to_numpy(dtype=np.float32) adata = AnnData(X=np.log2(q3 + 1.0), obs=obs, var=var) adata.layers["q3"] = q3 + return adata diff --git a/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py b/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py index eff6d45b..19b469f5 100644 --- a/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py +++ b/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py @@ -79,6 +79,8 @@ def create_config(): coordinate_system="global", coordination_values={"obsType": "LMD region", "featureType": "protein", "fileUid": "lmd_regions"}, ) + + # TODO: remove the artefact stuff (Data configuration part and visualization/link_views configuration parts) artefacts = SpatialDataWrapper( sdata_url=SDATA_URL, table_path="tables/artefact_annotations", diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py index c5d44c80..bd75c44b 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py @@ -93,6 +93,7 @@ def create_config(): obs_sets.use_coordination(obs_color_encoding) # Each spatial view shows the tissue image and the pixels colored by one modality. + # TODO: do not use a for loop over modalities for modality, spatial, layers, features, scatterplot, feature_type, feature_value_type, feature in [ ("rna", rna_spatial, rna_layers, rna_features, rna_scatterplot, "gene", "expression", "Mbp"), ("cut_and_tag", ct_spatial, ct_layers, ct_features, ct_scatterplot, "geneScore", "score", "Hoxa9"), @@ -123,6 +124,7 @@ def create_config(): "spatialChannelVisible": True, }]), }]), + # TODO: use get_initial_coordination_scope_prefix here }, scope_prefix=f"init_{modality}_") vc.layout(vconcat( From ed3b5e57344c4fac1aa932ae903eb82ae1164d56 Mon Sep 17 00:00:00 2001 From: Mark Keller <7525285+keller-mark@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:23:38 -0500 Subject: [PATCH 9/9] Minor improvements --- .../src/vitessce_config.py | 14 +- .../vitessce.template.json | 39 +++-- .../anndata-parse-pbmc/src/vitessce_config.py | 6 +- .../anndata-parse-pbmc/vitessce.template.json | 13 +- demos/combat-2022/src/convert_to_zarr.py | 19 ++- .../meta-2022-azimuth/src/convert_to_zarr.py | 9 +- .../src/vitessce_config.py | 4 +- .../vitessce.template.json | 15 ++ .../src/vitessce_config.py | 15 +- .../vitessce.template.json | 34 ++-- .../src/vitessce_config.py | 5 +- .../vitessce.template.json | 16 +- demos/spatialdata-cosmx-nsclc/Snakefile | 2 +- .../src/convert_to_spatialdata.py | 97 ++++++----- .../src/vitessce_config.py | 5 +- .../vitessce.template.json | 15 +- .../src/convert_to_spatialdata.py | 7 +- .../src/vitessce_config.py | 32 +--- .../vitessce.template.json | 95 +++-------- .../src/vitessce_config.py | 96 +++++++---- .../vitessce.template.json | 160 ++++++++++-------- demos/spatialdata-visium/Snakefile | 20 ++- demos/spatialdata-visium/src/compute_hvg.py | 59 +++++++ .../spatialdata-visium/src/vitessce_config.py | 23 ++- .../spatialdata-visium/vitessce.template.json | 50 ++++-- 25 files changed, 515 insertions(+), 335 deletions(-) create mode 100644 demos/spatialdata-visium/src/compute_hvg.py diff --git a/demos/anndata-chromium-pbmc/src/vitessce_config.py b/demos/anndata-chromium-pbmc/src/vitessce_config.py index ba5bb530..f351b750 100644 --- a/demos/anndata-chromium-pbmc/src/vitessce_config.py +++ b/demos/anndata-chromium-pbmc/src/vitessce_config.py @@ -46,15 +46,16 @@ def create_config(): scatterplot = vc.add_view("scatterplot", dataset=dataset, mapping="UMAP") obs_sets = vc.add_view("obsSets", dataset=dataset) - obs_set_sizes = vc.add_view("obsSetSizes", dataset=dataset) feature_list = vc.add_view("featureList", dataset=dataset) violin = vc.add_view("obsSetFeatureValueDistribution", dataset=dataset) heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) + dot_plot = vc.add_view("dotPlot", dataset=dataset) + histogram = vc.add_view("featureValueHistogram", dataset=dataset) description = vc.add_view("description", dataset=dataset) - vc.link_views([scatterplot, obs_sets, obs_set_sizes, violin, heatmap], ["obsType"], ["cell"]) - vc.link_views([scatterplot, feature_list, violin, heatmap], ["featureType"], ["gene"]) - vc.link_views([scatterplot, violin, heatmap], ["featureValueType"], ["expression"]) + vc.link_views([scatterplot, obs_sets, violin, heatmap, dot_plot, histogram], ["obsType"], ["cell"]) + vc.link_views([scatterplot, feature_list, violin, heatmap, dot_plot, histogram], ["featureType"], ["gene"]) + vc.link_views([scatterplot, violin, heatmap, dot_plot, histogram], ["featureValueType"], ["expression"]) vc.layout(vconcat( hconcat( @@ -65,7 +66,7 @@ def create_config(): split=[4, 3], ), vconcat( - obs_set_sizes, + dot_plot, violin, split=[4, 3], ), @@ -73,8 +74,9 @@ def create_config(): ), hconcat( heatmap, + histogram, description, - split=[9, 3], + split=[6, 3, 3], ), split=[7, 5], )) diff --git a/demos/anndata-chromium-pbmc/vitessce.template.json b/demos/anndata-chromium-pbmc/vitessce.template.json index 6b400cce..98cf6745 100644 --- a/demos/anndata-chromium-pbmc/vitessce.template.json +++ b/demos/anndata-chromium-pbmc/vitessce.template.json @@ -83,17 +83,6 @@ "w": 3, "h": 4 }, - { - "component": "obsSetSizes", - "coordinationScopes": { - "dataset": "A", - "obsType": "A" - }, - "x": 8, - "y": 0, - "w": 4, - "h": 4 - }, { "component": "featureList", "coordinationScopes": { @@ -128,12 +117,38 @@ }, "x": 0, "y": 7, - "w": 9, + "w": 6, "h": 5, "props": { "transpose": true } }, + { + "component": "dotPlot", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "x": 8, + "y": 0, + "w": 4, + "h": 4 + }, + { + "component": "featureValueHistogram", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A", + "featureValueType": "A" + }, + "x": 6, + "y": 7, + "w": 3, + "h": 5 + }, { "component": "description", "coordinationScopes": { diff --git a/demos/anndata-parse-pbmc/src/vitessce_config.py b/demos/anndata-parse-pbmc/src/vitessce_config.py index b0536bf1..f5492a09 100644 --- a/demos/anndata-parse-pbmc/src/vitessce_config.py +++ b/demos/anndata-parse-pbmc/src/vitessce_config.py @@ -51,9 +51,10 @@ def create_config(): feature_list = vc.add_view("featureList", dataset=dataset) violin = vc.add_view("obsSetFeatureValueDistribution", dataset=dataset) heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) + treemap = vc.add_view("treemap", dataset=dataset) description = vc.add_view("description", dataset=dataset) - vc.link_views([scatterplot, obs_sets, obs_set_sizes, violin, heatmap], ["obsType"], ["cell"]) + vc.link_views([scatterplot, obs_sets, obs_set_sizes, violin, heatmap, treemap], ["obsType"], ["cell"]) vc.link_views([scatterplot, feature_list, violin, heatmap], ["featureType"], ["gene"]) vc.link_views([scatterplot, violin, heatmap], ["featureValueType"], ["expression"]) @@ -74,8 +75,9 @@ def create_config(): ), hconcat( heatmap, + treemap, description, - split=[9, 3], + split=[6, 3, 3], ), split=[7, 5], )) diff --git a/demos/anndata-parse-pbmc/vitessce.template.json b/demos/anndata-parse-pbmc/vitessce.template.json index fce2f557..b6b79fc5 100644 --- a/demos/anndata-parse-pbmc/vitessce.template.json +++ b/demos/anndata-parse-pbmc/vitessce.template.json @@ -132,12 +132,23 @@ }, "x": 0, "y": 7, - "w": 9, + "w": 6, "h": 5, "props": { "transpose": true } }, + { + "component": "treemap", + "coordinationScopes": { + "dataset": "A", + "obsType": "A" + }, + "x": 6, + "y": 7, + "w": 3, + "h": 5 + }, { "component": "description", "coordinationScopes": { diff --git a/demos/combat-2022/src/convert_to_zarr.py b/demos/combat-2022/src/convert_to_zarr.py index c9568701..e94a05c8 100644 --- a/demos/combat-2022/src/convert_to_zarr.py +++ b/demos/combat-2022/src/convert_to_zarr.py @@ -13,9 +13,7 @@ # /// import argparse from anndata import read_h5ad -import numpy as np -from scipy import sparse -from vitessce.data_utils import to_uint8 +from vitessce.data_utils import optimize_adata, to_uint8 def convert_h5ad_to_zarr(input_path, output_path): @@ -24,15 +22,18 @@ def convert_h5ad_to_zarr(input_path, output_path): adata.var['is_gene_expression'] = adata.var['feature_types'] == 'Gene Expression' adata.var['is_antibody_capture'] = adata.var['feature_types'] == 'Antibody Capture' - # TODO: automate conversion to csc in optimize_adata function adata.obsm['X_gene_expression_uint8'] = to_uint8(adata[:, adata.var['is_gene_expression']].X, norm_along="global") - if isinstance(adata.obsm['X_gene_expression_uint8'], sparse.spmatrix): - adata.obsm['X_gene_expression_uint8'] = adata.obsm['X_gene_expression_uint8'].tocsc() adata.obsm['X_antibody_capture_uint8'] = to_uint8(adata[:, adata.var['is_antibody_capture']].X, norm_along="global") - if isinstance(adata.obsm['X_antibody_capture_uint8'], sparse.spmatrix): - adata.obsm['X_antibody_capture_uint8'] = adata.obsm['X_antibody_capture_uint8'].tocsc() - adata.obsm['X_umap'] = adata.obsm['X_umap'].astype(np.dtype(' 0, connectivity=4, transform=Affine.translation(ox, oy)): - poly = to_shape(geom) - value = int(value) - if value not in best or poly.area > best[value].area: - best[value] = poly - for value, poly in best.items(): - ids.append(cell_key(fov, value)) - geoms.append(poly.simplify(0.5, preserve_topology=True)) - # Orientation check on a sample of cells: polygon centroid vs. metadata center. + + # Orientation check on a sample of cells: mask centroid vs. metadata center. fov_meta = meta[meta["fov"] == fov].set_index("cell_ID") - for value in list(best.keys())[:200]: - if value in fov_meta.index: - c = best[value].centroid - m = fov_meta.loc[value] - offsets.append(np.hypot(c.x - (m["CenterX_global_px"] - x_min), c.y - (y_top - m["CenterY_global_px"]))) + sample = [v for v in np.unique(labels)[1:201] if v in fov_meta.index] + for value, (cy, cx) in zip(sample, ndimage.center_of_mass(labels > 0, labels, sample)): + m = fov_meta.loc[value] + offsets.append(np.hypot(ox + cx - (m["CenterX_global_px"] - x_min), oy + cy - (y_top - m["CenterY_global_px"]))) + + local_ids = np.unique(labels) + local_ids = local_ids[local_ids > 0] + keep = np.array([cell_key(fov, v) in cell_keys for v in local_ids], dtype=bool) + labels[~np.isin(labels, local_ids[keep])] = 0 + canvas[oy:oy + FOV_H, ox:ox + FOV_W] = np.where(labels > 0, labels + fov * FOV_LABEL_OFFSET, 0) med = float(np.median(offsets)) print(f"Median distance between mask centroids and metadata cell centers: {med:.2f} px") assert med < 10, "Label masks do not line up with the cell metadata; check the y-axis orientation." - return gpd.GeoDataFrame({"geometry": geoms}, index=pd.Index(ids, name="cell_id")) + + # Overlapping FOVs overwrite each other (as in stitch_composite), so collect the remaining cells. + present = set() + for fov, row in pos.iterrows(): + ox, oy = fov_offsets(row, x_min, y_top) + present.update(np.unique(canvas[oy:oy + FOV_H, ox:ox + FOV_W]).tolist()) + present.discard(0) + return canvas, present def build_table(flat_dir, section, x_min, y_top, tx_targets): @@ -149,8 +164,9 @@ def fix_name(col): obs = meta.drop(columns=["fov", "cell_ID"]).copy() obs.insert(0, "fov", pd.Categorical(meta["fov"].astype(str))) obs.insert(1, "fov_cell_ID", meta["cell_ID"].astype(int).to_numpy()) - obs["region"] = pd.Categorical(["cell_boundaries"] * len(obs)) + obs["region"] = pd.Categorical(["cell_labels"] * len(obs)) obs["cell_id"] = obs.index.to_numpy() + obs["label_id"] = np.array([label_id(f, c) for f, c in zip(meta["fov"], meta["cell_ID"])], dtype=np.int64) adata = AnnData(X=counts, obs=obs, var=pd.DataFrame(index=pd.Index(var_names))) adata.obs_names = pd.Index(obs_index) adata.obsm["spatial"] = np.stack([ @@ -216,11 +232,10 @@ def process(flat_dir, section, output_path): adata, meta = build_table(flat_dir, section, x_min, y_top, tx_targets) print(f"{adata.n_obs:,} cells x {adata.n_vars} genes; {adata.obs['leiden'].nunique()} Leiden clusters") - boundaries = trace_boundaries(flat_dir, pos, x_min, y_top, meta) - boundaries = boundaries.loc[boundaries.index.intersection(adata.obs_names)] - # Keep only cells that have a boundary, in the same order as the boundaries. - adata = adata[adata.obs_names.isin(boundaries.index)].copy() - boundaries = boundaries.loc[adata.obs_names] + labels, present = stitch_labels(flat_dir, pos, x_min, y_top, width, height, meta, set(adata.obs_names)) + # Keep only cells that are in the label image. + adata = adata[adata.obs["label_id"].isin(present).to_numpy()].copy() + print(f"{adata.n_obs:,} cells in the label image") image = stitch_composite(flat_dir, pos, x_min, y_top, width, height) @@ -232,9 +247,13 @@ def process(flat_dir, section, output_path): scale_factors=[2, 2, 2, 2, 2], chunks=(3, 1024, 1024), transformations=identity, ), }, - # TODO: store the cell masks (filled) as a label image - shapes={"cell_boundaries": ShapesModel.parse(boundaries, transformations=identity)}, - tables={"table": TableModel.parse(adata, region="cell_boundaries", region_key="region", instance_key="cell_id")}, + labels={ + "cell_labels": Labels2DModel.parse( + da.from_array(labels, chunks=(1024, 1024)), dims=("y", "x"), + scale_factors=[2, 2, 2, 2, 2], chunks=(1024, 1024), transformations=identity, + ), + }, + tables={"table": TableModel.parse(adata, region="cell_labels", region_key="region", instance_key="label_id")}, ) sdata.points["transcripts"] = PointsModel.parse( dd.from_pandas(tx, npartitions=max(1, len(tx) // 2_000_000)), diff --git a/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py b/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py index 4d081831..834901ef 100644 --- a/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py +++ b/demos/spatialdata-cosmx-nsclc/src/vitessce_config.py @@ -35,7 +35,7 @@ def create_config(): name="CosMx SMI NSCLC (Lung9_Rep1)", description=( "NanoString CosMx non-small-cell lung cancer FFPE dataset (He et al. 2022), section Lung9_Rep1: " - "stitched CellComposite image, cell boundaries, Leiden clusters, and morton-sorted transcripts" + "stitched CellComposite image, cell segmentation masks, Leiden clusters, and morton-sorted transcripts" ), ) cells = SpatialDataWrapper( @@ -43,7 +43,8 @@ def create_config(): image_path="images/composite", table_path="tables/table", obs_feature_matrix_path="tables/table/X", - obs_segmentations_path="shapes/cell_boundaries", + obs_segmentations_path="labels/cell_labels", + region="cell_labels", obs_set_paths=["tables/table/obs/leiden", "tables/table/obs/fov"], obs_set_names=["Leiden", "FOV"], coordinate_system="global", diff --git a/demos/spatialdata-cosmx-nsclc/vitessce.template.json b/demos/spatialdata-cosmx-nsclc/vitessce.template.json index 6b6e9aa4..8d55c5fd 100644 --- a/demos/spatialdata-cosmx-nsclc/vitessce.template.json +++ b/demos/spatialdata-cosmx-nsclc/vitessce.template.json @@ -1,7 +1,7 @@ { "version": "1.0.18", "name": "CosMx SMI NSCLC (Lung9_Rep1)", - "description": "NanoString CosMx non-small-cell lung cancer FFPE dataset (He et al. 2022), section Lung9_Rep1: stitched CellComposite image, cell boundaries, Leiden clusters, and morton-sorted transcripts", + "description": "NanoString CosMx non-small-cell lung cancer FFPE dataset (He et al. 2022), section Lung9_Rep1: stitched CellComposite image, cell segmentation masks, Leiden clusters, and morton-sorted transcripts", "datasets": [ { "uid": "A", @@ -12,7 +12,8 @@ "url": "{{ base_url }}/cosmx_nsclc_lung9_rep1.spatialdata.zarr", "options": { "obsFeatureMatrix": { - "path": "tables/table/X" + "path": "tables/table/X", + "region": "cell_labels" }, "obsSets": { "obsSets": [ @@ -25,14 +26,15 @@ "path": "tables/table/obs/fov" } ], - "tablePath": "tables/table" + "tablePath": "tables/table", + "region": "cell_labels" }, "image": { "path": "images/composite", "coordinateSystem": "global" }, "obsSegmentations": { - "path": "shapes/cell_boundaries", + "path": "labels/cell_labels", "tablePath": "tables/table", "coordinateSystem": "global" } @@ -205,7 +207,10 @@ "x": 6, "y": 0, "w": 6, - "h": 3 + "h": 3, + "props": { + "layerPerFeatureForPoints": true + } }, { "component": "featureList", diff --git a/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py b/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py index 08677d09..e4d84569 100644 --- a/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py +++ b/demos/spatialdata-geomx-mouse-embryo/src/convert_to_spatialdata.py @@ -44,6 +44,7 @@ from spatialdata import SpatialData from spatialdata.models import Image2DModel, ShapesModel, TableModel from spatialdata.transformations import Identity +from vitessce.data_utils import sort_var_axis CS = "global" NS = {"ome": "http://www.openmicroscopy.org/Schemas/OME/2016-06"} @@ -140,12 +141,14 @@ def load_table(xlsx_path, scan_label): var = var[[c for c in ["HUGOSymbol", "TargetGroup", "CodeClass"] if c in var.columns]].astype(str) var.index.name = None - # TODO: use vitessce's sort_var_axis to ensure the var axis has a more meaningful ordering (e.g., to improve how the heatmap looks) - q3 = counts.T.to_numpy(dtype=np.float32) adata = AnnData(X=np.log2(q3 + 1.0), obs=obs, var=var) adata.layers["q3"] = q3 + # Order the var axis by hierarchical clustering of the genes, + # so that genes with similar expression are adjacent in the heatmap. + adata = adata[:, sort_var_axis(adata.X, adata.var.index)].copy() + return adata diff --git a/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py b/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py index 19b469f5..867fba2d 100644 --- a/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py +++ b/demos/spatialdata-opendvp-tnbc/src/vitessce_config.py @@ -61,8 +61,8 @@ def create_config(): region="cell_labels", obs_feature_matrix_path="tables/table/X", obs_segmentations_path="labels/cell_labels", - obs_set_paths=["tables/table/obs/phenotype", "tables/table/obs/leiden", "tables/table/obs/artefact"], - obs_set_names=["Phenotype (openDVP gating)", "Leiden", "Artefact annotation"], + obs_set_paths=["tables/table/obs/phenotype", "tables/table/obs/leiden"], + obs_set_names=["Phenotype (openDVP gating)", "Leiden"], obs_embedding_paths=["tables/table/obsm/X_umap"], obs_embedding_names=["UMAP"], coordinate_system="global", @@ -79,19 +79,7 @@ def create_config(): coordinate_system="global", coordination_values={"obsType": "LMD region", "featureType": "protein", "fileUid": "lmd_regions"}, ) - - # TODO: remove the artefact stuff (Data configuration part and visualization/link_views configuration parts) - artefacts = SpatialDataWrapper( - sdata_url=SDATA_URL, - table_path="tables/artefact_annotations", - region="artefacts", - obs_segmentations_path="shapes/artefacts", - obs_set_paths=["tables/artefact_annotations/obs/artefact_class"], - obs_set_names=["Artefact class"], - coordinate_system="global", - coordination_values={"obsType": "artefact", "fileUid": "artefacts"}, - ) - dataset = vc.add_dataset(name=NAME).add_object(cells).add_object(lmd_regions).add_object(artefacts) + dataset = vc.add_dataset(name=NAME).add_object(cells).add_object(lmd_regions) spatial = vc.add_view("spatialBeta", dataset=dataset) layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) @@ -189,20 +177,6 @@ def create_config(): "spatialSegmentationFilled": True, }]), }, - { - # The manual artefact annotations are hidden initially. - "fileUid": "artefacts", - "spatialLayerVisible": False, - "spatialLayerOpacity": 1.0, - "segmentationChannel": CL([{ - "obsType": "artefact", - "obsColorEncoding": "cellSetSelection", - "spatialChannelVisible": True, - "spatialChannelOpacity": 1.0, - "spatialSegmentationFilled": False, - "spatialSegmentationStrokeWidth": 3.0, - }]), - }, ]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSegmentations")) diff --git a/demos/spatialdata-opendvp-tnbc/vitessce.template.json b/demos/spatialdata-opendvp-tnbc/vitessce.template.json index bbc4c9e1..c65010fa 100644 --- a/demos/spatialdata-opendvp-tnbc/vitessce.template.json +++ b/demos/spatialdata-opendvp-tnbc/vitessce.template.json @@ -24,10 +24,6 @@ { "name": "Leiden", "path": "tables/table/obs/leiden" - }, - { - "name": "Artefact annotation", - "path": "tables/table/obs/artefact" } ], "tablePath": "tables/table", @@ -92,31 +88,6 @@ "featureType": "protein", "fileUid": "lmd_regions" } - }, - { - "fileType": "spatialdata.zarr", - "url": "{{ base_url }}/opendvp_tnbc.spatialdata.zarr", - "options": { - "obsSets": { - "obsSets": [ - { - "name": "Artefact class", - "path": "tables/artefact_annotations/obs/artefact_class" - } - ], - "tablePath": "tables/artefact_annotations", - "region": "artefacts" - }, - "obsSegmentations": { - "path": "shapes/artefacts", - "tablePath": "tables/artefact_annotations", - "coordinateSystem": "global" - } - }, - "coordinationValues": { - "obsType": "artefact", - "fileUid": "artefacts" - } } ] } @@ -130,8 +101,7 @@ }, "obsType": { "A": "cell", - "B": "LMD region", - "init_A_obsSegmentations_0": "artefact" + "B": "LMD region" }, "featureType": { "A": "marker", @@ -143,8 +113,7 @@ }, "obsColorEncoding": { "A": "cellSetSelection", - "B": "cellSetSelection", - "init_A_obsSegmentations_0": "cellSetSelection" + "B": "cellSetSelection" }, "obsSetSelection": { "A": [ @@ -190,8 +159,7 @@ "fileUid": { "init_A_image_0": "cells", "init_A_obsSegmentations_0": "cells", - "init_A_obsSegmentations_1": "lmd_regions", - "init_A_obsSegmentations_2": "artefacts" + "init_A_obsSegmentations_1": "lmd_regions" }, "photometricInterpretation": { "init_A_image_0": "BlackIsZero" @@ -199,14 +167,12 @@ "spatialLayerOpacity": { "init_A_image_0": 1.0, "init_A_obsSegmentations_0": 1.0, - "init_A_obsSegmentations_1": 1.0, - "init_A_obsSegmentations_2": 1.0 + "init_A_obsSegmentations_1": 1.0 }, "spatialLayerVisible": { "init_A_image_0": true, "init_A_obsSegmentations_0": true, - "init_A_obsSegmentations_1": true, - "init_A_obsSegmentations_2": false + "init_A_obsSegmentations_1": true }, "imageChannel": { "init_A_image_0": "__dummy__", @@ -278,8 +244,7 @@ "init_A_image_3": true, "init_A_image_4": true, "init_A_obsSegmentations_0": true, - "init_A_obsSegmentations_1": true, - "init_A_obsSegmentations_2": true + "init_A_obsSegmentations_1": true }, "spatialChannelOpacity": { "init_A_image_0": 1.0, @@ -288,8 +253,7 @@ "init_A_image_3": 1.0, "init_A_image_4": 1.0, "init_A_obsSegmentations_0": 1.0, - "init_A_obsSegmentations_1": 0.5, - "init_A_obsSegmentations_2": 1.0 + "init_A_obsSegmentations_1": 0.5 }, "metaCoordinationScopes": { "init_A_image_0": { @@ -300,8 +264,7 @@ "init_A_obsSegmentations_0": { "segmentationLayer": [ "init_A_obsSegmentations_0", - "init_A_obsSegmentations_1", - "init_A_obsSegmentations_2" + "init_A_obsSegmentations_1" ] } }, @@ -372,18 +335,15 @@ "segmentationLayer": { "fileUid": { "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", - "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "spatialLayerVisible": { "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", - "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "spatialLayerOpacity": { "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", - "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "segmentationChannel": { "init_A_obsSegmentations_0": [ @@ -391,17 +351,13 @@ ], "init_A_obsSegmentations_1": [ "init_A_obsSegmentations_1" - ], - "init_A_obsSegmentations_2": [ - "init_A_obsSegmentations_2" ] } }, "segmentationChannel": { "obsType": { "init_A_obsSegmentations_0": "A", - "init_A_obsSegmentations_1": "B", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_0" + "init_A_obsSegmentations_1": "B" }, "featureType": { "init_A_obsSegmentations_0": "A", @@ -413,27 +369,22 @@ }, "obsColorEncoding": { "init_A_obsSegmentations_0": "A", - "init_A_obsSegmentations_1": "B", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_0" + "init_A_obsSegmentations_1": "B" }, "spatialChannelVisible": { "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", - "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "spatialChannelOpacity": { "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", - "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "spatialSegmentationFilled": { "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", - "init_A_obsSegmentations_1": "init_A_obsSegmentations_1", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_2" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "spatialSegmentationStrokeWidth": { - "init_A_obsSegmentations_0": "init_A_obsSegmentations_0", - "init_A_obsSegmentations_2": "init_A_obsSegmentations_1" + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" }, "obsSetSelection": { "init_A_obsSegmentations_1": "A" @@ -446,22 +397,18 @@ }, "segmentationLayer": { "init_A_obsSegmentations_0": "__dummy__", - "init_A_obsSegmentations_1": "__dummy__", - "init_A_obsSegmentations_2": "__dummy__" + "init_A_obsSegmentations_1": "__dummy__" }, "segmentationChannel": { "init_A_obsSegmentations_0": "__dummy__", - "init_A_obsSegmentations_1": "__dummy__", - "init_A_obsSegmentations_2": "__dummy__" + "init_A_obsSegmentations_1": "__dummy__" }, "spatialSegmentationFilled": { "init_A_obsSegmentations_0": false, - "init_A_obsSegmentations_1": true, - "init_A_obsSegmentations_2": false + "init_A_obsSegmentations_1": true }, "spatialSegmentationStrokeWidth": { - "init_A_obsSegmentations_0": 1.0, - "init_A_obsSegmentations_1": 3.0 + "init_A_obsSegmentations_0": 1.0 } }, "layout": [ diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py index bd75c44b..4c5c76a0 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/src/vitessce_config.py @@ -20,6 +20,7 @@ VitessceConfig, SpatialDataWrapper, CoordinationLevel as CL, + get_initial_coordination_scope_prefix, hconcat, vconcat, ) @@ -93,39 +94,72 @@ def create_config(): obs_sets.use_coordination(obs_color_encoding) # Each spatial view shows the tissue image and the pixels colored by one modality. - # TODO: do not use a for loop over modalities - for modality, spatial, layers, features, scatterplot, feature_type, feature_value_type, feature in [ - ("rna", rna_spatial, rna_layers, rna_features, rna_scatterplot, "gene", "expression", "Mbp"), - ("cut_and_tag", ct_spatial, ct_layers, ct_features, ct_scatterplot, "geneScore", "score", "Hoxa9"), - ]: - f_type, f_value_type, f_selection = vc.add_coordination( - "featureType", "featureValueType", "featureSelection", - ) - f_type.set_value(feature_type) - f_value_type.set_value(feature_value_type) - f_selection.set_value([feature]) - for view in [features, scatterplot]: - view.use_coordination(f_type, f_value_type, f_selection, obs_color_encoding) - vc.link_views_by_dict([spatial, layers], { - "imageLayer": CL([{ - "photometricInterpretation": "RGB", - "spatialLayerOpacity": image_opacity, + # RNA: features, coloring of the UMAP, and coloring of the pixels in the RNA spatial view. + rna_f_type, rna_f_value_type, rna_f_selection = vc.add_coordination( + "featureType", "featureValueType", "featureSelection", + ) + rna_f_type.set_value("gene") + rna_f_value_type.set_value("expression") + rna_f_selection.set_value(["Mbp"]) + for view in [rna_features, rna_scatterplot]: + view.use_coordination(rna_f_type, rna_f_value_type, rna_f_selection, obs_color_encoding) + + # H3K27me3 CUT&Tag: likewise, for the gene scores. + ct_f_type, ct_f_value_type, ct_f_selection = vc.add_coordination( + "featureType", "featureValueType", "featureSelection", + ) + ct_f_type.set_value("geneScore") + ct_f_value_type.set_value("score") + ct_f_selection.set_value(["Hoxa9"]) + for view in [ct_features, ct_scatterplot]: + view.use_coordination(ct_f_type, ct_f_value_type, ct_f_selection, obs_color_encoding) + + image_scope_prefix = get_initial_coordination_scope_prefix("A", "image") + segmentations_scope_prefix = get_initial_coordination_scope_prefix("A", "obsSegmentations") + + vc.link_views_by_dict([rna_spatial, rna_layers], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + "spatialLayerOpacity": image_opacity, + }]), + }, scope_prefix=image_scope_prefix) + vc.link_views_by_dict([rna_spatial, rna_layers], { + "segmentationLayer": CL([{ + "spatialLayerOpacity": segmentation_opacity, + "segmentationChannel": CL([{ + "obsType": "pixel", + "featureType": rna_f_type, + "featureValueType": rna_f_value_type, + "featureSelection": rna_f_selection, + "obsColorEncoding": obs_color_encoding, + "spatialChannelOpacity": 0.8, + "spatialSegmentationFilled": True, + "spatialChannelVisible": True, }]), - "segmentationLayer": CL([{ - "spatialLayerOpacity": segmentation_opacity, - "segmentationChannel": CL([{ - "obsType": "pixel", - "featureType": f_type, - "featureValueType": f_value_type, - "featureSelection": f_selection, - "obsColorEncoding": obs_color_encoding, - "spatialChannelOpacity": 0.8, - "spatialSegmentationFilled": True, - "spatialChannelVisible": True, - }]), + }]), + }, scope_prefix=segmentations_scope_prefix) + + vc.link_views_by_dict([ct_spatial, ct_layers], { + "imageLayer": CL([{ + "photometricInterpretation": "RGB", + "spatialLayerOpacity": image_opacity, + }]), + }, scope_prefix=image_scope_prefix) + vc.link_views_by_dict([ct_spatial, ct_layers], { + "segmentationLayer": CL([{ + "spatialLayerOpacity": segmentation_opacity, + "segmentationChannel": CL([{ + "obsType": "pixel", + "featureType": ct_f_type, + "featureValueType": ct_f_value_type, + "featureSelection": ct_f_selection, + "obsColorEncoding": obs_color_encoding, + "spatialChannelOpacity": 0.8, + "spatialSegmentationFilled": True, + "spatialChannelVisible": True, }]), - # TODO: use get_initial_coordination_scope_prefix here - }, scope_prefix=f"init_{modality}_") + }]), + }, scope_prefix=segmentations_scope_prefix) vc.layout(vconcat( hconcat( diff --git a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json index 44a49150..755e9255 100644 --- a/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json +++ b/demos/spatialdata-spatial-cut-and-tag-rna-mouse-brain/vitessce.template.json @@ -96,8 +96,8 @@ }, "obsType": { "A": "pixel", - "init_rna_0": "pixel", - "init_cut_and_tag_0": "pixel" + "init_A_obsSegmentations_0": "pixel", + "init_A_obsSegmentations_1": "pixel" }, "embeddingType": { "A": "UMAP (RNA)", @@ -127,144 +127,152 @@ ] }, "imageLayer": { - "init_rna_0": "__dummy__", - "init_cut_and_tag_0": "__dummy__" + "init_A_image_0": "__dummy__", + "init_A_image_1": "__dummy__" }, "photometricInterpretation": { - "init_rna_0": "RGB", - "init_cut_and_tag_0": "RGB" - }, - "segmentationLayer": { - "init_rna_0": "__dummy__", - "init_cut_and_tag_0": "__dummy__" - }, - "segmentationChannel": { - "init_rna_0": "__dummy__", - "init_cut_and_tag_0": "__dummy__" - }, - "spatialChannelOpacity": { - "init_rna_0": 0.8, - "init_cut_and_tag_0": 0.8 - }, - "spatialSegmentationFilled": { - "init_rna_0": true, - "init_cut_and_tag_0": true - }, - "spatialChannelVisible": { - "init_rna_0": true, - "init_cut_and_tag_0": true + "init_A_image_0": "RGB", + "init_A_image_1": "RGB" }, "metaCoordinationScopes": { - "init_rna_0": { + "init_A_image_0": { "imageLayer": [ - "init_rna_0" - ], + "init_A_image_0" + ] + }, + "init_A_obsSegmentations_0": { "segmentationLayer": [ - "init_rna_0" + "init_A_obsSegmentations_0" ] }, - "init_cut_and_tag_0": { + "init_A_image_1": { "imageLayer": [ - "init_cut_and_tag_0" - ], + "init_A_image_1" + ] + }, + "init_A_obsSegmentations_1": { "segmentationLayer": [ - "init_cut_and_tag_0" + "init_A_obsSegmentations_1" ] } }, "metaCoordinationScopesBy": { - "init_rna_0": { + "init_A_image_0": { "imageLayer": { "photometricInterpretation": { - "init_rna_0": "init_rna_0" + "init_A_image_0": "init_A_image_0" }, "spatialLayerOpacity": { - "init_rna_0": "A" + "init_A_image_0": "A" } - }, + } + }, + "init_A_obsSegmentations_0": { "segmentationLayer": { "spatialLayerOpacity": { - "init_rna_0": "B" + "init_A_obsSegmentations_0": "B" }, "segmentationChannel": { - "init_rna_0": [ - "init_rna_0" + "init_A_obsSegmentations_0": [ + "init_A_obsSegmentations_0" ] } }, "segmentationChannel": { "obsType": { - "init_rna_0": "init_rna_0" + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" }, "featureType": { - "init_rna_0": "A" + "init_A_obsSegmentations_0": "A" }, "featureValueType": { - "init_rna_0": "A" + "init_A_obsSegmentations_0": "A" }, "featureSelection": { - "init_rna_0": "A" + "init_A_obsSegmentations_0": "A" }, "obsColorEncoding": { - "init_rna_0": "A" + "init_A_obsSegmentations_0": "A" }, "spatialChannelOpacity": { - "init_rna_0": "init_rna_0" + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" }, "spatialSegmentationFilled": { - "init_rna_0": "init_rna_0" + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" }, "spatialChannelVisible": { - "init_rna_0": "init_rna_0" + "init_A_obsSegmentations_0": "init_A_obsSegmentations_0" } } }, - "init_cut_and_tag_0": { + "init_A_image_1": { "imageLayer": { "photometricInterpretation": { - "init_cut_and_tag_0": "init_cut_and_tag_0" + "init_A_image_1": "init_A_image_1" }, "spatialLayerOpacity": { - "init_cut_and_tag_0": "A" + "init_A_image_1": "A" } - }, + } + }, + "init_A_obsSegmentations_1": { "segmentationLayer": { "spatialLayerOpacity": { - "init_cut_and_tag_0": "B" + "init_A_obsSegmentations_1": "B" }, "segmentationChannel": { - "init_cut_and_tag_0": [ - "init_cut_and_tag_0" + "init_A_obsSegmentations_1": [ + "init_A_obsSegmentations_1" ] } }, "segmentationChannel": { "obsType": { - "init_cut_and_tag_0": "init_cut_and_tag_0" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "featureType": { - "init_cut_and_tag_0": "B" + "init_A_obsSegmentations_1": "B" }, "featureValueType": { - "init_cut_and_tag_0": "B" + "init_A_obsSegmentations_1": "B" }, "featureSelection": { - "init_cut_and_tag_0": "B" + "init_A_obsSegmentations_1": "B" }, "obsColorEncoding": { - "init_cut_and_tag_0": "A" + "init_A_obsSegmentations_1": "A" }, "spatialChannelOpacity": { - "init_cut_and_tag_0": "init_cut_and_tag_0" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "spatialSegmentationFilled": { - "init_cut_and_tag_0": "init_cut_and_tag_0" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" }, "spatialChannelVisible": { - "init_cut_and_tag_0": "init_cut_and_tag_0" + "init_A_obsSegmentations_1": "init_A_obsSegmentations_1" } } } + }, + "segmentationLayer": { + "init_A_obsSegmentations_0": "__dummy__", + "init_A_obsSegmentations_1": "__dummy__" + }, + "segmentationChannel": { + "init_A_obsSegmentations_0": "__dummy__", + "init_A_obsSegmentations_1": "__dummy__" + }, + "spatialChannelOpacity": { + "init_A_obsSegmentations_0": 0.8, + "init_A_obsSegmentations_1": 0.8 + }, + "spatialSegmentationFilled": { + "init_A_obsSegmentations_0": true, + "init_A_obsSegmentations_1": true + }, + "spatialChannelVisible": { + "init_A_obsSegmentations_0": true, + "init_A_obsSegmentations_1": true } }, "layout": [ @@ -277,10 +285,12 @@ "spatialTargetY": "A", "obsType": "A", "metaCoordinationScopes": [ - "init_rna_0" + "init_A_image_0", + "init_A_obsSegmentations_0" ], "metaCoordinationScopesBy": [ - "init_rna_0" + "init_A_image_0", + "init_A_obsSegmentations_0" ] }, "x": 0, @@ -297,10 +307,12 @@ "dataset": "A", "obsType": "A", "metaCoordinationScopes": [ - "init_rna_0" + "init_A_image_0", + "init_A_obsSegmentations_0" ], "metaCoordinationScopesBy": [ - "init_rna_0" + "init_A_image_0", + "init_A_obsSegmentations_0" ] }, "x": 3, @@ -338,10 +350,12 @@ "spatialTargetY": "A", "obsType": "A", "metaCoordinationScopes": [ - "init_cut_and_tag_0" + "init_A_image_1", + "init_A_obsSegmentations_1" ], "metaCoordinationScopesBy": [ - "init_cut_and_tag_0" + "init_A_image_1", + "init_A_obsSegmentations_1" ] }, "x": 6, @@ -358,10 +372,12 @@ "dataset": "A", "obsType": "A", "metaCoordinationScopes": [ - "init_cut_and_tag_0" + "init_A_image_1", + "init_A_obsSegmentations_1" ], "metaCoordinationScopesBy": [ - "init_cut_and_tag_0" + "init_A_image_1", + "init_A_obsSegmentations_1" ] }, "x": 9, diff --git a/demos/spatialdata-visium/Snakefile b/demos/spatialdata-visium/Snakefile index 78cb662d..a2cdc27c 100644 --- a/demos/spatialdata-visium/Snakefile +++ b/demos/spatialdata-visium/Snakefile @@ -15,13 +15,29 @@ rule all: [ (PROCESSED_DIR / f) for f in OUTPUTS ], "vitessce.template.json" -# No processing is needed beyond unzipping: the spots are Shapes (circles) annotated by the table. +# The spots are Shapes (circles) annotated by the table. +# Compute the highly variable genes and store their log-normalized expression in obsm/X_hvg, +# which the heatmap view loads instead of the full spot-by-gene matrix. +rule compute_hvg: + input: + (RAW_DIR / "visium.spatialdata.zarr") + output: + directory(PROCESSED_DIR / "visium.spatialdata.zarr") + params: + script=(SRC_DIR / "compute_hvg.py") + shell: + ''' + uv run --script {params.script} \ + -i {input} \ + -o {output} + ''' + # The zip file contains a single top-level data.zarr directory. rule unzip_data: input: (RAW_DIR / "visium_spatialdata_0.7.1.zip") output: - directory(PROCESSED_DIR / "visium.spatialdata.zarr") + directory(RAW_DIR / "visium.spatialdata.zarr") shell: ''' rm -rf {output}.tmp diff --git a/demos/spatialdata-visium/src/compute_hvg.py b/demos/spatialdata-visium/src/compute_hvg.py new file mode 100644 index 00000000..b33d61af --- /dev/null +++ b/demos/spatialdata-visium/src/compute_hvg.py @@ -0,0 +1,59 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = [ +# "spatialdata==0.7.3", +# "anndata==0.12.19", # anndata 0.13 exposes X as layers[None], which spatialdata 0.7.3 TableModel.parse rejects. +# "scanpy", +# "scikit-misc", +# "numpy", +# "scipy", +# ] +# /// +"""Add a highly variable gene (HVG) expression matrix to the Visium SpatialData table. + +The sandbox table stores raw counts (CSR) for the spots of both sections. +This script writes a copy of the store in which the table has: +- X: raw counts, as CSC, so that Vitessce can load a single gene's values efficiently. +- var/highly_variable: the top N_TOP_GENES genes (Seurat v3 flavor, computed on the counts). +- obsm/X_hvg: dense, log-normalized expression of the highly variable genes, with columns + in the same order as the highly variable genes appear in var. Vitessce reads this + matrix with `featureFilterPath` pointing to var/highly_variable. +""" +import argparse + +import numpy as np +import scanpy as sc +from scipy import sparse +from spatialdata import read_zarr + +N_TOP_GENES = 500 + + +def process(input_path, output_path): + sdata = read_zarr(input_path) + table = sdata.tables["table"] + + sc.pp.highly_variable_genes(table, n_top_genes=N_TOP_GENES, flavor="seurat_v3") + + norm = table.copy() + sc.pp.normalize_total(norm, target_sum=1e4) + sc.pp.log1p(norm) + hvg_mask = table.var["highly_variable"].to_numpy() + X_hvg = norm[:, hvg_mask].X + table.obsm["X_hvg"] = np.asarray(X_hvg.todense() if sparse.issparse(X_hvg) else X_hvg, dtype=np.float32) + + table.X = sparse.csc_matrix(table.X, dtype=np.float32) + table.var = table.var[["highly_variable"]].copy() + table.uns.pop("hvg", None) + + sdata.write(output_path, overwrite=True) + print(sdata) + print(sdata.tables["table"]) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-i", "--input", type=str, required=True, help="Input SpatialData .zarr store") + parser.add_argument("-o", "--output", type=str, required=True, help="Output SpatialData .zarr store") + args = parser.parse_args() + process(args.input, args.output) diff --git a/demos/spatialdata-visium/src/vitessce_config.py b/demos/spatialdata-visium/src/vitessce_config.py index 2c353846..bce3a162 100644 --- a/demos/spatialdata-visium/src/vitessce_config.py +++ b/demos/spatialdata-visium/src/vitessce_config.py @@ -38,7 +38,9 @@ def create_config(): sdata_url=f"{BASE_URL}/visium.spatialdata.zarr", image_path="images/ST8059048_hires_image", table_path="tables/table", - obs_feature_matrix_path="tables/table/X", + # Log-normalized expression of the highly variable genes (computed by src/compute_hvg.py). + obs_feature_matrix_path="tables/table/obsm/X_hvg", + feature_filter_path="tables/table/var/highly_variable", obs_spots_path="shapes/ST8059048", # The table annotates the spots of two sections (ST8059048 and ST8059050). region="ST8059048", @@ -50,6 +52,7 @@ def create_config(): spatial = vc.add_view("spatialBeta", dataset=dataset) feature_list = vc.add_view("featureList", dataset=dataset) layer_controller = vc.add_view("layerControllerBeta", dataset=dataset) + heatmap = vc.add_view("heatmap", dataset=dataset).set_props(transpose=True) vc.link_views_by_dict([spatial, layer_controller], { "imageLayer": CL([{ @@ -61,14 +64,20 @@ def create_config(): "obsColorEncoding": "geneSelection", }]), }, scope_prefix=get_initial_coordination_scope_prefix("A", "obsSpots")) - vc.link_views([spatial, layer_controller, feature_list], ["obsType"], ["spot"]) + vc.link_views([spatial, layer_controller, feature_list, heatmap], ["obsType"], ["spot"]) + vc.link_views([spatial, layer_controller, feature_list, heatmap], ["featureType"], ["gene"]) - vc.layout(hconcat( - spatial, - vconcat( - feature_list, - layer_controller, + vc.layout(vconcat( + hconcat( + spatial, + vconcat( + feature_list, + layer_controller, + ), + split=[8, 4], ), + heatmap, + split=[7, 5], )) return vc diff --git a/demos/spatialdata-visium/vitessce.template.json b/demos/spatialdata-visium/vitessce.template.json index 4ef32963..eac1c11e 100644 --- a/demos/spatialdata-visium/vitessce.template.json +++ b/demos/spatialdata-visium/vitessce.template.json @@ -12,8 +12,9 @@ "url": "{{ base_url }}/visium.spatialdata.zarr", "options": { "obsFeatureMatrix": { - "path": "tables/table/X", - "region": "ST8059048" + "path": "tables/table/obsm/X_hvg", + "region": "ST8059048", + "featureFilterPath": "tables/table/var/highly_variable" }, "obsSpots": { "path": "shapes/ST8059048", @@ -79,6 +80,9 @@ }, "obsType": { "A": "spot" + }, + "featureType": { + "A": "gene" } }, "layout": [ @@ -94,23 +98,25 @@ "init_A_image_0", "init_A_obsSpots_0" ], - "obsType": "A" + "obsType": "A", + "featureType": "A" }, "x": 0, "y": 0, - "w": 6, - "h": 12 + "w": 8, + "h": 7 }, { "component": "featureList", "coordinationScopes": { "dataset": "A", - "obsType": "A" + "obsType": "A", + "featureType": "A" }, - "x": 6, + "x": 8, "y": 0, - "w": 6, - "h": 6 + "w": 4, + "h": 3 }, { "component": "layerControllerBeta", @@ -124,12 +130,28 @@ "init_A_image_0", "init_A_obsSpots_0" ], - "obsType": "A" + "obsType": "A", + "featureType": "A" }, - "x": 6, - "y": 6, - "w": 6, - "h": 6 + "x": 8, + "y": 3, + "w": 4, + "h": 3 + }, + { + "component": "heatmap", + "coordinationScopes": { + "dataset": "A", + "obsType": "A", + "featureType": "A" + }, + "x": 0, + "y": 7, + "w": 12, + "h": 5, + "props": { + "transpose": true + } } ], "initStrategy": "auto"