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

***

#### 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*.

**url**

URL to download from.

**output\_path**

Local destination path.

***

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

**api\_url**

Base URL of the inference server (e.g. `http://localhost:8080`).

**timeout**

HTTP request timeout in seconds.

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

**wsi\_path**

Path to the whole-slide image file.

**thumbnail\_size**

Maximum `(width, height)` of the returned thumbnail.

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

**tsv\_path**

Path to a tab-separated RNA-seq counts file.

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

**path**

Path to the CSV or TSV file.

**symbol\_column**

Column containing gene symbols (e.g. `"gene_name"`).

**id\_column**

Column containing gene identifiers (e.g. `"gene_id"`).

**separator**

Column delimiter. Inferred from file extension when `None` (`.tsv` → tab, otherwise comma).

**strip\_version**

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

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

Loads a Zarr inference output into a dictionary.

**path**

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

***

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

**tissue\_positions**

Path to a 10x `tissue_positions` CSV with spot centres in full-resolution pixels.

**native\_mpp**

Microns-per-pixel of the slide's full resolution (read from the WSI reader, e.g. `reader.mpp`).

**tile\_px**

Tile edge in pixels the model reads (e.g. `224`).

**tile\_mpp**

Microns-per-pixel the model expects (e.g. `0.5`).

**x\_column**

Column holding the spot centre x in full-resolution pixels.

**y\_column**

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

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

**spot\_metadata**

Path to a `metadata.json` with `tile_shape` (`{"width", "height"}`) or a scalar `spot_diameter` in full-resolution pixels.

**native\_mpp**

Microns-per-pixel of the slide's full resolution.

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

**wsi\_path**

Path to the whole-slide image file.

**mask\_path**

Path to the tissue mask image (PNG).

**threshold**

Binarization threshold for the mask.

**figsize**

Matplotlib figure size `(width, height)`.

***

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

**embeddings**

Tile embeddings array of shape `(n_tiles, dim)`.

**n\_components**

Number of PCA components to compute.

**title**

Plot title.

**cmap**

Matplotlib colormap name.

**figsize**

Figure size `(width, height)`.

**point\_size**

Scatter point size.

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

**scores**

PCA-transformed array of shape `(n_tiles, n_components)`.

**coords**

Tile coordinates of shape `(n_tiles, 2)`.

**components**

Indices of PCs to plot (0-indexed).

**title\_prefix**

Prefix prepended to each subplot title.

**figsize**

Figure size `(width, height)`.

***

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

**embeddings**

Tile embeddings array of shape `(n_tiles, dim)`.

**coords**

Tile coordinates array of shape `(n_tiles, 2)`.

**wsi\_path**

Path to the WSI file for reading tile images.

**query\_indices**

Specific tile indices to use as queries. If *None*, `n_queries` tiles are sampled from distinct PCA regions.

**n\_queries**

Number of query tiles (used when *query\_indices* is None).

**n\_neighbors**

Number of nearest neighbors to show per query.

**tile\_size**

Tile width/height in pixels at the target resolution.

**mpp**

Microns per pixel for tile extraction.

**seed**

Random seed for reproducible query selection.

**figsize\_per\_tile**

Figure size per tile in inches.

***

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

**values**

Per-tile expression values of shape `(n_tiles,)`.

**coords**

Tile coordinates of shape `(n_tiles, 2)`.

**wsi\_path**

Path to the whole-slide image file.

**gene\_name**

Gene symbol for the title.

**title**

Custom plot title (overrides *gene\_name*).

**cmap**

Matplotlib colormap name.

**alpha**

Heatmap overlay opacity.

**vmin**

Colormap minimum.

**vmax**

Colormap maximum.

**ax**

Existing axes to draw on. Creates a new figure when `None`.

**figsize**

Figure size when creating a new figure.

**thumbnail\_size**

Maximum `(width, height)` of the slide thumbnail.

***

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

**preds\_a**

Predictions array for condition A, shape `(n_tiles, n_genes)`.

**coords\_a**

Tile coordinates for condition A.

**preds\_b**

Predictions array for condition B.

**coords\_b**

Tile coordinates for condition B.

**gene\_idx**

Column index of the gene to plot.

**wsi\_path**

Path to the whole-slide image file.

**gene\_name**

Gene symbol for the title.

**label\_a**

Display label for condition A.

**label\_b**

Display label for condition B.

**slide\_id**

Slide identifier shown in the title.

**cmap**

Matplotlib colormap name.

**alpha**

Heatmap overlay opacity.

**figsize**

Figure size `(width, height)`.

**thumbnail\_size**

Maximum `(width, height)` of the slide thumbnail.

***

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

**predictions**

Predictions array of shape `(n_tiles, n_genes)`.

**coords**

Tile coordinates of shape `(n_tiles, 2)`.

**gene\_names**

List of gene identifiers matching prediction columns.

**genes\_to\_plot**

Mapping of gene symbol → identifier to visualize.

**wsi\_path**

Path to the whole-slide image file.

**cols**

Number of columns in the subplot grid.

**figsize\_per\_plot**

Size `(width, height)` per subplot.

**cmap**

Matplotlib colormap name.

**alpha**

Heatmap overlay opacity.

**thumbnail\_size**

Maximum `(width, height)` of the slide thumbnail.

***

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

**predictions**

Predictions array of shape `(n_tiles, n_genes)`.

**coords**

Tile coordinates of shape `(n_tiles, 2)`.

**gene\_idx**

Column index of the gene to plot.

**wsi\_path**

Path to the whole-slide image file.

**gene\_name**

Gene symbol for the plot title.

**n\_top**

Number of highest-expression tiles to show.

**n\_bottom**

Number of lowest-expression tiles to show.

**tile\_size**

Tile width/height in pixels.

**mpp**

Microns per pixel for tile extraction.

**figsize\_per\_tile**

Figure size per tile in inches.

***

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

**values**

Per-tile expression values of shape `(n_tiles,)`.

**coords**

Tile coordinates of shape `(n_tiles, 2)`.

**gene\_name**

Gene symbol for the title.

**title**

Custom plot title (overrides *gene\_name*).

**cmap**

Matplotlib colormap name.

**vmin**

Colormap minimum.

**vmax**

Colormap maximum.

**ax**

Existing axes to draw on. Creates a new figure when `None`.

**figsize**

Figure size when creating a new figure.

***

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

**preds\_a**

Predictions array for condition A, shape `(n_tiles, n_genes)`.

**coords\_a**

Tile coordinates for condition A.

**preds\_b**

Predictions array for condition B.

**coords\_b**

Tile coordinates for condition B.

**gene\_idx**

Column index of the gene to plot.

**gene\_name**

Gene symbol for the title.

**label\_a**

Display label for condition A.

**label\_b**

Display label for condition B.

**slide\_id**

Slide identifier shown in the title.

**cmap**

Matplotlib colormap name.

**figsize**

Figure size `(width, height)`.

***

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

**predictions**

Predictions array of shape `(n_tiles, n_genes)`.

**coords**

Tile coordinates of shape `(n_tiles, 2)`.

**gene\_names**

List of gene identifiers matching prediction columns.

**genes\_to\_plot**

Mapping of gene symbol → identifier to visualize.

**cols**

Number of columns in the subplot grid.

**figsize\_per\_plot**

Size `(width, height)` per subplot.

**cmap**

Matplotlib colormap name.

***

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