File size: 10,803 Bytes
ed8ebc1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {
"nbsphinx": "hidden"
},
"source": [
"# Vitessce Widget Tutorial"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Visualization of a SpatialData object"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Import dependencies\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from os.path import join, isfile, isdir\n",
"from urllib.request import urlretrieve\n",
"import zipfile\n",
"import shutil\n",
"\n",
"from vitessce import (\n",
" VitessceConfig,\n",
" ViewType as vt,\n",
" CoordinationType as ct,\n",
" CoordinationLevel as CL,\n",
" SpatialDataWrapper,\n",
" get_initial_coordination_scope_prefix\n",
")\n",
"\n",
"from vitessce.data_utils import (\n",
" sdata_morton_sort_points,\n",
" sdata_points_process_columns,\n",
" sdata_points_write_bounding_box_attrs,\n",
" sdata_points_modify_row_group_size,\n",
" sdata_morton_query_rect,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from spatialdata import read_zarr\n",
"\n",
"import anndata as ad\n",
"\n",
"ad.settings.zarr_write_format = 3\n",
"print(ad.settings.zarr_write_format)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import dask\n",
"import tempfile\n",
"\n",
"# Point Dask temp dir to your external drive\n",
"dask.config.set({'temporary_directory': '/Volumes/T7 Shield/tmp'})\n",
"\n",
"# Create the dir if it doesn't exist\n",
"import os\n",
"os.makedirs('/Volumes/T7 Shield/tmp', exist_ok=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ls"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"from spatialdata_io import xenium\n",
"import spatialdata as sd\n",
"import pandas as pd\n",
"\n",
"xenium_dir = Path(\"../data/instrument_data/Xenium_V1_hPancreas_Cancer_Add_on_FFPE_outs/\") # folder containing experiment.xenium\n",
"out_zarr = Path(\"../data/processed_data/vitessce/Xenium_V1_hPancreas_Cancer_Add_on_FFPE_outs.zarr\")\n",
"\n",
"sdata = xenium(\n",
" xenium_dir,\n",
" cells_boundaries=True,\n",
" nucleus_boundaries=True,\n",
" cells_labels=True,\n",
" nucleus_labels=True,\n",
" transcripts=True,\n",
" morphology_focus=True,\n",
" aligned_images=True,\n",
" cells_table=True,\n",
" gex_only=True,\n",
")\n",
"\n",
"print(sdata)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Add cluster labels from Xenium instrument output\n",
"clusters = pd.read_csv(\n",
" xenium_dir / \"analysis/clustering/gene_expression_graphclust/clusters.csv\"\n",
")\n",
"sdata.tables[\"table\"].obs = sdata.tables[\"table\"].obs.merge(\n",
" clusters.set_index(\"Barcode\")[[\"Cluster\"]].rename(columns={\"Cluster\": \"leiden\"}),\n",
" left_index=True,\n",
" right_index=True,\n",
" how=\"left\",\n",
")\n",
"sdata.tables[\"table\"].obs[\"leiden\"] = sdata.tables[\"table\"].obs[\"leiden\"].astype(str)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Save as a SpatialData Zarr store\n",
"sdata.write(out_zarr)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sdata[\"transcripts\"].shape[0].compute()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sdata.tables[\"table\"].X = sdata.tables[\"table\"].X.toarray()\n",
"sdata.tables[\"dense_table\"] = sdata.tables[\"table\"]\n",
"sdata.write_element(\"dense_table\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# TODO: store the two separate images as a single image with two channels.\n",
"# Similar to https://github.com/EricMoerthVis/tissue-map-tools/pull/12"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# sdata.tables['table'].obs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# sdata"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# sdata.points['transcripts'].head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Sorting Points and creating a new Points element in the SpatialData object"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 1. Sort rows with `sdata_morton_sort_points`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import importlib.metadata\n",
"print(importlib.metadata.version(\"vitessce\"))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# sdata = sdata_morton_sort_points(sdata, \"transcripts\")\n",
"from vitessce.data_utils.spatialdata_points_zorder import norm_ddf_to_uint, morton_interleave\n",
"\n",
"element = \"transcripts\"\n",
"ddf = sdata.points[element]\n",
"attrs = ddf.attrs.copy()\n",
"\n",
"ddf = norm_ddf_to_uint(ddf)\n",
"ddf[\"morton_code_2d\"] = morton_interleave(ddf)\n",
"sorted_ddf = ddf.sort_values(by=\"morton_code_2d\", ascending=True)\n",
"sorted_ddf.attrs.update(attrs)\n",
"sdata.points[element] = sorted_ddf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 2. Clean up columns with `sdata_points_process_columns`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Add feature_index column to dataframe, and reorder columns so that feature_name (dict column) is the rightmost column.\n",
"ddf = sdata_points_process_columns(sdata, \"transcripts\", var_name_col=\"feature_name\", table_name=\"table\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ddf.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 3. Save sorted dataframe to new Points element"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# sdata[\"transcripts_with_morton_codes\"] = ddf\n",
"# sdata.write_element(\"transcripts_with_morton_codes\")\n",
"\n",
"from spatialdata.models import PointsModel\n",
"\n",
"transformations = sdata[\"transcripts\"].attrs[\"transform\"]\n",
"del ddf.attrs[\"transform\"]\n",
"\n",
"sdata[\"transcripts_with_morton_codes\"] = PointsModel.parse(\n",
" ddf, feature_key=\"feature_name\", instance_key=\"cell_id\", transformations=transformations\n",
")\n",
"sdata.write_element(\"transcripts_with_morton_codes\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 4. Write bounding box metadata with `sdata_points_write_bounding_box_attrs`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import shutil\n",
"import os\n",
"\n",
"tmp_dir = '/Volumes/T7 Shield/tmp'\n",
"shutil.rmtree(tmp_dir)\n",
"os.makedirs(tmp_dir)\n",
"print(\"Done\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sdata_points_write_bounding_box_attrs(sdata, \"transcripts_with_morton_codes\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 5. Modify the row group sizes of the Parquet files with `sdata_points_modify_row_group_size`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import shutil\n",
"import os\n",
"\n",
"tmp_dir = '/Volumes/T7 Shield/tmp'\n",
"shutil.rmtree(tmp_dir)\n",
"os.makedirs(tmp_dir)\n",
"print(\"Done\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sdata_points_modify_row_group_size(sdata, \"transcripts_with_morton_codes\", row_group_size=25_000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Done"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Optionally, check the number of row groups in one of the parquet file parts.\n",
"import pyarrow.parquet as pq\n",
"from os.path import join\n",
"\n",
"parquet_file = pq.ParquetFile(join(sdata.path, \"points\", \"transcripts_with_morton_codes\", \"points.parquet\", \"part.0.parquet\"))\n",
"\n",
"# Get the number of row groups in this part-0 file.\n",
"num_groups = parquet_file.num_row_groups\n",
"num_groups"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.1"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {
"undefined": {
"model_module": "anywidget",
"model_module_version": "2.0.0",
"model_name": "AnyModel",
"state": {
"_view_name": "ErrorWidgetView",
"error": {},
"msg": "Model class 'AnyModel' from module 'anywidget' is loaded but can not be instantiated"
}
}
},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|