Skip to main content
Shared utilities for Bioptimus SDK tutorial notebooks. Provides common helpers for data download, WSI inspection, output loading, and visualization — used by both the H-Optimus-1 and M-Optimus tutorials. Documentation: https://docs.bioptimus.com/guides/get-started/sdk

download_if_needed

Downloads a file from url if it does not already exist at output_path.
URL to download from.
Local destination path.

check_server

Verifies that the inference server at api_url is healthy. Raises on connection error or non-200 status.
Base URL of the inference server (e.g. http://localhost:8080).
HTTP request timeout in seconds.
Returns: The JSON body of GET /ping.

display_slide_info

Prints slide metadata and returns a PIL thumbnail image. Uses the SDK’s WSI reader; see https://docs.bioptimus.com/guides/reference/wsi-reader
Path to the whole-slide image file.
Maximum (width, height) of the returned thumbnail.
Returns: A PIL thumbnail of the slide.

display_rna_summary

Prints summary statistics for a bulk RNA-seq TSV file.
Path to a tab-separated RNA-seq counts file.
Returns: The loaded DataFrame for further inspection.

read_gene_mapping

Reads a gene symbol → ID mapping from a bulk RNA file. Parses a long-format bulk RNA file (one row per gene) and returns a dict mapping gene symbols to identifiers (typically Ensembl IDs). Useful for converting human-readable gene names into the Ensembl IDs used by M-Optimus prediction outputs.
Path to the CSV or TSV file.
Column containing gene symbols (e.g. "gene_name").
Column containing gene identifiers (e.g. "gene_id").
Column delimiter. Inferred from file extension when None (.tsv → tab, otherwise comma).
When True, strips version suffixes from the id_column (e.g. ENSG00000119888.12 → ENSG00000119888).
Returns: A dict mapping each symbol to the corresponding identifier.

load_zarr_output

Loads a Zarr inference output into a dictionary.
Path to the Zarr store directory.
Returns: A dict with keys outputs, coords, metadata, and optionally gene_names (M-Optimus predictions), thumbnail, tissue_mask, and tissue_ratios. See https://docs.bioptimus.com/guides/get-started/visualizing-results

convert_spot_to_coord

Converts spatial-transcriptomics spot centres to tile coordinates. Turns a 10x-style tissue_positions table (spot centres in full-resolution pixels) into the (x, y) top-left tile positions that Inference expects via its coordinates argument. Two conversions are applied:
  1. Resolution scaling. Spot pixels are at the slide’s native resolution (native_mpp), but the model reads tiles at tile_mpp, so centres are scaled by native_mpp / tile_mpp.
  2. Centre → top-left. The model always reads a fixed tile_px x tile_px window, so the top-left is the scaled centre minus half the tile size (tile_px // 2). Anchoring on the tile size (rather than the spot’s own footprint) keeps the model’s window centred on each spot regardless of the spot/bin size.
Path to a 10x tissue_positions CSV with spot centres in full-resolution pixels.
Microns-per-pixel of the slide’s full resolution (read from the WSI reader, e.g. reader.mpp).
Tile edge in pixels the model reads (e.g. 224).
Microns-per-pixel the model expects (e.g. 0.5).
Column holding the spot centre x in full-resolution pixels.
Column holding the spot centre y in full-resolution pixels.
Returns: A tuple (coordinates, spots) where coordinates is a list of (x, y) top-left, slide-origin pixel pairs at the tile resolution (ready to pass as Inference(..., coordinates=...)), and spots is the loaded table augmented with integer tile_x/tile_y columns (row-aligned with coordinates) for downstream benchmark alignment. Example:

load_spot_size_um

Returns the spot footprint (width, height) in microns from metadata. Reads a platform metadata.json (10x-style) and converts the spot footprint to microns. Informational only — the model reads a fixed tile window regardless of spot size — but useful to report the spot footprint against the model’s field of view.
Path to a metadata.json with tile_shape ({"width", "height"}) or a scalar spot_diameter in full-resolution pixels.
Microns-per-pixel of the slide’s full resolution.
Returns: The spot (width_um, height_um).

plot_slide_and_mask

Shows a slide thumbnail alongside its tissue mask.
Path to the whole-slide image file.
Path to the tissue mask image (PNG).
Binarization threshold for the mask.
Matplotlib figure size (width, height).

plot_pca_scatter

Fits PCA on embeddings and plots the first two components.
Tile embeddings array of shape (n_tiles, dim).
Number of PCA components to compute.
Plot title.
Matplotlib colormap name.
Figure size (width, height).
Scatter point size.
Returns: A (scores, pca) tuple — the transformed array and the fitted PCA object.

plot_spatial_pca

Maps PCA scores back to tile coordinates as spatial heatmaps. components selects which PCs to plot (0-indexed); defaults to the first 3 (or 2 if fewer are available).
PCA-transformed array of shape (n_tiles, n_components).
Tile coordinates of shape (n_tiles, 2).
Indices of PCs to plot (0-indexed).
Prefix prepended to each subplot title.
Figure size (width, height).

plot_nearest_neighbor_tiles

Shows that tiles with similar embeddings look visually similar. For each query tile, finds its nearest neighbors in embedding space and displays them side-by-side. This is a visual proof that the model captures meaningful morphology.
Tile embeddings array of shape (n_tiles, dim).
Tile coordinates array of shape (n_tiles, 2).
Path to the WSI file for reading tile images.
Specific tile indices to use as queries. If None, n_queries tiles are sampled from distinct PCA regions.
Number of query tiles (used when query_indices is None).
Number of nearest neighbors to show per query.
Tile width/height in pixels at the target resolution.
Microns per pixel for tile extraction.
Random seed for reproducible query selection.
Figure size per tile in inches.

plot_gene_overlay

Overlays a gene-expression heatmap on the slide thumbnail.
Per-tile expression values of shape (n_tiles,).
Tile coordinates of shape (n_tiles, 2).
Path to the whole-slide image file.
Gene symbol for the title.
Custom plot title (overrides gene_name).
Matplotlib colormap name.
Heatmap overlay opacity.
Colormap minimum.
Colormap maximum.
Existing axes to draw on. Creates a new figure when None.
Figure size when creating a new figure.
Maximum (width, height) of the slide thumbnail.

plot_gene_overlay_comparison

Side-by-side gene-expression overlays on the slide thumbnail.
Predictions array for condition A, shape (n_tiles, n_genes).
Tile coordinates for condition A.
Predictions array for condition B.
Tile coordinates for condition B.
Column index of the gene to plot.
Path to the whole-slide image file.
Gene symbol for the title.
Display label for condition A.
Display label for condition B.
Slide identifier shown in the title.
Matplotlib colormap name.
Heatmap overlay opacity.
Figure size (width, height).
Maximum (width, height) of the slide thumbnail.

plot_gene_panel_overlay

Overlays spatial heatmaps for multiple genes on the slide thumbnail.
Predictions array of shape (n_tiles, n_genes).
Tile coordinates of shape (n_tiles, 2).
List of gene identifiers matching prediction columns.
Mapping of gene symbol → identifier to visualize.
Path to the whole-slide image file.
Number of columns in the subplot grid.
Size (width, height) per subplot.
Matplotlib colormap name.
Heatmap overlay opacity.
Maximum (width, height) of the slide thumbnail.

plot_top_gene_tiles

Shows tiles with the highest and lowest predicted expression for a gene. Displays two rows: top-N highest-expression tiles and top-N lowest-expression tiles, with expression values as labels.
Predictions array of shape (n_tiles, n_genes).
Tile coordinates of shape (n_tiles, 2).
Column index of the gene to plot.
Path to the whole-slide image file.
Gene symbol for the plot title.
Number of highest-expression tiles to show.
Number of lowest-expression tiles to show.
Tile width/height in pixels.
Microns per pixel for tile extraction.
Figure size per tile in inches.

plot_spatial_gene

Plots a spatial gene-expression heatmap at tile coordinates.
Per-tile expression values of shape (n_tiles,).
Tile coordinates of shape (n_tiles, 2).
Gene symbol for the title.
Custom plot title (overrides gene_name).
Matplotlib colormap name.
Colormap minimum.
Colormap maximum.
Existing axes to draw on. Creates a new figure when None.
Figure size when creating a new figure.

plot_gene_comparison

Side-by-side spatial heatmaps comparing a gene under two conditions.
Predictions array for condition A, shape (n_tiles, n_genes).
Tile coordinates for condition A.
Predictions array for condition B.
Tile coordinates for condition B.
Column index of the gene to plot.
Gene symbol for the title.
Display label for condition A.
Display label for condition B.
Slide identifier shown in the title.
Matplotlib colormap name.
Figure size (width, height).

plot_gene_panel

Plots spatial heatmaps for multiple genes in a grid. genes_to_plot maps gene symbol → Ensembl ID (or name in gene_names).
Predictions array of shape (n_tiles, n_genes).
Tile coordinates of shape (n_tiles, 2).
List of gene identifiers matching prediction columns.
Mapping of gene symbol → identifier to visualize.
Number of columns in the subplot grid.
Size (width, height) per subplot.
Matplotlib colormap name.

Pretty-prints experiment configuration as an aligned key-value table.