> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bioptimus.com/llms.txt
> Use this file to discover all available pages before exploring further.

# bioptimus.utils.utils

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](https://docs.bioptimus.com/guides/get-started/sdk)

***

#### download\_if\_needed

```python theme={null}
def download_if_needed(url: str, output_path: Path) -> None
```

Downloads a file from *url* if it does not already exist at *output\_path*.

<ParamField body="url">
  URL to download from.
</ParamField>

<ParamField body="output_path">
  Local destination path.
</ParamField>

***

#### check\_server

```python theme={null}
def check_server(api_url: str, *, timeout: float = 5.0) -> dict[str, Any]
```

Verifies that the inference server at *api\_url* is healthy.

Raises on connection error or non-200 status.

<ParamField body="api_url">
  Base URL of the inference server (e.g. `http://localhost:8080`).
</ParamField>

<ParamField body="timeout">
  HTTP request timeout in seconds.
</ParamField>

**Returns**:

The JSON body of `GET /ping`.

***

#### display\_slide\_info

```python theme={null}
def display_slide_info(
    wsi_path: str | Path, thumbnail_size: tuple[int, int] = (512, 512)
) -> PIL.Image.Image
```

Prints slide metadata and returns a PIL thumbnail image.

Uses the SDK's WSI reader; see [https://docs.bioptimus.com/guides/reference/wsi-reader](https://docs.bioptimus.com/guides/reference/wsi-reader)

<ParamField body="wsi_path">
  Path to the whole-slide image file.
</ParamField>

<ParamField body="thumbnail_size">
  Maximum `(width, height)` of the returned thumbnail.
</ParamField>

**Returns**:

A PIL thumbnail of the slide.

***

#### display\_rna\_summary

```python theme={null}
def display_rna_summary(tsv_path: str | Path) -> pd.DataFrame
```

Prints summary statistics for a bulk RNA-seq TSV file.

<ParamField body="tsv_path">
  Path to a tab-separated RNA-seq counts file.
</ParamField>

**Returns**:

The loaded DataFrame for further inspection.

***

#### read\_gene\_mapping

```python theme={null}
def read_gene_mapping(path: str | Path,
                      symbol_column: str = "gene_name",
                      id_column: str = "gene_id",
                      *,
                      separator: str | None = None,
                      strip_version: bool = False) -> dict[str, str]
```

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.

<ParamField body="path">
  Path to the CSV or TSV file.
</ParamField>

<ParamField body="symbol_column">
  Column containing gene symbols (e.g. `"gene_name"`).
</ParamField>

<ParamField body="id_column">
  Column containing gene identifiers (e.g. `"gene_id"`).
</ParamField>

<ParamField body="separator">
  Column delimiter. Inferred from file extension when `None` (`.tsv` → tab, otherwise comma).
</ParamField>

<ParamField body="strip_version">
  When `True`, strips version suffixes from the *id\_column* (e.g. `ENSG00000119888.12` → `ENSG00000119888`).
</ParamField>

**Returns**:

A dict mapping each symbol to the corresponding identifier.

***

#### load\_zarr\_output

```python theme={null}
def load_zarr_output(path: str | Path) -> dict
```

Loads a Zarr inference output into a dictionary.

<ParamField body="path">
  Path to the Zarr store directory.
</ParamField>

**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](https://docs.bioptimus.com/guides/get-started/visualizing-results)

***

#### convert\_spot\_to\_coord

```python theme={null}
def convert_spot_to_coord(
    tissue_positions: str | Path,
    *,
    native_mpp: float,
    tile_px: int,
    tile_mpp: float,
    x_column: str = "pxl_col_in_fullres",
    y_column: str = "pxl_row_in_fullres"
) -> tuple[list[tuple[int, int]], pd.DataFrame]
```

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.

<ParamField body="tissue_positions">
  Path to a 10x `tissue_positions` CSV with spot centres in full-resolution pixels.
</ParamField>

<ParamField body="native_mpp">
  Microns-per-pixel of the slide's full resolution (read from the WSI reader, e.g. `reader.mpp`).
</ParamField>

<ParamField body="tile_px">
  Tile edge in pixels the model reads (e.g. `224`).
</ParamField>

<ParamField body="tile_mpp">
  Microns-per-pixel the model expects (e.g. `0.5`).
</ParamField>

<ParamField body="x_column">
  Column holding the spot centre x in full-resolution pixels.
</ParamField>

<ParamField body="y_column">
  Column holding the spot centre y in full-resolution pixels.
</ParamField>

**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**:

```python theme={null}
>>> coords, spots = convert_spot_to_coord(
...     "tissue_positions.csv", native_mpp=0.2738, tile_px=224, tile_mpp=0.5
... )
>>> infer = Inference(model_name="m-optimus", coordinates=coords, ...)
```

***

#### load\_spot\_size\_um

```python theme={null}
def load_spot_size_um(spot_metadata: str | Path, *,
                      native_mpp: float) -> tuple[float, float]
```

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.

<ParamField body="spot_metadata">
  Path to a `metadata.json` with `tile_shape` (`{"width", "height"}`) or a scalar `spot_diameter` in full-resolution pixels.
</ParamField>

<ParamField body="native_mpp">
  Microns-per-pixel of the slide's full resolution.
</ParamField>

**Returns**:

The spot `(width_um, height_um)`.

***

#### plot\_slide\_and\_mask

```python theme={null}
def plot_slide_and_mask(
    wsi_path: str | Path,
    mask_path: str | Path,
    *,
    threshold: float = 0.5,
    figsize: tuple[int, int] = (14, 5)) -> None
```

Shows a slide thumbnail alongside its tissue mask.

<ParamField body="wsi_path">
  Path to the whole-slide image file.
</ParamField>

<ParamField body="mask_path">
  Path to the tissue mask image (PNG).
</ParamField>

<ParamField body="threshold">
  Binarization threshold for the mask.
</ParamField>

<ParamField body="figsize">
  Matplotlib figure size `(width, height)`.
</ParamField>

***

#### plot\_pca\_scatter

```python theme={null}
def plot_pca_scatter(embeddings: np.ndarray,
                     *,
                     n_components: int = 2,
                     title: str = "Embedding PCA",
                     cmap: str = "viridis",
                     figsize: tuple[int, int] = (8, 6),
                     point_size: float = 10) -> tuple[np.ndarray, Any]
```

Fits PCA on *embeddings* and plots the first two components.

<ParamField body="embeddings">
  Tile embeddings array of shape `(n_tiles, dim)`.
</ParamField>

<ParamField body="n_components">
  Number of PCA components to compute.
</ParamField>

<ParamField body="title">
  Plot title.
</ParamField>

<ParamField body="cmap">
  Matplotlib colormap name.
</ParamField>

<ParamField body="figsize">
  Figure size `(width, height)`.
</ParamField>

<ParamField body="point_size">
  Scatter point size.
</ParamField>

**Returns**:

A `(scores, pca)` tuple — the transformed array and the fitted
PCA object.

***

#### plot\_spatial\_pca

```python theme={null}
def plot_spatial_pca(
    scores: np.ndarray,
    coords: np.ndarray,
    *,
    components: list[int] | None = None,
    title_prefix: str = "",
    figsize: tuple[int, int] = (18, 5)) -> None
```

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).

<ParamField body="scores">
  PCA-transformed array of shape `(n_tiles, n_components)`.
</ParamField>

<ParamField body="coords">
  Tile coordinates of shape `(n_tiles, 2)`.
</ParamField>

<ParamField body="components">
  Indices of PCs to plot (0-indexed).
</ParamField>

<ParamField body="title_prefix">
  Prefix prepended to each subplot title.
</ParamField>

<ParamField body="figsize">
  Figure size `(width, height)`.
</ParamField>

***

#### plot\_nearest\_neighbor\_tiles

```python theme={null}
def plot_nearest_neighbor_tiles(embeddings: np.ndarray,
                                coords: np.ndarray,
                                wsi_path: str | Path,
                                *,
                                query_indices: list[int] | None = None,
                                n_queries: int = 4,
                                n_neighbors: int = 5,
                                tile_size: int = 224,
                                mpp: float = 0.5,
                                seed: int = 42,
                                figsize_per_tile: float = 1.8) -> None
```

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.

<ParamField body="embeddings">
  Tile embeddings array of shape `(n_tiles, dim)`.
</ParamField>

<ParamField body="coords">
  Tile coordinates array of shape `(n_tiles, 2)`.
</ParamField>

<ParamField body="wsi_path">
  Path to the WSI file for reading tile images.
</ParamField>

<ParamField body="query_indices">
  Specific tile indices to use as queries. If *None*, `n_queries` tiles are sampled from distinct PCA regions.
</ParamField>

<ParamField body="n_queries">
  Number of query tiles (used when *query\_indices* is None).
</ParamField>

<ParamField body="n_neighbors">
  Number of nearest neighbors to show per query.
</ParamField>

<ParamField body="tile_size">
  Tile width/height in pixels at the target resolution.
</ParamField>

<ParamField body="mpp">
  Microns per pixel for tile extraction.
</ParamField>

<ParamField body="seed">
  Random seed for reproducible query selection.
</ParamField>

<ParamField body="figsize_per_tile">
  Figure size per tile in inches.
</ParamField>

***

#### plot\_gene\_overlay

```python theme={null}
def plot_gene_overlay(
    values: np.ndarray,
    coords: np.ndarray,
    wsi_path: str | Path,
    *,
    gene_name: str = "",
    title: str = "",
    cmap: str = "inferno",
    alpha: float = 0.55,
    vmin: float | None = 0.0,
    vmax: float | None = None,
    ax: plt.Axes | None = None,
    figsize: tuple[int, int] = (8, 7),
    thumbnail_size: tuple[int, int] = (1024, 1024)
) -> None
```

Overlays a gene-expression heatmap on the slide thumbnail.

<ParamField body="values">
  Per-tile expression values of shape `(n_tiles,)`.
</ParamField>

<ParamField body="coords">
  Tile coordinates of shape `(n_tiles, 2)`.
</ParamField>

<ParamField body="wsi_path">
  Path to the whole-slide image file.
</ParamField>

<ParamField body="gene_name">
  Gene symbol for the title.
</ParamField>

<ParamField body="title">
  Custom plot title (overrides *gene\_name*).
</ParamField>

<ParamField body="cmap">
  Matplotlib colormap name.
</ParamField>

<ParamField body="alpha">
  Heatmap overlay opacity.
</ParamField>

<ParamField body="vmin">
  Colormap minimum.
</ParamField>

<ParamField body="vmax">
  Colormap maximum.
</ParamField>

<ParamField body="ax">
  Existing axes to draw on. Creates a new figure when `None`.
</ParamField>

<ParamField body="figsize">
  Figure size when creating a new figure.
</ParamField>

<ParamField body="thumbnail_size">
  Maximum `(width, height)` of the slide thumbnail.
</ParamField>

***

#### plot\_gene\_overlay\_comparison

```python theme={null}
def plot_gene_overlay_comparison(
    preds_a: np.ndarray,
    coords_a: np.ndarray,
    preds_b: np.ndarray,
    coords_b: np.ndarray,
    gene_idx: int,
    wsi_path: str | Path,
    *,
    gene_name: str = "",
    label_a: str = "Condition A",
    label_b: str = "Condition B",
    slide_id: str = "",
    cmap: str = "inferno",
    alpha: float = 0.55,
    figsize: tuple[int, int] = (18, 8),
    thumbnail_size: tuple[int, int] = (1024, 1024)
) -> None
```

Side-by-side gene-expression overlays on the slide thumbnail.

<ParamField body="preds_a">
  Predictions array for condition A, shape `(n_tiles, n_genes)`.
</ParamField>

<ParamField body="coords_a">
  Tile coordinates for condition A.
</ParamField>

<ParamField body="preds_b">
  Predictions array for condition B.
</ParamField>

<ParamField body="coords_b">
  Tile coordinates for condition B.
</ParamField>

<ParamField body="gene_idx">
  Column index of the gene to plot.
</ParamField>

<ParamField body="wsi_path">
  Path to the whole-slide image file.
</ParamField>

<ParamField body="gene_name">
  Gene symbol for the title.
</ParamField>

<ParamField body="label_a">
  Display label for condition A.
</ParamField>

<ParamField body="label_b">
  Display label for condition B.
</ParamField>

<ParamField body="slide_id">
  Slide identifier shown in the title.
</ParamField>

<ParamField body="cmap">
  Matplotlib colormap name.
</ParamField>

<ParamField body="alpha">
  Heatmap overlay opacity.
</ParamField>

<ParamField body="figsize">
  Figure size `(width, height)`.
</ParamField>

<ParamField body="thumbnail_size">
  Maximum `(width, height)` of the slide thumbnail.
</ParamField>

***

#### plot\_gene\_panel\_overlay

```python theme={null}
def plot_gene_panel_overlay(
    predictions: np.ndarray,
    coords: np.ndarray,
    gene_names: list[str],
    genes_to_plot: dict[str, str],
    wsi_path: str | Path,
    *,
    cols: int = 3,
    figsize_per_plot: tuple[int, int] = (6, 5),
    cmap: str = "inferno",
    alpha: float = 0.55,
    thumbnail_size: tuple[int, int] = (1024, 1024)) -> None
```

Overlays spatial heatmaps for multiple genes on the slide thumbnail.

<ParamField body="predictions">
  Predictions array of shape `(n_tiles, n_genes)`.
</ParamField>

<ParamField body="coords">
  Tile coordinates of shape `(n_tiles, 2)`.
</ParamField>

<ParamField body="gene_names">
  List of gene identifiers matching prediction columns.
</ParamField>

<ParamField body="genes_to_plot">
  Mapping of gene symbol → identifier to visualize.
</ParamField>

<ParamField body="wsi_path">
  Path to the whole-slide image file.
</ParamField>

<ParamField body="cols">
  Number of columns in the subplot grid.
</ParamField>

<ParamField body="figsize_per_plot">
  Size `(width, height)` per subplot.
</ParamField>

<ParamField body="cmap">
  Matplotlib colormap name.
</ParamField>

<ParamField body="alpha">
  Heatmap overlay opacity.
</ParamField>

<ParamField body="thumbnail_size">
  Maximum `(width, height)` of the slide thumbnail.
</ParamField>

***

#### plot\_top\_gene\_tiles

```python theme={null}
def plot_top_gene_tiles(predictions: np.ndarray,
                        coords: np.ndarray,
                        gene_idx: int,
                        wsi_path: str | Path,
                        *,
                        gene_name: str = "",
                        n_top: int = 5,
                        n_bottom: int = 5,
                        tile_size: int = 224,
                        mpp: float = 0.5,
                        figsize_per_tile: float = 2.0) -> None
```

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.

<ParamField body="predictions">
  Predictions array of shape `(n_tiles, n_genes)`.
</ParamField>

<ParamField body="coords">
  Tile coordinates of shape `(n_tiles, 2)`.
</ParamField>

<ParamField body="gene_idx">
  Column index of the gene to plot.
</ParamField>

<ParamField body="wsi_path">
  Path to the whole-slide image file.
</ParamField>

<ParamField body="gene_name">
  Gene symbol for the plot title.
</ParamField>

<ParamField body="n_top">
  Number of highest-expression tiles to show.
</ParamField>

<ParamField body="n_bottom">
  Number of lowest-expression tiles to show.
</ParamField>

<ParamField body="tile_size">
  Tile width/height in pixels.
</ParamField>

<ParamField body="mpp">
  Microns per pixel for tile extraction.
</ParamField>

<ParamField body="figsize_per_tile">
  Figure size per tile in inches.
</ParamField>

***

#### plot\_spatial\_gene

```python theme={null}
def plot_spatial_gene(
    values: np.ndarray,
    coords: np.ndarray,
    *,
    gene_name: str = "",
    title: str = "",
    cmap: str = "inferno",
    vmin: float | None = None,
    vmax: float | None = None,
    ax: plt.Axes | None = None,
    figsize: tuple[int, int] = (8, 7)) -> None
```

Plots a spatial gene-expression heatmap at tile coordinates.

<ParamField body="values">
  Per-tile expression values of shape `(n_tiles,)`.
</ParamField>

<ParamField body="coords">
  Tile coordinates of shape `(n_tiles, 2)`.
</ParamField>

<ParamField body="gene_name">
  Gene symbol for the title.
</ParamField>

<ParamField body="title">
  Custom plot title (overrides *gene\_name*).
</ParamField>

<ParamField body="cmap">
  Matplotlib colormap name.
</ParamField>

<ParamField body="vmin">
  Colormap minimum.
</ParamField>

<ParamField body="vmax">
  Colormap maximum.
</ParamField>

<ParamField body="ax">
  Existing axes to draw on. Creates a new figure when `None`.
</ParamField>

<ParamField body="figsize">
  Figure size when creating a new figure.
</ParamField>

***

#### plot\_gene\_comparison

```python theme={null}
def plot_gene_comparison(
    preds_a: np.ndarray,
    coords_a: np.ndarray,
    preds_b: np.ndarray,
    coords_b: np.ndarray,
    gene_idx: int,
    *,
    gene_name: str = "",
    label_a: str = "Condition A",
    label_b: str = "Condition B",
    slide_id: str = "",
    cmap: str = "inferno",
    figsize: tuple[int, int] = (18, 8)) -> None
```

Side-by-side spatial heatmaps comparing a gene under two conditions.

<ParamField body="preds_a">
  Predictions array for condition A, shape `(n_tiles, n_genes)`.
</ParamField>

<ParamField body="coords_a">
  Tile coordinates for condition A.
</ParamField>

<ParamField body="preds_b">
  Predictions array for condition B.
</ParamField>

<ParamField body="coords_b">
  Tile coordinates for condition B.
</ParamField>

<ParamField body="gene_idx">
  Column index of the gene to plot.
</ParamField>

<ParamField body="gene_name">
  Gene symbol for the title.
</ParamField>

<ParamField body="label_a">
  Display label for condition A.
</ParamField>

<ParamField body="label_b">
  Display label for condition B.
</ParamField>

<ParamField body="slide_id">
  Slide identifier shown in the title.
</ParamField>

<ParamField body="cmap">
  Matplotlib colormap name.
</ParamField>

<ParamField body="figsize">
  Figure size `(width, height)`.
</ParamField>

***

#### plot\_gene\_panel

```python theme={null}
def plot_gene_panel(predictions: np.ndarray,
                    coords: np.ndarray,
                    gene_names: list[str],
                    genes_to_plot: dict[str, str],
                    *,
                    cols: int = 3,
                    figsize_per_plot: tuple[int, int] = (6, 5),
                    cmap: str = "inferno") -> None
```

Plots spatial heatmaps for multiple genes in a grid.

*genes\_to\_plot* maps gene symbol → Ensembl ID (or name in gene\_names).

<ParamField body="predictions">
  Predictions array of shape `(n_tiles, n_genes)`.
</ParamField>

<ParamField body="coords">
  Tile coordinates of shape `(n_tiles, 2)`.
</ParamField>

<ParamField body="gene_names">
  List of gene identifiers matching prediction columns.
</ParamField>

<ParamField body="genes_to_plot">
  Mapping of gene symbol → identifier to visualize.
</ParamField>

<ParamField body="cols">
  Number of columns in the subplot grid.
</ParamField>

<ParamField body="figsize_per_plot">
  Size `(width, height)` per subplot.
</ParamField>

<ParamField body="cmap">
  Matplotlib colormap name.
</ParamField>

***

#### print\_config

```python theme={null}
def print_config(**kwargs: object) -> None
```

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


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.