jaspreetishar commited on
Commit
ed8ebc1
·
verified ·
1 Parent(s): ff91b96

Upload folder using huggingface_hub

Browse files
notebooks/._bar_plots.ipynb ADDED
Binary file (4.1 kB). View file
 
notebooks/._celldega_viz.ipynb ADDED
Binary file (4.1 kB). View file
 
notebooks/._vitessce_pre-process.ipynb ADDED
Binary file (4.1 kB). View file
 
notebooks/.ipynb_checkpoints/._vitessce_pre-process-checkpoint.ipynb ADDED
Binary file (4.1 kB). View file
 
notebooks/.ipynb_checkpoints/bar_plots-checkpoint.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/.ipynb_checkpoints/celldega_pre-process-checkpoint.ipynb ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "8ce6b74e-54af-48ba-abf2-7ce2caa573bf",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Xenium Pre-process"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": null,
14
+ "id": "b81ab32e",
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "%load_ext autoreload\n",
19
+ "%autoreload 2\n",
20
+ "%env ANYWIDGET_HMR=1\n",
21
+ "\n",
22
+ "import celldega as dega"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "markdown",
27
+ "id": "b47f611d",
28
+ "metadata": {},
29
+ "source": [
30
+ "## Xenium pre processing"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "id": "52602e61-45e7-45a2-83a0-9a1b364d6619",
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": [
40
+ "sample = 'Xenium_V1_humanLung_Cancer_FFPE_outs'\n",
41
+ "data_dir = f'../data/instrument_data'\n",
42
+ "path_landscape_files=f'../data/processed_data/DegaFiles/{sample}'"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": null,
48
+ "id": "13350680",
49
+ "metadata": {},
50
+ "outputs": [],
51
+ "source": [
52
+ "tile_size=250\n",
53
+ "\n",
54
+ "dega.pre.main(\n",
55
+ " sample=sample,\n",
56
+ " data_root_dir=data_dir,\n",
57
+ " tile_size=tile_size,\n",
58
+ " path_landscape_files=path_landscape_files,\n",
59
+ " use_int_index=True,\n",
60
+ " image_tile_layer=\"all\"\n",
61
+ " )"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": null,
67
+ "id": "2fd7f196-c6cc-4321-8481-6249ed0b96a7",
68
+ "metadata": {},
69
+ "outputs": [],
70
+ "source": []
71
+ }
72
+ ],
73
+ "metadata": {
74
+ "kernelspec": {
75
+ "display_name": "Python 3 (ipykernel)",
76
+ "language": "python",
77
+ "name": "python3"
78
+ },
79
+ "language_info": {
80
+ "codemirror_mode": {
81
+ "name": "ipython",
82
+ "version": 3
83
+ },
84
+ "file_extension": ".py",
85
+ "mimetype": "text/x-python",
86
+ "name": "python",
87
+ "nbconvert_exporter": "python",
88
+ "pygments_lexer": "ipython3",
89
+ "version": "3.12.1"
90
+ },
91
+ "toc": {
92
+ "base_numbering": 1,
93
+ "nav_menu": {},
94
+ "number_sections": true,
95
+ "sideBar": true,
96
+ "skip_h1_title": false,
97
+ "title_cell": "Table of Contents",
98
+ "title_sidebar": "Contents",
99
+ "toc_cell": false,
100
+ "toc_position": {},
101
+ "toc_section_display": true,
102
+ "toc_window_display": false
103
+ },
104
+ "widgets": {
105
+ "application/vnd.jupyter.widget-state+json": {
106
+ "state": {},
107
+ "version_major": 2,
108
+ "version_minor": 0
109
+ }
110
+ }
111
+ },
112
+ "nbformat": 4,
113
+ "nbformat_minor": 5
114
+ }
notebooks/.ipynb_checkpoints/celldega_viz-checkpoint.ipynb ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "8ce6b74e-54af-48ba-abf2-7ce2caa573bf",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Xenium Viz"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": null,
14
+ "id": "56843452-1a1c-4ae7-95ad-0a7bd909bc90",
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "%load_ext autoreload\n",
19
+ "%autoreload 2\n",
20
+ "%env ANYWIDGET_HMR=1"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "cec165b0-bd8f-40d5-b130-22486970aca8",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "import celldega as dega"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "id": "b66e327c-8c1e-41b7-9fbc-48d3f5c06fe3",
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": [
40
+ "sample = \"WTA_Preview_FFPE_Cervical_Cancer_outs\"\n",
41
+ "path_dega_files = f\"../data/processed_data/DegaFiles/{sample}\"\n",
42
+ "\n",
43
+ "landscape_ist = dega.viz.Landscape(\n",
44
+ " technology=\"Xenium\",\n",
45
+ " base_url=f\"http://localhost:{dega.viz.get_local_server()}/{path_dega_files}\",\n",
46
+ ")\n",
47
+ "\n",
48
+ "landscape_ist"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "id": "c8cd7207-7604-49bb-9172-d92af31ad74b",
55
+ "metadata": {},
56
+ "outputs": [],
57
+ "source": []
58
+ }
59
+ ],
60
+ "metadata": {
61
+ "kernelspec": {
62
+ "display_name": "Python 3 (ipykernel)",
63
+ "language": "python",
64
+ "name": "python3"
65
+ },
66
+ "language_info": {
67
+ "codemirror_mode": {
68
+ "name": "ipython",
69
+ "version": 3
70
+ },
71
+ "file_extension": ".py",
72
+ "mimetype": "text/x-python",
73
+ "name": "python",
74
+ "nbconvert_exporter": "python",
75
+ "pygments_lexer": "ipython3",
76
+ "version": "3.12.1"
77
+ },
78
+ "toc": {
79
+ "base_numbering": 1,
80
+ "nav_menu": {},
81
+ "number_sections": true,
82
+ "sideBar": true,
83
+ "skip_h1_title": false,
84
+ "title_cell": "Table of Contents",
85
+ "title_sidebar": "Contents",
86
+ "toc_cell": false,
87
+ "toc_position": {},
88
+ "toc_section_display": true,
89
+ "toc_window_display": false
90
+ },
91
+ "widgets": {
92
+ "application/vnd.jupyter.widget-state+json": {
93
+ "state": {},
94
+ "version_major": 2,
95
+ "version_minor": 0
96
+ }
97
+ }
98
+ },
99
+ "nbformat": 4,
100
+ "nbformat_minor": 5
101
+ }
notebooks/.ipynb_checkpoints/tissuumaps_pre-process-checkpoint.ipynb ADDED
@@ -0,0 +1,1274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "07f7dbb1-63c6-40e4-b0d9-6ec104aa0adc",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# !pip install zarr\n",
11
+ "\n",
12
+ "import os\n",
13
+ "import json\n",
14
+ "from pathlib import Path\n",
15
+ "import glob\n",
16
+ "import numpy as np\n",
17
+ "import pandas as pd\n",
18
+ "import scanpy as sc\n",
19
+ "import pyvips\n",
20
+ "import zarr\n",
21
+ "import geopandas as gpd\n",
22
+ "from shapely.geometry import Polygon\n",
23
+ "from scipy.sparse import csc_matrix\n",
24
+ "\n",
25
+ "import tissuumaps.jupyter as tj\n",
26
+ "from tissuumaps import read_h5ad\n",
27
+ "\n",
28
+ "\n",
29
+ "# ----------------------------\n",
30
+ "# Paths\n",
31
+ "# ----------------------------\n",
32
+ "# sample = \"WTA_Preview_FFPE_Cervical_Cancer_outs\"\n",
33
+ "# sample = \"Xenium_Prime_Human_Lymph_Node_Reactive_FFPE_outs\"\n",
34
+ "# sample = \"Xenium_Prime_Ovarian_Cancer_FFPE_XRrun_outs\"\n",
35
+ "# sample = \"Xenium_V1_humanLung_Cancer_FFPE_outs\"\n",
36
+ "\n",
37
+ "xenium_dir = os.path.abspath(f\"../data/instrument_data/{sample}\")\n",
38
+ "basedir = os.path.abspath(f\"../data/processed_data/tissuumaps_h5ad/{sample}\")\n",
39
+ "os.makedirs(basedir, exist_ok=True)\n",
40
+ "\n",
41
+ "out_h5ad_name = f\"{sample}_tmap.h5ad\"\n",
42
+ "out_h5ad = os.path.join(basedir, out_h5ad_name)\n",
43
+ "\n",
44
+ "project_path = os.path.join(basedir, \"_project_h5ad.tmap\")"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": null,
50
+ "id": "aec44404-259a-4042-9230-5a244ec9df0e",
51
+ "metadata": {},
52
+ "outputs": [],
53
+ "source": [
54
+ "# ----------------------------\n",
55
+ "# Transform helpers\n",
56
+ "# ----------------------------\n",
57
+ "def write_xenium_transform(data_dir, path_landscape_files):\n",
58
+ " cells_zarr_path = Path(data_dir) / \"cells.zarr.zip\"\n",
59
+ " if not cells_zarr_path.exists():\n",
60
+ " raise FileNotFoundError(f\"Missing: {cells_zarr_path}\")\n",
61
+ "\n",
62
+ " store = zarr.ZipStore(str(cells_zarr_path), mode=\"r\")\n",
63
+ " root = zarr.group(store=store)\n",
64
+ "\n",
65
+ " transform = root[\"masks\"][\"homogeneous_transform\"][:]\n",
66
+ "\n",
67
+ " pd.DataFrame(transform[:3, :3]).to_csv(\n",
68
+ " Path(path_landscape_files) / \"micron_to_image_transform.csv\",\n",
69
+ " sep=\" \",\n",
70
+ " header=False,\n",
71
+ " index=False,\n",
72
+ " )\n",
73
+ "\n",
74
+ " return transform\n",
75
+ "\n",
76
+ "\n",
77
+ "def apply_homogeneous_transform_xy(x, y, transform):\n",
78
+ " transform = np.asarray(transform)[:3, :3]\n",
79
+ "\n",
80
+ " xy1 = np.vstack([\n",
81
+ " np.asarray(x, dtype=float),\n",
82
+ " np.asarray(y, dtype=float),\n",
83
+ " np.ones(len(x)),\n",
84
+ " ])\n",
85
+ "\n",
86
+ " out = transform @ xy1\n",
87
+ " return out[0] / out[2], out[1] / out[2]\n",
88
+ " \n",
89
+ "# ----------------------------\n",
90
+ "# 1. Transform\n",
91
+ "# ----------------------------\n",
92
+ "transform = write_xenium_transform(xenium_dir, basedir)"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "execution_count": null,
98
+ "id": "16f90ba5-914a-4a3d-b3bc-9960481cef1f",
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "# ----------------------------\n",
103
+ "# Polygon helper\n",
104
+ "# ----------------------------\n",
105
+ "def xenium_boundaries_to_geojson(\n",
106
+ " boundary_path,\n",
107
+ " out_geojson,\n",
108
+ " transform,\n",
109
+ " id_col=\"cell_id\",\n",
110
+ " max_polygons=None,\n",
111
+ "):\n",
112
+ " if not os.path.exists(boundary_path):\n",
113
+ " return None\n",
114
+ "\n",
115
+ " if boundary_path.endswith(\".parquet\"):\n",
116
+ " df = pd.read_parquet(boundary_path)\n",
117
+ " else:\n",
118
+ " df = pd.read_csv(boundary_path)\n",
119
+ "\n",
120
+ " x_col = \"vertex_x\" if \"vertex_x\" in df.columns else \"x\"\n",
121
+ " y_col = \"vertex_y\" if \"vertex_y\" in df.columns else \"y\"\n",
122
+ "\n",
123
+ " x_new, y_new = apply_homogeneous_transform_xy(\n",
124
+ " df[x_col].values,\n",
125
+ " df[y_col].values,\n",
126
+ " transform,\n",
127
+ " )\n",
128
+ "\n",
129
+ " df = df.copy()\n",
130
+ " df[\"x_img\"] = x_new\n",
131
+ " df[\"y_img\"] = y_new\n",
132
+ "\n",
133
+ " ids = []\n",
134
+ " geoms = []\n",
135
+ "\n",
136
+ " for i, (cid, sub) in enumerate(df.groupby(id_col, sort=False)):\n",
137
+ " if max_polygons is not None and i >= max_polygons:\n",
138
+ " break\n",
139
+ "\n",
140
+ " if len(sub) < 3:\n",
141
+ " continue\n",
142
+ "\n",
143
+ " coords = list(zip(sub[\"x_img\"].astype(float), sub[\"y_img\"].astype(float)))\n",
144
+ "\n",
145
+ " if coords[0] != coords[-1]:\n",
146
+ " coords.append(coords[0])\n",
147
+ "\n",
148
+ " poly = Polygon(coords)\n",
149
+ "\n",
150
+ " if poly.is_valid and not poly.is_empty:\n",
151
+ " ids.append(cid)\n",
152
+ " geoms.append(poly)\n",
153
+ "\n",
154
+ " gdf = gpd.GeoDataFrame({id_col: ids}, geometry=geoms, crs=None)\n",
155
+ " gdf.to_file(out_geojson, driver=\"GeoJSON\")\n",
156
+ "\n",
157
+ " return os.path.basename(out_geojson)"
158
+ ]
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "execution_count": null,
163
+ "id": "a97826c2-0864-4a35-a7d0-5a64c117a1e2",
164
+ "metadata": {},
165
+ "outputs": [],
166
+ "source": [
167
+ "def add_xenium_default_clustering(adata, xenium_dir):\n",
168
+ " import os\n",
169
+ " import glob\n",
170
+ " import pandas as pd\n",
171
+ "\n",
172
+ " candidates = sorted(glob.glob(\n",
173
+ " os.path.join(xenium_dir, \"analysis\", \"clustering\", \"**\", \"clusters.csv\"),\n",
174
+ " recursive=True,\n",
175
+ " ))\n",
176
+ "\n",
177
+ " if not candidates:\n",
178
+ " print(\"No clusters.csv found.\")\n",
179
+ " return adata\n",
180
+ "\n",
181
+ " preferred = None\n",
182
+ " for p in candidates:\n",
183
+ " if \"gene_expression_graphclust\" in p:\n",
184
+ " preferred = p\n",
185
+ " break\n",
186
+ "\n",
187
+ " if preferred is None:\n",
188
+ " preferred = candidates[0]\n",
189
+ "\n",
190
+ " print(\"Using clustering file:\", preferred)\n",
191
+ "\n",
192
+ " clusters = pd.read_csv(preferred)\n",
193
+ "\n",
194
+ " id_col = \"Barcode\" if \"Barcode\" in clusters.columns else clusters.columns[0]\n",
195
+ " cluster_col = \"Cluster\" if \"Cluster\" in clusters.columns else clusters.columns[1]\n",
196
+ "\n",
197
+ " clusters[id_col] = clusters[id_col].astype(str)\n",
198
+ " clusters[cluster_col] = clusters[cluster_col].astype(str)\n",
199
+ "\n",
200
+ " s = clusters.set_index(id_col)[cluster_col]\n",
201
+ "\n",
202
+ " # IMPORTANT: reindex allows cells missing from clustering file\n",
203
+ " adata.obs[\"xenium_default_cluster\"] = (\n",
204
+ " s.reindex(adata.obs_names)\n",
205
+ " .fillna(\"unclustered\")\n",
206
+ " .astype(str)\n",
207
+ " .astype(\"category\")\n",
208
+ " )\n",
209
+ "\n",
210
+ " print(adata.obs[\"xenium_default_cluster\"].value_counts())\n",
211
+ "\n",
212
+ " return adata\n",
213
+ "\n",
214
+ "\n",
215
+ "# ----------------------------\n",
216
+ "# 2. Build h5ad in image pixel space\n",
217
+ "# ----------------------------\n",
218
+ "adata = sc.read_10x_h5(os.path.join(xenium_dir, \"cell_feature_matrix.h5\"))\n",
219
+ "adata.var_names_make_unique()\n",
220
+ "\n",
221
+ "cells = pd.read_csv(os.path.join(xenium_dir, \"cells.csv.gz\"), index_col=0)\n",
222
+ "cells = cells.loc[adata.obs_names]\n",
223
+ "\n",
224
+ "x_img, y_img = apply_homogeneous_transform_xy(\n",
225
+ " cells[\"x_centroid\"].values,\n",
226
+ " cells[\"y_centroid\"].values,\n",
227
+ " transform,\n",
228
+ ")\n",
229
+ "\n",
230
+ "adata.obs[\"x\"] = x_img.astype(float)\n",
231
+ "adata.obs[\"y\"] = y_img.astype(float)\n",
232
+ "adata.obsm[\"spatial\"] = adata.obs[[\"x\", \"y\"]].to_numpy(dtype=\"float64\")\n",
233
+ "\n",
234
+ "adata.obs[\"x_centroid_um\"] = cells[\"x_centroid\"].astype(float).values\n",
235
+ "adata.obs[\"y_centroid_um\"] = cells[\"y_centroid\"].astype(float).values\n",
236
+ "\n",
237
+ "obs_cols = [\n",
238
+ " \"transcript_counts\",\n",
239
+ " \"control_probe_counts\",\n",
240
+ " \"genomic_control_counts\",\n",
241
+ " \"control_codeword_counts\",\n",
242
+ " \"unassigned_codeword_counts\",\n",
243
+ " \"deprecated_codeword_counts\",\n",
244
+ " \"total_counts\",\n",
245
+ " \"cell_area\",\n",
246
+ " \"nucleus_area\",\n",
247
+ " \"nucleus_count\",\n",
248
+ "]\n",
249
+ "\n",
250
+ "for col in obs_cols:\n",
251
+ " if col in cells.columns:\n",
252
+ " adata.obs[col] = cells[col].values\n",
253
+ "\n",
254
+ "for col in adata.obs.columns:\n",
255
+ " if pd.api.types.is_object_dtype(adata.obs[col]):\n",
256
+ " adata.obs[col] = adata.obs[col].astype(\"category\")\n",
257
+ "\n",
258
+ "adata = add_xenium_default_clustering(adata, xenium_dir)\n",
259
+ "\n",
260
+ "adata.X = csc_matrix(adata.X)\n",
261
+ "adata.uns.pop(\"tmap_obsgroups\", None)\n",
262
+ "adata.write_h5ad(out_h5ad)"
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "execution_count": null,
268
+ "id": "f50d1a11-11ae-40f2-a35a-d0cd24a69935",
269
+ "metadata": {},
270
+ "outputs": [],
271
+ "source": [
272
+ "# ----------------------------\n",
273
+ "# 3. Make image pyramid\n",
274
+ "# ----------------------------\n",
275
+ "def make_one_xenium_pyramid_tifffile_zarr(\n",
276
+ " xenium_dir,\n",
277
+ " basedir,\n",
278
+ " channel=\"morphology_focus_0000.ome.tif\",\n",
279
+ " plane=0,\n",
280
+ " low=0,\n",
281
+ " high=12000,\n",
282
+ " gamma=0.5,\n",
283
+ " out_name=None,\n",
284
+ " rows_per_chunk=512,\n",
285
+ "):\n",
286
+ " import os\n",
287
+ " import numpy as np\n",
288
+ " import tifffile\n",
289
+ " import zarr\n",
290
+ " import pyvips\n",
291
+ "\n",
292
+ " src = os.path.join(xenium_dir, \"morphology_focus\", channel)\n",
293
+ "\n",
294
+ " if out_name is None:\n",
295
+ " out_name = channel.replace(\".ome.tif\", f\"_plane{plane}_pyramid.tif\")\n",
296
+ "\n",
297
+ " tmp_name = out_name.replace(\".tif\", \"_uint8_tmp.tif\")\n",
298
+ " tmp_path = os.path.join(basedir, tmp_name)\n",
299
+ " out_path = os.path.join(basedir, out_name)\n",
300
+ "\n",
301
+ " for p in [tmp_path, out_path]:\n",
302
+ " if os.path.exists(p):\n",
303
+ " os.remove(p)\n",
304
+ "\n",
305
+ " with tifffile.TiffFile(src) as tf:\n",
306
+ " store = tf.aszarr(series=0, level=0)\n",
307
+ " z = zarr.open(store, mode=\"r\")\n",
308
+ "\n",
309
+ " print(\"zarr shape:\", z.shape, \"dtype:\", z.dtype)\n",
310
+ "\n",
311
+ " if len(z.shape) == 3:\n",
312
+ " arr2d = z[plane]\n",
313
+ " elif len(z.shape) == 2:\n",
314
+ " arr2d = z\n",
315
+ " else:\n",
316
+ " raise ValueError(f\"Unexpected image shape: {z.shape}\")\n",
317
+ "\n",
318
+ " height, width = arr2d.shape\n",
319
+ " print(\"using plane:\", plane, \"height:\", height, \"width:\", width)\n",
320
+ "\n",
321
+ " # Create one full-size uint8 temp TIFF, memory-mapped on disk\n",
322
+ " tmp_mm = tifffile.memmap(\n",
323
+ " tmp_path,\n",
324
+ " shape=(height, width),\n",
325
+ " dtype=\"uint8\",\n",
326
+ " photometric=\"minisblack\",\n",
327
+ " bigtiff=True,\n",
328
+ " )\n",
329
+ "\n",
330
+ " for y0 in range(0, height, rows_per_chunk):\n",
331
+ " y1 = min(y0 + rows_per_chunk, height)\n",
332
+ "\n",
333
+ " block = arr2d[y0:y1, :].astype(\"float32\")\n",
334
+ " block = (block - low) / (high - low)\n",
335
+ " block = np.clip(block, 0, 1)\n",
336
+ "\n",
337
+ " if gamma is not None:\n",
338
+ " block = block ** gamma\n",
339
+ "\n",
340
+ " tmp_mm[y0:y1, :] = (block * 255).astype(\"uint8\")\n",
341
+ "\n",
342
+ " tmp_mm.flush()\n",
343
+ " del tmp_mm\n",
344
+ " store.close()\n",
345
+ "\n",
346
+ " img = pyvips.Image.new_from_file(tmp_path, access=\"sequential\")\n",
347
+ "\n",
348
+ " img.tiffsave(\n",
349
+ " out_path,\n",
350
+ " tile=True,\n",
351
+ " pyramid=True,\n",
352
+ " compression=\"jpeg\",\n",
353
+ " Q=90,\n",
354
+ " tile_width=256,\n",
355
+ " tile_height=256,\n",
356
+ " bigtiff=True,\n",
357
+ " )\n",
358
+ "\n",
359
+ " os.remove(tmp_path)\n",
360
+ "\n",
361
+ " print(\"wrote:\", out_path)\n",
362
+ "\n",
363
+ " return {\n",
364
+ " \"name\": out_name,\n",
365
+ " \"tileSource\": out_name + \".dzi\",\n",
366
+ " \"x\": 0,\n",
367
+ " \"y\": 0,\n",
368
+ " \"scale\": 1,\n",
369
+ " \"rotation\": 0,\n",
370
+ " \"flip\": False,\n",
371
+ " }\n",
372
+ "\n",
373
+ "morph_files = sorted(glob.glob(os.path.join(xenium_dir, \"morphology_focus\", \"*.ome.tif\")))\n",
374
+ "morph_files"
375
+ ]
376
+ },
377
+ {
378
+ "cell_type": "code",
379
+ "execution_count": null,
380
+ "id": "4109411c-f39c-40d8-94f1-72be456f8c4d",
381
+ "metadata": {},
382
+ "outputs": [],
383
+ "source": [
384
+ "# # ----------------------------\n",
385
+ "# # 3. Make image pyramid\n",
386
+ "# # ----------------------------\n",
387
+ "# def make_one_xenium_pyramid_tifffile_zarr(\n",
388
+ "# xenium_dir,\n",
389
+ "# basedir,\n",
390
+ "# channel=\"morphology_focus_0000.ome.tif\",\n",
391
+ "# plane=0,\n",
392
+ "# low=0,\n",
393
+ "# high=12000,\n",
394
+ "# gamma=0.5,\n",
395
+ "# out_name=None,\n",
396
+ "# rows_per_chunk=512,\n",
397
+ "# ):\n",
398
+ "# import os\n",
399
+ "# import numpy as np\n",
400
+ "# import tifffile\n",
401
+ "# import zarr\n",
402
+ "# import pyvips\n",
403
+ "\n",
404
+ "# src = os.path.join(xenium_dir, channel)\n",
405
+ "\n",
406
+ "# if out_name is None:\n",
407
+ "# out_name = channel.replace(\".ome.tif\", f\"_plane{plane}_pyramid.tif\")\n",
408
+ "\n",
409
+ "# tmp_name = out_name.replace(\".tif\", \"_uint8_tmp.tif\")\n",
410
+ "# tmp_path = os.path.join(basedir, tmp_name)\n",
411
+ "# out_path = os.path.join(basedir, out_name)\n",
412
+ "\n",
413
+ "# for p in [tmp_path, out_path]:\n",
414
+ "# if os.path.exists(p):\n",
415
+ "# os.remove(p)\n",
416
+ "\n",
417
+ "# with tifffile.TiffFile(src) as tf:\n",
418
+ "# store = tf.aszarr(series=0, level=0)\n",
419
+ "# z = zarr.open(store, mode=\"r\")\n",
420
+ "\n",
421
+ "# print(\"zarr shape:\", z.shape, \"dtype:\", z.dtype)\n",
422
+ "\n",
423
+ "# if len(z.shape) == 3:\n",
424
+ "# arr2d = z[plane]\n",
425
+ "# elif len(z.shape) == 2:\n",
426
+ "# arr2d = z\n",
427
+ "# else:\n",
428
+ "# raise ValueError(f\"Unexpected image shape: {z.shape}\")\n",
429
+ "\n",
430
+ "# height, width = arr2d.shape\n",
431
+ "# print(\"using plane:\", plane, \"height:\", height, \"width:\", width)\n",
432
+ "\n",
433
+ "# # Create one full-size uint8 temp TIFF, memory-mapped on disk\n",
434
+ "# tmp_mm = tifffile.memmap(\n",
435
+ "# tmp_path,\n",
436
+ "# shape=(height, width),\n",
437
+ "# dtype=\"uint8\",\n",
438
+ "# photometric=\"minisblack\",\n",
439
+ "# bigtiff=True,\n",
440
+ "# )\n",
441
+ "\n",
442
+ "# for y0 in range(0, height, rows_per_chunk):\n",
443
+ "# y1 = min(y0 + rows_per_chunk, height)\n",
444
+ "\n",
445
+ "# block = arr2d[y0:y1, :].astype(\"float32\")\n",
446
+ "# block = (block - low) / (high - low)\n",
447
+ "# block = np.clip(block, 0, 1)\n",
448
+ "\n",
449
+ "# if gamma is not None:\n",
450
+ "# block = block ** gamma\n",
451
+ "\n",
452
+ "# tmp_mm[y0:y1, :] = (block * 255).astype(\"uint8\")\n",
453
+ "\n",
454
+ "# tmp_mm.flush()\n",
455
+ "# del tmp_mm\n",
456
+ "# store.close()\n",
457
+ "\n",
458
+ "# img = pyvips.Image.new_from_file(tmp_path, access=\"sequential\")\n",
459
+ "\n",
460
+ "# img.tiffsave(\n",
461
+ "# out_path,\n",
462
+ "# tile=True,\n",
463
+ "# pyramid=True,\n",
464
+ "# compression=\"jpeg\",\n",
465
+ "# Q=90,\n",
466
+ "# tile_width=256,\n",
467
+ "# tile_height=256,\n",
468
+ "# bigtiff=True,\n",
469
+ "# )\n",
470
+ "\n",
471
+ "# os.remove(tmp_path)\n",
472
+ "\n",
473
+ "# print(\"wrote:\", out_path)\n",
474
+ "\n",
475
+ "# return {\n",
476
+ "# \"name\": out_name,\n",
477
+ "# \"tileSource\": out_name + \".dzi\",\n",
478
+ "# \"x\": 0,\n",
479
+ "# \"y\": 0,\n",
480
+ "# \"scale\": 1,\n",
481
+ "# \"rotation\": 0,\n",
482
+ "# \"flip\": False,\n",
483
+ "# }\n",
484
+ " \n",
485
+ "# morph_files = sorted(glob.glob(os.path.join(xenium_dir, \"morphology_focus.ome.tif\")))\n",
486
+ "# morph_files"
487
+ ]
488
+ },
489
+ {
490
+ "cell_type": "code",
491
+ "execution_count": null,
492
+ "id": "622a8749-399c-4bd4-855c-10be911d0198",
493
+ "metadata": {
494
+ "scrolled": true
495
+ },
496
+ "outputs": [],
497
+ "source": [
498
+ "image_layers = []\n",
499
+ "\n",
500
+ "# Use the first OME file, but extract each plane as a separate stain/channel\n",
501
+ "channel_file = os.path.basename(morph_files[0])\n",
502
+ "\n",
503
+ "for plane in range(4):\n",
504
+ " image_layer = make_one_xenium_pyramid_tifffile_zarr(\n",
505
+ " xenium_dir=xenium_dir,\n",
506
+ " basedir=basedir,\n",
507
+ " channel=channel_file,\n",
508
+ " plane=plane,\n",
509
+ " low=0,\n",
510
+ " high=3000,\n",
511
+ " gamma=0.4,\n",
512
+ " out_name=f\"morphology_focus_plane{plane}_pyramid.tif\",\n",
513
+ " )\n",
514
+ "\n",
515
+ " image_layer[\"name\"] = f\"morphology_focus_plane{plane}\"\n",
516
+ " image_layers.append(image_layer)"
517
+ ]
518
+ },
519
+ {
520
+ "cell_type": "code",
521
+ "execution_count": null,
522
+ "id": "784a65f6-f500-4b7f-9ca6-5c9a3be4361e",
523
+ "metadata": {},
524
+ "outputs": [],
525
+ "source": [
526
+ "# ----------------------------\n",
527
+ "# 4. Create cell boundary GeoJSON\n",
528
+ "# ----------------------------\n",
529
+ "region_files = []\n",
530
+ "\n",
531
+ "for candidate in [\n",
532
+ " os.path.join(xenium_dir, \"cell_boundaries.parquet\"),\n",
533
+ " os.path.join(xenium_dir, \"cell_boundaries.csv.gz\"),\n",
534
+ "]:\n",
535
+ " if os.path.exists(candidate):\n",
536
+ " name = xenium_boundaries_to_geojson(\n",
537
+ " candidate,\n",
538
+ " os.path.join(basedir, \"cell_boundaries_image_space.geojson\"),\n",
539
+ " transform,\n",
540
+ " id_col=\"cell_id\",\n",
541
+ " )\n",
542
+ " region_files.append({\n",
543
+ " \"path\": name,\n",
544
+ " \"title\": \"Load cell boundaries\",\n",
545
+ " \"comment\": \"Cell boundaries\",\n",
546
+ " \"autoLoad\": False,\n",
547
+ " })\n",
548
+ " break"
549
+ ]
550
+ },
551
+ {
552
+ "cell_type": "code",
553
+ "execution_count": null,
554
+ "id": "43159e9d-5279-4b90-a5b8-cc39aa08facd",
555
+ "metadata": {},
556
+ "outputs": [],
557
+ "source": [
558
+ "# def xenium_transcripts_to_csv_streaming(\n",
559
+ "# xenium_dir,\n",
560
+ "# basedir,\n",
561
+ "# transform,\n",
562
+ "# out_name=\"transcripts_image_space.csv\",\n",
563
+ "# min_qv=20,\n",
564
+ "# max_transcripts=2_000_000,\n",
565
+ "# rows_per_group=None,\n",
566
+ "# ):\n",
567
+ "# import os\n",
568
+ "# import numpy as np\n",
569
+ "# import pandas as pd\n",
570
+ "# import pyarrow.parquet as pq\n",
571
+ "\n",
572
+ "# transcript_path = os.path.join(xenium_dir, \"transcripts.parquet\")\n",
573
+ "# if not os.path.exists(transcript_path):\n",
574
+ "# raise FileNotFoundError(transcript_path)\n",
575
+ "\n",
576
+ "# out_path = os.path.join(basedir, out_name)\n",
577
+ "# if os.path.exists(out_path):\n",
578
+ "# os.remove(out_path)\n",
579
+ "\n",
580
+ "# pf = pq.ParquetFile(transcript_path)\n",
581
+ "\n",
582
+ "# transform3 = np.asarray(transform)[:3, :3]\n",
583
+ "\n",
584
+ "# written = 0\n",
585
+ "# wrote_header = False\n",
586
+ "\n",
587
+ "# needed_cols = [\"x_location\", \"y_location\", \"feature_name\"]\n",
588
+ "# optional_cols = [\"qv\", \"cell_id\"]\n",
589
+ "\n",
590
+ "# # keep only columns that exist\n",
591
+ "# schema_cols = set(pf.schema.names)\n",
592
+ "# cols = [c for c in needed_cols + optional_cols if c in schema_cols]\n",
593
+ "\n",
594
+ "# print(\"Transcript columns:\", cols)\n",
595
+ "# print(\"Row groups:\", pf.num_row_groups)\n",
596
+ "\n",
597
+ "# for rg in range(pf.num_row_groups):\n",
598
+ "# if max_transcripts is not None and written >= max_transcripts:\n",
599
+ "# break\n",
600
+ "\n",
601
+ "# table = pf.read_row_group(rg, columns=cols)\n",
602
+ "# tx = table.to_pandas()\n",
603
+ "\n",
604
+ "# if \"qv\" in tx.columns:\n",
605
+ "# tx = tx[tx[\"qv\"] >= min_qv]\n",
606
+ "\n",
607
+ "# if tx.empty:\n",
608
+ "# continue\n",
609
+ "\n",
610
+ "# if max_transcripts is not None:\n",
611
+ "# remaining = max_transcripts - written\n",
612
+ "# if len(tx) > remaining:\n",
613
+ "# tx = tx.sample(remaining, random_state=rg)\n",
614
+ "\n",
615
+ "# x = tx[\"x_location\"].to_numpy(dtype=float)\n",
616
+ "# y = tx[\"y_location\"].to_numpy(dtype=float)\n",
617
+ "\n",
618
+ "# xy1 = np.vstack([x, y, np.ones(len(x))])\n",
619
+ "# out = transform3 @ xy1\n",
620
+ "\n",
621
+ "# out_df = pd.DataFrame({\n",
622
+ "# \"x\": out[0] / out[2],\n",
623
+ "# \"y\": out[1] / out[2],\n",
624
+ "# \"gene\": tx[\"feature_name\"].astype(str).to_numpy(),\n",
625
+ "# })\n",
626
+ "\n",
627
+ "# if \"qv\" in tx.columns:\n",
628
+ "# out_df[\"qv\"] = tx[\"qv\"].to_numpy()\n",
629
+ "\n",
630
+ "# if \"cell_id\" in tx.columns:\n",
631
+ "# out_df[\"cell_id\"] = tx[\"cell_id\"].astype(str).to_numpy()\n",
632
+ "\n",
633
+ "# out_df.to_csv(\n",
634
+ "# out_path,\n",
635
+ "# mode=\"a\",\n",
636
+ "# header=not wrote_header,\n",
637
+ "# index=False,\n",
638
+ "# )\n",
639
+ "\n",
640
+ "# wrote_header = True\n",
641
+ "# written += len(out_df)\n",
642
+ "\n",
643
+ "# print(f\"row group {rg + 1}/{pf.num_row_groups}: wrote {written:,}\")\n",
644
+ "\n",
645
+ "# print(\"wrote:\", out_path, \"n=\", written)\n",
646
+ "# return out_name\n",
647
+ "\n",
648
+ "# transcript_csv = xenium_transcripts_to_csv_streaming(\n",
649
+ "# xenium_dir=xenium_dir,\n",
650
+ "# basedir=basedir,\n",
651
+ "# transform=transform,\n",
652
+ "# min_qv=20,\n",
653
+ "# max_transcripts=None,\n",
654
+ "# )\n",
655
+ "\n",
656
+ "# print(\"Done\")"
657
+ ]
658
+ },
659
+ {
660
+ "cell_type": "code",
661
+ "execution_count": null,
662
+ "id": "b5398cfe-3a3d-4841-b385-f1467f20e45f",
663
+ "metadata": {
664
+ "scrolled": true
665
+ },
666
+ "outputs": [],
667
+ "source": [
668
+ "# def xenium_all_transcripts_to_h5ad_empty_X(\n",
669
+ "# xenium_dir,\n",
670
+ "# basedir,\n",
671
+ "# transform,\n",
672
+ "# out_name=\"transcripts_all_emptyX_tmap.h5ad\",\n",
673
+ "# min_qv=None,\n",
674
+ "# include_cell_id=False,\n",
675
+ "# ):\n",
676
+ "# import os\n",
677
+ "# import numpy as np\n",
678
+ "# import pandas as pd\n",
679
+ "# import pyarrow.parquet as pq\n",
680
+ "# import anndata as ad\n",
681
+ "# from scipy.sparse import csc_matrix\n",
682
+ "\n",
683
+ "# transcript_path = os.path.join(xenium_dir, \"transcripts.parquet\")\n",
684
+ "# out_path = os.path.join(basedir, out_name)\n",
685
+ "\n",
686
+ "# pf = pq.ParquetFile(transcript_path)\n",
687
+ "# transform3 = np.asarray(transform, dtype=np.float64)[:3, :3]\n",
688
+ "\n",
689
+ "# obs_chunks = []\n",
690
+ "# spatial_chunks = []\n",
691
+ "# written = 0\n",
692
+ "\n",
693
+ "# schema_cols = set(pf.schema.names)\n",
694
+ "\n",
695
+ "# cols = [\"x_location\", \"y_location\", \"feature_name\"]\n",
696
+ "# if min_qv is not None and \"qv\" in schema_cols:\n",
697
+ "# cols.append(\"qv\")\n",
698
+ "# elif \"qv\" in schema_cols:\n",
699
+ "# cols.append(\"qv\")\n",
700
+ "\n",
701
+ "# if include_cell_id and \"cell_id\" in schema_cols:\n",
702
+ "# cols.append(\"cell_id\")\n",
703
+ "\n",
704
+ "# for rg in range(pf.num_row_groups):\n",
705
+ "# tx = pf.read_row_group(rg, columns=cols).to_pandas()\n",
706
+ "\n",
707
+ "# if min_qv is not None and \"qv\" in tx.columns:\n",
708
+ "# tx = tx[tx[\"qv\"] >= min_qv]\n",
709
+ "\n",
710
+ "# if tx.empty:\n",
711
+ "# continue\n",
712
+ "\n",
713
+ "# x = tx[\"x_location\"].to_numpy(dtype=np.float64)\n",
714
+ "# y = tx[\"y_location\"].to_numpy(dtype=np.float64)\n",
715
+ "\n",
716
+ "# xy1 = np.vstack([\n",
717
+ "# x,\n",
718
+ "# y,\n",
719
+ "# np.ones(len(tx), dtype=np.float64),\n",
720
+ "# ])\n",
721
+ "\n",
722
+ "# out = transform3 @ xy1\n",
723
+ "\n",
724
+ "# spatial_chunks.append(\n",
725
+ "# np.column_stack([\n",
726
+ "# out[0] / out[2],\n",
727
+ "# out[1] / out[2],\n",
728
+ "# ]).astype(np.float32)\n",
729
+ "# )\n",
730
+ "\n",
731
+ "# # Compact index: RangeIndex, no huge tx_... strings\n",
732
+ "# obs = pd.DataFrame(index=pd.RangeIndex(written, written + len(tx)))\n",
733
+ "\n",
734
+ "# obs[\"gene\"] = tx[\"feature_name\"].astype(\"category\").values\n",
735
+ "\n",
736
+ "# if \"qv\" in tx.columns:\n",
737
+ "# obs[\"qv\"] = pd.to_numeric(tx[\"qv\"], downcast=\"integer\")\n",
738
+ "\n",
739
+ "# if include_cell_id and \"cell_id\" in tx.columns:\n",
740
+ "# obs[\"cell_id\"] = tx[\"cell_id\"].astype(\"category\").values\n",
741
+ "\n",
742
+ "# obs_chunks.append(obs)\n",
743
+ "\n",
744
+ "# written += len(tx)\n",
745
+ "# print(f\"row group {rg + 1}/{pf.num_row_groups}: {written:,}\")\n",
746
+ "\n",
747
+ "# obs = pd.concat(obs_chunks, axis=0)\n",
748
+ "\n",
749
+ "# # Ensure compact categoricals after concat\n",
750
+ "# obs[\"gene\"] = obs[\"gene\"].astype(\"category\")\n",
751
+ "\n",
752
+ "# if include_cell_id and \"cell_id\" in obs.columns:\n",
753
+ "# obs[\"cell_id\"] = obs[\"cell_id\"].astype(\"category\")\n",
754
+ "\n",
755
+ "# if \"qv\" in obs.columns:\n",
756
+ "# obs[\"qv\"] = pd.to_numeric(obs[\"qv\"], downcast=\"integer\")\n",
757
+ "\n",
758
+ "# spatial = np.vstack(spatial_chunks).astype(np.float32)\n",
759
+ "\n",
760
+ "# # Empty X: n_obs x 0 vars\n",
761
+ "# X = csc_matrix((len(obs), 0), dtype=np.float32)\n",
762
+ "# var = pd.DataFrame(index=pd.Index([], dtype=str))\n",
763
+ "\n",
764
+ "# transcript_adata = ad.AnnData(X=X, obs=obs, var=var)\n",
765
+ "# transcript_adata.obsm[\"spatial\"] = spatial\n",
766
+ "\n",
767
+ "# transcript_adata.write_h5ad(out_path)\n",
768
+ "\n",
769
+ "# print(\"wrote:\", out_path)\n",
770
+ "# print(\"shape:\", transcript_adata.shape)\n",
771
+ "# print(\"obs columns:\", list(transcript_adata.obs.columns))\n",
772
+ "# print(\"spatial dtype:\", transcript_adata.obsm[\"spatial\"].dtype)\n",
773
+ "\n",
774
+ "# return out_name\n",
775
+ "\n",
776
+ "# transcript_h5ad = xenium_all_transcripts_to_h5ad_empty_X(\n",
777
+ "# xenium_dir=xenium_dir,\n",
778
+ "# basedir=basedir,\n",
779
+ "# transform=transform,\n",
780
+ "# min_qv=None,\n",
781
+ "# include_cell_id=False,\n",
782
+ "# )"
783
+ ]
784
+ },
785
+ {
786
+ "cell_type": "code",
787
+ "execution_count": null,
788
+ "id": "9423d36b-5e04-484c-8901-b32a494ce7ad",
789
+ "metadata": {
790
+ "scrolled": true
791
+ },
792
+ "outputs": [],
793
+ "source": [
794
+ "# def xenium_all_transcripts_to_h5ad_empty_X(\n",
795
+ "# xenium_dir,\n",
796
+ "# basedir,\n",
797
+ "# transform,\n",
798
+ "# out_name=\"transcripts_all_emptyX_tmap.h5ad\",\n",
799
+ "# min_qv=None,\n",
800
+ "# include_cell_id=False,\n",
801
+ "# tmp_path=None,\n",
802
+ "# ):\n",
803
+ "# import os\n",
804
+ "# import numpy as np\n",
805
+ "# import pandas as pd\n",
806
+ "# import pyarrow as pa\n",
807
+ "# import pyarrow.parquet as pq\n",
808
+ "# import anndata as ad\n",
809
+ "# from scipy.sparse import csc_matrix\n",
810
+ "\n",
811
+ "# transcript_path = os.path.join(xenium_dir, \"transcripts.parquet\")\n",
812
+ "# out_path = os.path.join(basedir, out_name)\n",
813
+ "# if tmp_path is None:\n",
814
+ "# tmp_path = out_path.replace(\".h5ad\", \"_tmp.parquet\")\n",
815
+ "\n",
816
+ "# pf = pq.ParquetFile(transcript_path)\n",
817
+ "# transform3 = np.asarray(transform, dtype=np.float64)[:3, :3]\n",
818
+ "\n",
819
+ "# schema_cols = set(pf.schema.names)\n",
820
+ "# cols = [\"x_location\", \"y_location\", \"feature_name\"]\n",
821
+ "# if \"qv\" in schema_cols:\n",
822
+ "# cols.append(\"qv\")\n",
823
+ "# if include_cell_id and \"cell_id\" in schema_cols:\n",
824
+ "# cols.append(\"cell_id\")\n",
825
+ "\n",
826
+ "# writer = None\n",
827
+ "# written = 0\n",
828
+ "\n",
829
+ "# for rg in range(pf.num_row_groups):\n",
830
+ "# tx = pf.read_row_group(rg, columns=cols).to_pandas()\n",
831
+ "# if min_qv is not None and \"qv\" in tx.columns:\n",
832
+ "# tx = tx[tx[\"qv\"] >= min_qv]\n",
833
+ "# if tx.empty:\n",
834
+ "# continue\n",
835
+ "\n",
836
+ "# x = tx[\"x_location\"].to_numpy(dtype=np.float64)\n",
837
+ "# y = tx[\"y_location\"].to_numpy(dtype=np.float64)\n",
838
+ "# xy1 = np.vstack([x, y, np.ones(len(tx), dtype=np.float64)])\n",
839
+ "# out = transform3 @ xy1\n",
840
+ "\n",
841
+ "# chunk = pd.DataFrame({\n",
842
+ "# \"spatial_x\": (out[0] / out[2]).astype(np.float32),\n",
843
+ "# \"spatial_y\": (out[1] / out[2]).astype(np.float32),\n",
844
+ "# \"gene\": tx[\"feature_name\"].astype(str).values,\n",
845
+ "# })\n",
846
+ "# if \"qv\" in tx.columns:\n",
847
+ "# chunk[\"qv\"] = pd.to_numeric(tx[\"qv\"], downcast=\"integer\").values\n",
848
+ "# if include_cell_id and \"cell_id\" in tx.columns:\n",
849
+ "# chunk[\"cell_id\"] = tx[\"cell_id\"].astype(str).values\n",
850
+ "\n",
851
+ "# table = pa.Table.from_pandas(chunk, preserve_index=False)\n",
852
+ "# if writer is None:\n",
853
+ "# writer = pq.ParquetWriter(tmp_path, table.schema)\n",
854
+ "# writer.write_table(table)\n",
855
+ "\n",
856
+ "# written += len(chunk)\n",
857
+ "# print(f\"row group {rg + 1}/{pf.num_row_groups}: {written:,}\")\n",
858
+ "\n",
859
+ "# writer.close()\n",
860
+ "# print(\"All row groups written to tmp parquet. Building AnnData...\")\n",
861
+ "\n",
862
+ "# df = pd.read_parquet(tmp_path)\n",
863
+ "# df[\"gene\"] = df[\"gene\"].astype(\"category\")\n",
864
+ "# if include_cell_id and \"cell_id\" in df.columns:\n",
865
+ "# df[\"cell_id\"] = df[\"cell_id\"].astype(\"category\")\n",
866
+ "\n",
867
+ "# spatial = df[[\"spatial_x\", \"spatial_y\"]].to_numpy(dtype=np.float32)\n",
868
+ "# obs = df.drop(columns=[\"spatial_x\", \"spatial_y\"])\n",
869
+ "# obs.index = pd.RangeIndex(len(obs)).astype(str)\n",
870
+ "\n",
871
+ "# X = csc_matrix((len(obs), 0), dtype=np.float32)\n",
872
+ "# var = pd.DataFrame(index=pd.Index([], dtype=str))\n",
873
+ "# transcript_adata = ad.AnnData(X=X, obs=obs, var=var)\n",
874
+ "# transcript_adata.obsm[\"spatial\"] = spatial\n",
875
+ "# transcript_adata.write_h5ad(out_path)\n",
876
+ "\n",
877
+ "# os.remove(tmp_path)\n",
878
+ "# print(\"wrote:\", out_path)\n",
879
+ "# print(\"shape:\", transcript_adata.shape)\n",
880
+ "# print(\"obs columns:\", list(transcript_adata.obs.columns))\n",
881
+ "# return out_name\n",
882
+ "\n",
883
+ "\n",
884
+ "# transcript_h5ad = xenium_all_transcripts_to_h5ad_empty_X(\n",
885
+ "# xenium_dir=xenium_dir,\n",
886
+ "# basedir=basedir,\n",
887
+ "# transform=transform,\n",
888
+ "# min_qv=None,\n",
889
+ "# include_cell_id=False,\n",
890
+ "# tmp_path=\"/Volumes/T7 Shield/tmp/transcripts_tmp.parquet\",\n",
891
+ "# )"
892
+ ]
893
+ },
894
+ {
895
+ "cell_type": "code",
896
+ "execution_count": null,
897
+ "id": "02d53e78-c105-413c-9b30-f950b42ed200",
898
+ "metadata": {},
899
+ "outputs": [],
900
+ "source": [
901
+ "def xenium_all_transcripts_to_h5ad_empty_X(\n",
902
+ " xenium_dir,\n",
903
+ " basedir,\n",
904
+ " transform,\n",
905
+ " out_name=\"transcripts_all_emptyX_tmap.h5ad\",\n",
906
+ " min_qv=None,\n",
907
+ " include_cell_id=False,\n",
908
+ " tmp_path=None,\n",
909
+ "):\n",
910
+ " import os\n",
911
+ " import numpy as np\n",
912
+ " import pandas as pd\n",
913
+ " import pyarrow as pa\n",
914
+ " import pyarrow.parquet as pq\n",
915
+ " import h5py\n",
916
+ " from scipy.sparse import csc_matrix\n",
917
+ "\n",
918
+ " transcript_path = os.path.join(xenium_dir, \"transcripts.parquet\")\n",
919
+ " out_path = os.path.join(basedir, out_name)\n",
920
+ " if tmp_path is None:\n",
921
+ " tmp_path = out_path.replace(\".h5ad\", \"_tmp.parquet\")\n",
922
+ "\n",
923
+ " pf = pq.ParquetFile(transcript_path)\n",
924
+ " transform3 = np.asarray(transform, dtype=np.float64)[:3, :3]\n",
925
+ "\n",
926
+ " schema_cols = set(pf.schema.names)\n",
927
+ " cols = [\"x_location\", \"y_location\", \"feature_name\"]\n",
928
+ " if \"qv\" in schema_cols:\n",
929
+ " cols.append(\"qv\")\n",
930
+ " if include_cell_id and \"cell_id\" in schema_cols:\n",
931
+ " cols.append(\"cell_id\")\n",
932
+ "\n",
933
+ " # --- Pass 1: stream row groups → tmp parquet ---\n",
934
+ " writer = None\n",
935
+ " written = 0\n",
936
+ " for rg in range(pf.num_row_groups):\n",
937
+ " tx = pf.read_row_group(rg, columns=cols).to_pandas()\n",
938
+ " if min_qv is not None and \"qv\" in tx.columns:\n",
939
+ " tx = tx[tx[\"qv\"] >= min_qv]\n",
940
+ " if tx.empty:\n",
941
+ " continue\n",
942
+ "\n",
943
+ " x = tx[\"x_location\"].to_numpy(dtype=np.float64)\n",
944
+ " y = tx[\"y_location\"].to_numpy(dtype=np.float64)\n",
945
+ " xy1 = np.vstack([x, y, np.ones(len(tx), dtype=np.float64)])\n",
946
+ " out = transform3 @ xy1\n",
947
+ "\n",
948
+ " chunk = pd.DataFrame({\n",
949
+ " \"spatial_x\": (out[0] / out[2]).astype(np.float32),\n",
950
+ " \"spatial_y\": (out[1] / out[2]).astype(np.float32),\n",
951
+ " \"gene\": tx[\"feature_name\"].astype(str).values,\n",
952
+ " })\n",
953
+ " if \"qv\" in tx.columns:\n",
954
+ " chunk[\"qv\"] = pd.to_numeric(tx[\"qv\"], downcast=\"integer\").values\n",
955
+ " if include_cell_id and \"cell_id\" in tx.columns:\n",
956
+ " chunk[\"cell_id\"] = tx[\"cell_id\"].astype(str).values\n",
957
+ "\n",
958
+ " table = pa.Table.from_pandas(chunk, preserve_index=False)\n",
959
+ " if writer is None:\n",
960
+ " writer = pq.ParquetWriter(tmp_path, table.schema)\n",
961
+ " writer.write_table(table)\n",
962
+ " written += len(chunk)\n",
963
+ " print(f\"row group {rg + 1}/{pf.num_row_groups}: {written:,}\")\n",
964
+ "\n",
965
+ " writer.close()\n",
966
+ " total_rows = written\n",
967
+ " print(f\"Pass 1 done. {total_rows:,} rows. Writing h5ad...\")\n",
968
+ "\n",
969
+ " # --- Pass 2: stream tmp parquet → h5ad via h5py, one chunk at a time ---\n",
970
+ " pf2 = pq.ParquetFile(tmp_path)\n",
971
+ " obs_col_names = [c for c in pf2.schema.names if c not in (\"spatial_x\", \"spatial_y\")]\n",
972
+ "\n",
973
+ " with h5py.File(out_path, \"w\") as f:\n",
974
+ " # AnnData minimal structure\n",
975
+ " f.attrs[\"encoding-type\"] = \"anndata\"\n",
976
+ " f.attrs[\"encoding-version\"] = \"0.1.0\"\n",
977
+ "\n",
978
+ " # X group — empty (0 vars)\n",
979
+ " xgrp = f.create_group(\"X\")\n",
980
+ " xgrp.attrs[\"encoding-type\"] = \"array\"\n",
981
+ " xgrp.attrs[\"encoding-version\"] = \"0.2.0\"\n",
982
+ " xgrp.create_dataset(\"data\", data=np.array([], dtype=np.float32))\n",
983
+ " xgrp.create_dataset(\"indices\",data=np.array([], dtype=np.int32))\n",
984
+ " xgrp.create_dataset(\"indptr\", data=np.zeros(1, dtype=np.int32))\n",
985
+ " xgrp.attrs[\"shape\"] = [total_rows, 0]\n",
986
+ "\n",
987
+ " # obsm/spatial — pre-allocate, fill in chunks\n",
988
+ " obsm = f.create_group(\"obsm\")\n",
989
+ " spatial_ds = obsm.create_dataset(\n",
990
+ " \"spatial\", shape=(total_rows, 2), dtype=np.float32\n",
991
+ " )\n",
992
+ "\n",
993
+ " # obs — pre-allocate string datasets per column\n",
994
+ " obs_grp = f.create_group(\"obs\")\n",
995
+ " obs_grp.attrs[\"_index\"] = \"_index\"\n",
996
+ " obs_grp.attrs[\"encoding-type\"] = \"dataframe\"\n",
997
+ " obs_grp.attrs[\"encoding-version\"] = \"0.2.0\"\n",
998
+ " obs_grp.attrs[\"column-order\"] = obs_col_names\n",
999
+ "\n",
1000
+ " # pre-allocate index\n",
1001
+ " idx_ds = obs_grp.create_dataset(\n",
1002
+ " \"_index\", shape=(total_rows,), dtype=h5py.string_dtype()\n",
1003
+ " )\n",
1004
+ " col_datasets = {}\n",
1005
+ " for col in obs_col_names:\n",
1006
+ " col_datasets[col] = obs_grp.create_dataset(\n",
1007
+ " col, shape=(total_rows,), dtype=h5py.string_dtype()\n",
1008
+ " )\n",
1009
+ "\n",
1010
+ " # var — empty\n",
1011
+ " var_grp = f.create_group(\"var\")\n",
1012
+ " var_grp.attrs[\"_index\"] = \"_index\"\n",
1013
+ " var_grp.attrs[\"encoding-type\"] = \"dataframe\"\n",
1014
+ " var_grp.attrs[\"encoding-version\"] = \"0.2.0\"\n",
1015
+ " var_grp.attrs[\"column-order\"] = []\n",
1016
+ " var_grp.create_dataset(\"_index\", data=np.array([], dtype=h5py.string_dtype()))\n",
1017
+ "\n",
1018
+ " # stream fill\n",
1019
+ " cursor = 0\n",
1020
+ " for rg in range(pf2.num_row_groups):\n",
1021
+ " chunk = pf2.read_row_group(rg).to_pandas()\n",
1022
+ " n = len(chunk)\n",
1023
+ " sl = slice(cursor, cursor + n)\n",
1024
+ "\n",
1025
+ " spatial_ds[sl] = chunk[[\"spatial_x\", \"spatial_y\"]].to_numpy(dtype=np.float32)\n",
1026
+ " idx_ds[sl] = np.arange(cursor, cursor + n).astype(str)\n",
1027
+ " for col in obs_col_names:\n",
1028
+ " col_datasets[col][sl] = chunk[col].astype(str).values\n",
1029
+ "\n",
1030
+ " cursor += n\n",
1031
+ " if rg % 50 == 0:\n",
1032
+ " print(f\" h5ad pass {rg + 1}/{pf2.num_row_groups}: {cursor:,}\")\n",
1033
+ "\n",
1034
+ " os.remove(tmp_path)\n",
1035
+ " print(\"wrote:\", out_path)\n",
1036
+ " print(\"shape:\", (total_rows, 0))\n",
1037
+ " print(\"obs columns:\", obs_col_names)\n",
1038
+ " return out_name"
1039
+ ]
1040
+ },
1041
+ {
1042
+ "cell_type": "code",
1043
+ "execution_count": null,
1044
+ "id": "cc5c8636-ed10-47e9-bf9c-08d5608095f8",
1045
+ "metadata": {
1046
+ "scrolled": true
1047
+ },
1048
+ "outputs": [],
1049
+ "source": [
1050
+ "transcript_h5ad = xenium_all_transcripts_to_h5ad_empty_X(\n",
1051
+ " xenium_dir=xenium_dir,\n",
1052
+ " basedir=basedir,\n",
1053
+ " transform=transform,\n",
1054
+ " min_qv=None,\n",
1055
+ " include_cell_id=False,\n",
1056
+ " tmp_path=\"/Volumes/T7 Shield/tmp/transcripts_tmp.parquet\",\n",
1057
+ ")"
1058
+ ]
1059
+ },
1060
+ {
1061
+ "cell_type": "code",
1062
+ "execution_count": null,
1063
+ "id": "a53c9e37-da32-4583-a74c-604d60df358b",
1064
+ "metadata": {},
1065
+ "outputs": [],
1066
+ "source": [
1067
+ "# basedir = os.path.abspath(f\"tissuumaps/{sample}\")\n",
1068
+ "# transcript_csv = f\"transcripts_image_space.csv\"\n",
1069
+ "\n",
1070
+ "# print(basedir)\n",
1071
+ "\n",
1072
+ "# region_files = []\n",
1073
+ "\n",
1074
+ "# for geojson_path in glob.glob(os.path.join(basedir, \"*boundaries*.geojson\")):\n",
1075
+ "# geojson_name = os.path.basename(geojson_path)\n",
1076
+ "\n",
1077
+ "# region_files.append({\n",
1078
+ "# \"path\": geojson_name, # relative path only\n",
1079
+ "# \"title\": geojson_name,\n",
1080
+ "# \"comment\": geojson_name,\n",
1081
+ "# \"autoLoad\": True,\n",
1082
+ "# })\n",
1083
+ "\n",
1084
+ "# print(region_files)\n",
1085
+ "\n",
1086
+ "# image_layers = []\n",
1087
+ "\n",
1088
+ "# for tif_path in sorted(\n",
1089
+ "# glob.glob(os.path.join(basedir, \"morphology_focus_plane*_pyramid.tif\"))\n",
1090
+ "# ):\n",
1091
+ "# name = os.path.basename(tif_path)\n",
1092
+ "\n",
1093
+ "# image_layers.append({\n",
1094
+ "# \"name\": name.replace(\".tif\", \"\"),\n",
1095
+ "# \"tileSource\": name + \".dzi\",\n",
1096
+ "# \"x\": 0,\n",
1097
+ "# \"y\": 0,\n",
1098
+ "# \"scale\": 1,\n",
1099
+ "# \"rotation\": 0,\n",
1100
+ "# \"flip\": False,\n",
1101
+ "# })\n",
1102
+ "\n",
1103
+ "# print(f\"Found {len(image_layers)} image layers\")"
1104
+ ]
1105
+ },
1106
+ {
1107
+ "cell_type": "code",
1108
+ "execution_count": null,
1109
+ "id": "1ee1ac2d-6de4-4fe2-b31a-90725d67669c",
1110
+ "metadata": {},
1111
+ "outputs": [],
1112
+ "source": [
1113
+ "# # ----------------------------\n",
1114
+ "# # 5. Generate TissUUmaps project\n",
1115
+ "# # ----------------------------\n",
1116
+ "# project = read_h5ad.h5ad_to_tmap(basedir, out_h5ad_name)\n",
1117
+ "\n",
1118
+ "# # Images: all stacked and visible\n",
1119
+ "# project[\"layers\"] = image_layers\n",
1120
+ "# project[\"collectionMode\"] = False\n",
1121
+ "# project[\"compositeMode\"] = \"lighter\"\n",
1122
+ "# project[\"backgroundColor\"] = \"#000000\"\n",
1123
+ "\n",
1124
+ "# project[\"filters\"] = []\n",
1125
+ "# project[\"layerFilters\"] = {}\n",
1126
+ "# project[\"layerOpacities\"] = {str(i): 1 for i in range(len(image_layers))}\n",
1127
+ "# project[\"layerVisibilities\"] = {str(i): True for i in range(len(image_layers))}\n",
1128
+ "\n",
1129
+ "# # Polygons: autoload\n",
1130
+ "# project[\"regionFiles\"] = []\n",
1131
+ "# for rf in region_files:\n",
1132
+ "# rf = dict(rf)\n",
1133
+ "# rf[\"autoLoad\"] = True\n",
1134
+ "# project[\"regionFiles\"].append(rf)\n",
1135
+ "\n",
1136
+ "# # Keep h5ad/cell-expression dropdowns available, but not autoloaded\n",
1137
+ "# for mf in project.get(\"markerFiles\", []):\n",
1138
+ "# mf[\"autoLoad\"] = False\n",
1139
+ "# mf.setdefault(\"expectedHeader\", {})\n",
1140
+ "# mf[\"expectedHeader\"][\"shape_fixed\"] = \"disc\"\n",
1141
+ "# mf[\"expectedHeader\"][\"scale_factor\"] = 1\n",
1142
+ "\n",
1143
+ "# mf.setdefault(\"expectedRadios\", {})\n",
1144
+ "# mf[\"expectedRadios\"][\"shape_fixed\"] = True\n",
1145
+ "# mf[\"expectedRadios\"][\"shape_gr\"] = False\n",
1146
+ "# mf[\"expectedRadios\"][\"shape_gr_rand\"] = False\n",
1147
+ "# mf[\"expectedRadios\"][\"sortby_check\"] = False\n",
1148
+ "\n",
1149
+ "# # Transcripts: autoload default marker layer\n",
1150
+ "# if transcript_csv is not None:\n",
1151
+ "# project[\"markerFiles\"].insert(\n",
1152
+ "# 0,\n",
1153
+ "# {\n",
1154
+ "# \"path\": transcript_csv,\n",
1155
+ "# \"title\": \"Load transcripts\",\n",
1156
+ "# \"comment\": \"Transcript molecules\",\n",
1157
+ "# \"name\": \"Transcripts\",\n",
1158
+ "# \"uid\": \"transcripts\",\n",
1159
+ "# \"autoLoad\": True,\n",
1160
+ "# \"hideSettings\": True,\n",
1161
+ "# \"expectedHeader\": {\n",
1162
+ "# \"X\": \"x\",\n",
1163
+ "# \"Y\": \"y\",\n",
1164
+ "# \"gb_col\": \"gene\",\n",
1165
+ "# \"gb_name\": \"\",\n",
1166
+ "# \"cb_col\": \"\",\n",
1167
+ "# \"cb_cmap\": \"\",\n",
1168
+ "# \"scale_factor\": 0.15,\n",
1169
+ "# \"shape_fixed\": \"disc\",\n",
1170
+ "# \"opacity\": 0.7,\n",
1171
+ "# },\n",
1172
+ "# \"expectedRadios\": {\n",
1173
+ "# \"cb_col\": False,\n",
1174
+ "# \"cb_gr\": True,\n",
1175
+ "# \"cb_gr_rand\": True,\n",
1176
+ "# \"cb_gr_dict\": False,\n",
1177
+ "# \"cb_gr_key\": False,\n",
1178
+ "# \"pie_check\": False,\n",
1179
+ "# \"scale_check\": False,\n",
1180
+ "# \"shape_col\": False,\n",
1181
+ "# \"shape_fixed\": True,\n",
1182
+ "# \"shape_gr\": False,\n",
1183
+ "# \"shape_gr_rand\": False,\n",
1184
+ "# \"shape_gr_dict\": False,\n",
1185
+ "# \"sortby_check\": False,\n",
1186
+ "# },\n",
1187
+ "# },\n",
1188
+ "# )\n",
1189
+ "\n",
1190
+ "# # project[\"markerFiles\"].insert(\n",
1191
+ "# # 0,\n",
1192
+ "# # {\n",
1193
+ "# # \"path\": transcript_h5ad,\n",
1194
+ "# # \"title\": \"Load transcript AnnData\",\n",
1195
+ "# # \"comment\": \"All transcript molecules\",\n",
1196
+ "# # \"name\": \"Transcript AnnData\",\n",
1197
+ "# # \"uid\": \"transcript_h5ad\",\n",
1198
+ "# # \"autoLoad\": True,\n",
1199
+ "# # \"hideSettings\": True,\n",
1200
+ "# # \"expectedHeader\": {\n",
1201
+ "# # \"X\": \"/obsm/spatial;0\",\n",
1202
+ "# # \"Y\": \"/obsm/spatial;1\",\n",
1203
+ "# # \"gb_col\": \"/obs/gene\",\n",
1204
+ "# # \"gb_name\": \"\",\n",
1205
+ "# # \"cb_col\": \"\",\n",
1206
+ "# # \"cb_cmap\": \"\",\n",
1207
+ "# # \"scale_factor\": 0.15,\n",
1208
+ "# # \"shape_fixed\": \"disc\",\n",
1209
+ "# # \"opacity\": 0.7,\n",
1210
+ "# # },\n",
1211
+ "# # \"expectedRadios\": {\n",
1212
+ "# # \"cb_col\": False,\n",
1213
+ "# # \"cb_gr\": True,\n",
1214
+ "# # \"cb_gr_rand\": True,\n",
1215
+ "# # \"shape_fixed\": True,\n",
1216
+ "# # \"shape_gr\": False,\n",
1217
+ "# # \"scale_check\": False,\n",
1218
+ "# # \"sortby_check\": False,\n",
1219
+ "# # },\n",
1220
+ "# # },\n",
1221
+ "# # )\n",
1222
+ "\n",
1223
+ "# with open(project_path, \"w\") as f:\n",
1224
+ "# json.dump(project, f, indent=2)\n",
1225
+ "\n",
1226
+ "# viewer = tj.opentmap(project_path)"
1227
+ ]
1228
+ },
1229
+ {
1230
+ "cell_type": "code",
1231
+ "execution_count": null,
1232
+ "id": "68db233e-7105-4862-9635-c68875497962",
1233
+ "metadata": {},
1234
+ "outputs": [],
1235
+ "source": []
1236
+ },
1237
+ {
1238
+ "cell_type": "code",
1239
+ "execution_count": null,
1240
+ "id": "696e478b-61c6-4d35-8b90-813569c4a0ed",
1241
+ "metadata": {},
1242
+ "outputs": [],
1243
+ "source": []
1244
+ }
1245
+ ],
1246
+ "metadata": {
1247
+ "kernelspec": {
1248
+ "display_name": "Python (tissuumaps_env)",
1249
+ "language": "python",
1250
+ "name": "tissuumaps_env"
1251
+ },
1252
+ "language_info": {
1253
+ "codemirror_mode": {
1254
+ "name": "ipython",
1255
+ "version": 3
1256
+ },
1257
+ "file_extension": ".py",
1258
+ "mimetype": "text/x-python",
1259
+ "name": "python",
1260
+ "nbconvert_exporter": "python",
1261
+ "pygments_lexer": "ipython3",
1262
+ "version": "3.9.23"
1263
+ },
1264
+ "widgets": {
1265
+ "application/vnd.jupyter.widget-state+json": {
1266
+ "state": {},
1267
+ "version_major": 2,
1268
+ "version_minor": 0
1269
+ }
1270
+ }
1271
+ },
1272
+ "nbformat": 4,
1273
+ "nbformat_minor": 5
1274
+ }
notebooks/.ipynb_checkpoints/tissuumaps_viz-checkpoint.ipynb ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "07f7dbb1-63c6-40e4-b0d9-6ec104aa0adc",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# !pip install zarr\n",
11
+ "\n",
12
+ "import os\n",
13
+ "import json\n",
14
+ "from pathlib import Path\n",
15
+ "import glob\n",
16
+ "import numpy as np\n",
17
+ "import pandas as pd\n",
18
+ "import scanpy as sc\n",
19
+ "import pyvips\n",
20
+ "import zarr\n",
21
+ "import geopandas as gpd\n",
22
+ "from shapely.geometry import Polygon\n",
23
+ "from scipy.sparse import csc_matrix\n",
24
+ "\n",
25
+ "import tissuumaps.jupyter as tj\n",
26
+ "from tissuumaps import read_h5ad\n",
27
+ "\n",
28
+ "\n",
29
+ "# ----------------------------\n",
30
+ "# Paths\n",
31
+ "# ----------------------------\n",
32
+ "sample = \"WTA_Preview_FFPE_Cervical_Cancer_outs\"\n",
33
+ "# sample = \"Xenium_Prime_Human_Lymph_Node_Reactive_FFPE_outs\"\n",
34
+ "# sample = \"Xenium_Prime_Ovarian_Cancer_FFPE_XRrun_outs\"\n",
35
+ "# sample = \"Xenium_V1_humanLung_Cancer_FFPE_outs\"\n",
36
+ "\n",
37
+ "\n",
38
+ "xenium_dir = os.path.abspath(f\"../data/instrument_data/{sample}\")\n",
39
+ "basedir = os.path.abspath(f\"../data/processed_data/tissuumaps_h5ad/{sample}\")\n",
40
+ "os.makedirs(basedir, exist_ok=True)\n",
41
+ "\n",
42
+ "out_h5ad_name = f\"{sample}_tmap.h5ad\"\n",
43
+ "out_h5ad = os.path.join(basedir, out_h5ad_name)\n",
44
+ "\n",
45
+ "project_path = os.path.join(basedir, \"_project_h5ad.tmap\")"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "execution_count": null,
51
+ "id": "a53c9e37-da32-4583-a74c-604d60df358b",
52
+ "metadata": {},
53
+ "outputs": [],
54
+ "source": [
55
+ "basedir = os.path.abspath(f\"../data/processed_data/tissuumaps_h5ad/{sample}\")\n",
56
+ "# transcript_csv = f\"transcripts_image_space.csv\"\n",
57
+ "transcript_h5ad = f\"transcripts_all_emptyX_tmap.h5ad\"\n",
58
+ "\n",
59
+ "print(basedir)\n",
60
+ "\n",
61
+ "region_files = []\n",
62
+ "\n",
63
+ "for geojson_path in glob.glob(os.path.join(basedir, \"*boundaries*.geojson\")):\n",
64
+ " geojson_name = os.path.basename(geojson_path)\n",
65
+ "\n",
66
+ " region_files.append({\n",
67
+ " \"path\": geojson_name, # relative path only\n",
68
+ " \"title\": geojson_name,\n",
69
+ " \"comment\": geojson_name,\n",
70
+ " \"autoLoad\": True,\n",
71
+ " })\n",
72
+ "\n",
73
+ "print(region_files)\n",
74
+ "\n",
75
+ "image_layers = []\n",
76
+ "\n",
77
+ "for tif_path in sorted(\n",
78
+ " glob.glob(os.path.join(basedir, \"morphology_focus_plane*_pyramid.tif\"))\n",
79
+ "):\n",
80
+ " name = os.path.basename(tif_path)\n",
81
+ "\n",
82
+ " image_layers.append({\n",
83
+ " \"name\": name.replace(\".tif\", \"\"),\n",
84
+ " \"tileSource\": name + \".dzi\",\n",
85
+ " \"x\": 0,\n",
86
+ " \"y\": 0,\n",
87
+ " \"scale\": 1,\n",
88
+ " \"rotation\": 0,\n",
89
+ " \"flip\": False,\n",
90
+ " })\n",
91
+ "\n",
92
+ "print(f\"Found {len(image_layers)} image layers\")"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "execution_count": null,
98
+ "id": "bbcabbbd-3f76-48dd-b589-c80e47fc8cbc",
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "# ----------------------------\n",
103
+ "# 5. Generate TissUUmaps project\n",
104
+ "# ----------------------------\n",
105
+ "project = read_h5ad.h5ad_to_tmap(basedir, out_h5ad_name)\n",
106
+ "\n",
107
+ "# Images: all stacked and visible\n",
108
+ "project[\"layers\"] = image_layers\n",
109
+ "\n",
110
+ "project[\"collectionMode\"] = False\n",
111
+ "project[\"compositeMode\"] = \"lighter\"\n",
112
+ "project[\"backgroundColor\"] = \"#000000\"\n",
113
+ "\n",
114
+ "project[\"filters\"] = []\n",
115
+ "project[\"layerFilters\"] = {}\n",
116
+ "project[\"layerOpacities\"] = {str(i): 1 for i in range(len(image_layers))}\n",
117
+ "project[\"layerVisibilities\"] = {str(i): True for i in range(len(image_layers))}\n",
118
+ "\n",
119
+ "# Polygons: autoload\n",
120
+ "project[\"regionFiles\"] = []\n",
121
+ "for rf in region_files:\n",
122
+ " rf = dict(rf)\n",
123
+ " rf[\"autoLoad\"] = True\n",
124
+ " project[\"regionFiles\"].append(rf)\n",
125
+ "\n",
126
+ "for i, mf in enumerate(project.get(\"markerFiles\", [])):\n",
127
+ " mf.setdefault(\"expectedHeader\", {})\n",
128
+ " mf[\"expectedHeader\"][\"shape_fixed\"] = \"disc\"\n",
129
+ " mf[\"expectedHeader\"][\"scale_factor\"] = 1\n",
130
+ " mf.setdefault(\"expectedRadios\", {})\n",
131
+ " mf[\"expectedRadios\"][\"shape_fixed\"] = True\n",
132
+ " mf[\"expectedRadios\"][\"shape_gr\"] = False\n",
133
+ " mf[\"expectedRadios\"][\"shape_gr_rand\"] = False\n",
134
+ " mf[\"expectedRadios\"][\"sortby_check\"] = False\n",
135
+ "\n",
136
+ "# Transcripts: autoload default marker layer\n",
137
+ "# if transcript_csv is not None:\n",
138
+ "# project[\"markerFiles\"].insert(\n",
139
+ "# 0,\n",
140
+ "# {\n",
141
+ "# \"path\": transcript_csv,\n",
142
+ "# \"title\": \"Load transcripts\",\n",
143
+ "# \"comment\": \"Transcript molecules\",\n",
144
+ "# \"name\": \"Transcripts\",\n",
145
+ "# \"uid\": \"transcripts\",\n",
146
+ "# \"autoLoad\": True,\n",
147
+ "# \"hideSettings\": True,\n",
148
+ "# \"expectedHeader\": {\n",
149
+ "# \"X\": \"x\",\n",
150
+ "# \"Y\": \"y\",\n",
151
+ "# \"gb_col\": \"gene\",\n",
152
+ "# \"gb_name\": \"\",\n",
153
+ "# \"cb_col\": \"\",\n",
154
+ "# \"cb_cmap\": \"\",\n",
155
+ "# \"scale_factor\": 0.15,\n",
156
+ "# \"shape_fixed\": \"disc\",\n",
157
+ "# \"opacity\": 0.7,\n",
158
+ "# },\n",
159
+ "# \"expectedRadios\": {\n",
160
+ "# \"cb_col\": False,\n",
161
+ "# \"cb_gr\": True,\n",
162
+ "# \"cb_gr_rand\": True,\n",
163
+ "# \"cb_gr_dict\": False,\n",
164
+ "# \"cb_gr_key\": False,\n",
165
+ "# \"pie_check\": False,\n",
166
+ "# \"scale_check\": False,\n",
167
+ "# \"shape_col\": False,\n",
168
+ "# \"shape_fixed\": True,\n",
169
+ "# \"shape_gr\": False,\n",
170
+ "# \"shape_gr_rand\": False,\n",
171
+ "# \"shape_gr_dict\": False,\n",
172
+ "# \"sortby_check\": False,\n",
173
+ "# },\n",
174
+ "# },\n",
175
+ "# )\n",
176
+ "\n",
177
+ "project[\"markerFiles\"].insert(\n",
178
+ " 0,\n",
179
+ " {\n",
180
+ " \"path\": transcript_h5ad,\n",
181
+ " \"title\": \"Load transcript AnnData\",\n",
182
+ " \"comment\": \"All transcript molecules\",\n",
183
+ " \"name\": \"Transcript AnnData\",\n",
184
+ " \"uid\": \"transcript_h5ad\",\n",
185
+ " \"autoLoad\": True,\n",
186
+ " \"hideSettings\": True,\n",
187
+ " \"expectedHeader\": {\n",
188
+ " \"X\": \"/obsm/spatial;0\",\n",
189
+ " \"Y\": \"/obsm/spatial;1\",\n",
190
+ " \"gb_col\": \"/obs/gene\",\n",
191
+ " \"gb_name\": \"\",\n",
192
+ " \"cb_col\": \"\",\n",
193
+ " \"cb_cmap\": \"\",\n",
194
+ " \"scale_factor\": 0.15,\n",
195
+ " \"shape_fixed\": \"disc\",\n",
196
+ " \"opacity\": 0.7,\n",
197
+ " },\n",
198
+ " \"expectedRadios\": {\n",
199
+ " \"cb_col\": False,\n",
200
+ " \"cb_gr\": True,\n",
201
+ " \"cb_gr_rand\": True,\n",
202
+ " \"shape_fixed\": True,\n",
203
+ " \"shape_gr\": False,\n",
204
+ " \"scale_check\": False,\n",
205
+ " \"sortby_check\": False,\n",
206
+ " },\n",
207
+ " },\n",
208
+ ")\n",
209
+ "\n",
210
+ "# Set autoLoad explicitly by name after insert\n",
211
+ "for mf in project[\"markerFiles\"]:\n",
212
+ " if mf.get(\"name\") in (\"Transcript AnnData\", \"Categorical observations\"):\n",
213
+ " mf[\"autoLoad\"] = True\n",
214
+ " else:\n",
215
+ " mf[\"autoLoad\"] = False\n",
216
+ "\n",
217
+ "with open(project_path, \"w\") as f:\n",
218
+ " json.dump(project, f, indent=2)\n",
219
+ "\n",
220
+ "print(\"done\")"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "code",
225
+ "execution_count": null,
226
+ "id": "1ee1ac2d-6de4-4fe2-b31a-90725d67669c",
227
+ "metadata": {},
228
+ "outputs": [],
229
+ "source": [
230
+ "viewer = tj.opentmap(project_path)\n",
231
+ "viewer"
232
+ ]
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "execution_count": null,
237
+ "id": "db4873e9-ba2e-4814-80a9-e32f92a5677a",
238
+ "metadata": {},
239
+ "outputs": [],
240
+ "source": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "execution_count": null,
245
+ "id": "7394d91a-54ad-49b1-834f-bda9f24f4944",
246
+ "metadata": {},
247
+ "outputs": [],
248
+ "source": []
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "execution_count": null,
253
+ "id": "68db233e-7105-4862-9635-c68875497962",
254
+ "metadata": {},
255
+ "outputs": [],
256
+ "source": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": null,
261
+ "id": "4c8a97c2-3285-4b9d-8a6c-7bdb6a89c4a8",
262
+ "metadata": {},
263
+ "outputs": [],
264
+ "source": []
265
+ }
266
+ ],
267
+ "metadata": {
268
+ "kernelspec": {
269
+ "display_name": "Python (tissuumaps_env)",
270
+ "language": "python",
271
+ "name": "tissuumaps_env"
272
+ },
273
+ "language_info": {
274
+ "codemirror_mode": {
275
+ "name": "ipython",
276
+ "version": 3
277
+ },
278
+ "file_extension": ".py",
279
+ "mimetype": "text/x-python",
280
+ "name": "python",
281
+ "nbconvert_exporter": "python",
282
+ "pygments_lexer": "ipython3",
283
+ "version": "3.9.23"
284
+ },
285
+ "widgets": {
286
+ "application/vnd.jupyter.widget-state+json": {
287
+ "state": {},
288
+ "version_major": 2,
289
+ "version_minor": 0
290
+ }
291
+ }
292
+ },
293
+ "nbformat": 4,
294
+ "nbformat_minor": 5
295
+ }
notebooks/.ipynb_checkpoints/vitessce_pre-process-checkpoint.ipynb ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "nbsphinx": "hidden"
7
+ },
8
+ "source": [
9
+ "# Vitessce Widget Tutorial"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "# Visualization of a SpatialData object"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {},
22
+ "source": [
23
+ "## Import dependencies\n"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "import os\n",
33
+ "from os.path import join, isfile, isdir\n",
34
+ "from urllib.request import urlretrieve\n",
35
+ "import zipfile\n",
36
+ "import shutil\n",
37
+ "\n",
38
+ "from vitessce import (\n",
39
+ " VitessceConfig,\n",
40
+ " ViewType as vt,\n",
41
+ " CoordinationType as ct,\n",
42
+ " CoordinationLevel as CL,\n",
43
+ " SpatialDataWrapper,\n",
44
+ " get_initial_coordination_scope_prefix\n",
45
+ ")\n",
46
+ "\n",
47
+ "from vitessce.data_utils import (\n",
48
+ " sdata_morton_sort_points,\n",
49
+ " sdata_points_process_columns,\n",
50
+ " sdata_points_write_bounding_box_attrs,\n",
51
+ " sdata_points_modify_row_group_size,\n",
52
+ " sdata_morton_query_rect,\n",
53
+ ")"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": null,
59
+ "metadata": {},
60
+ "outputs": [],
61
+ "source": [
62
+ "from spatialdata import read_zarr\n",
63
+ "\n",
64
+ "import anndata as ad\n",
65
+ "\n",
66
+ "ad.settings.zarr_write_format = 3\n",
67
+ "print(ad.settings.zarr_write_format)"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": null,
73
+ "metadata": {},
74
+ "outputs": [],
75
+ "source": [
76
+ "import dask\n",
77
+ "import tempfile\n",
78
+ "\n",
79
+ "# Point Dask temp dir to your external drive\n",
80
+ "dask.config.set({'temporary_directory': '/Volumes/T7 Shield/tmp'})\n",
81
+ "\n",
82
+ "# Create the dir if it doesn't exist\n",
83
+ "import os\n",
84
+ "os.makedirs('/Volumes/T7 Shield/tmp', exist_ok=True)"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "execution_count": null,
90
+ "metadata": {},
91
+ "outputs": [],
92
+ "source": [
93
+ "ls"
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "execution_count": null,
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "from pathlib import Path\n",
103
+ "from spatialdata_io import xenium\n",
104
+ "import spatialdata as sd\n",
105
+ "import pandas as pd\n",
106
+ "\n",
107
+ "xenium_dir = Path(\"../data/instrument_data/Xenium_V1_hPancreas_Cancer_Add_on_FFPE_outs/\") # folder containing experiment.xenium\n",
108
+ "out_zarr = Path(\"../data/processed_data/vitessce/Xenium_V1_hPancreas_Cancer_Add_on_FFPE_outs.zarr\")\n",
109
+ "\n",
110
+ "sdata = xenium(\n",
111
+ " xenium_dir,\n",
112
+ " cells_boundaries=True,\n",
113
+ " nucleus_boundaries=True,\n",
114
+ " cells_labels=True,\n",
115
+ " nucleus_labels=True,\n",
116
+ " transcripts=True,\n",
117
+ " morphology_focus=True,\n",
118
+ " aligned_images=True,\n",
119
+ " cells_table=True,\n",
120
+ " gex_only=True,\n",
121
+ ")\n",
122
+ "\n",
123
+ "print(sdata)\n"
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "execution_count": null,
129
+ "metadata": {},
130
+ "outputs": [],
131
+ "source": [
132
+ "# Add cluster labels from Xenium instrument output\n",
133
+ "clusters = pd.read_csv(\n",
134
+ " xenium_dir / \"analysis/clustering/gene_expression_graphclust/clusters.csv\"\n",
135
+ ")\n",
136
+ "sdata.tables[\"table\"].obs = sdata.tables[\"table\"].obs.merge(\n",
137
+ " clusters.set_index(\"Barcode\")[[\"Cluster\"]].rename(columns={\"Cluster\": \"leiden\"}),\n",
138
+ " left_index=True,\n",
139
+ " right_index=True,\n",
140
+ " how=\"left\",\n",
141
+ ")\n",
142
+ "sdata.tables[\"table\"].obs[\"leiden\"] = sdata.tables[\"table\"].obs[\"leiden\"].astype(str)\n"
143
+ ]
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "execution_count": null,
148
+ "metadata": {},
149
+ "outputs": [],
150
+ "source": [
151
+ "# Save as a SpatialData Zarr store\n",
152
+ "sdata.write(out_zarr)\n"
153
+ ]
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": null,
158
+ "metadata": {},
159
+ "outputs": [],
160
+ "source": [
161
+ "sdata[\"transcripts\"].shape[0].compute()"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": null,
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "sdata.tables[\"table\"].X = sdata.tables[\"table\"].X.toarray()\n",
171
+ "sdata.tables[\"dense_table\"] = sdata.tables[\"table\"]\n",
172
+ "sdata.write_element(\"dense_table\")"
173
+ ]
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "execution_count": null,
178
+ "metadata": {},
179
+ "outputs": [],
180
+ "source": [
181
+ "# TODO: store the two separate images as a single image with two channels.\n",
182
+ "# Similar to https://github.com/EricMoerthVis/tissue-map-tools/pull/12"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": null,
188
+ "metadata": {},
189
+ "outputs": [],
190
+ "source": [
191
+ "# sdata.tables['table'].obs"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": null,
197
+ "metadata": {},
198
+ "outputs": [],
199
+ "source": [
200
+ "# sdata"
201
+ ]
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "execution_count": null,
206
+ "metadata": {},
207
+ "outputs": [],
208
+ "source": [
209
+ "# sdata.points['transcripts'].head()"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "markdown",
214
+ "metadata": {},
215
+ "source": [
216
+ "## Sorting Points and creating a new Points element in the SpatialData object"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "markdown",
221
+ "metadata": {},
222
+ "source": [
223
+ "### Step 1. Sort rows with `sdata_morton_sort_points`"
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "execution_count": null,
229
+ "metadata": {},
230
+ "outputs": [],
231
+ "source": [
232
+ "import importlib.metadata\n",
233
+ "print(importlib.metadata.version(\"vitessce\"))"
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "execution_count": null,
239
+ "metadata": {},
240
+ "outputs": [],
241
+ "source": [
242
+ "# sdata = sdata_morton_sort_points(sdata, \"transcripts\")\n",
243
+ "from vitessce.data_utils.spatialdata_points_zorder import norm_ddf_to_uint, morton_interleave\n",
244
+ "\n",
245
+ "element = \"transcripts\"\n",
246
+ "ddf = sdata.points[element]\n",
247
+ "attrs = ddf.attrs.copy()\n",
248
+ "\n",
249
+ "ddf = norm_ddf_to_uint(ddf)\n",
250
+ "ddf[\"morton_code_2d\"] = morton_interleave(ddf)\n",
251
+ "sorted_ddf = ddf.sort_values(by=\"morton_code_2d\", ascending=True)\n",
252
+ "sorted_ddf.attrs.update(attrs)\n",
253
+ "sdata.points[element] = sorted_ddf"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "markdown",
258
+ "metadata": {},
259
+ "source": [
260
+ "### Step 2. Clean up columns with `sdata_points_process_columns`"
261
+ ]
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "execution_count": null,
266
+ "metadata": {},
267
+ "outputs": [],
268
+ "source": [
269
+ "# Add feature_index column to dataframe, and reorder columns so that feature_name (dict column) is the rightmost column.\n",
270
+ "ddf = sdata_points_process_columns(sdata, \"transcripts\", var_name_col=\"feature_name\", table_name=\"table\")"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "execution_count": null,
276
+ "metadata": {},
277
+ "outputs": [],
278
+ "source": [
279
+ "# ddf.head()"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "markdown",
284
+ "metadata": {},
285
+ "source": [
286
+ "### Step 3. Save sorted dataframe to new Points element"
287
+ ]
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "execution_count": null,
292
+ "metadata": {},
293
+ "outputs": [],
294
+ "source": [
295
+ "# sdata[\"transcripts_with_morton_codes\"] = ddf\n",
296
+ "# sdata.write_element(\"transcripts_with_morton_codes\")\n",
297
+ "\n",
298
+ "from spatialdata.models import PointsModel\n",
299
+ "\n",
300
+ "transformations = sdata[\"transcripts\"].attrs[\"transform\"]\n",
301
+ "del ddf.attrs[\"transform\"]\n",
302
+ "\n",
303
+ "sdata[\"transcripts_with_morton_codes\"] = PointsModel.parse(\n",
304
+ " ddf, feature_key=\"feature_name\", instance_key=\"cell_id\", transformations=transformations\n",
305
+ ")\n",
306
+ "sdata.write_element(\"transcripts_with_morton_codes\")"
307
+ ]
308
+ },
309
+ {
310
+ "cell_type": "markdown",
311
+ "metadata": {},
312
+ "source": [
313
+ "### Step 4. Write bounding box metadata with `sdata_points_write_bounding_box_attrs`"
314
+ ]
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "execution_count": null,
319
+ "metadata": {},
320
+ "outputs": [],
321
+ "source": [
322
+ "import shutil\n",
323
+ "import os\n",
324
+ "\n",
325
+ "tmp_dir = '/Volumes/T7 Shield/tmp'\n",
326
+ "shutil.rmtree(tmp_dir)\n",
327
+ "os.makedirs(tmp_dir)\n",
328
+ "print(\"Done\")"
329
+ ]
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "execution_count": null,
334
+ "metadata": {},
335
+ "outputs": [],
336
+ "source": [
337
+ "sdata_points_write_bounding_box_attrs(sdata, \"transcripts_with_morton_codes\")"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "metadata": {},
343
+ "source": [
344
+ "### Step 5. Modify the row group sizes of the Parquet files with `sdata_points_modify_row_group_size`"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": null,
350
+ "metadata": {},
351
+ "outputs": [],
352
+ "source": [
353
+ "import shutil\n",
354
+ "import os\n",
355
+ "\n",
356
+ "tmp_dir = '/Volumes/T7 Shield/tmp'\n",
357
+ "shutil.rmtree(tmp_dir)\n",
358
+ "os.makedirs(tmp_dir)\n",
359
+ "print(\"Done\")"
360
+ ]
361
+ },
362
+ {
363
+ "cell_type": "code",
364
+ "execution_count": null,
365
+ "metadata": {},
366
+ "outputs": [],
367
+ "source": [
368
+ "sdata_points_modify_row_group_size(sdata, \"transcripts_with_morton_codes\", row_group_size=25_000)"
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "code",
373
+ "execution_count": null,
374
+ "metadata": {},
375
+ "outputs": [],
376
+ "source": [
377
+ "# Done"
378
+ ]
379
+ },
380
+ {
381
+ "cell_type": "code",
382
+ "execution_count": null,
383
+ "metadata": {},
384
+ "outputs": [],
385
+ "source": [
386
+ "# Optionally, check the number of row groups in one of the parquet file parts.\n",
387
+ "import pyarrow.parquet as pq\n",
388
+ "from os.path import join\n",
389
+ "\n",
390
+ "parquet_file = pq.ParquetFile(join(sdata.path, \"points\", \"transcripts_with_morton_codes\", \"points.parquet\", \"part.0.parquet\"))\n",
391
+ "\n",
392
+ "# Get the number of row groups in this part-0 file.\n",
393
+ "num_groups = parquet_file.num_row_groups\n",
394
+ "num_groups"
395
+ ]
396
+ },
397
+ {
398
+ "cell_type": "code",
399
+ "execution_count": null,
400
+ "metadata": {},
401
+ "outputs": [],
402
+ "source": []
403
+ }
404
+ ],
405
+ "metadata": {
406
+ "kernelspec": {
407
+ "display_name": "Python 3 (ipykernel)",
408
+ "language": "python",
409
+ "name": "python3"
410
+ },
411
+ "language_info": {
412
+ "codemirror_mode": {
413
+ "name": "ipython",
414
+ "version": 3
415
+ },
416
+ "file_extension": ".py",
417
+ "mimetype": "text/x-python",
418
+ "name": "python",
419
+ "nbconvert_exporter": "python",
420
+ "pygments_lexer": "ipython3",
421
+ "version": "3.12.1"
422
+ },
423
+ "widgets": {
424
+ "application/vnd.jupyter.widget-state+json": {
425
+ "state": {
426
+ "undefined": {
427
+ "model_module": "anywidget",
428
+ "model_module_version": "2.0.0",
429
+ "model_name": "AnyModel",
430
+ "state": {
431
+ "_view_name": "ErrorWidgetView",
432
+ "error": {},
433
+ "msg": "Model class 'AnyModel' from module 'anywidget' is loaded but can not be instantiated"
434
+ }
435
+ }
436
+ },
437
+ "version_major": 2,
438
+ "version_minor": 0
439
+ }
440
+ }
441
+ },
442
+ "nbformat": 4,
443
+ "nbformat_minor": 4
444
+ }
notebooks/.ipynb_checkpoints/vitessce_viz-checkpoint.ipynb ADDED
@@ -0,0 +1,1133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "nbsphinx": "hidden"
7
+ },
8
+ "source": [
9
+ "# Vitessce Widget Tutorial"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "# Visualization of a SpatialData object"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {},
22
+ "source": [
23
+ "## Import dependencies\n"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "import os\n",
33
+ "from os.path import join, isfile, isdir\n",
34
+ "from urllib.request import urlretrieve\n",
35
+ "import zipfile\n",
36
+ "import shutil\n",
37
+ "\n",
38
+ "from vitessce import (\n",
39
+ " VitessceConfig,\n",
40
+ " ViewType as vt,\n",
41
+ " CoordinationType as ct,\n",
42
+ " CoordinationLevel as CL,\n",
43
+ " SpatialDataWrapper,\n",
44
+ " get_initial_coordination_scope_prefix\n",
45
+ ")\n",
46
+ "\n",
47
+ "from vitessce.data_utils import (\n",
48
+ " sdata_morton_sort_points,\n",
49
+ " sdata_points_process_columns,\n",
50
+ " sdata_points_write_bounding_box_attrs,\n",
51
+ " sdata_points_modify_row_group_size,\n",
52
+ " sdata_morton_query_rect,\n",
53
+ ")"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": null,
59
+ "metadata": {},
60
+ "outputs": [],
61
+ "source": [
62
+ "from pathlib import Path\n",
63
+ "from spatialdata_io import xenium\n",
64
+ "import spatialdata as sd\n",
65
+ "import pandas as pd"
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "execution_count": null,
71
+ "metadata": {},
72
+ "outputs": [],
73
+ "source": [
74
+ "from spatialdata import read_zarr\n",
75
+ "\n",
76
+ "import anndata as ad\n",
77
+ "\n",
78
+ "ad.settings.zarr_write_format = 3\n",
79
+ "print(ad.settings.zarr_write_format)"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": null,
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "ls"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "markdown",
93
+ "metadata": {},
94
+ "source": [
95
+ "## Configure Vitessce\n",
96
+ "\n",
97
+ "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."
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": null,
103
+ "metadata": {},
104
+ "outputs": [],
105
+ "source": [
106
+ "# out_zarr = \"../data/processed_data/vitessce/WTA_Preview_FFPE_Cervical_Cancer_outs.zarr\"\n",
107
+ "# out_zarr = \"../data/processed_data/vitessce/Xenium_Prime_Human_Lymph_Node_Reactive_FFPE_outs.zarr\"\n",
108
+ "# out_zarr = \"../data/processed_data/vitessce/Xenium_Prime_Ovarian_Cancer_FFPE_XRrun_outs.zarr\"\n",
109
+ "out_zarr = \"../data/processed_data/vitessce/Xenium_V1_humanLung_Cancer_FFPE_outs.zarr\""
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "execution_count": null,
115
+ "metadata": {},
116
+ "outputs": [],
117
+ "source": [
118
+ "vc = VitessceConfig(\n",
119
+ " schema_version=\"1.0.18\",\n",
120
+ " name='Xenium SpatialData Demo',\n",
121
+ ")\n",
122
+ "\n",
123
+ "# Cell segmentations + gene expression\n",
124
+ "wrapper = SpatialDataWrapper(\n",
125
+ " sdata_path=out_zarr,\n",
126
+ " image_path=\"images/morphology_focus\",\n",
127
+ " table_path=\"tables/table\",\n",
128
+ " obs_feature_matrix_path=\"tables/table/X\",\n",
129
+ " obs_segmentations_path=\"shapes/cell_boundaries\",\n",
130
+ " # obs_set_paths=[\"tables/table/obs/leiden\"],\n",
131
+ " # obs_set_names=[\"Cluster\"],\n",
132
+ " coordinate_system=\"global\",\n",
133
+ " coordination_values={\n",
134
+ " \"obsType\": \"cell\",\n",
135
+ " }\n",
136
+ ")\n",
137
+ "\n",
138
+ "# Transcripts\n",
139
+ "points_wrapper = SpatialDataWrapper(\n",
140
+ " sdata_path=out_zarr,\n",
141
+ " obs_points_path=\"points/transcripts_with_morton_codes\",\n",
142
+ " obs_feature_matrix_path=\"tables/dense_table/X\",\n",
143
+ " coordinate_system=\"global\",\n",
144
+ " coordination_values={\n",
145
+ " \"obsType\": \"point\",\n",
146
+ " \"featureType\": \"gene\",\n",
147
+ " }\n",
148
+ ")\n",
149
+ "\n",
150
+ "dataset = vc.add_dataset(name='Xenium').add_object(wrapper).add_object(points_wrapper)\n",
151
+ "\n",
152
+ "spatial = vc.add_view(\"spatialBeta\", dataset=dataset)\n",
153
+ "feature_list = vc.add_view(\"featureList\", dataset=dataset)\n",
154
+ "layer_controller = vc.add_view(\"layerControllerBeta\", dataset=dataset)\n",
155
+ "obs_sets = vc.add_view(\"obsSets\", dataset=dataset)\n",
156
+ "\n",
157
+ "vc.link_views_by_dict([spatial, layer_controller], {\n",
158
+ " 'segmentationLayer': CL([{\n",
159
+ " 'segmentationChannel': CL([{\n",
160
+ " 'obsType': 'cell',\n",
161
+ " # 'obsColorEncoding': 'cellSetSelection', # <-- this makes it default to cluster colors\n",
162
+ " }]),\n",
163
+ " }]),\n",
164
+ "}, scope_prefix=get_initial_coordination_scope_prefix(\"A\", \"obsSegmentations\"))\n",
165
+ "\n",
166
+ "vc.link_views_by_dict([spatial, layer_controller], {\n",
167
+ " 'pointLayer': CL([{\n",
168
+ " 'obsType': 'point',\n",
169
+ " }]),\n",
170
+ "}, scope_prefix=get_initial_coordination_scope_prefix(\"A\", \"obsPoints\"))\n",
171
+ "\n",
172
+ "vc.link_views([spatial, layer_controller, feature_list, obs_sets], ['obsType'], [wrapper.obs_type_label])\n",
173
+ "\n",
174
+ "# vc.layout(spatial | (feature_list / layer_controller / obs_sets))\n",
175
+ "vc.layout(spatial)\n"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "markdown",
180
+ "metadata": {},
181
+ "source": [
182
+ "### Render the widget"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": null,
188
+ "metadata": {},
189
+ "outputs": [],
190
+ "source": [
191
+ "vw = vc.widget()\n",
192
+ "vw"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "execution_count": null,
198
+ "metadata": {},
199
+ "outputs": [],
200
+ "source": []
201
+ }
202
+ ],
203
+ "metadata": {
204
+ "kernelspec": {
205
+ "display_name": "Python 3 (ipykernel)",
206
+ "language": "python",
207
+ "name": "python3"
208
+ },
209
+ "language_info": {
210
+ "codemirror_mode": {
211
+ "name": "ipython",
212
+ "version": 3
213
+ },
214
+ "file_extension": ".py",
215
+ "mimetype": "text/x-python",
216
+ "name": "python",
217
+ "nbconvert_exporter": "python",
218
+ "pygments_lexer": "ipython3",
219
+ "version": "3.12.1"
220
+ },
221
+ "widgets": {
222
+ "application/vnd.jupyter.widget-state+json": {
223
+ "state": {
224
+ "8fa17251e5d6449a84f5cbc270c6674d": {
225
+ "model_module": "anywidget",
226
+ "model_module_version": "2.0.0",
227
+ "model_name": "AnyModel",
228
+ "state": {
229
+ "_anywidget_id": "vitessce.widget.VitessceWidget",
230
+ "_config": {
231
+ "coordinationSpace": {
232
+ "additionalObsSets": {
233
+ "A": null
234
+ },
235
+ "dataset": {
236
+ "A": "A",
237
+ "init_A_image_0": "init_A_image_0",
238
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
239
+ },
240
+ "featureAggregationStrategy": {
241
+ "A": null,
242
+ "B": null
243
+ },
244
+ "featureColor": {
245
+ "A": null
246
+ },
247
+ "featureFilter": {
248
+ "A": null
249
+ },
250
+ "featureFilterMode": {
251
+ "A": null
252
+ },
253
+ "featureHighlight": {
254
+ "A": null
255
+ },
256
+ "featureSelection": {
257
+ "A": null
258
+ },
259
+ "featureType": {
260
+ "A": "gene"
261
+ },
262
+ "featureValueColormap": {
263
+ "A": "plasma",
264
+ "init_A_obsSegmentations_0": "plasma"
265
+ },
266
+ "featureValueColormapRange": {
267
+ "A": [
268
+ 0,
269
+ 1
270
+ ]
271
+ },
272
+ "featureValueType": {
273
+ "A": "expression"
274
+ },
275
+ "fileUid": {
276
+ "A": null,
277
+ "init_A_image_0": null,
278
+ "init_A_obsSegmentations_0": null
279
+ },
280
+ "imageChannel": {
281
+ "A": null,
282
+ "init_A_image_0": "__dummy__",
283
+ "init_A_image_1": "__dummy__",
284
+ "init_A_image_2": "__dummy__",
285
+ "init_A_image_3": "__dummy__"
286
+ },
287
+ "imageLayer": {
288
+ "A": null,
289
+ "init_A_image_0": "__dummy__"
290
+ },
291
+ "legendVisible": {
292
+ "A": true
293
+ },
294
+ "metaCoordinationScopes": {
295
+ "init_A_image_0": {
296
+ "imageLayer": [
297
+ "init_A_image_0"
298
+ ],
299
+ "spatialImageLayer": "init_A_image_0",
300
+ "spatialTargetT": "init_A_image_0",
301
+ "spatialTargetZ": "init_A_image_0"
302
+ },
303
+ "init_A_obsPoints_0": {
304
+ "pointLayer": [
305
+ "init_A_obsPoints_0"
306
+ ]
307
+ },
308
+ "init_A_obsSegmentations_0": {
309
+ "segmentationLayer": [
310
+ "init_A_obsSegmentations_0"
311
+ ]
312
+ }
313
+ },
314
+ "metaCoordinationScopesBy": {
315
+ "init_A_image_0": {
316
+ "imageChannel": {
317
+ "spatialChannelColor": {
318
+ "init_A_image_0": "init_A_image_0",
319
+ "init_A_image_1": "init_A_image_1",
320
+ "init_A_image_2": "init_A_image_2",
321
+ "init_A_image_3": "init_A_image_3"
322
+ },
323
+ "spatialChannelOpacity": {
324
+ "init_A_image_0": "init_A_image_0",
325
+ "init_A_image_1": "init_A_image_1",
326
+ "init_A_image_2": "init_A_image_2",
327
+ "init_A_image_3": "init_A_image_3"
328
+ },
329
+ "spatialChannelVisible": {
330
+ "init_A_image_0": "init_A_image_0",
331
+ "init_A_image_1": "init_A_image_1",
332
+ "init_A_image_2": "init_A_image_2",
333
+ "init_A_image_3": "init_A_image_3"
334
+ },
335
+ "spatialChannelWindow": {
336
+ "init_A_image_0": "init_A_image_0",
337
+ "init_A_image_1": "init_A_image_1",
338
+ "init_A_image_2": "init_A_image_2",
339
+ "init_A_image_3": "init_A_image_3"
340
+ },
341
+ "spatialTargetC": {
342
+ "init_A_image_0": "init_A_image_0",
343
+ "init_A_image_1": "init_A_image_1",
344
+ "init_A_image_2": "init_A_image_2",
345
+ "init_A_image_3": "init_A_image_3"
346
+ }
347
+ },
348
+ "imageLayer": {
349
+ "fileUid": {
350
+ "init_A_image_0": "init_A_image_0"
351
+ },
352
+ "imageChannel": {
353
+ "init_A_image_0": [
354
+ "init_A_image_0",
355
+ "init_A_image_1",
356
+ "init_A_image_2",
357
+ "init_A_image_3"
358
+ ]
359
+ },
360
+ "photometricInterpretation": {
361
+ "init_A_image_0": "init_A_image_0"
362
+ },
363
+ "spatialLayerOpacity": {
364
+ "init_A_image_0": "init_A_image_0"
365
+ },
366
+ "spatialLayerVisible": {
367
+ "init_A_image_0": "init_A_image_0"
368
+ },
369
+ "spatialTargetResolution": {
370
+ "init_A_image_0": "init_A_image_0"
371
+ },
372
+ "volumetricRenderingAlgorithm": {
373
+ "init_A_image_0": "init_A_image_0"
374
+ }
375
+ }
376
+ },
377
+ "init_A_obsPoints_0": {
378
+ "pointLayer": {
379
+ "obsType": {
380
+ "init_A_obsPoints_0": "init_A_obsPoints_0"
381
+ }
382
+ }
383
+ },
384
+ "init_A_obsSegmentations_0": {
385
+ "segmentationChannel": {
386
+ "featureValueColormap": {
387
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
388
+ },
389
+ "obsColorEncoding": {
390
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
391
+ },
392
+ "obsHighlight": {
393
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
394
+ },
395
+ "obsType": {
396
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
397
+ },
398
+ "spatialChannelColor": {
399
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
400
+ },
401
+ "spatialChannelOpacity": {
402
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
403
+ },
404
+ "spatialChannelVisible": {
405
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
406
+ },
407
+ "spatialChannelWindow": {
408
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
409
+ },
410
+ "spatialSegmentationFilled": {
411
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
412
+ },
413
+ "spatialSegmentationStrokeWidth": {
414
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
415
+ }
416
+ },
417
+ "segmentationLayer": {
418
+ "fileUid": {
419
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
420
+ },
421
+ "segmentationChannel": {
422
+ "init_A_obsSegmentations_0": [
423
+ "init_A_obsSegmentations_0"
424
+ ]
425
+ },
426
+ "spatialLayerOpacity": {
427
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
428
+ },
429
+ "spatialLayerVisible": {
430
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
431
+ }
432
+ }
433
+ }
434
+ },
435
+ "moleculeHighlight": {
436
+ "A": null
437
+ },
438
+ "obsColorEncoding": {
439
+ "A": "cellSetSelection",
440
+ "init_A_obsSegmentations_0": "spatialChannelColor"
441
+ },
442
+ "obsFilter": {
443
+ "A": null
444
+ },
445
+ "obsHighlight": {
446
+ "A": null,
447
+ "init_A_obsSegmentations_0": null
448
+ },
449
+ "obsLabelsType": {
450
+ "A": null
451
+ },
452
+ "obsSetColor": {
453
+ "A": null
454
+ },
455
+ "obsSetExpansion": {
456
+ "A": null
457
+ },
458
+ "obsSetFilter": {
459
+ "A": null
460
+ },
461
+ "obsSetHighlight": {
462
+ "A": null
463
+ },
464
+ "obsSetSelection": {
465
+ "A": null
466
+ },
467
+ "obsType": {
468
+ "A": "cell",
469
+ "init_A_obsPoints_0": "point",
470
+ "init_A_obsSegmentations_0": "cell"
471
+ },
472
+ "photometricInterpretation": {
473
+ "A": null,
474
+ "init_A_image_0": "BlackIsZero"
475
+ },
476
+ "pixelHighlight": {
477
+ "A": null
478
+ },
479
+ "pointLayer": {
480
+ "A": null,
481
+ "init_A_obsPoints_0": "__dummy__"
482
+ },
483
+ "segmentationChannel": {
484
+ "A": null,
485
+ "init_A_obsSegmentations_0": "__dummy__"
486
+ },
487
+ "segmentationLayer": {
488
+ "A": null,
489
+ "init_A_obsSegmentations_0": "__dummy__"
490
+ },
491
+ "spatialAxisFixed": {
492
+ "A": false
493
+ },
494
+ "spatialChannelColor": {
495
+ "A": [
496
+ 255,
497
+ 255,
498
+ 255
499
+ ],
500
+ "init_A_image_0": [
501
+ 0,
502
+ 0,
503
+ 255
504
+ ],
505
+ "init_A_image_1": [
506
+ 0,
507
+ 255,
508
+ 0
509
+ ],
510
+ "init_A_image_2": [
511
+ 255,
512
+ 0,
513
+ 255
514
+ ],
515
+ "init_A_image_3": [
516
+ 255,
517
+ 255,
518
+ 0
519
+ ],
520
+ "init_A_obsSegmentations_0": [
521
+ 255,
522
+ 255,
523
+ 255
524
+ ]
525
+ },
526
+ "spatialChannelLabelSize": {
527
+ "A": 14
528
+ },
529
+ "spatialChannelLabelsOrientation": {
530
+ "A": "vertical"
531
+ },
532
+ "spatialChannelLabelsVisible": {
533
+ "A": true
534
+ },
535
+ "spatialChannelOpacity": {
536
+ "A": 1,
537
+ "init_A_image_0": 1,
538
+ "init_A_image_1": 1,
539
+ "init_A_image_2": 1,
540
+ "init_A_image_3": 1,
541
+ "init_A_obsSegmentations_0": 1
542
+ },
543
+ "spatialChannelVisible": {
544
+ "A": true,
545
+ "init_A_image_0": true,
546
+ "init_A_image_1": true,
547
+ "init_A_image_2": true,
548
+ "init_A_image_3": true,
549
+ "init_A_obsSegmentations_0": true
550
+ },
551
+ "spatialChannelWindow": {
552
+ "A": null,
553
+ "init_A_image_0": [
554
+ 0,
555
+ 8339
556
+ ],
557
+ "init_A_image_1": [
558
+ 0,
559
+ 8617
560
+ ],
561
+ "init_A_image_2": [
562
+ 0,
563
+ 10931
564
+ ],
565
+ "init_A_image_3": [
566
+ 0,
567
+ 10716
568
+ ],
569
+ "init_A_obsSegmentations_0": null
570
+ },
571
+ "spatialImageLayer": {
572
+ "init_A_image_0": [
573
+ {
574
+ "channels": [
575
+ {
576
+ "color": [
577
+ 255,
578
+ 255,
579
+ 255
580
+ ],
581
+ "selection": {
582
+ "c": 0
583
+ },
584
+ "slider": [
585
+ 0,
586
+ 255
587
+ ],
588
+ "visible": true
589
+ },
590
+ {
591
+ "color": [
592
+ 255,
593
+ 255,
594
+ 255
595
+ ],
596
+ "selection": {
597
+ "c": 1
598
+ },
599
+ "slider": [
600
+ 0,
601
+ 255
602
+ ],
603
+ "visible": true
604
+ },
605
+ {
606
+ "color": [
607
+ 255,
608
+ 255,
609
+ 255
610
+ ],
611
+ "selection": {
612
+ "c": 2
613
+ },
614
+ "slider": [
615
+ 0,
616
+ 255
617
+ ],
618
+ "visible": true
619
+ },
620
+ {
621
+ "color": [
622
+ 255,
623
+ 255,
624
+ 255
625
+ ],
626
+ "selection": {
627
+ "c": 3
628
+ },
629
+ "slider": [
630
+ 0,
631
+ 255
632
+ ],
633
+ "visible": true
634
+ }
635
+ ],
636
+ "colormap": null,
637
+ "domainType": "Min/Max",
638
+ "index": 0,
639
+ "modelMatrix": [
640
+ 1,
641
+ 0,
642
+ 0,
643
+ 0,
644
+ 0,
645
+ 1,
646
+ 0,
647
+ 0,
648
+ 0,
649
+ 0,
650
+ 1,
651
+ 0,
652
+ 0,
653
+ 0,
654
+ 0,
655
+ 1
656
+ ],
657
+ "opacity": 1,
658
+ "renderingMode": "Additive",
659
+ "transparentColor": null,
660
+ "type": "raster",
661
+ "use3d": false,
662
+ "visible": true
663
+ }
664
+ ]
665
+ },
666
+ "spatialLayerColor": {
667
+ "A": null
668
+ },
669
+ "spatialLayerColormap": {
670
+ "A": null
671
+ },
672
+ "spatialLayerModelMatrix": {
673
+ "A": null
674
+ },
675
+ "spatialLayerOpacity": {
676
+ "A": 1,
677
+ "init_A_image_0": 1,
678
+ "init_A_obsSegmentations_0": 1
679
+ },
680
+ "spatialLayerTransparentColor": {
681
+ "A": null
682
+ },
683
+ "spatialLayerVisible": {
684
+ "A": true,
685
+ "init_A_image_0": true,
686
+ "init_A_obsSegmentations_0": true
687
+ },
688
+ "spatialMaxResolution": {
689
+ "A": null
690
+ },
691
+ "spatialNeighborhoodLayer": {
692
+ "A": null
693
+ },
694
+ "spatialOrbitAxis": {
695
+ "A": "Y",
696
+ "B": "Y"
697
+ },
698
+ "spatialPointLayer": {
699
+ "A": null
700
+ },
701
+ "spatialPointStrokeWidth": {
702
+ "A": 0
703
+ },
704
+ "spatialRenderingMode": {
705
+ "A": "2D"
706
+ },
707
+ "spatialRotation": {
708
+ "A": 0
709
+ },
710
+ "spatialRotationOrbit": {
711
+ "A": 0,
712
+ "B": 0
713
+ },
714
+ "spatialRotationX": {
715
+ "A": 0,
716
+ "B": 0
717
+ },
718
+ "spatialRotationY": {
719
+ "A": 0,
720
+ "B": 0
721
+ },
722
+ "spatialRotationZ": {
723
+ "A": 0,
724
+ "B": 0
725
+ },
726
+ "spatialSegmentationFilled": {
727
+ "A": true,
728
+ "init_A_obsSegmentations_0": true
729
+ },
730
+ "spatialSegmentationStrokeWidth": {
731
+ "A": 1,
732
+ "init_A_obsSegmentations_0": 1
733
+ },
734
+ "spatialSliceX": {
735
+ "A": null
736
+ },
737
+ "spatialSliceY": {
738
+ "A": null
739
+ },
740
+ "spatialSliceZ": {
741
+ "A": null
742
+ },
743
+ "spatialSpotFilled": {
744
+ "A": true
745
+ },
746
+ "spatialSpotRadius": {
747
+ "A": 25
748
+ },
749
+ "spatialSpotStrokeWidth": {
750
+ "A": 1
751
+ },
752
+ "spatialTargetC": {
753
+ "A": null,
754
+ "init_A_image_0": 0,
755
+ "init_A_image_1": 1,
756
+ "init_A_image_2": 2,
757
+ "init_A_image_3": 3
758
+ },
759
+ "spatialTargetResolution": {
760
+ "A": 0,
761
+ "init_A_image_0": null
762
+ },
763
+ "spatialTargetT": {
764
+ "A": null,
765
+ "init_A_image_0": 0
766
+ },
767
+ "spatialTargetX": {
768
+ "A": null,
769
+ "B": null
770
+ },
771
+ "spatialTargetY": {
772
+ "A": null,
773
+ "B": null
774
+ },
775
+ "spatialTargetZ": {
776
+ "A": null,
777
+ "B": null,
778
+ "init_A_image_0": null
779
+ },
780
+ "spatialZoom": {
781
+ "A": null,
782
+ "B": null
783
+ },
784
+ "spotLayer": {
785
+ "A": null
786
+ },
787
+ "tooltipCrosshairsVisible": {
788
+ "A": true
789
+ },
790
+ "tooltipsVisible": {
791
+ "A": true
792
+ },
793
+ "volumetricRenderingAlgorithm": {
794
+ "A": "additive",
795
+ "init_A_image_0": "maximumIntensityProjection"
796
+ }
797
+ },
798
+ "datasets": [
799
+ {
800
+ "files": [
801
+ {
802
+ "coordinationValues": {
803
+ "featureType": "gene",
804
+ "featureValueType": "expression",
805
+ "obsType": "cell"
806
+ },
807
+ "fileType": "obsFeatureMatrix.spatialdata.zarr",
808
+ "options": {
809
+ "path": "tables/table/X"
810
+ },
811
+ "url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
812
+ },
813
+ {
814
+ "coordinationValues": {
815
+ "featureType": "gene"
816
+ },
817
+ "fileType": "image.spatialdata.zarr",
818
+ "options": {
819
+ "coordinateSystem": "global",
820
+ "path": "images/morphology_focus"
821
+ },
822
+ "url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
823
+ },
824
+ {
825
+ "coordinationValues": {
826
+ "obsType": "cell"
827
+ },
828
+ "fileType": "shapes.spatialdata.zarr",
829
+ "options": {
830
+ "coordinateSystem": "global",
831
+ "path": "shapes/cell_boundaries",
832
+ "tablePath": "tables/table"
833
+ },
834
+ "url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
835
+ },
836
+ {
837
+ "coordinationValues": {
838
+ "featureType": "gene",
839
+ "featureValueType": "expression",
840
+ "obsType": "point"
841
+ },
842
+ "fileType": "obsFeatureMatrix.spatialdata.zarr",
843
+ "options": {
844
+ "path": "tables/dense_table/X"
845
+ },
846
+ "url": "http://localhost:8000/A/1/afd11240-c386-4fe7-8bfd-f77a5138e9bc.sdata.zarr"
847
+ },
848
+ {
849
+ "coordinationValues": {
850
+ "obsType": "point"
851
+ },
852
+ "fileType": "obsPoints.spatialdata.zarr",
853
+ "options": {
854
+ "coordinateSystem": "global",
855
+ "path": "points/transcripts_with_morton_codes",
856
+ "tablePath": "tables/table"
857
+ },
858
+ "url": "http://localhost:8000/A/1/afd11240-c386-4fe7-8bfd-f77a5138e9bc.sdata.zarr"
859
+ }
860
+ ],
861
+ "name": "Xenium",
862
+ "uid": "A"
863
+ }
864
+ ],
865
+ "description": "",
866
+ "initStrategy": "auto",
867
+ "layout": [
868
+ {
869
+ "component": "spatialBeta",
870
+ "coordinationScopes": {
871
+ "additionalObsSets": "A",
872
+ "dataset": "A",
873
+ "featureAggregationStrategy": "A",
874
+ "featureColor": "A",
875
+ "featureFilterMode": "A",
876
+ "featureHighlight": "A",
877
+ "featureSelection": "A",
878
+ "featureType": "A",
879
+ "featureValueColormap": "A",
880
+ "featureValueColormapRange": "A",
881
+ "featureValueType": "A",
882
+ "fileUid": "A",
883
+ "imageChannel": "A",
884
+ "imageLayer": "A",
885
+ "legendVisible": "A",
886
+ "metaCoordinationScopes": [
887
+ "init_A_image_0",
888
+ "init_A_obsSegmentations_0",
889
+ "init_A_obsSegmentations_0",
890
+ "init_A_obsPoints_0"
891
+ ],
892
+ "metaCoordinationScopesBy": [
893
+ "init_A_image_0",
894
+ "init_A_obsSegmentations_0",
895
+ "init_A_obsSegmentations_0",
896
+ "init_A_obsPoints_0"
897
+ ],
898
+ "moleculeHighlight": "A",
899
+ "obsColorEncoding": "A",
900
+ "obsFilter": "A",
901
+ "obsHighlight": "A",
902
+ "obsLabelsType": "A",
903
+ "obsSetColor": "A",
904
+ "obsSetFilter": "A",
905
+ "obsSetHighlight": "A",
906
+ "obsSetSelection": "A",
907
+ "obsType": "A",
908
+ "photometricInterpretation": "A",
909
+ "pixelHighlight": "A",
910
+ "pointLayer": "A",
911
+ "segmentationChannel": "A",
912
+ "segmentationLayer": "A",
913
+ "spatialAxisFixed": "A",
914
+ "spatialChannelColor": "A",
915
+ "spatialChannelLabelSize": "A",
916
+ "spatialChannelLabelsOrientation": "A",
917
+ "spatialChannelLabelsVisible": "A",
918
+ "spatialChannelOpacity": "A",
919
+ "spatialChannelVisible": "A",
920
+ "spatialChannelWindow": "A",
921
+ "spatialLayerColor": "A",
922
+ "spatialLayerColormap": "A",
923
+ "spatialLayerModelMatrix": "A",
924
+ "spatialLayerOpacity": "A",
925
+ "spatialLayerTransparentColor": "A",
926
+ "spatialLayerVisible": "A",
927
+ "spatialMaxResolution": "A",
928
+ "spatialNeighborhoodLayer": "A",
929
+ "spatialOrbitAxis": "A",
930
+ "spatialPointLayer": "A",
931
+ "spatialRenderingMode": "A",
932
+ "spatialRotation": "A",
933
+ "spatialRotationOrbit": "A",
934
+ "spatialRotationX": "A",
935
+ "spatialRotationY": "A",
936
+ "spatialRotationZ": "A",
937
+ "spatialSegmentationFilled": "A",
938
+ "spatialSegmentationStrokeWidth": "A",
939
+ "spatialSliceX": "A",
940
+ "spatialSliceY": "A",
941
+ "spatialSliceZ": "A",
942
+ "spatialSpotFilled": "A",
943
+ "spatialSpotRadius": "A",
944
+ "spatialSpotStrokeWidth": "A",
945
+ "spatialTargetC": "A",
946
+ "spatialTargetResolution": "A",
947
+ "spatialTargetT": "A",
948
+ "spatialTargetX": "A",
949
+ "spatialTargetY": "A",
950
+ "spatialTargetZ": "A",
951
+ "spatialZoom": "A",
952
+ "spotLayer": "A",
953
+ "tooltipCrosshairsVisible": "A",
954
+ "tooltipsVisible": "A",
955
+ "volumetricRenderingAlgorithm": "A"
956
+ },
957
+ "h": 12,
958
+ "uid": "A",
959
+ "w": 12,
960
+ "x": 0,
961
+ "y": 0
962
+ },
963
+ {
964
+ "component": "featureList",
965
+ "coordinationScopes": {
966
+ "dataset": "A",
967
+ "featureFilter": "A",
968
+ "featureHighlight": "A",
969
+ "featureSelection": "A",
970
+ "featureType": "A",
971
+ "featureValueType": "A",
972
+ "obsColorEncoding": "A",
973
+ "obsSetSelection": "A",
974
+ "obsType": "A"
975
+ },
976
+ "h": 1,
977
+ "uid": "B",
978
+ "w": 1,
979
+ "x": 0,
980
+ "y": 0
981
+ },
982
+ {
983
+ "component": "layerControllerBeta",
984
+ "coordinationScopes": {
985
+ "dataset": "A",
986
+ "featureAggregationStrategy": "B",
987
+ "featureColor": "A",
988
+ "featureFilterMode": "A",
989
+ "featureSelection": "A",
990
+ "featureType": "A",
991
+ "featureValueColormap": "A",
992
+ "featureValueColormapRange": "A",
993
+ "featureValueType": "A",
994
+ "fileUid": "A",
995
+ "imageChannel": "A",
996
+ "imageLayer": "A",
997
+ "legendVisible": "A",
998
+ "metaCoordinationScopes": [
999
+ "init_A_image_0",
1000
+ "init_A_obsSegmentations_0",
1001
+ "init_A_obsSegmentations_0",
1002
+ "init_A_obsPoints_0"
1003
+ ],
1004
+ "metaCoordinationScopesBy": [
1005
+ "init_A_image_0",
1006
+ "init_A_obsSegmentations_0",
1007
+ "init_A_obsSegmentations_0",
1008
+ "init_A_obsPoints_0"
1009
+ ],
1010
+ "obsColorEncoding": "A",
1011
+ "obsType": "A",
1012
+ "photometricInterpretation": "A",
1013
+ "pointLayer": "A",
1014
+ "segmentationChannel": "A",
1015
+ "segmentationLayer": "A",
1016
+ "spatialChannelColor": "A",
1017
+ "spatialChannelLabelSize": "A",
1018
+ "spatialChannelLabelsOrientation": "A",
1019
+ "spatialChannelLabelsVisible": "A",
1020
+ "spatialChannelOpacity": "A",
1021
+ "spatialChannelVisible": "A",
1022
+ "spatialChannelWindow": "A",
1023
+ "spatialLayerColor": "A",
1024
+ "spatialLayerColormap": "A",
1025
+ "spatialLayerModelMatrix": "A",
1026
+ "spatialLayerOpacity": "A",
1027
+ "spatialLayerTransparentColor": "A",
1028
+ "spatialLayerVisible": "A",
1029
+ "spatialMaxResolution": "A",
1030
+ "spatialNeighborhoodLayer": "A",
1031
+ "spatialOrbitAxis": "B",
1032
+ "spatialPointLayer": "A",
1033
+ "spatialPointStrokeWidth": "A",
1034
+ "spatialRenderingMode": "A",
1035
+ "spatialRotationOrbit": "B",
1036
+ "spatialRotationX": "B",
1037
+ "spatialRotationY": "B",
1038
+ "spatialRotationZ": "B",
1039
+ "spatialSegmentationFilled": "A",
1040
+ "spatialSegmentationStrokeWidth": "A",
1041
+ "spatialSliceX": "A",
1042
+ "spatialSliceY": "A",
1043
+ "spatialSliceZ": "A",
1044
+ "spatialSpotFilled": "A",
1045
+ "spatialSpotRadius": "A",
1046
+ "spatialSpotStrokeWidth": "A",
1047
+ "spatialTargetC": "A",
1048
+ "spatialTargetResolution": "A",
1049
+ "spatialTargetT": "A",
1050
+ "spatialTargetX": "B",
1051
+ "spatialTargetY": "B",
1052
+ "spatialTargetZ": "B",
1053
+ "spatialZoom": "B",
1054
+ "spotLayer": "A",
1055
+ "tooltipCrosshairsVisible": "A",
1056
+ "tooltipsVisible": "A",
1057
+ "volumetricRenderingAlgorithm": "A"
1058
+ },
1059
+ "h": 1,
1060
+ "uid": "C",
1061
+ "w": 1,
1062
+ "x": 0,
1063
+ "y": 0
1064
+ },
1065
+ {
1066
+ "component": "obsSets",
1067
+ "coordinationScopes": {
1068
+ "additionalObsSets": "A",
1069
+ "dataset": "A",
1070
+ "featureSelection": "A",
1071
+ "obsColorEncoding": "A",
1072
+ "obsSetColor": "A",
1073
+ "obsSetExpansion": "A",
1074
+ "obsSetFilter": "A",
1075
+ "obsSetHighlight": "A",
1076
+ "obsSetSelection": "A",
1077
+ "obsType": "A"
1078
+ },
1079
+ "h": 1,
1080
+ "uid": "D",
1081
+ "w": 1,
1082
+ "x": 0,
1083
+ "y": 0
1084
+ }
1085
+ ],
1086
+ "name": "Xenium SpatialData Demo",
1087
+ "uid": "A",
1088
+ "version": "1.0.18"
1089
+ },
1090
+ "_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 <Vitessce/>),\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 <Vitessce/> 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",
1091
+ "_model_module": "anywidget",
1092
+ "_model_name": "AnyModel",
1093
+ "_view_name": "ErrorWidgetView",
1094
+ "custom_js_url": "",
1095
+ "error": {},
1096
+ "has_host_name": false,
1097
+ "height": 600,
1098
+ "invoke_batched": true,
1099
+ "invoke_timeout": 300000,
1100
+ "js_dev_mode": false,
1101
+ "js_package_version": "3.9.9",
1102
+ "layout": "IPY_MODEL_6adbd17d7ac6415890bb669e3aaf670f",
1103
+ "msg": "Failed to load model class 'AnyModel' from module 'anywidget'",
1104
+ "page_esm": "",
1105
+ "page_mode": false,
1106
+ "plugin_esm": [],
1107
+ "prevent_scroll": true,
1108
+ "proxy": false,
1109
+ "remount_on_uid_change": true,
1110
+ "store_urls": [],
1111
+ "theme": "auto",
1112
+ "uid": "e7a1"
1113
+ }
1114
+ },
1115
+ "undefined": {
1116
+ "model_module": "anywidget",
1117
+ "model_module_version": "2.0.0",
1118
+ "model_name": "AnyModel",
1119
+ "state": {
1120
+ "_view_name": "ErrorWidgetView",
1121
+ "error": {},
1122
+ "msg": "Failed to load model class 'AnyModel' from module 'anywidget'"
1123
+ }
1124
+ }
1125
+ },
1126
+ "version_major": 2,
1127
+ "version_minor": 0
1128
+ }
1129
+ }
1130
+ },
1131
+ "nbformat": 4,
1132
+ "nbformat_minor": 4
1133
+ }
notebooks/bar_plots.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/celldega_pre-process.ipynb ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "8ce6b74e-54af-48ba-abf2-7ce2caa573bf",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Xenium Pre-process"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": null,
14
+ "id": "b81ab32e",
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "%load_ext autoreload\n",
19
+ "%autoreload 2\n",
20
+ "%env ANYWIDGET_HMR=1\n",
21
+ "\n",
22
+ "import celldega as dega"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "markdown",
27
+ "id": "b47f611d",
28
+ "metadata": {},
29
+ "source": [
30
+ "## Xenium pre processing"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "id": "52602e61-45e7-45a2-83a0-9a1b364d6619",
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": [
40
+ "sample = 'Xenium_V1_humanLung_Cancer_FFPE_outs'\n",
41
+ "data_dir = f'../data/instrument_data'\n",
42
+ "path_landscape_files=f'../data/processed_data/DegaFiles/{sample}'"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": null,
48
+ "id": "13350680",
49
+ "metadata": {},
50
+ "outputs": [],
51
+ "source": [
52
+ "tile_size=250\n",
53
+ "\n",
54
+ "dega.pre.main(\n",
55
+ " sample=sample,\n",
56
+ " data_root_dir=data_dir,\n",
57
+ " tile_size=tile_size,\n",
58
+ " path_landscape_files=path_landscape_files,\n",
59
+ " use_int_index=True,\n",
60
+ " image_tile_layer=\"all\"\n",
61
+ " )"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": null,
67
+ "id": "2fd7f196-c6cc-4321-8481-6249ed0b96a7",
68
+ "metadata": {},
69
+ "outputs": [],
70
+ "source": []
71
+ }
72
+ ],
73
+ "metadata": {
74
+ "kernelspec": {
75
+ "display_name": "Python 3 (ipykernel)",
76
+ "language": "python",
77
+ "name": "python3"
78
+ },
79
+ "language_info": {
80
+ "codemirror_mode": {
81
+ "name": "ipython",
82
+ "version": 3
83
+ },
84
+ "file_extension": ".py",
85
+ "mimetype": "text/x-python",
86
+ "name": "python",
87
+ "nbconvert_exporter": "python",
88
+ "pygments_lexer": "ipython3",
89
+ "version": "3.12.1"
90
+ },
91
+ "toc": {
92
+ "base_numbering": 1,
93
+ "nav_menu": {},
94
+ "number_sections": true,
95
+ "sideBar": true,
96
+ "skip_h1_title": false,
97
+ "title_cell": "Table of Contents",
98
+ "title_sidebar": "Contents",
99
+ "toc_cell": false,
100
+ "toc_position": {},
101
+ "toc_section_display": true,
102
+ "toc_window_display": false
103
+ },
104
+ "widgets": {
105
+ "application/vnd.jupyter.widget-state+json": {
106
+ "state": {},
107
+ "version_major": 2,
108
+ "version_minor": 0
109
+ }
110
+ }
111
+ },
112
+ "nbformat": 4,
113
+ "nbformat_minor": 5
114
+ }
notebooks/celldega_viz.ipynb ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "8ce6b74e-54af-48ba-abf2-7ce2caa573bf",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Xenium Viz"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": null,
14
+ "id": "56843452-1a1c-4ae7-95ad-0a7bd909bc90",
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "%load_ext autoreload\n",
19
+ "%autoreload 2\n",
20
+ "%env ANYWIDGET_HMR=1"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "cec165b0-bd8f-40d5-b130-22486970aca8",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "import celldega as dega"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "id": "b66e327c-8c1e-41b7-9fbc-48d3f5c06fe3",
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": [
40
+ "sample = \"WTA_Preview_FFPE_Cervical_Cancer_outs\"\n",
41
+ "path_dega_files = f\"../data/processed_data/DegaFiles/{sample}\"\n",
42
+ "\n",
43
+ "landscape_ist = dega.viz.Landscape(\n",
44
+ " technology=\"Xenium\",\n",
45
+ " base_url=f\"http://localhost:{dega.viz.get_local_server()}/{path_dega_files}\",\n",
46
+ ")\n",
47
+ "\n",
48
+ "landscape_ist"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "id": "c8cd7207-7604-49bb-9172-d92af31ad74b",
55
+ "metadata": {},
56
+ "outputs": [],
57
+ "source": []
58
+ }
59
+ ],
60
+ "metadata": {
61
+ "kernelspec": {
62
+ "display_name": "Python 3 (ipykernel)",
63
+ "language": "python",
64
+ "name": "python3"
65
+ },
66
+ "language_info": {
67
+ "codemirror_mode": {
68
+ "name": "ipython",
69
+ "version": 3
70
+ },
71
+ "file_extension": ".py",
72
+ "mimetype": "text/x-python",
73
+ "name": "python",
74
+ "nbconvert_exporter": "python",
75
+ "pygments_lexer": "ipython3",
76
+ "version": "3.12.1"
77
+ },
78
+ "toc": {
79
+ "base_numbering": 1,
80
+ "nav_menu": {},
81
+ "number_sections": true,
82
+ "sideBar": true,
83
+ "skip_h1_title": false,
84
+ "title_cell": "Table of Contents",
85
+ "title_sidebar": "Contents",
86
+ "toc_cell": false,
87
+ "toc_position": {},
88
+ "toc_section_display": true,
89
+ "toc_window_display": false
90
+ },
91
+ "widgets": {
92
+ "application/vnd.jupyter.widget-state+json": {
93
+ "state": {},
94
+ "version_major": 2,
95
+ "version_minor": 0
96
+ }
97
+ }
98
+ },
99
+ "nbformat": 4,
100
+ "nbformat_minor": 5
101
+ }
notebooks/tissuumaps_pre-process.ipynb ADDED
@@ -0,0 +1,1274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "07f7dbb1-63c6-40e4-b0d9-6ec104aa0adc",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# !pip install zarr\n",
11
+ "\n",
12
+ "import os\n",
13
+ "import json\n",
14
+ "from pathlib import Path\n",
15
+ "import glob\n",
16
+ "import numpy as np\n",
17
+ "import pandas as pd\n",
18
+ "import scanpy as sc\n",
19
+ "import pyvips\n",
20
+ "import zarr\n",
21
+ "import geopandas as gpd\n",
22
+ "from shapely.geometry import Polygon\n",
23
+ "from scipy.sparse import csc_matrix\n",
24
+ "\n",
25
+ "import tissuumaps.jupyter as tj\n",
26
+ "from tissuumaps import read_h5ad\n",
27
+ "\n",
28
+ "\n",
29
+ "# ----------------------------\n",
30
+ "# Paths\n",
31
+ "# ----------------------------\n",
32
+ "# sample = \"WTA_Preview_FFPE_Cervical_Cancer_outs\"\n",
33
+ "# sample = \"Xenium_Prime_Human_Lymph_Node_Reactive_FFPE_outs\"\n",
34
+ "# sample = \"Xenium_Prime_Ovarian_Cancer_FFPE_XRrun_outs\"\n",
35
+ "# sample = \"Xenium_V1_humanLung_Cancer_FFPE_outs\"\n",
36
+ "\n",
37
+ "xenium_dir = os.path.abspath(f\"../data/instrument_data/{sample}\")\n",
38
+ "basedir = os.path.abspath(f\"../data/processed_data/tissuumaps_h5ad/{sample}\")\n",
39
+ "os.makedirs(basedir, exist_ok=True)\n",
40
+ "\n",
41
+ "out_h5ad_name = f\"{sample}_tmap.h5ad\"\n",
42
+ "out_h5ad = os.path.join(basedir, out_h5ad_name)\n",
43
+ "\n",
44
+ "project_path = os.path.join(basedir, \"_project_h5ad.tmap\")"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": null,
50
+ "id": "aec44404-259a-4042-9230-5a244ec9df0e",
51
+ "metadata": {},
52
+ "outputs": [],
53
+ "source": [
54
+ "# ----------------------------\n",
55
+ "# Transform helpers\n",
56
+ "# ----------------------------\n",
57
+ "def write_xenium_transform(data_dir, path_landscape_files):\n",
58
+ " cells_zarr_path = Path(data_dir) / \"cells.zarr.zip\"\n",
59
+ " if not cells_zarr_path.exists():\n",
60
+ " raise FileNotFoundError(f\"Missing: {cells_zarr_path}\")\n",
61
+ "\n",
62
+ " store = zarr.ZipStore(str(cells_zarr_path), mode=\"r\")\n",
63
+ " root = zarr.group(store=store)\n",
64
+ "\n",
65
+ " transform = root[\"masks\"][\"homogeneous_transform\"][:]\n",
66
+ "\n",
67
+ " pd.DataFrame(transform[:3, :3]).to_csv(\n",
68
+ " Path(path_landscape_files) / \"micron_to_image_transform.csv\",\n",
69
+ " sep=\" \",\n",
70
+ " header=False,\n",
71
+ " index=False,\n",
72
+ " )\n",
73
+ "\n",
74
+ " return transform\n",
75
+ "\n",
76
+ "\n",
77
+ "def apply_homogeneous_transform_xy(x, y, transform):\n",
78
+ " transform = np.asarray(transform)[:3, :3]\n",
79
+ "\n",
80
+ " xy1 = np.vstack([\n",
81
+ " np.asarray(x, dtype=float),\n",
82
+ " np.asarray(y, dtype=float),\n",
83
+ " np.ones(len(x)),\n",
84
+ " ])\n",
85
+ "\n",
86
+ " out = transform @ xy1\n",
87
+ " return out[0] / out[2], out[1] / out[2]\n",
88
+ " \n",
89
+ "# ----------------------------\n",
90
+ "# 1. Transform\n",
91
+ "# ----------------------------\n",
92
+ "transform = write_xenium_transform(xenium_dir, basedir)"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "execution_count": null,
98
+ "id": "16f90ba5-914a-4a3d-b3bc-9960481cef1f",
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "# ----------------------------\n",
103
+ "# Polygon helper\n",
104
+ "# ----------------------------\n",
105
+ "def xenium_boundaries_to_geojson(\n",
106
+ " boundary_path,\n",
107
+ " out_geojson,\n",
108
+ " transform,\n",
109
+ " id_col=\"cell_id\",\n",
110
+ " max_polygons=None,\n",
111
+ "):\n",
112
+ " if not os.path.exists(boundary_path):\n",
113
+ " return None\n",
114
+ "\n",
115
+ " if boundary_path.endswith(\".parquet\"):\n",
116
+ " df = pd.read_parquet(boundary_path)\n",
117
+ " else:\n",
118
+ " df = pd.read_csv(boundary_path)\n",
119
+ "\n",
120
+ " x_col = \"vertex_x\" if \"vertex_x\" in df.columns else \"x\"\n",
121
+ " y_col = \"vertex_y\" if \"vertex_y\" in df.columns else \"y\"\n",
122
+ "\n",
123
+ " x_new, y_new = apply_homogeneous_transform_xy(\n",
124
+ " df[x_col].values,\n",
125
+ " df[y_col].values,\n",
126
+ " transform,\n",
127
+ " )\n",
128
+ "\n",
129
+ " df = df.copy()\n",
130
+ " df[\"x_img\"] = x_new\n",
131
+ " df[\"y_img\"] = y_new\n",
132
+ "\n",
133
+ " ids = []\n",
134
+ " geoms = []\n",
135
+ "\n",
136
+ " for i, (cid, sub) in enumerate(df.groupby(id_col, sort=False)):\n",
137
+ " if max_polygons is not None and i >= max_polygons:\n",
138
+ " break\n",
139
+ "\n",
140
+ " if len(sub) < 3:\n",
141
+ " continue\n",
142
+ "\n",
143
+ " coords = list(zip(sub[\"x_img\"].astype(float), sub[\"y_img\"].astype(float)))\n",
144
+ "\n",
145
+ " if coords[0] != coords[-1]:\n",
146
+ " coords.append(coords[0])\n",
147
+ "\n",
148
+ " poly = Polygon(coords)\n",
149
+ "\n",
150
+ " if poly.is_valid and not poly.is_empty:\n",
151
+ " ids.append(cid)\n",
152
+ " geoms.append(poly)\n",
153
+ "\n",
154
+ " gdf = gpd.GeoDataFrame({id_col: ids}, geometry=geoms, crs=None)\n",
155
+ " gdf.to_file(out_geojson, driver=\"GeoJSON\")\n",
156
+ "\n",
157
+ " return os.path.basename(out_geojson)"
158
+ ]
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "execution_count": null,
163
+ "id": "a97826c2-0864-4a35-a7d0-5a64c117a1e2",
164
+ "metadata": {},
165
+ "outputs": [],
166
+ "source": [
167
+ "def add_xenium_default_clustering(adata, xenium_dir):\n",
168
+ " import os\n",
169
+ " import glob\n",
170
+ " import pandas as pd\n",
171
+ "\n",
172
+ " candidates = sorted(glob.glob(\n",
173
+ " os.path.join(xenium_dir, \"analysis\", \"clustering\", \"**\", \"clusters.csv\"),\n",
174
+ " recursive=True,\n",
175
+ " ))\n",
176
+ "\n",
177
+ " if not candidates:\n",
178
+ " print(\"No clusters.csv found.\")\n",
179
+ " return adata\n",
180
+ "\n",
181
+ " preferred = None\n",
182
+ " for p in candidates:\n",
183
+ " if \"gene_expression_graphclust\" in p:\n",
184
+ " preferred = p\n",
185
+ " break\n",
186
+ "\n",
187
+ " if preferred is None:\n",
188
+ " preferred = candidates[0]\n",
189
+ "\n",
190
+ " print(\"Using clustering file:\", preferred)\n",
191
+ "\n",
192
+ " clusters = pd.read_csv(preferred)\n",
193
+ "\n",
194
+ " id_col = \"Barcode\" if \"Barcode\" in clusters.columns else clusters.columns[0]\n",
195
+ " cluster_col = \"Cluster\" if \"Cluster\" in clusters.columns else clusters.columns[1]\n",
196
+ "\n",
197
+ " clusters[id_col] = clusters[id_col].astype(str)\n",
198
+ " clusters[cluster_col] = clusters[cluster_col].astype(str)\n",
199
+ "\n",
200
+ " s = clusters.set_index(id_col)[cluster_col]\n",
201
+ "\n",
202
+ " # IMPORTANT: reindex allows cells missing from clustering file\n",
203
+ " adata.obs[\"xenium_default_cluster\"] = (\n",
204
+ " s.reindex(adata.obs_names)\n",
205
+ " .fillna(\"unclustered\")\n",
206
+ " .astype(str)\n",
207
+ " .astype(\"category\")\n",
208
+ " )\n",
209
+ "\n",
210
+ " print(adata.obs[\"xenium_default_cluster\"].value_counts())\n",
211
+ "\n",
212
+ " return adata\n",
213
+ "\n",
214
+ "\n",
215
+ "# ----------------------------\n",
216
+ "# 2. Build h5ad in image pixel space\n",
217
+ "# ----------------------------\n",
218
+ "adata = sc.read_10x_h5(os.path.join(xenium_dir, \"cell_feature_matrix.h5\"))\n",
219
+ "adata.var_names_make_unique()\n",
220
+ "\n",
221
+ "cells = pd.read_csv(os.path.join(xenium_dir, \"cells.csv.gz\"), index_col=0)\n",
222
+ "cells = cells.loc[adata.obs_names]\n",
223
+ "\n",
224
+ "x_img, y_img = apply_homogeneous_transform_xy(\n",
225
+ " cells[\"x_centroid\"].values,\n",
226
+ " cells[\"y_centroid\"].values,\n",
227
+ " transform,\n",
228
+ ")\n",
229
+ "\n",
230
+ "adata.obs[\"x\"] = x_img.astype(float)\n",
231
+ "adata.obs[\"y\"] = y_img.astype(float)\n",
232
+ "adata.obsm[\"spatial\"] = adata.obs[[\"x\", \"y\"]].to_numpy(dtype=\"float64\")\n",
233
+ "\n",
234
+ "adata.obs[\"x_centroid_um\"] = cells[\"x_centroid\"].astype(float).values\n",
235
+ "adata.obs[\"y_centroid_um\"] = cells[\"y_centroid\"].astype(float).values\n",
236
+ "\n",
237
+ "obs_cols = [\n",
238
+ " \"transcript_counts\",\n",
239
+ " \"control_probe_counts\",\n",
240
+ " \"genomic_control_counts\",\n",
241
+ " \"control_codeword_counts\",\n",
242
+ " \"unassigned_codeword_counts\",\n",
243
+ " \"deprecated_codeword_counts\",\n",
244
+ " \"total_counts\",\n",
245
+ " \"cell_area\",\n",
246
+ " \"nucleus_area\",\n",
247
+ " \"nucleus_count\",\n",
248
+ "]\n",
249
+ "\n",
250
+ "for col in obs_cols:\n",
251
+ " if col in cells.columns:\n",
252
+ " adata.obs[col] = cells[col].values\n",
253
+ "\n",
254
+ "for col in adata.obs.columns:\n",
255
+ " if pd.api.types.is_object_dtype(adata.obs[col]):\n",
256
+ " adata.obs[col] = adata.obs[col].astype(\"category\")\n",
257
+ "\n",
258
+ "adata = add_xenium_default_clustering(adata, xenium_dir)\n",
259
+ "\n",
260
+ "adata.X = csc_matrix(adata.X)\n",
261
+ "adata.uns.pop(\"tmap_obsgroups\", None)\n",
262
+ "adata.write_h5ad(out_h5ad)"
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "execution_count": null,
268
+ "id": "f50d1a11-11ae-40f2-a35a-d0cd24a69935",
269
+ "metadata": {},
270
+ "outputs": [],
271
+ "source": [
272
+ "# ----------------------------\n",
273
+ "# 3. Make image pyramid\n",
274
+ "# ----------------------------\n",
275
+ "def make_one_xenium_pyramid_tifffile_zarr(\n",
276
+ " xenium_dir,\n",
277
+ " basedir,\n",
278
+ " channel=\"morphology_focus_0000.ome.tif\",\n",
279
+ " plane=0,\n",
280
+ " low=0,\n",
281
+ " high=12000,\n",
282
+ " gamma=0.5,\n",
283
+ " out_name=None,\n",
284
+ " rows_per_chunk=512,\n",
285
+ "):\n",
286
+ " import os\n",
287
+ " import numpy as np\n",
288
+ " import tifffile\n",
289
+ " import zarr\n",
290
+ " import pyvips\n",
291
+ "\n",
292
+ " src = os.path.join(xenium_dir, \"morphology_focus\", channel)\n",
293
+ "\n",
294
+ " if out_name is None:\n",
295
+ " out_name = channel.replace(\".ome.tif\", f\"_plane{plane}_pyramid.tif\")\n",
296
+ "\n",
297
+ " tmp_name = out_name.replace(\".tif\", \"_uint8_tmp.tif\")\n",
298
+ " tmp_path = os.path.join(basedir, tmp_name)\n",
299
+ " out_path = os.path.join(basedir, out_name)\n",
300
+ "\n",
301
+ " for p in [tmp_path, out_path]:\n",
302
+ " if os.path.exists(p):\n",
303
+ " os.remove(p)\n",
304
+ "\n",
305
+ " with tifffile.TiffFile(src) as tf:\n",
306
+ " store = tf.aszarr(series=0, level=0)\n",
307
+ " z = zarr.open(store, mode=\"r\")\n",
308
+ "\n",
309
+ " print(\"zarr shape:\", z.shape, \"dtype:\", z.dtype)\n",
310
+ "\n",
311
+ " if len(z.shape) == 3:\n",
312
+ " arr2d = z[plane]\n",
313
+ " elif len(z.shape) == 2:\n",
314
+ " arr2d = z\n",
315
+ " else:\n",
316
+ " raise ValueError(f\"Unexpected image shape: {z.shape}\")\n",
317
+ "\n",
318
+ " height, width = arr2d.shape\n",
319
+ " print(\"using plane:\", plane, \"height:\", height, \"width:\", width)\n",
320
+ "\n",
321
+ " # Create one full-size uint8 temp TIFF, memory-mapped on disk\n",
322
+ " tmp_mm = tifffile.memmap(\n",
323
+ " tmp_path,\n",
324
+ " shape=(height, width),\n",
325
+ " dtype=\"uint8\",\n",
326
+ " photometric=\"minisblack\",\n",
327
+ " bigtiff=True,\n",
328
+ " )\n",
329
+ "\n",
330
+ " for y0 in range(0, height, rows_per_chunk):\n",
331
+ " y1 = min(y0 + rows_per_chunk, height)\n",
332
+ "\n",
333
+ " block = arr2d[y0:y1, :].astype(\"float32\")\n",
334
+ " block = (block - low) / (high - low)\n",
335
+ " block = np.clip(block, 0, 1)\n",
336
+ "\n",
337
+ " if gamma is not None:\n",
338
+ " block = block ** gamma\n",
339
+ "\n",
340
+ " tmp_mm[y0:y1, :] = (block * 255).astype(\"uint8\")\n",
341
+ "\n",
342
+ " tmp_mm.flush()\n",
343
+ " del tmp_mm\n",
344
+ " store.close()\n",
345
+ "\n",
346
+ " img = pyvips.Image.new_from_file(tmp_path, access=\"sequential\")\n",
347
+ "\n",
348
+ " img.tiffsave(\n",
349
+ " out_path,\n",
350
+ " tile=True,\n",
351
+ " pyramid=True,\n",
352
+ " compression=\"jpeg\",\n",
353
+ " Q=90,\n",
354
+ " tile_width=256,\n",
355
+ " tile_height=256,\n",
356
+ " bigtiff=True,\n",
357
+ " )\n",
358
+ "\n",
359
+ " os.remove(tmp_path)\n",
360
+ "\n",
361
+ " print(\"wrote:\", out_path)\n",
362
+ "\n",
363
+ " return {\n",
364
+ " \"name\": out_name,\n",
365
+ " \"tileSource\": out_name + \".dzi\",\n",
366
+ " \"x\": 0,\n",
367
+ " \"y\": 0,\n",
368
+ " \"scale\": 1,\n",
369
+ " \"rotation\": 0,\n",
370
+ " \"flip\": False,\n",
371
+ " }\n",
372
+ "\n",
373
+ "morph_files = sorted(glob.glob(os.path.join(xenium_dir, \"morphology_focus\", \"*.ome.tif\")))\n",
374
+ "morph_files"
375
+ ]
376
+ },
377
+ {
378
+ "cell_type": "code",
379
+ "execution_count": null,
380
+ "id": "4109411c-f39c-40d8-94f1-72be456f8c4d",
381
+ "metadata": {},
382
+ "outputs": [],
383
+ "source": [
384
+ "# # ----------------------------\n",
385
+ "# # 3. Make image pyramid\n",
386
+ "# # ----------------------------\n",
387
+ "# def make_one_xenium_pyramid_tifffile_zarr(\n",
388
+ "# xenium_dir,\n",
389
+ "# basedir,\n",
390
+ "# channel=\"morphology_focus_0000.ome.tif\",\n",
391
+ "# plane=0,\n",
392
+ "# low=0,\n",
393
+ "# high=12000,\n",
394
+ "# gamma=0.5,\n",
395
+ "# out_name=None,\n",
396
+ "# rows_per_chunk=512,\n",
397
+ "# ):\n",
398
+ "# import os\n",
399
+ "# import numpy as np\n",
400
+ "# import tifffile\n",
401
+ "# import zarr\n",
402
+ "# import pyvips\n",
403
+ "\n",
404
+ "# src = os.path.join(xenium_dir, channel)\n",
405
+ "\n",
406
+ "# if out_name is None:\n",
407
+ "# out_name = channel.replace(\".ome.tif\", f\"_plane{plane}_pyramid.tif\")\n",
408
+ "\n",
409
+ "# tmp_name = out_name.replace(\".tif\", \"_uint8_tmp.tif\")\n",
410
+ "# tmp_path = os.path.join(basedir, tmp_name)\n",
411
+ "# out_path = os.path.join(basedir, out_name)\n",
412
+ "\n",
413
+ "# for p in [tmp_path, out_path]:\n",
414
+ "# if os.path.exists(p):\n",
415
+ "# os.remove(p)\n",
416
+ "\n",
417
+ "# with tifffile.TiffFile(src) as tf:\n",
418
+ "# store = tf.aszarr(series=0, level=0)\n",
419
+ "# z = zarr.open(store, mode=\"r\")\n",
420
+ "\n",
421
+ "# print(\"zarr shape:\", z.shape, \"dtype:\", z.dtype)\n",
422
+ "\n",
423
+ "# if len(z.shape) == 3:\n",
424
+ "# arr2d = z[plane]\n",
425
+ "# elif len(z.shape) == 2:\n",
426
+ "# arr2d = z\n",
427
+ "# else:\n",
428
+ "# raise ValueError(f\"Unexpected image shape: {z.shape}\")\n",
429
+ "\n",
430
+ "# height, width = arr2d.shape\n",
431
+ "# print(\"using plane:\", plane, \"height:\", height, \"width:\", width)\n",
432
+ "\n",
433
+ "# # Create one full-size uint8 temp TIFF, memory-mapped on disk\n",
434
+ "# tmp_mm = tifffile.memmap(\n",
435
+ "# tmp_path,\n",
436
+ "# shape=(height, width),\n",
437
+ "# dtype=\"uint8\",\n",
438
+ "# photometric=\"minisblack\",\n",
439
+ "# bigtiff=True,\n",
440
+ "# )\n",
441
+ "\n",
442
+ "# for y0 in range(0, height, rows_per_chunk):\n",
443
+ "# y1 = min(y0 + rows_per_chunk, height)\n",
444
+ "\n",
445
+ "# block = arr2d[y0:y1, :].astype(\"float32\")\n",
446
+ "# block = (block - low) / (high - low)\n",
447
+ "# block = np.clip(block, 0, 1)\n",
448
+ "\n",
449
+ "# if gamma is not None:\n",
450
+ "# block = block ** gamma\n",
451
+ "\n",
452
+ "# tmp_mm[y0:y1, :] = (block * 255).astype(\"uint8\")\n",
453
+ "\n",
454
+ "# tmp_mm.flush()\n",
455
+ "# del tmp_mm\n",
456
+ "# store.close()\n",
457
+ "\n",
458
+ "# img = pyvips.Image.new_from_file(tmp_path, access=\"sequential\")\n",
459
+ "\n",
460
+ "# img.tiffsave(\n",
461
+ "# out_path,\n",
462
+ "# tile=True,\n",
463
+ "# pyramid=True,\n",
464
+ "# compression=\"jpeg\",\n",
465
+ "# Q=90,\n",
466
+ "# tile_width=256,\n",
467
+ "# tile_height=256,\n",
468
+ "# bigtiff=True,\n",
469
+ "# )\n",
470
+ "\n",
471
+ "# os.remove(tmp_path)\n",
472
+ "\n",
473
+ "# print(\"wrote:\", out_path)\n",
474
+ "\n",
475
+ "# return {\n",
476
+ "# \"name\": out_name,\n",
477
+ "# \"tileSource\": out_name + \".dzi\",\n",
478
+ "# \"x\": 0,\n",
479
+ "# \"y\": 0,\n",
480
+ "# \"scale\": 1,\n",
481
+ "# \"rotation\": 0,\n",
482
+ "# \"flip\": False,\n",
483
+ "# }\n",
484
+ " \n",
485
+ "# morph_files = sorted(glob.glob(os.path.join(xenium_dir, \"morphology_focus.ome.tif\")))\n",
486
+ "# morph_files"
487
+ ]
488
+ },
489
+ {
490
+ "cell_type": "code",
491
+ "execution_count": null,
492
+ "id": "622a8749-399c-4bd4-855c-10be911d0198",
493
+ "metadata": {
494
+ "scrolled": true
495
+ },
496
+ "outputs": [],
497
+ "source": [
498
+ "image_layers = []\n",
499
+ "\n",
500
+ "# Use the first OME file, but extract each plane as a separate stain/channel\n",
501
+ "channel_file = os.path.basename(morph_files[0])\n",
502
+ "\n",
503
+ "for plane in range(4):\n",
504
+ " image_layer = make_one_xenium_pyramid_tifffile_zarr(\n",
505
+ " xenium_dir=xenium_dir,\n",
506
+ " basedir=basedir,\n",
507
+ " channel=channel_file,\n",
508
+ " plane=plane,\n",
509
+ " low=0,\n",
510
+ " high=3000,\n",
511
+ " gamma=0.4,\n",
512
+ " out_name=f\"morphology_focus_plane{plane}_pyramid.tif\",\n",
513
+ " )\n",
514
+ "\n",
515
+ " image_layer[\"name\"] = f\"morphology_focus_plane{plane}\"\n",
516
+ " image_layers.append(image_layer)"
517
+ ]
518
+ },
519
+ {
520
+ "cell_type": "code",
521
+ "execution_count": null,
522
+ "id": "784a65f6-f500-4b7f-9ca6-5c9a3be4361e",
523
+ "metadata": {},
524
+ "outputs": [],
525
+ "source": [
526
+ "# ----------------------------\n",
527
+ "# 4. Create cell boundary GeoJSON\n",
528
+ "# ----------------------------\n",
529
+ "region_files = []\n",
530
+ "\n",
531
+ "for candidate in [\n",
532
+ " os.path.join(xenium_dir, \"cell_boundaries.parquet\"),\n",
533
+ " os.path.join(xenium_dir, \"cell_boundaries.csv.gz\"),\n",
534
+ "]:\n",
535
+ " if os.path.exists(candidate):\n",
536
+ " name = xenium_boundaries_to_geojson(\n",
537
+ " candidate,\n",
538
+ " os.path.join(basedir, \"cell_boundaries_image_space.geojson\"),\n",
539
+ " transform,\n",
540
+ " id_col=\"cell_id\",\n",
541
+ " )\n",
542
+ " region_files.append({\n",
543
+ " \"path\": name,\n",
544
+ " \"title\": \"Load cell boundaries\",\n",
545
+ " \"comment\": \"Cell boundaries\",\n",
546
+ " \"autoLoad\": False,\n",
547
+ " })\n",
548
+ " break"
549
+ ]
550
+ },
551
+ {
552
+ "cell_type": "code",
553
+ "execution_count": null,
554
+ "id": "43159e9d-5279-4b90-a5b8-cc39aa08facd",
555
+ "metadata": {},
556
+ "outputs": [],
557
+ "source": [
558
+ "# def xenium_transcripts_to_csv_streaming(\n",
559
+ "# xenium_dir,\n",
560
+ "# basedir,\n",
561
+ "# transform,\n",
562
+ "# out_name=\"transcripts_image_space.csv\",\n",
563
+ "# min_qv=20,\n",
564
+ "# max_transcripts=2_000_000,\n",
565
+ "# rows_per_group=None,\n",
566
+ "# ):\n",
567
+ "# import os\n",
568
+ "# import numpy as np\n",
569
+ "# import pandas as pd\n",
570
+ "# import pyarrow.parquet as pq\n",
571
+ "\n",
572
+ "# transcript_path = os.path.join(xenium_dir, \"transcripts.parquet\")\n",
573
+ "# if not os.path.exists(transcript_path):\n",
574
+ "# raise FileNotFoundError(transcript_path)\n",
575
+ "\n",
576
+ "# out_path = os.path.join(basedir, out_name)\n",
577
+ "# if os.path.exists(out_path):\n",
578
+ "# os.remove(out_path)\n",
579
+ "\n",
580
+ "# pf = pq.ParquetFile(transcript_path)\n",
581
+ "\n",
582
+ "# transform3 = np.asarray(transform)[:3, :3]\n",
583
+ "\n",
584
+ "# written = 0\n",
585
+ "# wrote_header = False\n",
586
+ "\n",
587
+ "# needed_cols = [\"x_location\", \"y_location\", \"feature_name\"]\n",
588
+ "# optional_cols = [\"qv\", \"cell_id\"]\n",
589
+ "\n",
590
+ "# # keep only columns that exist\n",
591
+ "# schema_cols = set(pf.schema.names)\n",
592
+ "# cols = [c for c in needed_cols + optional_cols if c in schema_cols]\n",
593
+ "\n",
594
+ "# print(\"Transcript columns:\", cols)\n",
595
+ "# print(\"Row groups:\", pf.num_row_groups)\n",
596
+ "\n",
597
+ "# for rg in range(pf.num_row_groups):\n",
598
+ "# if max_transcripts is not None and written >= max_transcripts:\n",
599
+ "# break\n",
600
+ "\n",
601
+ "# table = pf.read_row_group(rg, columns=cols)\n",
602
+ "# tx = table.to_pandas()\n",
603
+ "\n",
604
+ "# if \"qv\" in tx.columns:\n",
605
+ "# tx = tx[tx[\"qv\"] >= min_qv]\n",
606
+ "\n",
607
+ "# if tx.empty:\n",
608
+ "# continue\n",
609
+ "\n",
610
+ "# if max_transcripts is not None:\n",
611
+ "# remaining = max_transcripts - written\n",
612
+ "# if len(tx) > remaining:\n",
613
+ "# tx = tx.sample(remaining, random_state=rg)\n",
614
+ "\n",
615
+ "# x = tx[\"x_location\"].to_numpy(dtype=float)\n",
616
+ "# y = tx[\"y_location\"].to_numpy(dtype=float)\n",
617
+ "\n",
618
+ "# xy1 = np.vstack([x, y, np.ones(len(x))])\n",
619
+ "# out = transform3 @ xy1\n",
620
+ "\n",
621
+ "# out_df = pd.DataFrame({\n",
622
+ "# \"x\": out[0] / out[2],\n",
623
+ "# \"y\": out[1] / out[2],\n",
624
+ "# \"gene\": tx[\"feature_name\"].astype(str).to_numpy(),\n",
625
+ "# })\n",
626
+ "\n",
627
+ "# if \"qv\" in tx.columns:\n",
628
+ "# out_df[\"qv\"] = tx[\"qv\"].to_numpy()\n",
629
+ "\n",
630
+ "# if \"cell_id\" in tx.columns:\n",
631
+ "# out_df[\"cell_id\"] = tx[\"cell_id\"].astype(str).to_numpy()\n",
632
+ "\n",
633
+ "# out_df.to_csv(\n",
634
+ "# out_path,\n",
635
+ "# mode=\"a\",\n",
636
+ "# header=not wrote_header,\n",
637
+ "# index=False,\n",
638
+ "# )\n",
639
+ "\n",
640
+ "# wrote_header = True\n",
641
+ "# written += len(out_df)\n",
642
+ "\n",
643
+ "# print(f\"row group {rg + 1}/{pf.num_row_groups}: wrote {written:,}\")\n",
644
+ "\n",
645
+ "# print(\"wrote:\", out_path, \"n=\", written)\n",
646
+ "# return out_name\n",
647
+ "\n",
648
+ "# transcript_csv = xenium_transcripts_to_csv_streaming(\n",
649
+ "# xenium_dir=xenium_dir,\n",
650
+ "# basedir=basedir,\n",
651
+ "# transform=transform,\n",
652
+ "# min_qv=20,\n",
653
+ "# max_transcripts=None,\n",
654
+ "# )\n",
655
+ "\n",
656
+ "# print(\"Done\")"
657
+ ]
658
+ },
659
+ {
660
+ "cell_type": "code",
661
+ "execution_count": null,
662
+ "id": "b5398cfe-3a3d-4841-b385-f1467f20e45f",
663
+ "metadata": {
664
+ "scrolled": true
665
+ },
666
+ "outputs": [],
667
+ "source": [
668
+ "# def xenium_all_transcripts_to_h5ad_empty_X(\n",
669
+ "# xenium_dir,\n",
670
+ "# basedir,\n",
671
+ "# transform,\n",
672
+ "# out_name=\"transcripts_all_emptyX_tmap.h5ad\",\n",
673
+ "# min_qv=None,\n",
674
+ "# include_cell_id=False,\n",
675
+ "# ):\n",
676
+ "# import os\n",
677
+ "# import numpy as np\n",
678
+ "# import pandas as pd\n",
679
+ "# import pyarrow.parquet as pq\n",
680
+ "# import anndata as ad\n",
681
+ "# from scipy.sparse import csc_matrix\n",
682
+ "\n",
683
+ "# transcript_path = os.path.join(xenium_dir, \"transcripts.parquet\")\n",
684
+ "# out_path = os.path.join(basedir, out_name)\n",
685
+ "\n",
686
+ "# pf = pq.ParquetFile(transcript_path)\n",
687
+ "# transform3 = np.asarray(transform, dtype=np.float64)[:3, :3]\n",
688
+ "\n",
689
+ "# obs_chunks = []\n",
690
+ "# spatial_chunks = []\n",
691
+ "# written = 0\n",
692
+ "\n",
693
+ "# schema_cols = set(pf.schema.names)\n",
694
+ "\n",
695
+ "# cols = [\"x_location\", \"y_location\", \"feature_name\"]\n",
696
+ "# if min_qv is not None and \"qv\" in schema_cols:\n",
697
+ "# cols.append(\"qv\")\n",
698
+ "# elif \"qv\" in schema_cols:\n",
699
+ "# cols.append(\"qv\")\n",
700
+ "\n",
701
+ "# if include_cell_id and \"cell_id\" in schema_cols:\n",
702
+ "# cols.append(\"cell_id\")\n",
703
+ "\n",
704
+ "# for rg in range(pf.num_row_groups):\n",
705
+ "# tx = pf.read_row_group(rg, columns=cols).to_pandas()\n",
706
+ "\n",
707
+ "# if min_qv is not None and \"qv\" in tx.columns:\n",
708
+ "# tx = tx[tx[\"qv\"] >= min_qv]\n",
709
+ "\n",
710
+ "# if tx.empty:\n",
711
+ "# continue\n",
712
+ "\n",
713
+ "# x = tx[\"x_location\"].to_numpy(dtype=np.float64)\n",
714
+ "# y = tx[\"y_location\"].to_numpy(dtype=np.float64)\n",
715
+ "\n",
716
+ "# xy1 = np.vstack([\n",
717
+ "# x,\n",
718
+ "# y,\n",
719
+ "# np.ones(len(tx), dtype=np.float64),\n",
720
+ "# ])\n",
721
+ "\n",
722
+ "# out = transform3 @ xy1\n",
723
+ "\n",
724
+ "# spatial_chunks.append(\n",
725
+ "# np.column_stack([\n",
726
+ "# out[0] / out[2],\n",
727
+ "# out[1] / out[2],\n",
728
+ "# ]).astype(np.float32)\n",
729
+ "# )\n",
730
+ "\n",
731
+ "# # Compact index: RangeIndex, no huge tx_... strings\n",
732
+ "# obs = pd.DataFrame(index=pd.RangeIndex(written, written + len(tx)))\n",
733
+ "\n",
734
+ "# obs[\"gene\"] = tx[\"feature_name\"].astype(\"category\").values\n",
735
+ "\n",
736
+ "# if \"qv\" in tx.columns:\n",
737
+ "# obs[\"qv\"] = pd.to_numeric(tx[\"qv\"], downcast=\"integer\")\n",
738
+ "\n",
739
+ "# if include_cell_id and \"cell_id\" in tx.columns:\n",
740
+ "# obs[\"cell_id\"] = tx[\"cell_id\"].astype(\"category\").values\n",
741
+ "\n",
742
+ "# obs_chunks.append(obs)\n",
743
+ "\n",
744
+ "# written += len(tx)\n",
745
+ "# print(f\"row group {rg + 1}/{pf.num_row_groups}: {written:,}\")\n",
746
+ "\n",
747
+ "# obs = pd.concat(obs_chunks, axis=0)\n",
748
+ "\n",
749
+ "# # Ensure compact categoricals after concat\n",
750
+ "# obs[\"gene\"] = obs[\"gene\"].astype(\"category\")\n",
751
+ "\n",
752
+ "# if include_cell_id and \"cell_id\" in obs.columns:\n",
753
+ "# obs[\"cell_id\"] = obs[\"cell_id\"].astype(\"category\")\n",
754
+ "\n",
755
+ "# if \"qv\" in obs.columns:\n",
756
+ "# obs[\"qv\"] = pd.to_numeric(obs[\"qv\"], downcast=\"integer\")\n",
757
+ "\n",
758
+ "# spatial = np.vstack(spatial_chunks).astype(np.float32)\n",
759
+ "\n",
760
+ "# # Empty X: n_obs x 0 vars\n",
761
+ "# X = csc_matrix((len(obs), 0), dtype=np.float32)\n",
762
+ "# var = pd.DataFrame(index=pd.Index([], dtype=str))\n",
763
+ "\n",
764
+ "# transcript_adata = ad.AnnData(X=X, obs=obs, var=var)\n",
765
+ "# transcript_adata.obsm[\"spatial\"] = spatial\n",
766
+ "\n",
767
+ "# transcript_adata.write_h5ad(out_path)\n",
768
+ "\n",
769
+ "# print(\"wrote:\", out_path)\n",
770
+ "# print(\"shape:\", transcript_adata.shape)\n",
771
+ "# print(\"obs columns:\", list(transcript_adata.obs.columns))\n",
772
+ "# print(\"spatial dtype:\", transcript_adata.obsm[\"spatial\"].dtype)\n",
773
+ "\n",
774
+ "# return out_name\n",
775
+ "\n",
776
+ "# transcript_h5ad = xenium_all_transcripts_to_h5ad_empty_X(\n",
777
+ "# xenium_dir=xenium_dir,\n",
778
+ "# basedir=basedir,\n",
779
+ "# transform=transform,\n",
780
+ "# min_qv=None,\n",
781
+ "# include_cell_id=False,\n",
782
+ "# )"
783
+ ]
784
+ },
785
+ {
786
+ "cell_type": "code",
787
+ "execution_count": null,
788
+ "id": "9423d36b-5e04-484c-8901-b32a494ce7ad",
789
+ "metadata": {
790
+ "scrolled": true
791
+ },
792
+ "outputs": [],
793
+ "source": [
794
+ "# def xenium_all_transcripts_to_h5ad_empty_X(\n",
795
+ "# xenium_dir,\n",
796
+ "# basedir,\n",
797
+ "# transform,\n",
798
+ "# out_name=\"transcripts_all_emptyX_tmap.h5ad\",\n",
799
+ "# min_qv=None,\n",
800
+ "# include_cell_id=False,\n",
801
+ "# tmp_path=None,\n",
802
+ "# ):\n",
803
+ "# import os\n",
804
+ "# import numpy as np\n",
805
+ "# import pandas as pd\n",
806
+ "# import pyarrow as pa\n",
807
+ "# import pyarrow.parquet as pq\n",
808
+ "# import anndata as ad\n",
809
+ "# from scipy.sparse import csc_matrix\n",
810
+ "\n",
811
+ "# transcript_path = os.path.join(xenium_dir, \"transcripts.parquet\")\n",
812
+ "# out_path = os.path.join(basedir, out_name)\n",
813
+ "# if tmp_path is None:\n",
814
+ "# tmp_path = out_path.replace(\".h5ad\", \"_tmp.parquet\")\n",
815
+ "\n",
816
+ "# pf = pq.ParquetFile(transcript_path)\n",
817
+ "# transform3 = np.asarray(transform, dtype=np.float64)[:3, :3]\n",
818
+ "\n",
819
+ "# schema_cols = set(pf.schema.names)\n",
820
+ "# cols = [\"x_location\", \"y_location\", \"feature_name\"]\n",
821
+ "# if \"qv\" in schema_cols:\n",
822
+ "# cols.append(\"qv\")\n",
823
+ "# if include_cell_id and \"cell_id\" in schema_cols:\n",
824
+ "# cols.append(\"cell_id\")\n",
825
+ "\n",
826
+ "# writer = None\n",
827
+ "# written = 0\n",
828
+ "\n",
829
+ "# for rg in range(pf.num_row_groups):\n",
830
+ "# tx = pf.read_row_group(rg, columns=cols).to_pandas()\n",
831
+ "# if min_qv is not None and \"qv\" in tx.columns:\n",
832
+ "# tx = tx[tx[\"qv\"] >= min_qv]\n",
833
+ "# if tx.empty:\n",
834
+ "# continue\n",
835
+ "\n",
836
+ "# x = tx[\"x_location\"].to_numpy(dtype=np.float64)\n",
837
+ "# y = tx[\"y_location\"].to_numpy(dtype=np.float64)\n",
838
+ "# xy1 = np.vstack([x, y, np.ones(len(tx), dtype=np.float64)])\n",
839
+ "# out = transform3 @ xy1\n",
840
+ "\n",
841
+ "# chunk = pd.DataFrame({\n",
842
+ "# \"spatial_x\": (out[0] / out[2]).astype(np.float32),\n",
843
+ "# \"spatial_y\": (out[1] / out[2]).astype(np.float32),\n",
844
+ "# \"gene\": tx[\"feature_name\"].astype(str).values,\n",
845
+ "# })\n",
846
+ "# if \"qv\" in tx.columns:\n",
847
+ "# chunk[\"qv\"] = pd.to_numeric(tx[\"qv\"], downcast=\"integer\").values\n",
848
+ "# if include_cell_id and \"cell_id\" in tx.columns:\n",
849
+ "# chunk[\"cell_id\"] = tx[\"cell_id\"].astype(str).values\n",
850
+ "\n",
851
+ "# table = pa.Table.from_pandas(chunk, preserve_index=False)\n",
852
+ "# if writer is None:\n",
853
+ "# writer = pq.ParquetWriter(tmp_path, table.schema)\n",
854
+ "# writer.write_table(table)\n",
855
+ "\n",
856
+ "# written += len(chunk)\n",
857
+ "# print(f\"row group {rg + 1}/{pf.num_row_groups}: {written:,}\")\n",
858
+ "\n",
859
+ "# writer.close()\n",
860
+ "# print(\"All row groups written to tmp parquet. Building AnnData...\")\n",
861
+ "\n",
862
+ "# df = pd.read_parquet(tmp_path)\n",
863
+ "# df[\"gene\"] = df[\"gene\"].astype(\"category\")\n",
864
+ "# if include_cell_id and \"cell_id\" in df.columns:\n",
865
+ "# df[\"cell_id\"] = df[\"cell_id\"].astype(\"category\")\n",
866
+ "\n",
867
+ "# spatial = df[[\"spatial_x\", \"spatial_y\"]].to_numpy(dtype=np.float32)\n",
868
+ "# obs = df.drop(columns=[\"spatial_x\", \"spatial_y\"])\n",
869
+ "# obs.index = pd.RangeIndex(len(obs)).astype(str)\n",
870
+ "\n",
871
+ "# X = csc_matrix((len(obs), 0), dtype=np.float32)\n",
872
+ "# var = pd.DataFrame(index=pd.Index([], dtype=str))\n",
873
+ "# transcript_adata = ad.AnnData(X=X, obs=obs, var=var)\n",
874
+ "# transcript_adata.obsm[\"spatial\"] = spatial\n",
875
+ "# transcript_adata.write_h5ad(out_path)\n",
876
+ "\n",
877
+ "# os.remove(tmp_path)\n",
878
+ "# print(\"wrote:\", out_path)\n",
879
+ "# print(\"shape:\", transcript_adata.shape)\n",
880
+ "# print(\"obs columns:\", list(transcript_adata.obs.columns))\n",
881
+ "# return out_name\n",
882
+ "\n",
883
+ "\n",
884
+ "# transcript_h5ad = xenium_all_transcripts_to_h5ad_empty_X(\n",
885
+ "# xenium_dir=xenium_dir,\n",
886
+ "# basedir=basedir,\n",
887
+ "# transform=transform,\n",
888
+ "# min_qv=None,\n",
889
+ "# include_cell_id=False,\n",
890
+ "# tmp_path=\"/Volumes/T7 Shield/tmp/transcripts_tmp.parquet\",\n",
891
+ "# )"
892
+ ]
893
+ },
894
+ {
895
+ "cell_type": "code",
896
+ "execution_count": null,
897
+ "id": "02d53e78-c105-413c-9b30-f950b42ed200",
898
+ "metadata": {},
899
+ "outputs": [],
900
+ "source": [
901
+ "def xenium_all_transcripts_to_h5ad_empty_X(\n",
902
+ " xenium_dir,\n",
903
+ " basedir,\n",
904
+ " transform,\n",
905
+ " out_name=\"transcripts_all_emptyX_tmap.h5ad\",\n",
906
+ " min_qv=None,\n",
907
+ " include_cell_id=False,\n",
908
+ " tmp_path=None,\n",
909
+ "):\n",
910
+ " import os\n",
911
+ " import numpy as np\n",
912
+ " import pandas as pd\n",
913
+ " import pyarrow as pa\n",
914
+ " import pyarrow.parquet as pq\n",
915
+ " import h5py\n",
916
+ " from scipy.sparse import csc_matrix\n",
917
+ "\n",
918
+ " transcript_path = os.path.join(xenium_dir, \"transcripts.parquet\")\n",
919
+ " out_path = os.path.join(basedir, out_name)\n",
920
+ " if tmp_path is None:\n",
921
+ " tmp_path = out_path.replace(\".h5ad\", \"_tmp.parquet\")\n",
922
+ "\n",
923
+ " pf = pq.ParquetFile(transcript_path)\n",
924
+ " transform3 = np.asarray(transform, dtype=np.float64)[:3, :3]\n",
925
+ "\n",
926
+ " schema_cols = set(pf.schema.names)\n",
927
+ " cols = [\"x_location\", \"y_location\", \"feature_name\"]\n",
928
+ " if \"qv\" in schema_cols:\n",
929
+ " cols.append(\"qv\")\n",
930
+ " if include_cell_id and \"cell_id\" in schema_cols:\n",
931
+ " cols.append(\"cell_id\")\n",
932
+ "\n",
933
+ " # --- Pass 1: stream row groups → tmp parquet ---\n",
934
+ " writer = None\n",
935
+ " written = 0\n",
936
+ " for rg in range(pf.num_row_groups):\n",
937
+ " tx = pf.read_row_group(rg, columns=cols).to_pandas()\n",
938
+ " if min_qv is not None and \"qv\" in tx.columns:\n",
939
+ " tx = tx[tx[\"qv\"] >= min_qv]\n",
940
+ " if tx.empty:\n",
941
+ " continue\n",
942
+ "\n",
943
+ " x = tx[\"x_location\"].to_numpy(dtype=np.float64)\n",
944
+ " y = tx[\"y_location\"].to_numpy(dtype=np.float64)\n",
945
+ " xy1 = np.vstack([x, y, np.ones(len(tx), dtype=np.float64)])\n",
946
+ " out = transform3 @ xy1\n",
947
+ "\n",
948
+ " chunk = pd.DataFrame({\n",
949
+ " \"spatial_x\": (out[0] / out[2]).astype(np.float32),\n",
950
+ " \"spatial_y\": (out[1] / out[2]).astype(np.float32),\n",
951
+ " \"gene\": tx[\"feature_name\"].astype(str).values,\n",
952
+ " })\n",
953
+ " if \"qv\" in tx.columns:\n",
954
+ " chunk[\"qv\"] = pd.to_numeric(tx[\"qv\"], downcast=\"integer\").values\n",
955
+ " if include_cell_id and \"cell_id\" in tx.columns:\n",
956
+ " chunk[\"cell_id\"] = tx[\"cell_id\"].astype(str).values\n",
957
+ "\n",
958
+ " table = pa.Table.from_pandas(chunk, preserve_index=False)\n",
959
+ " if writer is None:\n",
960
+ " writer = pq.ParquetWriter(tmp_path, table.schema)\n",
961
+ " writer.write_table(table)\n",
962
+ " written += len(chunk)\n",
963
+ " print(f\"row group {rg + 1}/{pf.num_row_groups}: {written:,}\")\n",
964
+ "\n",
965
+ " writer.close()\n",
966
+ " total_rows = written\n",
967
+ " print(f\"Pass 1 done. {total_rows:,} rows. Writing h5ad...\")\n",
968
+ "\n",
969
+ " # --- Pass 2: stream tmp parquet → h5ad via h5py, one chunk at a time ---\n",
970
+ " pf2 = pq.ParquetFile(tmp_path)\n",
971
+ " obs_col_names = [c for c in pf2.schema.names if c not in (\"spatial_x\", \"spatial_y\")]\n",
972
+ "\n",
973
+ " with h5py.File(out_path, \"w\") as f:\n",
974
+ " # AnnData minimal structure\n",
975
+ " f.attrs[\"encoding-type\"] = \"anndata\"\n",
976
+ " f.attrs[\"encoding-version\"] = \"0.1.0\"\n",
977
+ "\n",
978
+ " # X group — empty (0 vars)\n",
979
+ " xgrp = f.create_group(\"X\")\n",
980
+ " xgrp.attrs[\"encoding-type\"] = \"array\"\n",
981
+ " xgrp.attrs[\"encoding-version\"] = \"0.2.0\"\n",
982
+ " xgrp.create_dataset(\"data\", data=np.array([], dtype=np.float32))\n",
983
+ " xgrp.create_dataset(\"indices\",data=np.array([], dtype=np.int32))\n",
984
+ " xgrp.create_dataset(\"indptr\", data=np.zeros(1, dtype=np.int32))\n",
985
+ " xgrp.attrs[\"shape\"] = [total_rows, 0]\n",
986
+ "\n",
987
+ " # obsm/spatial — pre-allocate, fill in chunks\n",
988
+ " obsm = f.create_group(\"obsm\")\n",
989
+ " spatial_ds = obsm.create_dataset(\n",
990
+ " \"spatial\", shape=(total_rows, 2), dtype=np.float32\n",
991
+ " )\n",
992
+ "\n",
993
+ " # obs — pre-allocate string datasets per column\n",
994
+ " obs_grp = f.create_group(\"obs\")\n",
995
+ " obs_grp.attrs[\"_index\"] = \"_index\"\n",
996
+ " obs_grp.attrs[\"encoding-type\"] = \"dataframe\"\n",
997
+ " obs_grp.attrs[\"encoding-version\"] = \"0.2.0\"\n",
998
+ " obs_grp.attrs[\"column-order\"] = obs_col_names\n",
999
+ "\n",
1000
+ " # pre-allocate index\n",
1001
+ " idx_ds = obs_grp.create_dataset(\n",
1002
+ " \"_index\", shape=(total_rows,), dtype=h5py.string_dtype()\n",
1003
+ " )\n",
1004
+ " col_datasets = {}\n",
1005
+ " for col in obs_col_names:\n",
1006
+ " col_datasets[col] = obs_grp.create_dataset(\n",
1007
+ " col, shape=(total_rows,), dtype=h5py.string_dtype()\n",
1008
+ " )\n",
1009
+ "\n",
1010
+ " # var — empty\n",
1011
+ " var_grp = f.create_group(\"var\")\n",
1012
+ " var_grp.attrs[\"_index\"] = \"_index\"\n",
1013
+ " var_grp.attrs[\"encoding-type\"] = \"dataframe\"\n",
1014
+ " var_grp.attrs[\"encoding-version\"] = \"0.2.0\"\n",
1015
+ " var_grp.attrs[\"column-order\"] = []\n",
1016
+ " var_grp.create_dataset(\"_index\", data=np.array([], dtype=h5py.string_dtype()))\n",
1017
+ "\n",
1018
+ " # stream fill\n",
1019
+ " cursor = 0\n",
1020
+ " for rg in range(pf2.num_row_groups):\n",
1021
+ " chunk = pf2.read_row_group(rg).to_pandas()\n",
1022
+ " n = len(chunk)\n",
1023
+ " sl = slice(cursor, cursor + n)\n",
1024
+ "\n",
1025
+ " spatial_ds[sl] = chunk[[\"spatial_x\", \"spatial_y\"]].to_numpy(dtype=np.float32)\n",
1026
+ " idx_ds[sl] = np.arange(cursor, cursor + n).astype(str)\n",
1027
+ " for col in obs_col_names:\n",
1028
+ " col_datasets[col][sl] = chunk[col].astype(str).values\n",
1029
+ "\n",
1030
+ " cursor += n\n",
1031
+ " if rg % 50 == 0:\n",
1032
+ " print(f\" h5ad pass {rg + 1}/{pf2.num_row_groups}: {cursor:,}\")\n",
1033
+ "\n",
1034
+ " os.remove(tmp_path)\n",
1035
+ " print(\"wrote:\", out_path)\n",
1036
+ " print(\"shape:\", (total_rows, 0))\n",
1037
+ " print(\"obs columns:\", obs_col_names)\n",
1038
+ " return out_name"
1039
+ ]
1040
+ },
1041
+ {
1042
+ "cell_type": "code",
1043
+ "execution_count": null,
1044
+ "id": "cc5c8636-ed10-47e9-bf9c-08d5608095f8",
1045
+ "metadata": {
1046
+ "scrolled": true
1047
+ },
1048
+ "outputs": [],
1049
+ "source": [
1050
+ "transcript_h5ad = xenium_all_transcripts_to_h5ad_empty_X(\n",
1051
+ " xenium_dir=xenium_dir,\n",
1052
+ " basedir=basedir,\n",
1053
+ " transform=transform,\n",
1054
+ " min_qv=None,\n",
1055
+ " include_cell_id=False,\n",
1056
+ " tmp_path=\"/Volumes/T7 Shield/tmp/transcripts_tmp.parquet\",\n",
1057
+ ")"
1058
+ ]
1059
+ },
1060
+ {
1061
+ "cell_type": "code",
1062
+ "execution_count": null,
1063
+ "id": "a53c9e37-da32-4583-a74c-604d60df358b",
1064
+ "metadata": {},
1065
+ "outputs": [],
1066
+ "source": [
1067
+ "# basedir = os.path.abspath(f\"tissuumaps/{sample}\")\n",
1068
+ "# transcript_csv = f\"transcripts_image_space.csv\"\n",
1069
+ "\n",
1070
+ "# print(basedir)\n",
1071
+ "\n",
1072
+ "# region_files = []\n",
1073
+ "\n",
1074
+ "# for geojson_path in glob.glob(os.path.join(basedir, \"*boundaries*.geojson\")):\n",
1075
+ "# geojson_name = os.path.basename(geojson_path)\n",
1076
+ "\n",
1077
+ "# region_files.append({\n",
1078
+ "# \"path\": geojson_name, # relative path only\n",
1079
+ "# \"title\": geojson_name,\n",
1080
+ "# \"comment\": geojson_name,\n",
1081
+ "# \"autoLoad\": True,\n",
1082
+ "# })\n",
1083
+ "\n",
1084
+ "# print(region_files)\n",
1085
+ "\n",
1086
+ "# image_layers = []\n",
1087
+ "\n",
1088
+ "# for tif_path in sorted(\n",
1089
+ "# glob.glob(os.path.join(basedir, \"morphology_focus_plane*_pyramid.tif\"))\n",
1090
+ "# ):\n",
1091
+ "# name = os.path.basename(tif_path)\n",
1092
+ "\n",
1093
+ "# image_layers.append({\n",
1094
+ "# \"name\": name.replace(\".tif\", \"\"),\n",
1095
+ "# \"tileSource\": name + \".dzi\",\n",
1096
+ "# \"x\": 0,\n",
1097
+ "# \"y\": 0,\n",
1098
+ "# \"scale\": 1,\n",
1099
+ "# \"rotation\": 0,\n",
1100
+ "# \"flip\": False,\n",
1101
+ "# })\n",
1102
+ "\n",
1103
+ "# print(f\"Found {len(image_layers)} image layers\")"
1104
+ ]
1105
+ },
1106
+ {
1107
+ "cell_type": "code",
1108
+ "execution_count": null,
1109
+ "id": "1ee1ac2d-6de4-4fe2-b31a-90725d67669c",
1110
+ "metadata": {},
1111
+ "outputs": [],
1112
+ "source": [
1113
+ "# # ----------------------------\n",
1114
+ "# # 5. Generate TissUUmaps project\n",
1115
+ "# # ----------------------------\n",
1116
+ "# project = read_h5ad.h5ad_to_tmap(basedir, out_h5ad_name)\n",
1117
+ "\n",
1118
+ "# # Images: all stacked and visible\n",
1119
+ "# project[\"layers\"] = image_layers\n",
1120
+ "# project[\"collectionMode\"] = False\n",
1121
+ "# project[\"compositeMode\"] = \"lighter\"\n",
1122
+ "# project[\"backgroundColor\"] = \"#000000\"\n",
1123
+ "\n",
1124
+ "# project[\"filters\"] = []\n",
1125
+ "# project[\"layerFilters\"] = {}\n",
1126
+ "# project[\"layerOpacities\"] = {str(i): 1 for i in range(len(image_layers))}\n",
1127
+ "# project[\"layerVisibilities\"] = {str(i): True for i in range(len(image_layers))}\n",
1128
+ "\n",
1129
+ "# # Polygons: autoload\n",
1130
+ "# project[\"regionFiles\"] = []\n",
1131
+ "# for rf in region_files:\n",
1132
+ "# rf = dict(rf)\n",
1133
+ "# rf[\"autoLoad\"] = True\n",
1134
+ "# project[\"regionFiles\"].append(rf)\n",
1135
+ "\n",
1136
+ "# # Keep h5ad/cell-expression dropdowns available, but not autoloaded\n",
1137
+ "# for mf in project.get(\"markerFiles\", []):\n",
1138
+ "# mf[\"autoLoad\"] = False\n",
1139
+ "# mf.setdefault(\"expectedHeader\", {})\n",
1140
+ "# mf[\"expectedHeader\"][\"shape_fixed\"] = \"disc\"\n",
1141
+ "# mf[\"expectedHeader\"][\"scale_factor\"] = 1\n",
1142
+ "\n",
1143
+ "# mf.setdefault(\"expectedRadios\", {})\n",
1144
+ "# mf[\"expectedRadios\"][\"shape_fixed\"] = True\n",
1145
+ "# mf[\"expectedRadios\"][\"shape_gr\"] = False\n",
1146
+ "# mf[\"expectedRadios\"][\"shape_gr_rand\"] = False\n",
1147
+ "# mf[\"expectedRadios\"][\"sortby_check\"] = False\n",
1148
+ "\n",
1149
+ "# # Transcripts: autoload default marker layer\n",
1150
+ "# if transcript_csv is not None:\n",
1151
+ "# project[\"markerFiles\"].insert(\n",
1152
+ "# 0,\n",
1153
+ "# {\n",
1154
+ "# \"path\": transcript_csv,\n",
1155
+ "# \"title\": \"Load transcripts\",\n",
1156
+ "# \"comment\": \"Transcript molecules\",\n",
1157
+ "# \"name\": \"Transcripts\",\n",
1158
+ "# \"uid\": \"transcripts\",\n",
1159
+ "# \"autoLoad\": True,\n",
1160
+ "# \"hideSettings\": True,\n",
1161
+ "# \"expectedHeader\": {\n",
1162
+ "# \"X\": \"x\",\n",
1163
+ "# \"Y\": \"y\",\n",
1164
+ "# \"gb_col\": \"gene\",\n",
1165
+ "# \"gb_name\": \"\",\n",
1166
+ "# \"cb_col\": \"\",\n",
1167
+ "# \"cb_cmap\": \"\",\n",
1168
+ "# \"scale_factor\": 0.15,\n",
1169
+ "# \"shape_fixed\": \"disc\",\n",
1170
+ "# \"opacity\": 0.7,\n",
1171
+ "# },\n",
1172
+ "# \"expectedRadios\": {\n",
1173
+ "# \"cb_col\": False,\n",
1174
+ "# \"cb_gr\": True,\n",
1175
+ "# \"cb_gr_rand\": True,\n",
1176
+ "# \"cb_gr_dict\": False,\n",
1177
+ "# \"cb_gr_key\": False,\n",
1178
+ "# \"pie_check\": False,\n",
1179
+ "# \"scale_check\": False,\n",
1180
+ "# \"shape_col\": False,\n",
1181
+ "# \"shape_fixed\": True,\n",
1182
+ "# \"shape_gr\": False,\n",
1183
+ "# \"shape_gr_rand\": False,\n",
1184
+ "# \"shape_gr_dict\": False,\n",
1185
+ "# \"sortby_check\": False,\n",
1186
+ "# },\n",
1187
+ "# },\n",
1188
+ "# )\n",
1189
+ "\n",
1190
+ "# # project[\"markerFiles\"].insert(\n",
1191
+ "# # 0,\n",
1192
+ "# # {\n",
1193
+ "# # \"path\": transcript_h5ad,\n",
1194
+ "# # \"title\": \"Load transcript AnnData\",\n",
1195
+ "# # \"comment\": \"All transcript molecules\",\n",
1196
+ "# # \"name\": \"Transcript AnnData\",\n",
1197
+ "# # \"uid\": \"transcript_h5ad\",\n",
1198
+ "# # \"autoLoad\": True,\n",
1199
+ "# # \"hideSettings\": True,\n",
1200
+ "# # \"expectedHeader\": {\n",
1201
+ "# # \"X\": \"/obsm/spatial;0\",\n",
1202
+ "# # \"Y\": \"/obsm/spatial;1\",\n",
1203
+ "# # \"gb_col\": \"/obs/gene\",\n",
1204
+ "# # \"gb_name\": \"\",\n",
1205
+ "# # \"cb_col\": \"\",\n",
1206
+ "# # \"cb_cmap\": \"\",\n",
1207
+ "# # \"scale_factor\": 0.15,\n",
1208
+ "# # \"shape_fixed\": \"disc\",\n",
1209
+ "# # \"opacity\": 0.7,\n",
1210
+ "# # },\n",
1211
+ "# # \"expectedRadios\": {\n",
1212
+ "# # \"cb_col\": False,\n",
1213
+ "# # \"cb_gr\": True,\n",
1214
+ "# # \"cb_gr_rand\": True,\n",
1215
+ "# # \"shape_fixed\": True,\n",
1216
+ "# # \"shape_gr\": False,\n",
1217
+ "# # \"scale_check\": False,\n",
1218
+ "# # \"sortby_check\": False,\n",
1219
+ "# # },\n",
1220
+ "# # },\n",
1221
+ "# # )\n",
1222
+ "\n",
1223
+ "# with open(project_path, \"w\") as f:\n",
1224
+ "# json.dump(project, f, indent=2)\n",
1225
+ "\n",
1226
+ "# viewer = tj.opentmap(project_path)"
1227
+ ]
1228
+ },
1229
+ {
1230
+ "cell_type": "code",
1231
+ "execution_count": null,
1232
+ "id": "68db233e-7105-4862-9635-c68875497962",
1233
+ "metadata": {},
1234
+ "outputs": [],
1235
+ "source": []
1236
+ },
1237
+ {
1238
+ "cell_type": "code",
1239
+ "execution_count": null,
1240
+ "id": "696e478b-61c6-4d35-8b90-813569c4a0ed",
1241
+ "metadata": {},
1242
+ "outputs": [],
1243
+ "source": []
1244
+ }
1245
+ ],
1246
+ "metadata": {
1247
+ "kernelspec": {
1248
+ "display_name": "Python (tissuumaps_env)",
1249
+ "language": "python",
1250
+ "name": "tissuumaps_env"
1251
+ },
1252
+ "language_info": {
1253
+ "codemirror_mode": {
1254
+ "name": "ipython",
1255
+ "version": 3
1256
+ },
1257
+ "file_extension": ".py",
1258
+ "mimetype": "text/x-python",
1259
+ "name": "python",
1260
+ "nbconvert_exporter": "python",
1261
+ "pygments_lexer": "ipython3",
1262
+ "version": "3.9.23"
1263
+ },
1264
+ "widgets": {
1265
+ "application/vnd.jupyter.widget-state+json": {
1266
+ "state": {},
1267
+ "version_major": 2,
1268
+ "version_minor": 0
1269
+ }
1270
+ }
1271
+ },
1272
+ "nbformat": 4,
1273
+ "nbformat_minor": 5
1274
+ }
notebooks/tissuumaps_viz.ipynb ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "07f7dbb1-63c6-40e4-b0d9-6ec104aa0adc",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# !pip install zarr\n",
11
+ "\n",
12
+ "import os\n",
13
+ "import json\n",
14
+ "from pathlib import Path\n",
15
+ "import glob\n",
16
+ "import numpy as np\n",
17
+ "import pandas as pd\n",
18
+ "import scanpy as sc\n",
19
+ "import pyvips\n",
20
+ "import zarr\n",
21
+ "import geopandas as gpd\n",
22
+ "from shapely.geometry import Polygon\n",
23
+ "from scipy.sparse import csc_matrix\n",
24
+ "\n",
25
+ "import tissuumaps.jupyter as tj\n",
26
+ "from tissuumaps import read_h5ad\n",
27
+ "\n",
28
+ "\n",
29
+ "# ----------------------------\n",
30
+ "# Paths\n",
31
+ "# ----------------------------\n",
32
+ "sample = \"WTA_Preview_FFPE_Cervical_Cancer_outs\"\n",
33
+ "# sample = \"Xenium_Prime_Human_Lymph_Node_Reactive_FFPE_outs\"\n",
34
+ "# sample = \"Xenium_Prime_Ovarian_Cancer_FFPE_XRrun_outs\"\n",
35
+ "# sample = \"Xenium_V1_humanLung_Cancer_FFPE_outs\"\n",
36
+ "\n",
37
+ "\n",
38
+ "xenium_dir = os.path.abspath(f\"../data/instrument_data/{sample}\")\n",
39
+ "basedir = os.path.abspath(f\"../data/processed_data/tissuumaps_h5ad/{sample}\")\n",
40
+ "os.makedirs(basedir, exist_ok=True)\n",
41
+ "\n",
42
+ "out_h5ad_name = f\"{sample}_tmap.h5ad\"\n",
43
+ "out_h5ad = os.path.join(basedir, out_h5ad_name)\n",
44
+ "\n",
45
+ "project_path = os.path.join(basedir, \"_project_h5ad.tmap\")"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "execution_count": null,
51
+ "id": "a53c9e37-da32-4583-a74c-604d60df358b",
52
+ "metadata": {},
53
+ "outputs": [],
54
+ "source": [
55
+ "basedir = os.path.abspath(f\"../data/processed_data/tissuumaps_h5ad/{sample}\")\n",
56
+ "# transcript_csv = f\"transcripts_image_space.csv\"\n",
57
+ "transcript_h5ad = f\"transcripts_all_emptyX_tmap.h5ad\"\n",
58
+ "\n",
59
+ "print(basedir)\n",
60
+ "\n",
61
+ "region_files = []\n",
62
+ "\n",
63
+ "for geojson_path in glob.glob(os.path.join(basedir, \"*boundaries*.geojson\")):\n",
64
+ " geojson_name = os.path.basename(geojson_path)\n",
65
+ "\n",
66
+ " region_files.append({\n",
67
+ " \"path\": geojson_name, # relative path only\n",
68
+ " \"title\": geojson_name,\n",
69
+ " \"comment\": geojson_name,\n",
70
+ " \"autoLoad\": True,\n",
71
+ " })\n",
72
+ "\n",
73
+ "print(region_files)\n",
74
+ "\n",
75
+ "image_layers = []\n",
76
+ "\n",
77
+ "for tif_path in sorted(\n",
78
+ " glob.glob(os.path.join(basedir, \"morphology_focus_plane*_pyramid.tif\"))\n",
79
+ "):\n",
80
+ " name = os.path.basename(tif_path)\n",
81
+ "\n",
82
+ " image_layers.append({\n",
83
+ " \"name\": name.replace(\".tif\", \"\"),\n",
84
+ " \"tileSource\": name + \".dzi\",\n",
85
+ " \"x\": 0,\n",
86
+ " \"y\": 0,\n",
87
+ " \"scale\": 1,\n",
88
+ " \"rotation\": 0,\n",
89
+ " \"flip\": False,\n",
90
+ " })\n",
91
+ "\n",
92
+ "print(f\"Found {len(image_layers)} image layers\")"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "execution_count": null,
98
+ "id": "bbcabbbd-3f76-48dd-b589-c80e47fc8cbc",
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "# ----------------------------\n",
103
+ "# 5. Generate TissUUmaps project\n",
104
+ "# ----------------------------\n",
105
+ "project = read_h5ad.h5ad_to_tmap(basedir, out_h5ad_name)\n",
106
+ "\n",
107
+ "# Images: all stacked and visible\n",
108
+ "project[\"layers\"] = image_layers\n",
109
+ "\n",
110
+ "project[\"collectionMode\"] = False\n",
111
+ "project[\"compositeMode\"] = \"lighter\"\n",
112
+ "project[\"backgroundColor\"] = \"#000000\"\n",
113
+ "\n",
114
+ "project[\"filters\"] = []\n",
115
+ "project[\"layerFilters\"] = {}\n",
116
+ "project[\"layerOpacities\"] = {str(i): 1 for i in range(len(image_layers))}\n",
117
+ "project[\"layerVisibilities\"] = {str(i): True for i in range(len(image_layers))}\n",
118
+ "\n",
119
+ "# Polygons: autoload\n",
120
+ "project[\"regionFiles\"] = []\n",
121
+ "for rf in region_files:\n",
122
+ " rf = dict(rf)\n",
123
+ " rf[\"autoLoad\"] = True\n",
124
+ " project[\"regionFiles\"].append(rf)\n",
125
+ "\n",
126
+ "for i, mf in enumerate(project.get(\"markerFiles\", [])):\n",
127
+ " mf.setdefault(\"expectedHeader\", {})\n",
128
+ " mf[\"expectedHeader\"][\"shape_fixed\"] = \"disc\"\n",
129
+ " mf[\"expectedHeader\"][\"scale_factor\"] = 1\n",
130
+ " mf.setdefault(\"expectedRadios\", {})\n",
131
+ " mf[\"expectedRadios\"][\"shape_fixed\"] = True\n",
132
+ " mf[\"expectedRadios\"][\"shape_gr\"] = False\n",
133
+ " mf[\"expectedRadios\"][\"shape_gr_rand\"] = False\n",
134
+ " mf[\"expectedRadios\"][\"sortby_check\"] = False\n",
135
+ "\n",
136
+ "# Transcripts: autoload default marker layer\n",
137
+ "# if transcript_csv is not None:\n",
138
+ "# project[\"markerFiles\"].insert(\n",
139
+ "# 0,\n",
140
+ "# {\n",
141
+ "# \"path\": transcript_csv,\n",
142
+ "# \"title\": \"Load transcripts\",\n",
143
+ "# \"comment\": \"Transcript molecules\",\n",
144
+ "# \"name\": \"Transcripts\",\n",
145
+ "# \"uid\": \"transcripts\",\n",
146
+ "# \"autoLoad\": True,\n",
147
+ "# \"hideSettings\": True,\n",
148
+ "# \"expectedHeader\": {\n",
149
+ "# \"X\": \"x\",\n",
150
+ "# \"Y\": \"y\",\n",
151
+ "# \"gb_col\": \"gene\",\n",
152
+ "# \"gb_name\": \"\",\n",
153
+ "# \"cb_col\": \"\",\n",
154
+ "# \"cb_cmap\": \"\",\n",
155
+ "# \"scale_factor\": 0.15,\n",
156
+ "# \"shape_fixed\": \"disc\",\n",
157
+ "# \"opacity\": 0.7,\n",
158
+ "# },\n",
159
+ "# \"expectedRadios\": {\n",
160
+ "# \"cb_col\": False,\n",
161
+ "# \"cb_gr\": True,\n",
162
+ "# \"cb_gr_rand\": True,\n",
163
+ "# \"cb_gr_dict\": False,\n",
164
+ "# \"cb_gr_key\": False,\n",
165
+ "# \"pie_check\": False,\n",
166
+ "# \"scale_check\": False,\n",
167
+ "# \"shape_col\": False,\n",
168
+ "# \"shape_fixed\": True,\n",
169
+ "# \"shape_gr\": False,\n",
170
+ "# \"shape_gr_rand\": False,\n",
171
+ "# \"shape_gr_dict\": False,\n",
172
+ "# \"sortby_check\": False,\n",
173
+ "# },\n",
174
+ "# },\n",
175
+ "# )\n",
176
+ "\n",
177
+ "project[\"markerFiles\"].insert(\n",
178
+ " 0,\n",
179
+ " {\n",
180
+ " \"path\": transcript_h5ad,\n",
181
+ " \"title\": \"Load transcript AnnData\",\n",
182
+ " \"comment\": \"All transcript molecules\",\n",
183
+ " \"name\": \"Transcript AnnData\",\n",
184
+ " \"uid\": \"transcript_h5ad\",\n",
185
+ " \"autoLoad\": True,\n",
186
+ " \"hideSettings\": True,\n",
187
+ " \"expectedHeader\": {\n",
188
+ " \"X\": \"/obsm/spatial;0\",\n",
189
+ " \"Y\": \"/obsm/spatial;1\",\n",
190
+ " \"gb_col\": \"/obs/gene\",\n",
191
+ " \"gb_name\": \"\",\n",
192
+ " \"cb_col\": \"\",\n",
193
+ " \"cb_cmap\": \"\",\n",
194
+ " \"scale_factor\": 0.15,\n",
195
+ " \"shape_fixed\": \"disc\",\n",
196
+ " \"opacity\": 0.7,\n",
197
+ " },\n",
198
+ " \"expectedRadios\": {\n",
199
+ " \"cb_col\": False,\n",
200
+ " \"cb_gr\": True,\n",
201
+ " \"cb_gr_rand\": True,\n",
202
+ " \"shape_fixed\": True,\n",
203
+ " \"shape_gr\": False,\n",
204
+ " \"scale_check\": False,\n",
205
+ " \"sortby_check\": False,\n",
206
+ " },\n",
207
+ " },\n",
208
+ ")\n",
209
+ "\n",
210
+ "# Set autoLoad explicitly by name after insert\n",
211
+ "for mf in project[\"markerFiles\"]:\n",
212
+ " if mf.get(\"name\") in (\"Transcript AnnData\", \"Categorical observations\"):\n",
213
+ " mf[\"autoLoad\"] = True\n",
214
+ " else:\n",
215
+ " mf[\"autoLoad\"] = False\n",
216
+ "\n",
217
+ "with open(project_path, \"w\") as f:\n",
218
+ " json.dump(project, f, indent=2)\n",
219
+ "\n",
220
+ "print(\"done\")"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "code",
225
+ "execution_count": null,
226
+ "id": "1ee1ac2d-6de4-4fe2-b31a-90725d67669c",
227
+ "metadata": {},
228
+ "outputs": [],
229
+ "source": [
230
+ "viewer = tj.opentmap(project_path)\n",
231
+ "viewer"
232
+ ]
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "execution_count": null,
237
+ "id": "db4873e9-ba2e-4814-80a9-e32f92a5677a",
238
+ "metadata": {},
239
+ "outputs": [],
240
+ "source": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "execution_count": null,
245
+ "id": "7394d91a-54ad-49b1-834f-bda9f24f4944",
246
+ "metadata": {},
247
+ "outputs": [],
248
+ "source": []
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "execution_count": null,
253
+ "id": "68db233e-7105-4862-9635-c68875497962",
254
+ "metadata": {},
255
+ "outputs": [],
256
+ "source": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": null,
261
+ "id": "4c8a97c2-3285-4b9d-8a6c-7bdb6a89c4a8",
262
+ "metadata": {},
263
+ "outputs": [],
264
+ "source": []
265
+ }
266
+ ],
267
+ "metadata": {
268
+ "kernelspec": {
269
+ "display_name": "Python (tissuumaps_env)",
270
+ "language": "python",
271
+ "name": "tissuumaps_env"
272
+ },
273
+ "language_info": {
274
+ "codemirror_mode": {
275
+ "name": "ipython",
276
+ "version": 3
277
+ },
278
+ "file_extension": ".py",
279
+ "mimetype": "text/x-python",
280
+ "name": "python",
281
+ "nbconvert_exporter": "python",
282
+ "pygments_lexer": "ipython3",
283
+ "version": "3.9.23"
284
+ },
285
+ "widgets": {
286
+ "application/vnd.jupyter.widget-state+json": {
287
+ "state": {},
288
+ "version_major": 2,
289
+ "version_minor": 0
290
+ }
291
+ }
292
+ },
293
+ "nbformat": 4,
294
+ "nbformat_minor": 5
295
+ }
notebooks/vitessce_pre-process.ipynb ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "nbsphinx": "hidden"
7
+ },
8
+ "source": [
9
+ "# Vitessce Widget Tutorial"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "# Visualization of a SpatialData object"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {},
22
+ "source": [
23
+ "## Import dependencies\n"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "import os\n",
33
+ "from os.path import join, isfile, isdir\n",
34
+ "from urllib.request import urlretrieve\n",
35
+ "import zipfile\n",
36
+ "import shutil\n",
37
+ "\n",
38
+ "from vitessce import (\n",
39
+ " VitessceConfig,\n",
40
+ " ViewType as vt,\n",
41
+ " CoordinationType as ct,\n",
42
+ " CoordinationLevel as CL,\n",
43
+ " SpatialDataWrapper,\n",
44
+ " get_initial_coordination_scope_prefix\n",
45
+ ")\n",
46
+ "\n",
47
+ "from vitessce.data_utils import (\n",
48
+ " sdata_morton_sort_points,\n",
49
+ " sdata_points_process_columns,\n",
50
+ " sdata_points_write_bounding_box_attrs,\n",
51
+ " sdata_points_modify_row_group_size,\n",
52
+ " sdata_morton_query_rect,\n",
53
+ ")"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": null,
59
+ "metadata": {},
60
+ "outputs": [],
61
+ "source": [
62
+ "from spatialdata import read_zarr\n",
63
+ "\n",
64
+ "import anndata as ad\n",
65
+ "\n",
66
+ "ad.settings.zarr_write_format = 3\n",
67
+ "print(ad.settings.zarr_write_format)"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": null,
73
+ "metadata": {},
74
+ "outputs": [],
75
+ "source": [
76
+ "import dask\n",
77
+ "import tempfile\n",
78
+ "\n",
79
+ "# Point Dask temp dir to your external drive\n",
80
+ "dask.config.set({'temporary_directory': '/Volumes/T7 Shield/tmp'})\n",
81
+ "\n",
82
+ "# Create the dir if it doesn't exist\n",
83
+ "import os\n",
84
+ "os.makedirs('/Volumes/T7 Shield/tmp', exist_ok=True)"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "execution_count": null,
90
+ "metadata": {},
91
+ "outputs": [],
92
+ "source": [
93
+ "ls"
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "execution_count": null,
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "from pathlib import Path\n",
103
+ "from spatialdata_io import xenium\n",
104
+ "import spatialdata as sd\n",
105
+ "import pandas as pd\n",
106
+ "\n",
107
+ "xenium_dir = Path(\"../data/instrument_data/Xenium_V1_hPancreas_Cancer_Add_on_FFPE_outs/\") # folder containing experiment.xenium\n",
108
+ "out_zarr = Path(\"../data/processed_data/vitessce/Xenium_V1_hPancreas_Cancer_Add_on_FFPE_outs.zarr\")\n",
109
+ "\n",
110
+ "sdata = xenium(\n",
111
+ " xenium_dir,\n",
112
+ " cells_boundaries=True,\n",
113
+ " nucleus_boundaries=True,\n",
114
+ " cells_labels=True,\n",
115
+ " nucleus_labels=True,\n",
116
+ " transcripts=True,\n",
117
+ " morphology_focus=True,\n",
118
+ " aligned_images=True,\n",
119
+ " cells_table=True,\n",
120
+ " gex_only=True,\n",
121
+ ")\n",
122
+ "\n",
123
+ "print(sdata)\n"
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "execution_count": null,
129
+ "metadata": {},
130
+ "outputs": [],
131
+ "source": [
132
+ "# Add cluster labels from Xenium instrument output\n",
133
+ "clusters = pd.read_csv(\n",
134
+ " xenium_dir / \"analysis/clustering/gene_expression_graphclust/clusters.csv\"\n",
135
+ ")\n",
136
+ "sdata.tables[\"table\"].obs = sdata.tables[\"table\"].obs.merge(\n",
137
+ " clusters.set_index(\"Barcode\")[[\"Cluster\"]].rename(columns={\"Cluster\": \"leiden\"}),\n",
138
+ " left_index=True,\n",
139
+ " right_index=True,\n",
140
+ " how=\"left\",\n",
141
+ ")\n",
142
+ "sdata.tables[\"table\"].obs[\"leiden\"] = sdata.tables[\"table\"].obs[\"leiden\"].astype(str)\n"
143
+ ]
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "execution_count": null,
148
+ "metadata": {},
149
+ "outputs": [],
150
+ "source": [
151
+ "# Save as a SpatialData Zarr store\n",
152
+ "sdata.write(out_zarr)\n"
153
+ ]
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": null,
158
+ "metadata": {},
159
+ "outputs": [],
160
+ "source": [
161
+ "sdata[\"transcripts\"].shape[0].compute()"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": null,
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "sdata.tables[\"table\"].X = sdata.tables[\"table\"].X.toarray()\n",
171
+ "sdata.tables[\"dense_table\"] = sdata.tables[\"table\"]\n",
172
+ "sdata.write_element(\"dense_table\")"
173
+ ]
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "execution_count": null,
178
+ "metadata": {},
179
+ "outputs": [],
180
+ "source": [
181
+ "# TODO: store the two separate images as a single image with two channels.\n",
182
+ "# Similar to https://github.com/EricMoerthVis/tissue-map-tools/pull/12"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": null,
188
+ "metadata": {},
189
+ "outputs": [],
190
+ "source": [
191
+ "# sdata.tables['table'].obs"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": null,
197
+ "metadata": {},
198
+ "outputs": [],
199
+ "source": [
200
+ "# sdata"
201
+ ]
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "execution_count": null,
206
+ "metadata": {},
207
+ "outputs": [],
208
+ "source": [
209
+ "# sdata.points['transcripts'].head()"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "markdown",
214
+ "metadata": {},
215
+ "source": [
216
+ "## Sorting Points and creating a new Points element in the SpatialData object"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "markdown",
221
+ "metadata": {},
222
+ "source": [
223
+ "### Step 1. Sort rows with `sdata_morton_sort_points`"
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "execution_count": null,
229
+ "metadata": {},
230
+ "outputs": [],
231
+ "source": [
232
+ "import importlib.metadata\n",
233
+ "print(importlib.metadata.version(\"vitessce\"))"
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "execution_count": null,
239
+ "metadata": {},
240
+ "outputs": [],
241
+ "source": [
242
+ "# sdata = sdata_morton_sort_points(sdata, \"transcripts\")\n",
243
+ "from vitessce.data_utils.spatialdata_points_zorder import norm_ddf_to_uint, morton_interleave\n",
244
+ "\n",
245
+ "element = \"transcripts\"\n",
246
+ "ddf = sdata.points[element]\n",
247
+ "attrs = ddf.attrs.copy()\n",
248
+ "\n",
249
+ "ddf = norm_ddf_to_uint(ddf)\n",
250
+ "ddf[\"morton_code_2d\"] = morton_interleave(ddf)\n",
251
+ "sorted_ddf = ddf.sort_values(by=\"morton_code_2d\", ascending=True)\n",
252
+ "sorted_ddf.attrs.update(attrs)\n",
253
+ "sdata.points[element] = sorted_ddf"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "markdown",
258
+ "metadata": {},
259
+ "source": [
260
+ "### Step 2. Clean up columns with `sdata_points_process_columns`"
261
+ ]
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "execution_count": null,
266
+ "metadata": {},
267
+ "outputs": [],
268
+ "source": [
269
+ "# Add feature_index column to dataframe, and reorder columns so that feature_name (dict column) is the rightmost column.\n",
270
+ "ddf = sdata_points_process_columns(sdata, \"transcripts\", var_name_col=\"feature_name\", table_name=\"table\")"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "execution_count": null,
276
+ "metadata": {},
277
+ "outputs": [],
278
+ "source": [
279
+ "# ddf.head()"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "markdown",
284
+ "metadata": {},
285
+ "source": [
286
+ "### Step 3. Save sorted dataframe to new Points element"
287
+ ]
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "execution_count": null,
292
+ "metadata": {},
293
+ "outputs": [],
294
+ "source": [
295
+ "# sdata[\"transcripts_with_morton_codes\"] = ddf\n",
296
+ "# sdata.write_element(\"transcripts_with_morton_codes\")\n",
297
+ "\n",
298
+ "from spatialdata.models import PointsModel\n",
299
+ "\n",
300
+ "transformations = sdata[\"transcripts\"].attrs[\"transform\"]\n",
301
+ "del ddf.attrs[\"transform\"]\n",
302
+ "\n",
303
+ "sdata[\"transcripts_with_morton_codes\"] = PointsModel.parse(\n",
304
+ " ddf, feature_key=\"feature_name\", instance_key=\"cell_id\", transformations=transformations\n",
305
+ ")\n",
306
+ "sdata.write_element(\"transcripts_with_morton_codes\")"
307
+ ]
308
+ },
309
+ {
310
+ "cell_type": "markdown",
311
+ "metadata": {},
312
+ "source": [
313
+ "### Step 4. Write bounding box metadata with `sdata_points_write_bounding_box_attrs`"
314
+ ]
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "execution_count": null,
319
+ "metadata": {},
320
+ "outputs": [],
321
+ "source": [
322
+ "import shutil\n",
323
+ "import os\n",
324
+ "\n",
325
+ "tmp_dir = '/Volumes/T7 Shield/tmp'\n",
326
+ "shutil.rmtree(tmp_dir)\n",
327
+ "os.makedirs(tmp_dir)\n",
328
+ "print(\"Done\")"
329
+ ]
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "execution_count": null,
334
+ "metadata": {},
335
+ "outputs": [],
336
+ "source": [
337
+ "sdata_points_write_bounding_box_attrs(sdata, \"transcripts_with_morton_codes\")"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "metadata": {},
343
+ "source": [
344
+ "### Step 5. Modify the row group sizes of the Parquet files with `sdata_points_modify_row_group_size`"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": null,
350
+ "metadata": {},
351
+ "outputs": [],
352
+ "source": [
353
+ "import shutil\n",
354
+ "import os\n",
355
+ "\n",
356
+ "tmp_dir = '/Volumes/T7 Shield/tmp'\n",
357
+ "shutil.rmtree(tmp_dir)\n",
358
+ "os.makedirs(tmp_dir)\n",
359
+ "print(\"Done\")"
360
+ ]
361
+ },
362
+ {
363
+ "cell_type": "code",
364
+ "execution_count": null,
365
+ "metadata": {},
366
+ "outputs": [],
367
+ "source": [
368
+ "sdata_points_modify_row_group_size(sdata, \"transcripts_with_morton_codes\", row_group_size=25_000)"
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "code",
373
+ "execution_count": null,
374
+ "metadata": {},
375
+ "outputs": [],
376
+ "source": [
377
+ "# Done"
378
+ ]
379
+ },
380
+ {
381
+ "cell_type": "code",
382
+ "execution_count": null,
383
+ "metadata": {},
384
+ "outputs": [],
385
+ "source": [
386
+ "# Optionally, check the number of row groups in one of the parquet file parts.\n",
387
+ "import pyarrow.parquet as pq\n",
388
+ "from os.path import join\n",
389
+ "\n",
390
+ "parquet_file = pq.ParquetFile(join(sdata.path, \"points\", \"transcripts_with_morton_codes\", \"points.parquet\", \"part.0.parquet\"))\n",
391
+ "\n",
392
+ "# Get the number of row groups in this part-0 file.\n",
393
+ "num_groups = parquet_file.num_row_groups\n",
394
+ "num_groups"
395
+ ]
396
+ },
397
+ {
398
+ "cell_type": "code",
399
+ "execution_count": null,
400
+ "metadata": {},
401
+ "outputs": [],
402
+ "source": []
403
+ }
404
+ ],
405
+ "metadata": {
406
+ "kernelspec": {
407
+ "display_name": "Python 3 (ipykernel)",
408
+ "language": "python",
409
+ "name": "python3"
410
+ },
411
+ "language_info": {
412
+ "codemirror_mode": {
413
+ "name": "ipython",
414
+ "version": 3
415
+ },
416
+ "file_extension": ".py",
417
+ "mimetype": "text/x-python",
418
+ "name": "python",
419
+ "nbconvert_exporter": "python",
420
+ "pygments_lexer": "ipython3",
421
+ "version": "3.12.1"
422
+ },
423
+ "widgets": {
424
+ "application/vnd.jupyter.widget-state+json": {
425
+ "state": {
426
+ "undefined": {
427
+ "model_module": "anywidget",
428
+ "model_module_version": "2.0.0",
429
+ "model_name": "AnyModel",
430
+ "state": {
431
+ "_view_name": "ErrorWidgetView",
432
+ "error": {},
433
+ "msg": "Model class 'AnyModel' from module 'anywidget' is loaded but can not be instantiated"
434
+ }
435
+ }
436
+ },
437
+ "version_major": 2,
438
+ "version_minor": 0
439
+ }
440
+ }
441
+ },
442
+ "nbformat": 4,
443
+ "nbformat_minor": 4
444
+ }
notebooks/vitessce_viz.ipynb ADDED
@@ -0,0 +1,1133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "nbsphinx": "hidden"
7
+ },
8
+ "source": [
9
+ "# Vitessce Widget Tutorial"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "# Visualization of a SpatialData object"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {},
22
+ "source": [
23
+ "## Import dependencies\n"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "import os\n",
33
+ "from os.path import join, isfile, isdir\n",
34
+ "from urllib.request import urlretrieve\n",
35
+ "import zipfile\n",
36
+ "import shutil\n",
37
+ "\n",
38
+ "from vitessce import (\n",
39
+ " VitessceConfig,\n",
40
+ " ViewType as vt,\n",
41
+ " CoordinationType as ct,\n",
42
+ " CoordinationLevel as CL,\n",
43
+ " SpatialDataWrapper,\n",
44
+ " get_initial_coordination_scope_prefix\n",
45
+ ")\n",
46
+ "\n",
47
+ "from vitessce.data_utils import (\n",
48
+ " sdata_morton_sort_points,\n",
49
+ " sdata_points_process_columns,\n",
50
+ " sdata_points_write_bounding_box_attrs,\n",
51
+ " sdata_points_modify_row_group_size,\n",
52
+ " sdata_morton_query_rect,\n",
53
+ ")"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": null,
59
+ "metadata": {},
60
+ "outputs": [],
61
+ "source": [
62
+ "from pathlib import Path\n",
63
+ "from spatialdata_io import xenium\n",
64
+ "import spatialdata as sd\n",
65
+ "import pandas as pd"
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "execution_count": null,
71
+ "metadata": {},
72
+ "outputs": [],
73
+ "source": [
74
+ "from spatialdata import read_zarr\n",
75
+ "\n",
76
+ "import anndata as ad\n",
77
+ "\n",
78
+ "ad.settings.zarr_write_format = 3\n",
79
+ "print(ad.settings.zarr_write_format)"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": null,
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "ls"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "markdown",
93
+ "metadata": {},
94
+ "source": [
95
+ "## Configure Vitessce\n",
96
+ "\n",
97
+ "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."
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": null,
103
+ "metadata": {},
104
+ "outputs": [],
105
+ "source": [
106
+ "# out_zarr = \"../data/processed_data/vitessce/WTA_Preview_FFPE_Cervical_Cancer_outs.zarr\"\n",
107
+ "# out_zarr = \"../data/processed_data/vitessce/Xenium_Prime_Human_Lymph_Node_Reactive_FFPE_outs.zarr\"\n",
108
+ "# out_zarr = \"../data/processed_data/vitessce/Xenium_Prime_Ovarian_Cancer_FFPE_XRrun_outs.zarr\"\n",
109
+ "out_zarr = \"../data/processed_data/vitessce/Xenium_V1_humanLung_Cancer_FFPE_outs.zarr\""
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "execution_count": null,
115
+ "metadata": {},
116
+ "outputs": [],
117
+ "source": [
118
+ "vc = VitessceConfig(\n",
119
+ " schema_version=\"1.0.18\",\n",
120
+ " name='Xenium SpatialData Demo',\n",
121
+ ")\n",
122
+ "\n",
123
+ "# Cell segmentations + gene expression\n",
124
+ "wrapper = SpatialDataWrapper(\n",
125
+ " sdata_path=out_zarr,\n",
126
+ " image_path=\"images/morphology_focus\",\n",
127
+ " table_path=\"tables/table\",\n",
128
+ " obs_feature_matrix_path=\"tables/table/X\",\n",
129
+ " obs_segmentations_path=\"shapes/cell_boundaries\",\n",
130
+ " # obs_set_paths=[\"tables/table/obs/leiden\"],\n",
131
+ " # obs_set_names=[\"Cluster\"],\n",
132
+ " coordinate_system=\"global\",\n",
133
+ " coordination_values={\n",
134
+ " \"obsType\": \"cell\",\n",
135
+ " }\n",
136
+ ")\n",
137
+ "\n",
138
+ "# Transcripts\n",
139
+ "points_wrapper = SpatialDataWrapper(\n",
140
+ " sdata_path=out_zarr,\n",
141
+ " obs_points_path=\"points/transcripts_with_morton_codes\",\n",
142
+ " obs_feature_matrix_path=\"tables/dense_table/X\",\n",
143
+ " coordinate_system=\"global\",\n",
144
+ " coordination_values={\n",
145
+ " \"obsType\": \"point\",\n",
146
+ " \"featureType\": \"gene\",\n",
147
+ " }\n",
148
+ ")\n",
149
+ "\n",
150
+ "dataset = vc.add_dataset(name='Xenium').add_object(wrapper).add_object(points_wrapper)\n",
151
+ "\n",
152
+ "spatial = vc.add_view(\"spatialBeta\", dataset=dataset)\n",
153
+ "feature_list = vc.add_view(\"featureList\", dataset=dataset)\n",
154
+ "layer_controller = vc.add_view(\"layerControllerBeta\", dataset=dataset)\n",
155
+ "obs_sets = vc.add_view(\"obsSets\", dataset=dataset)\n",
156
+ "\n",
157
+ "vc.link_views_by_dict([spatial, layer_controller], {\n",
158
+ " 'segmentationLayer': CL([{\n",
159
+ " 'segmentationChannel': CL([{\n",
160
+ " 'obsType': 'cell',\n",
161
+ " # 'obsColorEncoding': 'cellSetSelection', # <-- this makes it default to cluster colors\n",
162
+ " }]),\n",
163
+ " }]),\n",
164
+ "}, scope_prefix=get_initial_coordination_scope_prefix(\"A\", \"obsSegmentations\"))\n",
165
+ "\n",
166
+ "vc.link_views_by_dict([spatial, layer_controller], {\n",
167
+ " 'pointLayer': CL([{\n",
168
+ " 'obsType': 'point',\n",
169
+ " }]),\n",
170
+ "}, scope_prefix=get_initial_coordination_scope_prefix(\"A\", \"obsPoints\"))\n",
171
+ "\n",
172
+ "vc.link_views([spatial, layer_controller, feature_list, obs_sets], ['obsType'], [wrapper.obs_type_label])\n",
173
+ "\n",
174
+ "# vc.layout(spatial | (feature_list / layer_controller / obs_sets))\n",
175
+ "vc.layout(spatial)\n"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "markdown",
180
+ "metadata": {},
181
+ "source": [
182
+ "### Render the widget"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": null,
188
+ "metadata": {},
189
+ "outputs": [],
190
+ "source": [
191
+ "vw = vc.widget()\n",
192
+ "vw"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "execution_count": null,
198
+ "metadata": {},
199
+ "outputs": [],
200
+ "source": []
201
+ }
202
+ ],
203
+ "metadata": {
204
+ "kernelspec": {
205
+ "display_name": "Python 3 (ipykernel)",
206
+ "language": "python",
207
+ "name": "python3"
208
+ },
209
+ "language_info": {
210
+ "codemirror_mode": {
211
+ "name": "ipython",
212
+ "version": 3
213
+ },
214
+ "file_extension": ".py",
215
+ "mimetype": "text/x-python",
216
+ "name": "python",
217
+ "nbconvert_exporter": "python",
218
+ "pygments_lexer": "ipython3",
219
+ "version": "3.12.1"
220
+ },
221
+ "widgets": {
222
+ "application/vnd.jupyter.widget-state+json": {
223
+ "state": {
224
+ "8fa17251e5d6449a84f5cbc270c6674d": {
225
+ "model_module": "anywidget",
226
+ "model_module_version": "2.0.0",
227
+ "model_name": "AnyModel",
228
+ "state": {
229
+ "_anywidget_id": "vitessce.widget.VitessceWidget",
230
+ "_config": {
231
+ "coordinationSpace": {
232
+ "additionalObsSets": {
233
+ "A": null
234
+ },
235
+ "dataset": {
236
+ "A": "A",
237
+ "init_A_image_0": "init_A_image_0",
238
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
239
+ },
240
+ "featureAggregationStrategy": {
241
+ "A": null,
242
+ "B": null
243
+ },
244
+ "featureColor": {
245
+ "A": null
246
+ },
247
+ "featureFilter": {
248
+ "A": null
249
+ },
250
+ "featureFilterMode": {
251
+ "A": null
252
+ },
253
+ "featureHighlight": {
254
+ "A": null
255
+ },
256
+ "featureSelection": {
257
+ "A": null
258
+ },
259
+ "featureType": {
260
+ "A": "gene"
261
+ },
262
+ "featureValueColormap": {
263
+ "A": "plasma",
264
+ "init_A_obsSegmentations_0": "plasma"
265
+ },
266
+ "featureValueColormapRange": {
267
+ "A": [
268
+ 0,
269
+ 1
270
+ ]
271
+ },
272
+ "featureValueType": {
273
+ "A": "expression"
274
+ },
275
+ "fileUid": {
276
+ "A": null,
277
+ "init_A_image_0": null,
278
+ "init_A_obsSegmentations_0": null
279
+ },
280
+ "imageChannel": {
281
+ "A": null,
282
+ "init_A_image_0": "__dummy__",
283
+ "init_A_image_1": "__dummy__",
284
+ "init_A_image_2": "__dummy__",
285
+ "init_A_image_3": "__dummy__"
286
+ },
287
+ "imageLayer": {
288
+ "A": null,
289
+ "init_A_image_0": "__dummy__"
290
+ },
291
+ "legendVisible": {
292
+ "A": true
293
+ },
294
+ "metaCoordinationScopes": {
295
+ "init_A_image_0": {
296
+ "imageLayer": [
297
+ "init_A_image_0"
298
+ ],
299
+ "spatialImageLayer": "init_A_image_0",
300
+ "spatialTargetT": "init_A_image_0",
301
+ "spatialTargetZ": "init_A_image_0"
302
+ },
303
+ "init_A_obsPoints_0": {
304
+ "pointLayer": [
305
+ "init_A_obsPoints_0"
306
+ ]
307
+ },
308
+ "init_A_obsSegmentations_0": {
309
+ "segmentationLayer": [
310
+ "init_A_obsSegmentations_0"
311
+ ]
312
+ }
313
+ },
314
+ "metaCoordinationScopesBy": {
315
+ "init_A_image_0": {
316
+ "imageChannel": {
317
+ "spatialChannelColor": {
318
+ "init_A_image_0": "init_A_image_0",
319
+ "init_A_image_1": "init_A_image_1",
320
+ "init_A_image_2": "init_A_image_2",
321
+ "init_A_image_3": "init_A_image_3"
322
+ },
323
+ "spatialChannelOpacity": {
324
+ "init_A_image_0": "init_A_image_0",
325
+ "init_A_image_1": "init_A_image_1",
326
+ "init_A_image_2": "init_A_image_2",
327
+ "init_A_image_3": "init_A_image_3"
328
+ },
329
+ "spatialChannelVisible": {
330
+ "init_A_image_0": "init_A_image_0",
331
+ "init_A_image_1": "init_A_image_1",
332
+ "init_A_image_2": "init_A_image_2",
333
+ "init_A_image_3": "init_A_image_3"
334
+ },
335
+ "spatialChannelWindow": {
336
+ "init_A_image_0": "init_A_image_0",
337
+ "init_A_image_1": "init_A_image_1",
338
+ "init_A_image_2": "init_A_image_2",
339
+ "init_A_image_3": "init_A_image_3"
340
+ },
341
+ "spatialTargetC": {
342
+ "init_A_image_0": "init_A_image_0",
343
+ "init_A_image_1": "init_A_image_1",
344
+ "init_A_image_2": "init_A_image_2",
345
+ "init_A_image_3": "init_A_image_3"
346
+ }
347
+ },
348
+ "imageLayer": {
349
+ "fileUid": {
350
+ "init_A_image_0": "init_A_image_0"
351
+ },
352
+ "imageChannel": {
353
+ "init_A_image_0": [
354
+ "init_A_image_0",
355
+ "init_A_image_1",
356
+ "init_A_image_2",
357
+ "init_A_image_3"
358
+ ]
359
+ },
360
+ "photometricInterpretation": {
361
+ "init_A_image_0": "init_A_image_0"
362
+ },
363
+ "spatialLayerOpacity": {
364
+ "init_A_image_0": "init_A_image_0"
365
+ },
366
+ "spatialLayerVisible": {
367
+ "init_A_image_0": "init_A_image_0"
368
+ },
369
+ "spatialTargetResolution": {
370
+ "init_A_image_0": "init_A_image_0"
371
+ },
372
+ "volumetricRenderingAlgorithm": {
373
+ "init_A_image_0": "init_A_image_0"
374
+ }
375
+ }
376
+ },
377
+ "init_A_obsPoints_0": {
378
+ "pointLayer": {
379
+ "obsType": {
380
+ "init_A_obsPoints_0": "init_A_obsPoints_0"
381
+ }
382
+ }
383
+ },
384
+ "init_A_obsSegmentations_0": {
385
+ "segmentationChannel": {
386
+ "featureValueColormap": {
387
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
388
+ },
389
+ "obsColorEncoding": {
390
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
391
+ },
392
+ "obsHighlight": {
393
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
394
+ },
395
+ "obsType": {
396
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
397
+ },
398
+ "spatialChannelColor": {
399
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
400
+ },
401
+ "spatialChannelOpacity": {
402
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
403
+ },
404
+ "spatialChannelVisible": {
405
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
406
+ },
407
+ "spatialChannelWindow": {
408
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
409
+ },
410
+ "spatialSegmentationFilled": {
411
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
412
+ },
413
+ "spatialSegmentationStrokeWidth": {
414
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
415
+ }
416
+ },
417
+ "segmentationLayer": {
418
+ "fileUid": {
419
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
420
+ },
421
+ "segmentationChannel": {
422
+ "init_A_obsSegmentations_0": [
423
+ "init_A_obsSegmentations_0"
424
+ ]
425
+ },
426
+ "spatialLayerOpacity": {
427
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
428
+ },
429
+ "spatialLayerVisible": {
430
+ "init_A_obsSegmentations_0": "init_A_obsSegmentations_0"
431
+ }
432
+ }
433
+ }
434
+ },
435
+ "moleculeHighlight": {
436
+ "A": null
437
+ },
438
+ "obsColorEncoding": {
439
+ "A": "cellSetSelection",
440
+ "init_A_obsSegmentations_0": "spatialChannelColor"
441
+ },
442
+ "obsFilter": {
443
+ "A": null
444
+ },
445
+ "obsHighlight": {
446
+ "A": null,
447
+ "init_A_obsSegmentations_0": null
448
+ },
449
+ "obsLabelsType": {
450
+ "A": null
451
+ },
452
+ "obsSetColor": {
453
+ "A": null
454
+ },
455
+ "obsSetExpansion": {
456
+ "A": null
457
+ },
458
+ "obsSetFilter": {
459
+ "A": null
460
+ },
461
+ "obsSetHighlight": {
462
+ "A": null
463
+ },
464
+ "obsSetSelection": {
465
+ "A": null
466
+ },
467
+ "obsType": {
468
+ "A": "cell",
469
+ "init_A_obsPoints_0": "point",
470
+ "init_A_obsSegmentations_0": "cell"
471
+ },
472
+ "photometricInterpretation": {
473
+ "A": null,
474
+ "init_A_image_0": "BlackIsZero"
475
+ },
476
+ "pixelHighlight": {
477
+ "A": null
478
+ },
479
+ "pointLayer": {
480
+ "A": null,
481
+ "init_A_obsPoints_0": "__dummy__"
482
+ },
483
+ "segmentationChannel": {
484
+ "A": null,
485
+ "init_A_obsSegmentations_0": "__dummy__"
486
+ },
487
+ "segmentationLayer": {
488
+ "A": null,
489
+ "init_A_obsSegmentations_0": "__dummy__"
490
+ },
491
+ "spatialAxisFixed": {
492
+ "A": false
493
+ },
494
+ "spatialChannelColor": {
495
+ "A": [
496
+ 255,
497
+ 255,
498
+ 255
499
+ ],
500
+ "init_A_image_0": [
501
+ 0,
502
+ 0,
503
+ 255
504
+ ],
505
+ "init_A_image_1": [
506
+ 0,
507
+ 255,
508
+ 0
509
+ ],
510
+ "init_A_image_2": [
511
+ 255,
512
+ 0,
513
+ 255
514
+ ],
515
+ "init_A_image_3": [
516
+ 255,
517
+ 255,
518
+ 0
519
+ ],
520
+ "init_A_obsSegmentations_0": [
521
+ 255,
522
+ 255,
523
+ 255
524
+ ]
525
+ },
526
+ "spatialChannelLabelSize": {
527
+ "A": 14
528
+ },
529
+ "spatialChannelLabelsOrientation": {
530
+ "A": "vertical"
531
+ },
532
+ "spatialChannelLabelsVisible": {
533
+ "A": true
534
+ },
535
+ "spatialChannelOpacity": {
536
+ "A": 1,
537
+ "init_A_image_0": 1,
538
+ "init_A_image_1": 1,
539
+ "init_A_image_2": 1,
540
+ "init_A_image_3": 1,
541
+ "init_A_obsSegmentations_0": 1
542
+ },
543
+ "spatialChannelVisible": {
544
+ "A": true,
545
+ "init_A_image_0": true,
546
+ "init_A_image_1": true,
547
+ "init_A_image_2": true,
548
+ "init_A_image_3": true,
549
+ "init_A_obsSegmentations_0": true
550
+ },
551
+ "spatialChannelWindow": {
552
+ "A": null,
553
+ "init_A_image_0": [
554
+ 0,
555
+ 8339
556
+ ],
557
+ "init_A_image_1": [
558
+ 0,
559
+ 8617
560
+ ],
561
+ "init_A_image_2": [
562
+ 0,
563
+ 10931
564
+ ],
565
+ "init_A_image_3": [
566
+ 0,
567
+ 10716
568
+ ],
569
+ "init_A_obsSegmentations_0": null
570
+ },
571
+ "spatialImageLayer": {
572
+ "init_A_image_0": [
573
+ {
574
+ "channels": [
575
+ {
576
+ "color": [
577
+ 255,
578
+ 255,
579
+ 255
580
+ ],
581
+ "selection": {
582
+ "c": 0
583
+ },
584
+ "slider": [
585
+ 0,
586
+ 255
587
+ ],
588
+ "visible": true
589
+ },
590
+ {
591
+ "color": [
592
+ 255,
593
+ 255,
594
+ 255
595
+ ],
596
+ "selection": {
597
+ "c": 1
598
+ },
599
+ "slider": [
600
+ 0,
601
+ 255
602
+ ],
603
+ "visible": true
604
+ },
605
+ {
606
+ "color": [
607
+ 255,
608
+ 255,
609
+ 255
610
+ ],
611
+ "selection": {
612
+ "c": 2
613
+ },
614
+ "slider": [
615
+ 0,
616
+ 255
617
+ ],
618
+ "visible": true
619
+ },
620
+ {
621
+ "color": [
622
+ 255,
623
+ 255,
624
+ 255
625
+ ],
626
+ "selection": {
627
+ "c": 3
628
+ },
629
+ "slider": [
630
+ 0,
631
+ 255
632
+ ],
633
+ "visible": true
634
+ }
635
+ ],
636
+ "colormap": null,
637
+ "domainType": "Min/Max",
638
+ "index": 0,
639
+ "modelMatrix": [
640
+ 1,
641
+ 0,
642
+ 0,
643
+ 0,
644
+ 0,
645
+ 1,
646
+ 0,
647
+ 0,
648
+ 0,
649
+ 0,
650
+ 1,
651
+ 0,
652
+ 0,
653
+ 0,
654
+ 0,
655
+ 1
656
+ ],
657
+ "opacity": 1,
658
+ "renderingMode": "Additive",
659
+ "transparentColor": null,
660
+ "type": "raster",
661
+ "use3d": false,
662
+ "visible": true
663
+ }
664
+ ]
665
+ },
666
+ "spatialLayerColor": {
667
+ "A": null
668
+ },
669
+ "spatialLayerColormap": {
670
+ "A": null
671
+ },
672
+ "spatialLayerModelMatrix": {
673
+ "A": null
674
+ },
675
+ "spatialLayerOpacity": {
676
+ "A": 1,
677
+ "init_A_image_0": 1,
678
+ "init_A_obsSegmentations_0": 1
679
+ },
680
+ "spatialLayerTransparentColor": {
681
+ "A": null
682
+ },
683
+ "spatialLayerVisible": {
684
+ "A": true,
685
+ "init_A_image_0": true,
686
+ "init_A_obsSegmentations_0": true
687
+ },
688
+ "spatialMaxResolution": {
689
+ "A": null
690
+ },
691
+ "spatialNeighborhoodLayer": {
692
+ "A": null
693
+ },
694
+ "spatialOrbitAxis": {
695
+ "A": "Y",
696
+ "B": "Y"
697
+ },
698
+ "spatialPointLayer": {
699
+ "A": null
700
+ },
701
+ "spatialPointStrokeWidth": {
702
+ "A": 0
703
+ },
704
+ "spatialRenderingMode": {
705
+ "A": "2D"
706
+ },
707
+ "spatialRotation": {
708
+ "A": 0
709
+ },
710
+ "spatialRotationOrbit": {
711
+ "A": 0,
712
+ "B": 0
713
+ },
714
+ "spatialRotationX": {
715
+ "A": 0,
716
+ "B": 0
717
+ },
718
+ "spatialRotationY": {
719
+ "A": 0,
720
+ "B": 0
721
+ },
722
+ "spatialRotationZ": {
723
+ "A": 0,
724
+ "B": 0
725
+ },
726
+ "spatialSegmentationFilled": {
727
+ "A": true,
728
+ "init_A_obsSegmentations_0": true
729
+ },
730
+ "spatialSegmentationStrokeWidth": {
731
+ "A": 1,
732
+ "init_A_obsSegmentations_0": 1
733
+ },
734
+ "spatialSliceX": {
735
+ "A": null
736
+ },
737
+ "spatialSliceY": {
738
+ "A": null
739
+ },
740
+ "spatialSliceZ": {
741
+ "A": null
742
+ },
743
+ "spatialSpotFilled": {
744
+ "A": true
745
+ },
746
+ "spatialSpotRadius": {
747
+ "A": 25
748
+ },
749
+ "spatialSpotStrokeWidth": {
750
+ "A": 1
751
+ },
752
+ "spatialTargetC": {
753
+ "A": null,
754
+ "init_A_image_0": 0,
755
+ "init_A_image_1": 1,
756
+ "init_A_image_2": 2,
757
+ "init_A_image_3": 3
758
+ },
759
+ "spatialTargetResolution": {
760
+ "A": 0,
761
+ "init_A_image_0": null
762
+ },
763
+ "spatialTargetT": {
764
+ "A": null,
765
+ "init_A_image_0": 0
766
+ },
767
+ "spatialTargetX": {
768
+ "A": null,
769
+ "B": null
770
+ },
771
+ "spatialTargetY": {
772
+ "A": null,
773
+ "B": null
774
+ },
775
+ "spatialTargetZ": {
776
+ "A": null,
777
+ "B": null,
778
+ "init_A_image_0": null
779
+ },
780
+ "spatialZoom": {
781
+ "A": null,
782
+ "B": null
783
+ },
784
+ "spotLayer": {
785
+ "A": null
786
+ },
787
+ "tooltipCrosshairsVisible": {
788
+ "A": true
789
+ },
790
+ "tooltipsVisible": {
791
+ "A": true
792
+ },
793
+ "volumetricRenderingAlgorithm": {
794
+ "A": "additive",
795
+ "init_A_image_0": "maximumIntensityProjection"
796
+ }
797
+ },
798
+ "datasets": [
799
+ {
800
+ "files": [
801
+ {
802
+ "coordinationValues": {
803
+ "featureType": "gene",
804
+ "featureValueType": "expression",
805
+ "obsType": "cell"
806
+ },
807
+ "fileType": "obsFeatureMatrix.spatialdata.zarr",
808
+ "options": {
809
+ "path": "tables/table/X"
810
+ },
811
+ "url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
812
+ },
813
+ {
814
+ "coordinationValues": {
815
+ "featureType": "gene"
816
+ },
817
+ "fileType": "image.spatialdata.zarr",
818
+ "options": {
819
+ "coordinateSystem": "global",
820
+ "path": "images/morphology_focus"
821
+ },
822
+ "url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
823
+ },
824
+ {
825
+ "coordinationValues": {
826
+ "obsType": "cell"
827
+ },
828
+ "fileType": "shapes.spatialdata.zarr",
829
+ "options": {
830
+ "coordinateSystem": "global",
831
+ "path": "shapes/cell_boundaries",
832
+ "tablePath": "tables/table"
833
+ },
834
+ "url": "http://localhost:8000/A/0/f595faf2-239a-47f2-a3c7-27314f281a5a.sdata.zarr"
835
+ },
836
+ {
837
+ "coordinationValues": {
838
+ "featureType": "gene",
839
+ "featureValueType": "expression",
840
+ "obsType": "point"
841
+ },
842
+ "fileType": "obsFeatureMatrix.spatialdata.zarr",
843
+ "options": {
844
+ "path": "tables/dense_table/X"
845
+ },
846
+ "url": "http://localhost:8000/A/1/afd11240-c386-4fe7-8bfd-f77a5138e9bc.sdata.zarr"
847
+ },
848
+ {
849
+ "coordinationValues": {
850
+ "obsType": "point"
851
+ },
852
+ "fileType": "obsPoints.spatialdata.zarr",
853
+ "options": {
854
+ "coordinateSystem": "global",
855
+ "path": "points/transcripts_with_morton_codes",
856
+ "tablePath": "tables/table"
857
+ },
858
+ "url": "http://localhost:8000/A/1/afd11240-c386-4fe7-8bfd-f77a5138e9bc.sdata.zarr"
859
+ }
860
+ ],
861
+ "name": "Xenium",
862
+ "uid": "A"
863
+ }
864
+ ],
865
+ "description": "",
866
+ "initStrategy": "auto",
867
+ "layout": [
868
+ {
869
+ "component": "spatialBeta",
870
+ "coordinationScopes": {
871
+ "additionalObsSets": "A",
872
+ "dataset": "A",
873
+ "featureAggregationStrategy": "A",
874
+ "featureColor": "A",
875
+ "featureFilterMode": "A",
876
+ "featureHighlight": "A",
877
+ "featureSelection": "A",
878
+ "featureType": "A",
879
+ "featureValueColormap": "A",
880
+ "featureValueColormapRange": "A",
881
+ "featureValueType": "A",
882
+ "fileUid": "A",
883
+ "imageChannel": "A",
884
+ "imageLayer": "A",
885
+ "legendVisible": "A",
886
+ "metaCoordinationScopes": [
887
+ "init_A_image_0",
888
+ "init_A_obsSegmentations_0",
889
+ "init_A_obsSegmentations_0",
890
+ "init_A_obsPoints_0"
891
+ ],
892
+ "metaCoordinationScopesBy": [
893
+ "init_A_image_0",
894
+ "init_A_obsSegmentations_0",
895
+ "init_A_obsSegmentations_0",
896
+ "init_A_obsPoints_0"
897
+ ],
898
+ "moleculeHighlight": "A",
899
+ "obsColorEncoding": "A",
900
+ "obsFilter": "A",
901
+ "obsHighlight": "A",
902
+ "obsLabelsType": "A",
903
+ "obsSetColor": "A",
904
+ "obsSetFilter": "A",
905
+ "obsSetHighlight": "A",
906
+ "obsSetSelection": "A",
907
+ "obsType": "A",
908
+ "photometricInterpretation": "A",
909
+ "pixelHighlight": "A",
910
+ "pointLayer": "A",
911
+ "segmentationChannel": "A",
912
+ "segmentationLayer": "A",
913
+ "spatialAxisFixed": "A",
914
+ "spatialChannelColor": "A",
915
+ "spatialChannelLabelSize": "A",
916
+ "spatialChannelLabelsOrientation": "A",
917
+ "spatialChannelLabelsVisible": "A",
918
+ "spatialChannelOpacity": "A",
919
+ "spatialChannelVisible": "A",
920
+ "spatialChannelWindow": "A",
921
+ "spatialLayerColor": "A",
922
+ "spatialLayerColormap": "A",
923
+ "spatialLayerModelMatrix": "A",
924
+ "spatialLayerOpacity": "A",
925
+ "spatialLayerTransparentColor": "A",
926
+ "spatialLayerVisible": "A",
927
+ "spatialMaxResolution": "A",
928
+ "spatialNeighborhoodLayer": "A",
929
+ "spatialOrbitAxis": "A",
930
+ "spatialPointLayer": "A",
931
+ "spatialRenderingMode": "A",
932
+ "spatialRotation": "A",
933
+ "spatialRotationOrbit": "A",
934
+ "spatialRotationX": "A",
935
+ "spatialRotationY": "A",
936
+ "spatialRotationZ": "A",
937
+ "spatialSegmentationFilled": "A",
938
+ "spatialSegmentationStrokeWidth": "A",
939
+ "spatialSliceX": "A",
940
+ "spatialSliceY": "A",
941
+ "spatialSliceZ": "A",
942
+ "spatialSpotFilled": "A",
943
+ "spatialSpotRadius": "A",
944
+ "spatialSpotStrokeWidth": "A",
945
+ "spatialTargetC": "A",
946
+ "spatialTargetResolution": "A",
947
+ "spatialTargetT": "A",
948
+ "spatialTargetX": "A",
949
+ "spatialTargetY": "A",
950
+ "spatialTargetZ": "A",
951
+ "spatialZoom": "A",
952
+ "spotLayer": "A",
953
+ "tooltipCrosshairsVisible": "A",
954
+ "tooltipsVisible": "A",
955
+ "volumetricRenderingAlgorithm": "A"
956
+ },
957
+ "h": 12,
958
+ "uid": "A",
959
+ "w": 12,
960
+ "x": 0,
961
+ "y": 0
962
+ },
963
+ {
964
+ "component": "featureList",
965
+ "coordinationScopes": {
966
+ "dataset": "A",
967
+ "featureFilter": "A",
968
+ "featureHighlight": "A",
969
+ "featureSelection": "A",
970
+ "featureType": "A",
971
+ "featureValueType": "A",
972
+ "obsColorEncoding": "A",
973
+ "obsSetSelection": "A",
974
+ "obsType": "A"
975
+ },
976
+ "h": 1,
977
+ "uid": "B",
978
+ "w": 1,
979
+ "x": 0,
980
+ "y": 0
981
+ },
982
+ {
983
+ "component": "layerControllerBeta",
984
+ "coordinationScopes": {
985
+ "dataset": "A",
986
+ "featureAggregationStrategy": "B",
987
+ "featureColor": "A",
988
+ "featureFilterMode": "A",
989
+ "featureSelection": "A",
990
+ "featureType": "A",
991
+ "featureValueColormap": "A",
992
+ "featureValueColormapRange": "A",
993
+ "featureValueType": "A",
994
+ "fileUid": "A",
995
+ "imageChannel": "A",
996
+ "imageLayer": "A",
997
+ "legendVisible": "A",
998
+ "metaCoordinationScopes": [
999
+ "init_A_image_0",
1000
+ "init_A_obsSegmentations_0",
1001
+ "init_A_obsSegmentations_0",
1002
+ "init_A_obsPoints_0"
1003
+ ],
1004
+ "metaCoordinationScopesBy": [
1005
+ "init_A_image_0",
1006
+ "init_A_obsSegmentations_0",
1007
+ "init_A_obsSegmentations_0",
1008
+ "init_A_obsPoints_0"
1009
+ ],
1010
+ "obsColorEncoding": "A",
1011
+ "obsType": "A",
1012
+ "photometricInterpretation": "A",
1013
+ "pointLayer": "A",
1014
+ "segmentationChannel": "A",
1015
+ "segmentationLayer": "A",
1016
+ "spatialChannelColor": "A",
1017
+ "spatialChannelLabelSize": "A",
1018
+ "spatialChannelLabelsOrientation": "A",
1019
+ "spatialChannelLabelsVisible": "A",
1020
+ "spatialChannelOpacity": "A",
1021
+ "spatialChannelVisible": "A",
1022
+ "spatialChannelWindow": "A",
1023
+ "spatialLayerColor": "A",
1024
+ "spatialLayerColormap": "A",
1025
+ "spatialLayerModelMatrix": "A",
1026
+ "spatialLayerOpacity": "A",
1027
+ "spatialLayerTransparentColor": "A",
1028
+ "spatialLayerVisible": "A",
1029
+ "spatialMaxResolution": "A",
1030
+ "spatialNeighborhoodLayer": "A",
1031
+ "spatialOrbitAxis": "B",
1032
+ "spatialPointLayer": "A",
1033
+ "spatialPointStrokeWidth": "A",
1034
+ "spatialRenderingMode": "A",
1035
+ "spatialRotationOrbit": "B",
1036
+ "spatialRotationX": "B",
1037
+ "spatialRotationY": "B",
1038
+ "spatialRotationZ": "B",
1039
+ "spatialSegmentationFilled": "A",
1040
+ "spatialSegmentationStrokeWidth": "A",
1041
+ "spatialSliceX": "A",
1042
+ "spatialSliceY": "A",
1043
+ "spatialSliceZ": "A",
1044
+ "spatialSpotFilled": "A",
1045
+ "spatialSpotRadius": "A",
1046
+ "spatialSpotStrokeWidth": "A",
1047
+ "spatialTargetC": "A",
1048
+ "spatialTargetResolution": "A",
1049
+ "spatialTargetT": "A",
1050
+ "spatialTargetX": "B",
1051
+ "spatialTargetY": "B",
1052
+ "spatialTargetZ": "B",
1053
+ "spatialZoom": "B",
1054
+ "spotLayer": "A",
1055
+ "tooltipCrosshairsVisible": "A",
1056
+ "tooltipsVisible": "A",
1057
+ "volumetricRenderingAlgorithm": "A"
1058
+ },
1059
+ "h": 1,
1060
+ "uid": "C",
1061
+ "w": 1,
1062
+ "x": 0,
1063
+ "y": 0
1064
+ },
1065
+ {
1066
+ "component": "obsSets",
1067
+ "coordinationScopes": {
1068
+ "additionalObsSets": "A",
1069
+ "dataset": "A",
1070
+ "featureSelection": "A",
1071
+ "obsColorEncoding": "A",
1072
+ "obsSetColor": "A",
1073
+ "obsSetExpansion": "A",
1074
+ "obsSetFilter": "A",
1075
+ "obsSetHighlight": "A",
1076
+ "obsSetSelection": "A",
1077
+ "obsType": "A"
1078
+ },
1079
+ "h": 1,
1080
+ "uid": "D",
1081
+ "w": 1,
1082
+ "x": 0,
1083
+ "y": 0
1084
+ }
1085
+ ],
1086
+ "name": "Xenium SpatialData Demo",
1087
+ "uid": "A",
1088
+ "version": "1.0.18"
1089
+ },
1090
+ "_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 <Vitessce/>),\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 <Vitessce/> 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",
1091
+ "_model_module": "anywidget",
1092
+ "_model_name": "AnyModel",
1093
+ "_view_name": "ErrorWidgetView",
1094
+ "custom_js_url": "",
1095
+ "error": {},
1096
+ "has_host_name": false,
1097
+ "height": 600,
1098
+ "invoke_batched": true,
1099
+ "invoke_timeout": 300000,
1100
+ "js_dev_mode": false,
1101
+ "js_package_version": "3.9.9",
1102
+ "layout": "IPY_MODEL_6adbd17d7ac6415890bb669e3aaf670f",
1103
+ "msg": "Failed to load model class 'AnyModel' from module 'anywidget'",
1104
+ "page_esm": "",
1105
+ "page_mode": false,
1106
+ "plugin_esm": [],
1107
+ "prevent_scroll": true,
1108
+ "proxy": false,
1109
+ "remount_on_uid_change": true,
1110
+ "store_urls": [],
1111
+ "theme": "auto",
1112
+ "uid": "e7a1"
1113
+ }
1114
+ },
1115
+ "undefined": {
1116
+ "model_module": "anywidget",
1117
+ "model_module_version": "2.0.0",
1118
+ "model_name": "AnyModel",
1119
+ "state": {
1120
+ "_view_name": "ErrorWidgetView",
1121
+ "error": {},
1122
+ "msg": "Failed to load model class 'AnyModel' from module 'anywidget'"
1123
+ }
1124
+ }
1125
+ },
1126
+ "version_major": 2,
1127
+ "version_minor": 0
1128
+ }
1129
+ }
1130
+ },
1131
+ "nbformat": 4,
1132
+ "nbformat_minor": 4
1133
+ }