{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"nbsphinx": "hidden"
},
"source": [
"# Vitessce Widget Tutorial"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Visualization of a SpatialData object"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Import dependencies\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from os.path import join, isfile, isdir\n",
"from urllib.request import urlretrieve\n",
"import zipfile\n",
"import shutil\n",
"\n",
"from vitessce import (\n",
" VitessceConfig,\n",
" ViewType as vt,\n",
" CoordinationType as ct,\n",
" CoordinationLevel as CL,\n",
" SpatialDataWrapper,\n",
" get_initial_coordination_scope_prefix\n",
")\n",
"\n",
"from vitessce.data_utils import (\n",
" sdata_morton_sort_points,\n",
" sdata_points_process_columns,\n",
" sdata_points_write_bounding_box_attrs,\n",
" sdata_points_modify_row_group_size,\n",
" sdata_morton_query_rect,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"from spatialdata_io import xenium\n",
"import spatialdata as sd\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from spatialdata import read_zarr\n",
"\n",
"import anndata as ad\n",
"\n",
"ad.settings.zarr_write_format = 3\n",
"print(ad.settings.zarr_write_format)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ls"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Configure Vitessce\n",
"\n",
"Vitessce needs to know which pieces of data we are interested in visualizing, the visualization types we would like to use, and how we want to coordinate (or link) the views."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# out_zarr = \"../data/processed_data/vitessce/WTA_Preview_FFPE_Cervical_Cancer_outs.zarr\"\n",
"# out_zarr = \"../data/processed_data/vitessce/Xenium_Prime_Human_Lymph_Node_Reactive_FFPE_outs.zarr\"\n",
"# out_zarr = \"../data/processed_data/vitessce/Xenium_Prime_Ovarian_Cancer_FFPE_XRrun_outs.zarr\"\n",
"out_zarr = \"../data/processed_data/vitessce/Xenium_V1_humanLung_Cancer_FFPE_outs.zarr\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"vc = VitessceConfig(\n",
" schema_version=\"1.0.18\",\n",
" name='Xenium SpatialData Demo',\n",
")\n",
"\n",
"# Cell segmentations + gene expression\n",
"wrapper = SpatialDataWrapper(\n",
" sdata_path=out_zarr,\n",
" image_path=\"images/morphology_focus\",\n",
" table_path=\"tables/table\",\n",
" obs_feature_matrix_path=\"tables/table/X\",\n",
" obs_segmentations_path=\"shapes/cell_boundaries\",\n",
" # obs_set_paths=[\"tables/table/obs/leiden\"],\n",
" # obs_set_names=[\"Cluster\"],\n",
" coordinate_system=\"global\",\n",
" coordination_values={\n",
" \"obsType\": \"cell\",\n",
" }\n",
")\n",
"\n",
"# Transcripts\n",
"points_wrapper = SpatialDataWrapper(\n",
" sdata_path=out_zarr,\n",
" obs_points_path=\"points/transcripts_with_morton_codes\",\n",
" obs_feature_matrix_path=\"tables/dense_table/X\",\n",
" coordinate_system=\"global\",\n",
" coordination_values={\n",
" \"obsType\": \"point\",\n",
" \"featureType\": \"gene\",\n",
" }\n",
")\n",
"\n",
"dataset = vc.add_dataset(name='Xenium').add_object(wrapper).add_object(points_wrapper)\n",
"\n",
"spatial = vc.add_view(\"spatialBeta\", dataset=dataset)\n",
"feature_list = vc.add_view(\"featureList\", dataset=dataset)\n",
"layer_controller = vc.add_view(\"layerControllerBeta\", dataset=dataset)\n",
"obs_sets = vc.add_view(\"obsSets\", dataset=dataset)\n",
"\n",
"vc.link_views_by_dict([spatial, layer_controller], {\n",
" 'segmentationLayer': CL([{\n",
" 'segmentationChannel': CL([{\n",
" 'obsType': 'cell',\n",
" # 'obsColorEncoding': 'cellSetSelection', # <-- this makes it default to cluster colors\n",
" }]),\n",
" }]),\n",
"}, scope_prefix=get_initial_coordination_scope_prefix(\"A\", \"obsSegmentations\"))\n",
"\n",
"vc.link_views_by_dict([spatial, layer_controller], {\n",
" 'pointLayer': CL([{\n",
" 'obsType': 'point',\n",
" }]),\n",
"}, scope_prefix=get_initial_coordination_scope_prefix(\"A\", \"obsPoints\"))\n",
"\n",
"vc.link_views([spatial, layer_controller, feature_list, obs_sets], ['obsType'], [wrapper.obs_type_label])\n",
"\n",
"# vc.layout(spatial | (feature_list / layer_controller / obs_sets))\n",
"vc.layout(spatial)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Render the widget"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"vw = vc.widget()\n",
"vw"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.1"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {
"8fa17251e5d6449a84f5cbc270c6674d": {
"model_module": "anywidget",
"model_module_version": "2.0.0",
"model_name": "AnyModel",
"state": {
"_anywidget_id": "vitessce.widget.VitessceWidget",
"_config": {
"coordinationSpace": {
"additionalObsSets": {
"A": null
},
"dataset": {
"A": "A",
"init_A_image_0": "init_A_image_0",
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"featureAggregationStrategy": {
"A": null,
"B": null
},
"featureColor": {
"A": null
},
"featureFilter": {
"A": null
},
"featureFilterMode": {
"A": null
},
"featureHighlight": {
"A": null
},
"featureSelection": {
"A": null
},
"featureType": {
"A": "gene"
},
"featureValueColormap": {
"A": "plasma",
"init_A_obsSegmentations_0": "plasma"
},
"featureValueColormapRange": {
"A": [
0,
1
]
},
"featureValueType": {
"A": "expression"
},
"fileUid": {
"A": null,
"init_A_image_0": null,
"init_A_obsSegmentations_0": null
},
"imageChannel": {
"A": null,
"init_A_image_0": "__dummy__",
"init_A_image_1": "__dummy__",
"init_A_image_2": "__dummy__",
"init_A_image_3": "__dummy__"
},
"imageLayer": {
"A": null,
"init_A_image_0": "__dummy__"
},
"legendVisible": {
"A": true
},
"metaCoordinationScopes": {
"init_A_image_0": {
"imageLayer": [
"init_A_image_0"
],
"spatialImageLayer": "init_A_image_0",
"spatialTargetT": "init_A_image_0",
"spatialTargetZ": "init_A_image_0"
},
"init_A_obsPoints_0": {
"pointLayer": [
"init_A_obsPoints_0"
]
},
"init_A_obsSegmentations_0": {
"segmentationLayer": [
"init_A_obsSegmentations_0"
]
}
},
"metaCoordinationScopesBy": {
"init_A_image_0": {
"imageChannel": {
"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"
},
"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"
},
"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"
},
"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"
},
"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"
}
},
"imageLayer": {
"fileUid": {
"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"
]
},
"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"
},
"spatialTargetResolution": {
"init_A_image_0": "init_A_image_0"
},
"volumetricRenderingAlgorithm": {
"init_A_image_0": "init_A_image_0"
}
}
},
"init_A_obsPoints_0": {
"pointLayer": {
"obsType": {
"init_A_obsPoints_0": "init_A_obsPoints_0"
}
}
},
"init_A_obsSegmentations_0": {
"segmentationChannel": {
"featureValueColormap": {
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"obsColorEncoding": {
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"obsHighlight": {
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"obsType": {
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"spatialChannelColor": {
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"spatialChannelOpacity": {
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"spatialChannelVisible": {
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"spatialChannelWindow": {
"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": {
"fileUid": {
"init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
},
"segmentationChannel": {
"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"
}
}
}
},
"moleculeHighlight": {
"A": null
},
"obsColorEncoding": {
"A": "cellSetSelection",
"init_A_obsSegmentations_0": "spatialChannelColor"
},
"obsFilter": {
"A": null
},
"obsHighlight": {
"A": null,
"init_A_obsSegmentations_0": null
},
"obsLabelsType": {
"A": null
},
"obsSetColor": {
"A": null
},
"obsSetExpansion": {
"A": null
},
"obsSetFilter": {
"A": null
},
"obsSetHighlight": {
"A": null
},
"obsSetSelection": {
"A": null
},
"obsType": {
"A": "cell",
"init_A_obsPoints_0": "point",
"init_A_obsSegmentations_0": "cell"
},
"photometricInterpretation": {
"A": null,
"init_A_image_0": "BlackIsZero"
},
"pixelHighlight": {
"A": null
},
"pointLayer": {
"A": null,
"init_A_obsPoints_0": "__dummy__"
},
"segmentationChannel": {
"A": null,
"init_A_obsSegmentations_0": "__dummy__"
},
"segmentationLayer": {
"A": null,
"init_A_obsSegmentations_0": "__dummy__"
},
"spatialAxisFixed": {
"A": false
},
"spatialChannelColor": {
"A": [
255,
255,
255
],
"init_A_image_0": [
0,
0,
255
],
"init_A_image_1": [
0,
255,
0
],
"init_A_image_2": [
255,
0,
255
],
"init_A_image_3": [
255,
255,
0
],
"init_A_obsSegmentations_0": [
255,
255,
255
]
},
"spatialChannelLabelSize": {
"A": 14
},
"spatialChannelLabelsOrientation": {
"A": "vertical"
},
"spatialChannelLabelsVisible": {
"A": true
},
"spatialChannelOpacity": {
"A": 1,
"init_A_image_0": 1,
"init_A_image_1": 1,
"init_A_image_2": 1,
"init_A_image_3": 1,
"init_A_obsSegmentations_0": 1
},
"spatialChannelVisible": {
"A": true,
"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
},
"spatialChannelWindow": {
"A": null,
"init_A_image_0": [
0,
8339
],
"init_A_image_1": [
0,
8617
],
"init_A_image_2": [
0,
10931
],
"init_A_image_3": [
0,
10716
],
"init_A_obsSegmentations_0": null
},
"spatialImageLayer": {
"init_A_image_0": [
{
"channels": [
{
"color": [
255,
255,
255
],
"selection": {
"c": 0
},
"slider": [
0,
255
],
"visible": true
},
{
"color": [
255,
255,
255
],
"selection": {
"c": 1
},
"slider": [
0,
255
],
"visible": true
},
{
"color": [
255,
255,
255
],
"selection": {
"c": 2
},
"slider": [
0,
255
],
"visible": true
},
{
"color": [
255,
255,
255
],
"selection": {
"c": 3
},
"slider": [
0,
255
],
"visible": true
}
],
"colormap": null,
"domainType": "Min/Max",
"index": 0,
"modelMatrix": [
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
],
"opacity": 1,
"renderingMode": "Additive",
"transparentColor": null,
"type": "raster",
"use3d": false,
"visible": true
}
]
},
"spatialLayerColor": {
"A": null
},
"spatialLayerColormap": {
"A": null
},
"spatialLayerModelMatrix": {
"A": null
},
"spatialLayerOpacity": {
"A": 1,
"init_A_image_0": 1,
"init_A_obsSegmentations_0": 1
},
"spatialLayerTransparentColor": {
"A": null
},
"spatialLayerVisible": {
"A": true,
"init_A_image_0": true,
"init_A_obsSegmentations_0": true
},
"spatialMaxResolution": {
"A": null
},
"spatialNeighborhoodLayer": {
"A": null
},
"spatialOrbitAxis": {
"A": "Y",
"B": "Y"
},
"spatialPointLayer": {
"A": null
},
"spatialPointStrokeWidth": {
"A": 0
},
"spatialRenderingMode": {
"A": "2D"
},
"spatialRotation": {
"A": 0
},
"spatialRotationOrbit": {
"A": 0,
"B": 0
},
"spatialRotationX": {
"A": 0,
"B": 0
},
"spatialRotationY": {
"A": 0,
"B": 0
},
"spatialRotationZ": {
"A": 0,
"B": 0
},
"spatialSegmentationFilled": {
"A": true,
"init_A_obsSegmentations_0": true
},
"spatialSegmentationStrokeWidth": {
"A": 1,
"init_A_obsSegmentations_0": 1
},
"spatialSliceX": {
"A": null
},
"spatialSliceY": {
"A": null
},
"spatialSliceZ": {
"A": null
},
"spatialSpotFilled": {
"A": true
},
"spatialSpotRadius": {
"A": 25
},
"spatialSpotStrokeWidth": {
"A": 1
},
"spatialTargetC": {
"A": null,
"init_A_image_0": 0,
"init_A_image_1": 1,
"init_A_image_2": 2,
"init_A_image_3": 3
},
"spatialTargetResolution": {
"A": 0,
"init_A_image_0": null
},
"spatialTargetT": {
"A": null,
"init_A_image_0": 0
},
"spatialTargetX": {
"A": null,
"B": null
},
"spatialTargetY": {
"A": null,
"B": null
},
"spatialTargetZ": {
"A": null,
"B": null,
"init_A_image_0": null
},
"spatialZoom": {
"A": null,
"B": null
},
"spotLayer": {
"A": null
},
"tooltipCrosshairsVisible": {
"A": true
},
"tooltipsVisible": {
"A": true
},
"volumetricRenderingAlgorithm": {
"A": "additive",
"init_A_image_0": "maximumIntensityProjection"
}
},
"datasets": [
{
"files": [
{
"coordinationValues": {
"featureType": "gene",
"featureValueType": "expression",
"obsType": "cell"
},
"fileType": "obsFeatureMatrix.spatialdata.zarr",
"options": {
"path": "tables/table/X"
},
"url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
},
{
"coordinationValues": {
"featureType": "gene"
},
"fileType": "image.spatialdata.zarr",
"options": {
"coordinateSystem": "global",
"path": "images/morphology_focus"
},
"url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
},
{
"coordinationValues": {
"obsType": "cell"
},
"fileType": "shapes.spatialdata.zarr",
"options": {
"coordinateSystem": "global",
"path": "shapes/cell_boundaries",
"tablePath": "tables/table"
},
"url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
},
{
"coordinationValues": {
"featureType": "gene",
"featureValueType": "expression",
"obsType": "point"
},
"fileType": "obsFeatureMatrix.spatialdata.zarr",
"options": {
"path": "tables/dense_table/X"
},
"url": "http://localhost:8000/A/1/afd11240-c386-4fe7-8bfd-f77a5138e9bc.sdata.zarr"
},
{
"coordinationValues": {
"obsType": "point"
},
"fileType": "obsPoints.spatialdata.zarr",
"options": {
"coordinateSystem": "global",
"path": "points/transcripts_with_morton_codes",
"tablePath": "tables/table"
},
"url": "http://localhost:8000/A/1/afd11240-c386-4fe7-8bfd-f77a5138e9bc.sdata.zarr"
}
],
"name": "Xenium",
"uid": "A"
}
],
"description": "",
"initStrategy": "auto",
"layout": [
{
"component": "spatialBeta",
"coordinationScopes": {
"additionalObsSets": "A",
"dataset": "A",
"featureAggregationStrategy": "A",
"featureColor": "A",
"featureFilterMode": "A",
"featureHighlight": "A",
"featureSelection": "A",
"featureType": "A",
"featureValueColormap": "A",
"featureValueColormapRange": "A",
"featureValueType": "A",
"fileUid": "A",
"imageChannel": "A",
"imageLayer": "A",
"legendVisible": "A",
"metaCoordinationScopes": [
"init_A_image_0",
"init_A_obsSegmentations_0",
"init_A_obsSegmentations_0",
"init_A_obsPoints_0"
],
"metaCoordinationScopesBy": [
"init_A_image_0",
"init_A_obsSegmentations_0",
"init_A_obsSegmentations_0",
"init_A_obsPoints_0"
],
"moleculeHighlight": "A",
"obsColorEncoding": "A",
"obsFilter": "A",
"obsHighlight": "A",
"obsLabelsType": "A",
"obsSetColor": "A",
"obsSetFilter": "A",
"obsSetHighlight": "A",
"obsSetSelection": "A",
"obsType": "A",
"photometricInterpretation": "A",
"pixelHighlight": "A",
"pointLayer": "A",
"segmentationChannel": "A",
"segmentationLayer": "A",
"spatialAxisFixed": "A",
"spatialChannelColor": "A",
"spatialChannelLabelSize": "A",
"spatialChannelLabelsOrientation": "A",
"spatialChannelLabelsVisible": "A",
"spatialChannelOpacity": "A",
"spatialChannelVisible": "A",
"spatialChannelWindow": "A",
"spatialLayerColor": "A",
"spatialLayerColormap": "A",
"spatialLayerModelMatrix": "A",
"spatialLayerOpacity": "A",
"spatialLayerTransparentColor": "A",
"spatialLayerVisible": "A",
"spatialMaxResolution": "A",
"spatialNeighborhoodLayer": "A",
"spatialOrbitAxis": "A",
"spatialPointLayer": "A",
"spatialRenderingMode": "A",
"spatialRotation": "A",
"spatialRotationOrbit": "A",
"spatialRotationX": "A",
"spatialRotationY": "A",
"spatialRotationZ": "A",
"spatialSegmentationFilled": "A",
"spatialSegmentationStrokeWidth": "A",
"spatialSliceX": "A",
"spatialSliceY": "A",
"spatialSliceZ": "A",
"spatialSpotFilled": "A",
"spatialSpotRadius": "A",
"spatialSpotStrokeWidth": "A",
"spatialTargetC": "A",
"spatialTargetResolution": "A",
"spatialTargetT": "A",
"spatialTargetX": "A",
"spatialTargetY": "A",
"spatialTargetZ": "A",
"spatialZoom": "A",
"spotLayer": "A",
"tooltipCrosshairsVisible": "A",
"tooltipsVisible": "A",
"volumetricRenderingAlgorithm": "A"
},
"h": 12,
"uid": "A",
"w": 12,
"x": 0,
"y": 0
},
{
"component": "featureList",
"coordinationScopes": {
"dataset": "A",
"featureFilter": "A",
"featureHighlight": "A",
"featureSelection": "A",
"featureType": "A",
"featureValueType": "A",
"obsColorEncoding": "A",
"obsSetSelection": "A",
"obsType": "A"
},
"h": 1,
"uid": "B",
"w": 1,
"x": 0,
"y": 0
},
{
"component": "layerControllerBeta",
"coordinationScopes": {
"dataset": "A",
"featureAggregationStrategy": "B",
"featureColor": "A",
"featureFilterMode": "A",
"featureSelection": "A",
"featureType": "A",
"featureValueColormap": "A",
"featureValueColormapRange": "A",
"featureValueType": "A",
"fileUid": "A",
"imageChannel": "A",
"imageLayer": "A",
"legendVisible": "A",
"metaCoordinationScopes": [
"init_A_image_0",
"init_A_obsSegmentations_0",
"init_A_obsSegmentations_0",
"init_A_obsPoints_0"
],
"metaCoordinationScopesBy": [
"init_A_image_0",
"init_A_obsSegmentations_0",
"init_A_obsSegmentations_0",
"init_A_obsPoints_0"
],
"obsColorEncoding": "A",
"obsType": "A",
"photometricInterpretation": "A",
"pointLayer": "A",
"segmentationChannel": "A",
"segmentationLayer": "A",
"spatialChannelColor": "A",
"spatialChannelLabelSize": "A",
"spatialChannelLabelsOrientation": "A",
"spatialChannelLabelsVisible": "A",
"spatialChannelOpacity": "A",
"spatialChannelVisible": "A",
"spatialChannelWindow": "A",
"spatialLayerColor": "A",
"spatialLayerColormap": "A",
"spatialLayerModelMatrix": "A",
"spatialLayerOpacity": "A",
"spatialLayerTransparentColor": "A",
"spatialLayerVisible": "A",
"spatialMaxResolution": "A",
"spatialNeighborhoodLayer": "A",
"spatialOrbitAxis": "B",
"spatialPointLayer": "A",
"spatialPointStrokeWidth": "A",
"spatialRenderingMode": "A",
"spatialRotationOrbit": "B",
"spatialRotationX": "B",
"spatialRotationY": "B",
"spatialRotationZ": "B",
"spatialSegmentationFilled": "A",
"spatialSegmentationStrokeWidth": "A",
"spatialSliceX": "A",
"spatialSliceY": "A",
"spatialSliceZ": "A",
"spatialSpotFilled": "A",
"spatialSpotRadius": "A",
"spatialSpotStrokeWidth": "A",
"spatialTargetC": "A",
"spatialTargetResolution": "A",
"spatialTargetT": "A",
"spatialTargetX": "B",
"spatialTargetY": "B",
"spatialTargetZ": "B",
"spatialZoom": "B",
"spotLayer": "A",
"tooltipCrosshairsVisible": "A",
"tooltipsVisible": "A",
"volumetricRenderingAlgorithm": "A"
},
"h": 1,
"uid": "C",
"w": 1,
"x": 0,
"y": 0
},
{
"component": "obsSets",
"coordinationScopes": {
"additionalObsSets": "A",
"dataset": "A",
"featureSelection": "A",
"obsColorEncoding": "A",
"obsSetColor": "A",
"obsSetExpansion": "A",
"obsSetFilter": "A",
"obsSetHighlight": "A",
"obsSetSelection": "A",
"obsType": "A"
},
"h": 1,
"uid": "D",
"w": 1,
"x": 0,
"y": 0
}
],
"name": "Xenium SpatialData Demo",
"uid": "A",
"version": "1.0.18"
},
"_esm": "\nlet importWithMap;\ntry {\n importWithMap = (await import('https://unpkg.com/dynamic-importmap@0.1.0')).importWithMap;\n} catch(e) {\n console.warn(\"Import of dynamic-importmap failed, trying fallback.\");\n importWithMap = (await import('https://cdn.vitessce.io/dynamic-importmap@0.1.0/dist/index.js')).importWithMap;\n}\n\nconst successfulImportMap = {\n imports: {\n\n },\n};\nconst importMap = {\n imports: {\n \"react\": \"https://esm.sh/react@18.2.0?dev\",\n \"react-dom\": \"https://esm.sh/react-dom@18.2.0?dev\",\n \"react-dom/client\": \"https://esm.sh/react-dom@18.2.0/client?dev\",\n },\n};\nconst fallbackImportMap = {\n imports: {\n \"react\": \"https://cdn.vitessce.io/react@18.2.0/index.js\",\n \"react-dom\": \"https://cdn.vitessce.io/react-dom@18.2.0/index.js\",\n \"react-dom/client\": \"https://cdn.vitessce.io/react-dom@18.2.0/es2022/client.mjs\",\n // Replaced with version-specific URL below.\n \"vitessce\": \"https://cdn.vitessce.io/vitessce@VERSION/dist/index.min.js\",\n },\n};\n/*\nconst fallbackDevImportMap = {\n imports: {\n \"react\": \"https://cdn.vitessce.io/react@18.2.0/index_dev.js\",\n \"react-dom\": \"https://cdn.vitessce.io/react-dom@18.2.0/index_dev.js\",\n \"react-dom/client\": \"https://cdn.vitessce.io/react-dom@18.2.0/es2022/client.development.mjs\",\n // Replaced with version-specific URL below.\n \"vitessce\": \"https://cdn.vitessce.io/@vitessce/dev@VERSION/dist/index.js\",\n },\n};\n*/\n\nasync function importWithMapAndFallback(moduleName, importMap, fallbackMap) {\n let result = null;\n if (!fallbackMap) {\n // fallbackMap is null, user may have provided custom JS URL.\n result = await importWithMap(moduleName, {\n imports: {\n ...importMap.imports,\n ...successfulImportMap.imports,\n },\n });\n successfulImportMap.imports[moduleName] = importMap.imports[moduleName];\n } else {\n try {\n result = await importWithMap(moduleName, {\n imports: {\n ...importMap.imports,\n ...successfulImportMap.imports,\n },\n });\n successfulImportMap.imports[moduleName] = importMap.imports[moduleName];\n } catch (e) {\n console.warn(`Importing ${moduleName} failed with importMap`, importMap, \"trying fallback\", fallbackMap, successfulImportMap);\n result = await importWithMap(moduleName, {\n imports: {\n ...fallbackMap.imports,\n ...successfulImportMap.imports,\n },\n });\n successfulImportMap.imports[moduleName] = fallbackMap.imports[moduleName];\n }\n }\n return result;\n}\n\n\nconst React = await importWithMapAndFallback(\"react\", importMap, fallbackImportMap);\nconst { createRoot } = await importWithMapAndFallback(\"react-dom/client\", importMap, fallbackImportMap);\n\nconst e = React.createElement;\n\nfunction isAbsoluteUrl(s) {\n return s?.startsWith('http://') || s?.startsWith('https://');\n}\nconst WORKSPACES_URL_KEYWORD = 'https://workspaces-pt';\nconst OPTIONS_URL_KEYS = ['offsetsUrl', 'refSpecUrl'];\nconst prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;\n// The jupyter server may be running through a proxy,\n// which means that the client needs to prepend the part of the URL before /proxy/8000 such as\n// https://hub.gke2.mybinder.org/user/vitessce-vitessce-python-swi31vcv/proxy/8000/A/0/cells\n// For workspaces: https://workspaces-pt.hubmapconsortium.org/passthrough/HOSTNAME/PORT/ADDITIONAL_PATH_INFO?QUERY_PARAMS=HELLO_WORLD\nfunction prependBaseUrl(config, proxy, hasHostName) {\n if (!proxy || hasHostName) {\n return config;\n }\n const { origin, pathname } = new URL(window.location.href);\n const isInWorkspaces = origin.startsWith(WORKSPACES_URL_KEYWORD);\n const jupyterLabConfigEl = document.getElementById('jupyter-config-data');\n\n let baseUrl;\n if (isInWorkspaces) {\n const pathSegments = pathname.split('/');\n const passthroughIndex = pathSegments.indexOf('passthrough');\n if (passthroughIndex !== -1) {\n baseUrl = pathSegments.slice(0, passthroughIndex + 3).join('/');\n baseUrl += '/';\n }\n } else if (jupyterLabConfigEl) {\n // This is jupyter lab\n baseUrl = JSON.parse(jupyterLabConfigEl.textContent || '').baseUrl;\n } else {\n // This is jupyter notebook\n baseUrl = document.getElementsByTagName('body')[0].getAttribute('data-base-url');\n }\n return {\n ...config,\n datasets: config.datasets.map(d => ({\n ...d,\n files: d.files.map(f => {\n const updatedFileDef = { ...f };\n if (f.url && !isAbsoluteUrl(f.url) ) {\n // Update the main file URL if necessary.\n updatedFileDef.url = `${origin}${baseUrl}${f.url}`;\n }\n if (f.options) {\n // Update any urls within the options object\n const updatedOptions = { ...f.options };\n OPTIONS_URL_KEYS.forEach(key => {\n const optionValue = updatedOptions[key];\n if (optionValue && !isAbsoluteUrl(optionValue)) {\n updatedOptions[key] = `${origin}${baseUrl}${optionValue}`;\n }\n });\n\n // Update image URLs if they exist\n if ('images' in f.options && Array.isArray(f.options.images)) {\n const updatedImages = f.options.images.map(image => {\n const updatedImage = { ...image };\n\n if (image.url && !isAbsoluteUrl(image.url)) {\n updatedImage.url = `${origin}${baseUrl}${image.url}`;\n }\n\n const metadata = { ...image.metadata };\n if (metadata?.omeTiffOffsetsUrl && !isAbsoluteUrl(metadata.omeTiffOffsetsUrl)) {\n metadata.omeTiffOffsetsUrl = `${origin}${baseUrl}${metadata.omeTiffOffsetsUrl}`;\n }\n\n updatedImage.metadata = metadata;\n\n return updatedImage;\n });\n\n updatedOptions.images = updatedImages;\n }\n updatedFileDef.options = updatedOptions;\n }\n return updatedFileDef;\n }),\n })),\n };\n}\n\nasync function render(view) {\n const cssUid = view.model.get('uid');\n const jsDevMode = view.model.get('js_dev_mode');\n const jsPackageVersion = view.model.get('js_package_version');\n const customJsUrl = view.model.get('custom_js_url');\n const pluginEsmArr = view.model.get('plugin_esm');\n const remountOnUidChange = view.model.get('remount_on_uid_change');\n const storeUrls = view.model.get('store_urls');\n const invokeTimeout = view.model.get('invoke_timeout');\n const invokeBatched = view.model.get('invoke_batched');\n const preventScroll = view.model.get('prevent_scroll');\n\n const pageMode = view.model.get('page_mode');\n const pageEsm = view.model.get('page_esm');\n\n const pkgName = (jsDevMode ? \"@vitessce/dev\" : \"vitessce\");\n\n const hasCustomJsUrl = customJsUrl.length > 0;\n\n importMap.imports[\"vitessce\"] = (hasCustomJsUrl\n ? customJsUrl\n : `https://unpkg.com/${pkgName}@${jsPackageVersion}`\n );\n let fallbackImportMapToUse = null;\n if (!hasCustomJsUrl) {\n fallbackImportMapToUse = fallbackImportMap;\n if (jsDevMode) {\n fallbackImportMapToUse.imports[\"vitessce\"] = `https://cdn.vitessce.io/vitessce@${jsPackageVersion}/dist/index.min.js`;\n } else {\n fallbackImportMapToUse.imports[\"vitessce\"] = `https://cdn.vitessce.io/@vitessce/dev@${jsPackageVersion}/dist/index.js`;\n }\n }\n\n const {\n Vitessce,\n PluginFileType,\n PluginViewType,\n PluginCoordinationType,\n PluginJointFileType,\n PluginAsyncFunction,\n z,\n useCoordination,\n usePageModeView,\n useGridItemSize,\n // TODO: names and function signatures are subject to change for the following functions\n // Reference: https://github.com/keller-mark/use-coordination/issues/37#issuecomment-1946226827\n useComplexCoordination,\n useMultiCoordinationScopesNonNull,\n useMultiCoordinationScopesSecondaryNonNull,\n useComplexCoordinationSecondary,\n useCoordinationScopes,\n useCoordinationScopesBy,\n } = await importWithMapAndFallback(\"vitessce\", importMap, fallbackImportMapToUse);\n\n let pluginViewTypes = [];\n let pluginCoordinationTypes = [];\n let pluginFileTypes = [];\n let pluginJointFileTypes = [];\n let pluginAsyncFunctions = [];\n\n let pending = [];\n let batchId = 0;\n\n async function processBatch(prevPendingArr) {\n const [dataArr, buffersArr] = await view.experimental.invoke(\"_zarr_get_multi\", prevPendingArr.map(d => d.params), {\n signal: AbortSignal.timeout(invokeTimeout),\n });\n prevPendingArr.forEach((prevPendingItem, i) => {\n const data = dataArr[i];\n const bufferData = buffersArr[i];\n const { params, resolve, reject } = prevPendingItem;\n const [storeUrl, key] = params;\n\n if (!data.success) {\n resolve(undefined);\n return;\n }\n\n if (ArrayBuffer.isView(bufferData)) {\n resolve(new Uint8Array(bufferData.buffer, bufferData.byteOffset, bufferData.byteLength));\n return;\n }\n resolve(new Uint8Array(bufferData.buffer));\n return;\n });\n }\n\n function run() {\n processBatch(pending);\n pending = [];\n batchId = 0;\n }\n\n function enqueue(params) {\n batchId = batchId || requestAnimationFrame(() => run());\n let { promise, resolve, reject } = Promise.withResolvers();\n pending.push({ params, resolve, reject });\n return promise;\n }\n\n\n const stores = Object.fromEntries(\n storeUrls.map(storeUrl => ([\n storeUrl,\n {\n async get(key) {\n if (invokeBatched) {\n return enqueue([storeUrl, key]);\n } else {\n // Do not submit zarr gets in batches. Instead, submit individually.\n const [data, buffers] = await view.experimental.invoke(\"_zarr_get\", [storeUrl, key], {\n signal: AbortSignal.timeout(invokeTimeout),\n });\n if (!data.success) return undefined;\n\n if (ArrayBuffer.isView(buffers[0])) {\n return new Uint8Array(buffers[0].buffer, buffers[0].byteOffset, buffers[0].byteLength);\n }\n return new Uint8Array(buffers[0].buffer);\n }\n },\n async getRange(key, rangeQuery) {\n if (invokeBatched) {\n return enqueue([storeUrl, key, rangeQuery]);\n } else {\n // Do not submit zarr gets in batches. Instead, submit individually.\n const [data, buffers] = await view.experimental.invoke(\"_zarr_get_range\", [storeUrl, key, rangeQuery], {\n signal: AbortSignal.timeout(invokeTimeout),\n });\n if (!data.success) return undefined;\n\n if (ArrayBuffer.isView(buffers[0])) {\n return new Uint8Array(buffers[0].buffer, buffers[0].byteOffset, buffers[0].byteLength);\n }\n return new Uint8Array(buffers[0].buffer);\n }\n },\n }\n ])),\n );\n\n function invokePluginCommand(commandName, commandParams, commandBuffers) {\n return view.experimental.invoke(\"_plugin_command\", [commandName, commandParams], {\n signal: AbortSignal.timeout(invokeTimeout),\n ...(commandBuffers ? { buffers: commandBuffers } : {}),\n });\n }\n\n for (const pluginEsm of pluginEsmArr) {\n try {\n const pluginEsmUrl = URL.createObjectURL(new Blob([pluginEsm], { type: \"text/javascript\" }));\n const pluginModule = (await import(pluginEsmUrl)).default;\n URL.revokeObjectURL(pluginEsmUrl);\n\n const pluginDeps = {\n React,\n PluginFileType,\n PluginViewType,\n PluginCoordinationType,\n PluginJointFileType,\n PluginAsyncFunction,\n z,\n invokeCommand: invokePluginCommand,\n useCoordination,\n useGridItemSize,\n useComplexCoordination,\n useMultiCoordinationScopesNonNull,\n useMultiCoordinationScopesSecondaryNonNull,\n useComplexCoordinationSecondary,\n useCoordinationScopes,\n useCoordinationScopesBy,\n };\n const pluginsObj = await pluginModule.createPlugins(pluginDeps);\n if(Array.isArray(pluginsObj.pluginViewTypes)) {\n pluginViewTypes = [...pluginViewTypes, ...pluginsObj.pluginViewTypes];\n }\n if(Array.isArray(pluginsObj.pluginCoordinationTypes)) {\n pluginCoordinationTypes = [...pluginCoordinationTypes, ...pluginsObj.pluginCoordinationTypes];\n }\n if(Array.isArray(pluginsObj.pluginFileTypes)) {\n pluginFileTypes = [...pluginFileTypes, ...pluginsObj.pluginFileTypes];\n }\n if(Array.isArray(pluginsObj.pluginJointFileTypes)) {\n pluginJointFileTypes = [...pluginJointFileTypes, ...pluginsObj.pluginJointFileTypes];\n }\n if(Array.isArray(pluginsObj.pluginAsyncFunctions)) {\n pluginAsyncFunctions = [...pluginAsyncFunctions, ...pluginsObj.pluginAsyncFunctions];\n }\n } catch(e) {\n console.error(\"Error loading plugin ESM or executing createPlugins function.\");\n console.error(e);\n }\n }\n\n let PageComponent;\n if(pageMode && pageEsm.length > 0) {\n try {\n const pageEsmUrl = URL.createObjectURL(new Blob([pageEsm], { type: \"text/javascript\" }));\n const pageModule = (await import(pageEsmUrl)).default;\n URL.revokeObjectURL(pageEsmUrl);\n\n const pageDeps = {\n React,\n usePageModeView,\n };\n PageComponent = await pageModule.createPage(pageDeps);\n } catch(e) {\n console.error(\"Error loading page ESM or executing createPage function.\")\n console.error(e);\n }\n }\n\n function VitessceWidget(props) {\n const { model, styleContainer } = props;\n\n const [config, setConfig] = React.useState(prependBaseUrl(model.get('_config'), model.get('proxy'), model.get('has_host_name')));\n const [validateConfig, setValidateConfig] = React.useState(true);\n const height = model.get('height');\n const theme = model.get('theme') === 'auto' ? (prefersDark ? 'dark' : 'light') : model.get('theme');\n\n const divRef = React.useRef();\n\n React.useEffect(() => {\n if(!divRef.current || !preventScroll) {\n return () => {};\n }\n\n function handleMouseEnter() {\n const jpn = divRef.current.closest('.jp-Notebook');\n if(jpn) {\n jpn.style.overflow = \"hidden\";\n }\n }\n function handleMouseLeave(event) {\n if(event.relatedTarget === null || (event.relatedTarget && event.relatedTarget.closest('.jp-Notebook')?.length)) return;\n const jpn = divRef.current.closest('.jp-Notebook');\n if(jpn) {\n jpn.style.overflow = \"auto\";\n }\n }\n divRef.current.addEventListener(\"mouseenter\", handleMouseEnter);\n divRef.current.addEventListener(\"mouseleave\", handleMouseLeave);\n\n return () => {\n if(divRef.current) {\n divRef.current.removeEventListener(\"mouseenter\", handleMouseEnter);\n divRef.current.removeEventListener(\"mouseleave\", handleMouseLeave);\n }\n };\n }, [divRef, preventScroll]);\n\n // Config changed on JS side (from within ),\n // send updated config to Python side.\n const onConfigChange = React.useCallback((config) => {\n model.set('_config', config);\n setValidateConfig(false);\n model.save_changes();\n }, [model]);\n\n // Config changed on Python side,\n // pass to component to it is updated on JS side.\n React.useEffect(() => {\n model.on('change:_config', () => {\n const newConfig = prependBaseUrl(model.get('_config'), model.get('proxy'), model.get('has_host_name'));\n\n // Force a re-render and re-validation by setting a new config.uid value.\n // TODO: make this conditional on a parameter from Python.\n //newConfig.uid = `random-${Math.random()}`;\n //console.log('newConfig', newConfig);\n setConfig(newConfig);\n });\n }, []);\n\n const vitessceProps = {\n height, theme, config, onConfigChange, validateConfig,\n pluginViewTypes, pluginCoordinationTypes,\n pluginFileTypes,pluginJointFileTypes, pluginAsyncFunctions,\n remountOnUidChange, stores, pageMode, styleContainer,\n };\n\n return e('div', { ref: divRef, style: { height: height + 'px' } },\n e(React.Suspense, { fallback: e('div', {}, 'Loading...') },\n e(React.StrictMode, {},\n e(Vitessce, vitessceProps,\n (pageMode ? e(PageComponent, {}) : null)\n ),\n ),\n ),\n );\n }\n\n const root = createRoot(view.el);\n // Marimo puts AnyWidgets in a Shadow Root, so we need to tell Emotion to\n // insert styles within the Shadow DOM.\n const rootNode = view.el.getRootNode();\n const styleContainer = rootNode === document ? undefined : rootNode;\n root.render(e(VitessceWidget, { model: view.model, styleContainer }));\n\n return () => {\n // Re-enable scrolling.\n const jpn = view.el.closest('.jp-Notebook');\n if(jpn) {\n jpn.style.overflow = \"auto\";\n }\n\n // Clean up React and DOM state.\n root.unmount();\n if(view._isFromDisplay) {\n view.el.remove();\n }\n };\n}\nexport default { render };\n",
"_model_module": "anywidget",
"_model_name": "AnyModel",
"_view_name": "ErrorWidgetView",
"custom_js_url": "",
"error": {},
"has_host_name": false,
"height": 600,
"invoke_batched": true,
"invoke_timeout": 300000,
"js_dev_mode": false,
"js_package_version": "3.9.9",
"layout": "IPY_MODEL_6adbd17d7ac6415890bb669e3aaf670f",
"msg": "Failed to load model class 'AnyModel' from module 'anywidget'",
"page_esm": "",
"page_mode": false,
"plugin_esm": [],
"prevent_scroll": true,
"proxy": false,
"remount_on_uid_change": true,
"store_urls": [],
"theme": "auto",
"uid": "e7a1"
}
},
"undefined": {
"model_module": "anywidget",
"model_module_version": "2.0.0",
"model_name": "AnyModel",
"state": {
"_view_name": "ErrorWidgetView",
"error": {},
"msg": "Failed to load model class 'AnyModel' from module 'anywidget'"
}
}
},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}