Skip to content

Viz Module API Reference

For a conceptual overview of what each widget shows and how to use it, see the Visualizations section. Try the Chromium PBMC notebook for low dimensional embedding landscapes, or the Visium HD CRC notebook for linked spatial, expression, and enrichment views.

Landscape data sources and controls

Landscape supports spatial DegaFiles and single-cell AnnData Zarr for low dimensional embedding landscapes (UMAP/XY). Choose one expression source:

import celldega as dega

# Spatial image, centroid, boundary, transcript, and expression files.
spatial = dega.viz.Landscape(
    base_url="https://your-data-host/DegaFiles",
    adata=adata,
    cluster_attr="cell_type",
)

# Cell-level AnnData Zarr with a CSC expression layer.
single_cell = dega.viz.Landscape(
    zarr_url="cells.zarr",
    zarr_layer="counts_csc",
    cluster_attr="cell_type",
    nbhd_edit=True,
)

Local Zarr paths must be beneath the working directory; the widget starts a local HTTP server. HTTP(S) URLs are passed directly to the browser. Optional adata supplies cell metadata, cluster colors, and UMAP positions in preference to the source's metadata. It does not supply expression to the browser. Match its obs_names to the source cell IDs.

Argument / trait Purpose
base_url / base_urls DegaFiles URL or multiple DegaFiles datasets
zarr_url / zarr_layer Single-cell AnnData Zarr and its CSC expression layer; defaults to Chromium technology
adata Optional AnnData metadata, palette, and obsm["X_umap"]
cluster_attr / cell_attr Category used for cluster colors (default "leiden") and cell attributes
landscape_state "spatial", "umap", or "xy"; the available views depend on the dataset
xy_genes / xy_scale X/Y genes and "linear" or "log1p" scaling
adata_sig / gene_signature_url In-memory cell-type means or a separate signature AnnData Zarr for viewport estimates
nbhd / nbhd_edit Supplied neighborhoods and whether editing is enabled
gates / selected_cells Named polygons with coordinate-space metadata / current selected cell IDs
min_zoom / max_zoom Optional zoom limits
max_tiles_to_view / intermediate_zoom_limit Automatic and on-demand spatial transcript/boundary loading thresholds

XY and neighborhood selections

single_cell.set_xy("CD3D", "MS4A1", scale="log1p")
single_cell.landscape_state = "umap"  # requires obsm["X_umap"]

# After selecting clusters or drawing a neighborhood in the browser:
cell_ids = single_cell.get_selected_cells()
selected = single_cell.get_selected_cells(adata)  # copied AnnData subset
polygons = single_cell.nbhd_polygons
single_cell.save_nbhds("neighborhoods.geojson")
single_cell.load_nbhds("neighborhoods.geojson")

select_nbhd(name) restores a saved neighborhood's view/axes and selects its cells. save_gates, load_gates, and select_gate are equivalent names. Spatial polygons use native tissue coordinates; embedding polygons retain their coordinate-space metadata. Filter polygons["space"] before computing physical tissue areas or distances.

UMAP/XY viewport cell-type counts are exact. Gene bars estimate expression from matching cell-type signatures; no per-cell expression is fetched on pan/zoom. TRX indicates the summary mode in these views. Selected-gene coloring and XY coordinates read actual expression. See the Landscape guide for signature preparation, selection behavior, and adding aligned H&E to DegaFiles, and File Formats for storage schemas.

Source: Python widget and methods, browser entry points, and AnnData Zarr reader.

Widget Classes

The Clustergram widget accepts a parquet_data argument for efficient initialization. Use Matrix.export_viz_parquet to generate this data from a clustered matrix. Passing a JSON network object is deprecated; pass matrix or parquet_data instead.

Reusing widgets in notebooks

When rerunning a notebook cell, give a widget a name if the new instance should replace the previous one of that kind:

landscape = dega.viz.Landscape(
    base_url="https://your-data-host/DegaFiles",
    name="tissue_overview",
)

Creating another Landscape named "tissue_overview" closes the previous one. Use different names to keep several Landscapes open. registry_key is an alternative to name; if both are supplied, use the same value.

Without an explicit key, most widgets coexist. Clustergram uses its Matrix name by default, and Enrich uses "default", so give those widgets distinct names when displaying several instances. Call widget.close() to release a widget when it is no longer needed.

Source: widget lifecycle.

Yearbook Selection

A Yearbook renders a grid of cell "portraits". There are three ways to choose which cells it shows, in increasing order of power:

  1. An explicit id list — cells=["cell_1", "cell_2", ...]. The simplest path: you already know the cells you want.
  2. A back-end selection — selection=.... Accepts a celldega.select.Selection, a JSON-ready selection dict, or a plain id list. This is the recommended way to drive the grid from a Python AnnData object, because it carries the query, sampler, scores, and provenance with the cells. See the select module docs for the full query/sampling algebra.
  3. A stateless front-end query — front_end_query=.... Evaluated in the browser against the dataset's DegaFiles, so it needs only a base_url and no Python AnnData.

Passing both cells= and selection= is rejected. front_end_query= is independent of those two — when set, the browser computes the cell list itself.

Front-End Query

front_end_query is a small dict evaluated entirely in the browser. It is a deliberately narrow counterpart to the Python select module — it supports a single cluster filter and/or a single-gene ranking:

Query Behavior
{"cluster": {"attr": "leiden", "value": "8"}} Random cells from cluster 8 (capped at num_rows * num_cols * 10 by default).
{"gene": "BRCA1"} All cells ranked by BRCA1 expression, highest first.
{"cluster": {"attr": "leiden", "value": "8"}, "gene": "BRCA1"} Cells in cluster 8, ranked by BRCA1 expression.
{"gene": "BRCA1", "max_cells": 50} As above, capped at 50 cells.
yb = dega.viz.Yearbook(
    base_url="https://path-to-dataset",
    front_end_query={"gene": "BRCA1", "max_cells": 50},
    rows=2,
    cols=2,
)

Note

The former query= argument was renamed to front_end_query= to distinguish this stateless browser query from the Python-side celldega.select query module. Passing query= still works but emits a DeprecationWarning.

Snapshots and reopening from a PNG

A Snapshot combines a screenshot (raster image of the visualization), a memo, and metadata for reproducibility. snapshot() saves it as a PNG plus a readable .md companion. The PNG carries the memo, data links, constructor options, replay settings and data identity; the source data must remain available. from_png reopens it as an interactive widget:

saved = landscape.snapshot(
    "Cluster 3 rings the structure.", name="Cluster 3", path="figures/"
)

In a later cell, after the capture finishes:

view = dega.viz.from_png(saved.path)  # rebuilds from the recorded links
display(view)                       # restores once it renders
landscape.restore_png(saved.path)    # or restore into a widget already open

Pass in-memory inputs back, such as from_png(path, matrix=mat) or from_png(path, adata=adata). See Snapshots and Portable Snapshots. The earlier screenshot() spelling remains supported for compatibility.

Module for visualization

CellCloud

Bases: _SpatialWidget

3D orbit view of cell centroids (replaces Landscape(technology="point-cloud")).

Renders a pre-built point-cloud DegaFiles directory — cell positions from cell_metadata.parquet (or cell_metadata_<alignment>.parquet when alignment is set), colored by cluster/gene. Build one with celldega.pre.write_point_cloud_dataset.

Parameters:

Name Type Description Default
base_url str or list

DegaFiles URL(s), as in Landscape.

required
zarr_url str or Path

Self-contained AnnData Zarr instead of base_url. X (or zarr_layer) is CSC; obsm['spatial'] holds XYZ positions, with named variants at obsm['spatial_<alignment>']. Original observation IDs retain cell identity. Export with celldega.pre.write_point_cloud_zarr. Local paths use the shared local HTTP server.

required
zarr_layer str

CSC expression layer, or "X". Defaults to CSC X or the only CSC layer in the store.

required
adata AnnData

Source of cell attributes/metadata (clusters, colors, UMAP). Never used for spatial positions — those come from the DegaFiles — except when use_adata_3d_centroids is set. With zarr_url, positions always come from the store.

required
alignment str

Named alignment variant; cell positions are read from cell_metadata_<alignment>.parquet.

required
cell_size float

Default cell diameter in microns, assuming centroid coordinates are in microns. Default: 10. The CELL slider multiplies this diameter (0-2x, with 1x at its initial midpoint).

required
use_adata_3d_centroids bool

When an adata with obsm["spatial"] is given, render its centroids (obs[z_key] for Z, falling back to 0) instead of the on-disk geometry — to preview a candidate alignment without rewriting DegaFiles. Default: True.

required
z_key str

obs column holding the Z coordinate for use_adata_3d_centroids. Default: "Z".

required

use_adata_3d_centroids writes centroids to a small sidecar file next to base_url and fetches it over HTTP when base_url is a local celldega.viz.get_local_server() address (millions of per-cell centroids don't fit through the widget's comm channel); otherwise it falls back to syncing them through widget state, fine for smaller datasets.

Clerk

Bases: CelldegaWidget

Clerk -- Celldega's AI tool for exploring and interpreting its visualizations.

.. warning:: Experimental. Clerk is a proof of concept: its features, API and saved formats may change between releases, without deprecation.

Works like Enrich, but instead of the Enrichr API it talks to Claude via the local claude CLI (kernel-side, no API key). The scientist asks free-form questions in a chat box; Celldega bundles the available evidence -- the gene list, pre-fetched Enrichr terms, a captured Landscape raster, and any free-text context -- into a single-shot prompt so Claude reasons only from what it is shown.

Reads as both a law clerk (gathers evidence, drafts reasoning, the human decides) and a bodega clerk (fetches what you ask for).

Clerk is standalone and wide by default. Link it to other widgets (which can live in other notebook cells) either from the constructor or via dega.viz.link_clerk::

clerk = dega.viz.Clerk(landscape=ls, clustergram=cgm, enrich=en)

Or lay it out with them, linked: as a narrow sidecar column at the end of the row, like Enrich, or full width underneath::

dega.viz.spatial_clustergram(ls, cgm, clerk=True)                     # sidecar
dega.viz.spatial_clustergram(ls, cgm, clerk=True, clerk_layout="wide")

Enrichr results Clerk gets are drawn in the conversation, like the Enrich panel: a bar graph of the top terms and a paragraph of the genes tested.

Parameters:

Name Type Description Default
landscape Landscape

Optional. Link a Landscape; its raster + zoom/pan flow in as image evidence.

required
clustergram Clustergram

Optional. Link a Clustergram; selected genes flow into gene_list.

required
enrich Enrich

Optional. Remembered for enrichment-term evidence sharing (roadmap).

required
gene_list list

Marker / DE genes for the selection.

required
context_info str

Free-text context (dataset, cluster id, notes).

required
model str

Optional Claude model alias or id (e.g. "opus", "sonnet", "haiku"). Empty inherits the CLI default. A smaller model is cheaper/faster for routine annotation.

required
effort str

Reasoning effort, "low" to "max" ("xhigh" in between); empty inherits the CLI default. Higher effort is slower and uses more tokens.

required
width int

Widget width in px; 0 (default) means full container width.

required
name str

Registry key; creating a new Clerk with the same name closes the old.

required

snapshots property

The views Clerk was shown in this conversation, as Snapshots.

One per widget per capture, named by question: "Q1 Landscape", "Q1 Clustergram" (a later capture for the same question is "Q1.2 Landscape"), with the question as the memo; plus the Snapshots Clerk saved with its screenshot action. They're kept in memory (and written as Snapshot PNGs when you export a report); clerk.snapshots.save(folder) writes them::

clerk.snapshots.card("Q1 Landscape", landscape=landscape)
landscape.pins = clerk.snapshots

ask(question, **kwargs)

Ask a question from Python (bypasses the chat UI). Returns the answer text.

Unlike the chat box, this blocks until the answer arrives. A cell can't wait for the browser, so this uses the views' latest snapshots (e.g. the last Landscape capture and Clustergram.latest_state) rather than fresh ones.

close()

Close the conversation's Claude session, then the widget.

draft_notebook(offer_id=None)

Write a notebook Clerk suggested (as the panel's Draft notebook button does).

offer_id picks the suggestion; by default the latest one not yet drafted. Returns the notebook's path, or None if there was nothing to draft.

export(folder=None, *, title='', adata=None, groupby=None, key='clerk_cell_type', write_h5ad=False, names=None, html=True)

Save a record of this conversation that you can take with you.

Writes into folder (default <output_dir>/<title>, e.g. clerk_files/kidney-exploration, or clerk_files/report untitled; a name already taken gets -2, -3..., and the panel says so; the date is in record.json):

  • report.html: the whole conversation as one page. Each screenshot sits under the code that recreates that view (landscape.apply_state(...), cgm.apply_state(...)); Clerk's work and evidence are collapsed.
  • report.ipynb: the same as a notebook, to re-run the code.
  • record.json: everything, machine-readable.
  • screenshots/: each capture as a Celldega screenshot (a PNG carrying the record to reopen its view with dega.viz.from_png).
  • findings.csv: the cell types Clerk proposed.

With adata and groupby, the latest cell types are also written into adata.obs[key] (see write_cell_types; a column Clerk wrote before is replaced) and saved as cell_types.csv, plus adata.h5ad with write_h5ad=True.

Parameters:

Name Type Description Default
title str

Optional report name, shown as its heading and used in the default folder name.

''
names dict | None

Variable names for the reproduction code, default {"landscape": "landscape", "clustergram": "cgm"}.

None
html bool

Also render report.html (needs nbconvert).

True

Returns:

Name Type Description
dict dict[str, Path]

Paths written, by kind.

findings_df()

Cell types Clerk has proposed, one row per proposal (latest last).

Columns: cluster, label, confidence, markers (supporting genes), notes, question (what was asked) and recorded (time).

load_briefing(*sources, append=False)

Give Clerk earlier work to start from, as a visible, labeled briefing.

Each source is an exported report folder or its record.json (see export), a Markdown / text file, or another Clerk. Records are summarized (questions, final answers, recorded cell types). The briefing goes with every question under "Earlier work", as conclusions to check rather than evidence, and the panel shows that one is loaded. Set briefing directly for free text, or to "" to clear it.

Parameters:

Name Type Description Default
append bool

Add to the current briefing instead of replacing it.

False

Returns:

Name Type Description
str str

The briefing text.

load_conversation(path=None)

Reopen a saved conversation in the panel, without Claude.

Opens a file from save_conversation (or the panel's SAVE button), or a report folder from export (or its record.json). The panel shows the conversation as it was: its genes, clusters and cited views stay clickable and change the linked widgets, which need the same data loaded. A new question continues the conversation, with the loaded one as its history.

Replaces the current conversation, record and proposed cell types.

Parameters:

Name Type Description Default
path str | Path | None

The conversation .json, or an export folder or its record.json; a folder of them (default output_dir) opens the most recent. To also pin its views on the Landscape, use open_case.

None

Returns:

Name Type Description
dict dict

What was saved: title, saved, celldega, context_info

dict

and sources (the data the original widgets showed).

open_case(clerk_files=None)

Reopen a saved Clerk case, to explore it or keep working on it.

clerk_files is a report folder (from export or the panel's Report button), a saved conversation (.json), or a folder of them such as clerk_files (the default, output_dir), which opens the most recent. Same as Clerk(clerk_files=...).

The panel shows the conversation as it was: its findings and evidence, with genes, clusters and cited views that change the linked widgets (which need the same data loaded). Its views become pins on a linked Landscape that has none yet (PINS). None of this needs Claude; a new question continues the case (that needs Claude), and new reports are saved beside it.

Returns:

Name Type Description
dict dict

What was saved (see load_conversation), plus path.

run_analysis(which=-1, *, wait=False)

Have Claude Code run an analysis notebook Clerk drafted, in a separate process.

Claude Code may run the notebook (jupyter nbconvert) and fix small errors in it, and nothing else. Its summary appears in the conversation, so Clerk can interpret the results with the next question. Inspect the notebook first: its path is in analyses and on its line in the panel. You can also run it yourself instead.

Parameters:

Name Type Description Default
which str | int

An entry of analyses by id, path or index (default: the latest).

-1
wait bool

Block until the run finishes and return its result; otherwise the run continues in the background and its thread is returned.

False

save_conversation(path=None, *, title='')

Save the conversation to reopen later with load_conversation.

Writes one JSON file: the panel's messages (with their gene, cluster and view links and Enrichr results), the record of each question with the replay settings of its captures, Clerk's proposed cell types, the context, and links to the data the linked widgets show. Each question's screenshot preview is kept; full-size captures are left out to keep the file light (export keeps those).

Reading a saved conversation needs no Claude. Its links change the linked widgets, so they need the same data loaded.

Parameters:

Name Type Description Default
path str | Path | None

A .json file, or a folder for an auto-named one (default <output_dir>/conversations, i.e. clerk_files/conversations).

None
title str

Optional name, also used in the file name.

''

Returns:

Name Type Description
Path Path

The file written.

wait(timeout=None)

Block until the question in flight (if any) has been answered.

Parameters:

Name Type Description Default
timeout float | None

Seconds to wait; None waits indefinitely.

None

Returns:

Name Type Description
bool bool

True if Clerk is idle afterwards.

write_cell_types(adata, groupby, key='clerk_cell_type', *, overwrite=False, unassigned='Unassigned')

Write Clerk's latest proposed cell type per cluster into adata.obs[key].

Works for a cell-level AnnData (obs[groupby] holds each cell's cluster) and for a cluster-level one such as the signature AnnData behind a Clustergram. Clusters without a proposal get unassigned. Adds a column only: an existing key is left alone unless overwrite=True. The labels used, and where they came from, are recorded in adata.uns["clerk_cell_types"][key].

Returns:

Type Description
Series

pd.Series: The new column.

Clustergram

Bases: Screenshots, _RasterCapture, _StateSnapshots, CelldegaWidget

Minimal version of the Clustergram widget.

  • Frontend still gets: matrix/parquet data, row/col names, manual_cat, manual_cat_config, etc.
  • Manual categories are treated as a simple JSON string.
  • All the old DataFrame-based manual_cat plumbing is removed.

Matrix slices (browser is source of truth for net_mat) On row/column label and matrix-cell clicks, the front-end first updates click_info (interaction only), then emits matrix_slice_request so the handler fills matrix_slice_result with axis or cell data (slice_kind, entries, matrix_convention, etc.). Link another widget's trait with jslink((cgm, "matrix_slice_result"), ...) to consume slices without a Python round-trip.

Use `request_matrix_slice` to dispatch a non-blocking request, or
``await`` `request_matrix_slice_async` when you need the response in
Python (both require a **live kernel**).

**jslink:** Only traits sync between models. For linked custom widgets, mirror
``matrix_slice_result``; Python does not run in standalone exported HTML.

Python access to the same matrix If constructed with matrix=, use matrix_dataframe for the underlying pandas.DataFrame.

manual_cat_dict property

Convenience accessor: parsed JSON from manual_cat.

__init__(**kwargs)

Parameters

parquet_data : dict, optional Pre-exported parquet payload from your matrix object. matrix : object, optional If provided and has .export_viz_parquet(), we'll call that. network : dict, optional Deprecated path, kept only for backwards-compatibility.

apply_state(changes)

Change what the Clustergram shows, as its controls would.

Input structure is validated here, so mistakes raise in the calling cell. Availability (names, orders, controls) is checked in the browser, which then applies the changes; check get_apply_result with apply_request_id in a later cell, or observe apply_capture_id and apply_error. Runtime failures may leave partial changes.

Parameters:

Name Type Description Default
changes dict

Any of:

  • marker_level: marker genes per cluster (the DIM slider), snapped to the nearest precomputed level, or "all" for every row.
  • mode: "heatmap" or "dotplot".
  • size: "prop" (dot size by e.g. fraction expressing) or "unit" (full-size marks), like the PROP / UNIT buttons.
  • focus_gene: a row name to zoom to and bold, like the search box; "" clears it.
  • categories: manual categories, as for set_categories: {"values": {"<name>": "<category>"}, "axis": "col", "attribute": "cell_type", "colors": {...}, "replace": False}. Only the names given change.
  • annotations: {"row": spec, "col": spec} replacing each given axis's manual annotations, where spec is {"attribute", "values", "colors"} or None (clears the axis). Not with categories.
  • dendrogram: {"row": 35, "col": 65} cut percentages (0-100).
  • selection: any of rows, cols, genes, highlighted_genes (lists of names) and dendrogram ({"axis", "members"}, a group that exists at the current cut, or {"axis", "name"} with the name get_state lists it under).
  • view: {"target": [x, y], "zoom": [x_zoom, y_zoom]}.
  • crop: {"row": [...names], "col": None}; None clears an axis.
  • order: per axis, a named order ("clust", "rank", "rankvar", "ini", "alpha") or every name in display order.
required

Returns:

Type Description
list[str]

list[str]: What was submitted, e.g. "DIM -> 10 markers per cluster";

list[str]

not confirmation that the browser applied it.

Raises:

Type Description
ValueError

For an unknown key or an invalid value (nothing changes).

matrix_dataframe()

Return a copy of the Matrix data when this widget was created with matrix=.

request_matrix_slice(op, *, index=None, row=None, col=None, row_index=None, col_index=None, max_entries=None)

Request a slice from the browser Matrix and return its request ID.

This method deliberately does not wait for matrix_slice_result: blocking the executing kernel thread prevents inbound widget comm messages from being processed. Observe matrix_slice_result using the returned ID, or use await request_matrix_slice_async(...) in an async notebook cell.

Parameters

op row or col: pass index (matrix axis index). cell: pass row and col matrix indices. row_col: pass row_index and col_index to get both axis slices in one result; optional max_entries (negative means all, subject to a browser-side cap).

Returns

str Request ID that will be included in matrix_slice_result.

request_matrix_slice_async(op, *, index=None, row=None, col=None, row_index=None, col_index=None, max_entries=None, timeout=5.0) async

Request a browser matrix slice and asynchronously wait for its result.

await this method from an async notebook cell (awaiting yields to the kernel event loop so it can process the front-end comm message). Resolution is observer-driven: a temporary matrix_slice_result observer fulfills the wait the moment the response with this request's ID arrives, so the response cannot be missed even if a click-driven slice overwrites the shared matrix_slice_result mailbox immediately afterwards.

request_state(rows='viewport', cols='viewport', *, max_rows=50, max_cols=50, extra_rows=(), extra_cols=(), include_values=True, markers=None)

Ask the browser for bounded scientific observations of this Clustergram.

The snapshot reports, by name and in display order: the chosen rows and columns, each axis's order, the marker level (DIM slider), the dendrogram groups at the current cut, row/column attributes for the chosen items, the selection (clicked label, selected genes, dendrogram group, Enrich term genes, crop), and the values (and dot sizes) for the chosen rows x columns. Everything is bounded: an explicit (custom or attribute) order is labeled rather than listed, and a crop of more than 100 names is counted. Complete replay settings come with a saved view (request_snapshot).

Capture is asynchronous: the reply sets latest_state, or state_error on failure. observe latest_state or read it in a later cell; a cell that requests a snapshot can't wait for it.

Parameters:

Name Type Description Default
rows str | Sequence[str]

"viewport" (rows on screen), "ranked" (the top of the current order, after any crop or marker-level filter), or a list of row names.

'viewport'
cols str | Sequence[str]

Same for columns.

'viewport'
max_rows int

Cap on reported rows.

50
max_cols int

Cap on reported columns.

50
extra_rows Sequence[str]

Row names to add after the main selection (e.g. genes asked about that aren't on screen); listed in rows["added"].

()
extra_cols Sequence[str]

Same for columns.

()
include_values bool

Include the value and dot-size block.

True
markers dict | None

Also report ranked markers (rank_genes_groups) per cluster, read from the front end without changing the view: {"clusters": ["4", "5"], "n": 25} (clusters defaults to all). Lands in latest_state["cluster_markers"].

None

Returns:

Name Type Description
int int

The id of this request.

set_categories(values, *, axis='col', attribute=None, colors=None, replace=False)

Assign manual categories, as the category editor would.

For example cgm.set_categories({"4": "Goblet cells", "5": "Plasma cells"}) labels clusters 4 and 5 in the Clustergram's manual column category. The browser updates the category strips, bars and labels, and syncs the result back to manual_cat (and so to col_manual_df / row_manual_df).

Parameters:

Name Type Description Default
values dict

{row or column name: category}; an empty category removes the assignment.

required
axis str

"col" (default) or "row".

'col'
attribute str | None

The manual attribute, e.g. "cell_type". Defaults to the one set up with manual_col_cat / manual_row_cat; passing one turns manual categories on for that axis.

None
colors dict | None

Optional {category: hex}. New categories otherwise get the editor's next distinct color.

None
replace bool

Clear the axis's other assignments first.

False

Returns:

Name Type Description
int int

The id of this request.

to_cluster(axis='row', n_clusters=None, threshold=None, criterion=None)

Cut the dendrogram into flat cluster labels via the underlying Matrix.

Thin wrapper over celldega.clust.Matrix.cut_tree. When neither n_clusters nor threshold is passed, the cut is read from the front-end dendrogram slider state in dendro_cut[axis] — a dict of {"n_clusters": int} or {"threshold": float} that the JS widget writes as the user drags the slider. Passing an explicit value overrides the slider.

Parameters:

Name Type Description Default
axis str

"row" or "col" — which dendrogram to cut.

'row'
n_clusters int | None

Target number of flat clusters (overrides the slider).

None
threshold float | None

Linkage-distance cutoff (overrides the slider).

None
criterion str | None

Explicit scipy fcluster criterion.

None

Returns:

Type Description
Series

A pd.Series of cluster labels indexed by the axis names.

Raises:

Type Description
ValueError

If no Matrix is attached, or no cut is available from either the arguments or the front-end slider.

Composition

Bases: Clustergram

Composition view: count/proportion of categories compared across groups.

A Clustergram subclass with viz_mode="composition". The body draws each group (dataset/sample) as a stacked bar whose segments are populations (cell types), reusing the Clustergram's column-attribute tracks, reorder buttons (ini / sum / clust), and the control-panel PROP/COUNTS normalization toggle.

"Composition shows the count or relative proportion of categories within each group, and compares those compositions across groups."

Example::

# Cell-level AnnData: cells are cross-tabulated into samples x cell types
dega.viz.Composition(
    adata, groupby="sample_id", category="cell_type", group_attrs=["condition"]
)

Colors come from adata.uns[f"{category}_colors"]. A precomputed population matrix (AnnData with groups as obs and populations as var, a MuData modality, or a DataFrame) works too.

__init__(data, modality='population', *, groupby=None, category=None, colors=None, adata=None, group_attrs=None, normalized=None, col_weights=None, cluster=True, row_entity=None, col_entity=None, name='composition', width=700, height=450, **kwargs)

Parameters:

Name Type Description Default
data Any

A cell-level AnnData/MuData with groupby, or a precomputed population matrix: a MuData (or any object exposing mod), an AnnData (obs = groups, var = populations), or a DataFrame (rows = groups, columns = populations).

required
modality str

Modality key on a MuData (default "population").

'population'
groupby str | None

With cell-level data, the obs column defining the groups (e.g. a sample column); cells are cross-tabulated against category.

None
category str | None

Population obs column name (required with groupby); also used to resolve colors from uns[f"{category}_colors"] when the matrix has none.

None
colors dict[str, str] | None

Optional {population: hex} overrides.

None
adata Any

Optional source cell-level AnnData to fall back to for its color palette, e.g. for a plain DataFrame input.

None
group_attrs list[str] | None

Group-level obs columns to show as Clustergram column attribute tracks (e.g. ["condition", "timepoint"]). With groupby the first value per group is used.

None
normalized bool | None

Column-normalize each bar to 100%. Defaults to True for proportion matrices and False for count matrices.

None
col_weights dict[str, float] | None

Optional {group: n_cells} true per-group magnitude, used to scale bar height in non-normalized ("counts") mode. Defaults to the group sizes (groupby) or the matrix's own n_cells obs column when available — pass explicitly to override, e.g. for a plain DataFrame input.

None
cluster bool

Run hierarchical clustering before display (default True).

True
row_entity str | dict[str, str] | None

Population selection identity. Defaults to {"entity": "cell_population", "attr": "name"}. To link cell types to a Landscape, use {"entity": "cell", "attr": "cell_type"} with the Landscape's cluster attribute.

None
col_entity str | dict[str, str] | None

Group selection identity. Defaults to {"entity": "dataset", "attr": "name"}. Use "nbhd" to link band names to a Landscape's neighborhood geometries.

None
name str

Clustergram registry name.

'composition'
width / height

Widget size in pixels.

required
**kwargs Any

Forwarded to Clustergram.

{}

Enrich

Bases: _StateGetter, CelldegaWidget

A widget for interactive enrichment analysis using the Enrichr API.

Allows users to select a gene list, choose an enrichment library, and specify the number of terms to display. Automatically replaces older widgets with the same name to prevent notebook bloat.

request_state(max_terms=15)

Ask the browser for a snapshot of the enrichment results on screen.

The snapshot holds the library, the input gene list and its source, the top terms with their statistics (combined score, p-value, adjusted p-value, odds ratio) and overlapping genes, the selected term and its genes, and a link to the full results on Enrichr. Asynchronous, like Clustergram.request_state: the reply sets latest_state.

Parameters:

Name Type Description Default
max_terms int

Cap on reported terms.

15

Returns:

Name Type Description
int int

The id of this request.

Landmark

Bases: CelldegaWidget

A widget for interactively marking corresponding landmark points across dataset slices, for procrustes/thin-plate-spline alignment.

Alpha feature: the widget, its traits, and its output may change without notice.

Parameters:

Name Type Description Default
adatas AnnData | list[AnnData] | None

A single AnnData with slice_attr given, or a list of per-slice AnnData (list order is slice order) — the same two input shapes calc_landmarks accepts. Must resolve to at least 2 slices; any number beyond 2 is fine — both viewports can swap to any slice in the resolved set after construction (driven by the front-end dropdowns), not just the initial pair.

None
slice_attr str | None

For a single combined AnnData, the obs column identifying each cell's slice.

None
slices Sequence[Any] | None

The initial (slice_id_a, slice_id_b) pair to show. Defaults to the first two resolved slice ids.

None
cluster_key str | None

Optional obs column to color centroids by, for visual context while marking. Purely cosmetic — has no effect on the resulting landmark table.

None
slice_labels dict[Any, str] | None

Optional {slice_id: display_name} overrides for the dropdown/panel labels. Slices not present default to str(slice_id).

None
landmarks DataFrame | None

An optional pre-existing landmark table to load — calc_landmarks's output shape (columns label, x, y, and a slice-tagging column matching slice_attr), or this widget's own .landmarks from a previous session. Immediately visible on whichever of the initial pair already has points, reviewable/editable via MARK and MODIFY exactly like anything marked in this session, and safe to append new landmark sets onto (the auto-numbered label counter starts past whatever numeric labels are already present).

None
cell_radius

Cell-point radius in data-space (micron) units — the points scale with zoom, exactly like Landscape's cell layer (which defaults to 5.0), with a 1px on-screen floor. width/height/cell_radius are all plain synced traits, so this can also be set as Landmark(..., cell_radius=8.0) or afterward via lm.cell_radius = 8.0. The CELL control has a runtime opacity slider instead — radius rarely needs mid-session adjustment once set.

required
landscapes Any

Not implemented yet — planned future alternative to adatas that would point Landmark directly at two Landscape instances.

None

Raises:

Type Description
NotImplementedError

If landscapes is given.

ValueError

If adatas is missing, resolves to fewer than 2 slices, if a slices id isn't found among them, if a selected slice is missing obsm["spatial"], or if landmarks is missing a required column or references a slice id not among adatas.

calc_alignment_transform(**kwargs)

Fit a transform directly from the currently-marked landmarks.

Convenience wrapper over calc_alignment_transform — equivalent to calling it on landmarks directly.

Landscape

Bases: Screenshots, _RasterCapture, _StateSnapshots, CelldegaWidget

Interactive spatial tissue and low dimensional embedding landscapes.

Spatial datasets read image, cell-boundary, transcript, and expression DegaFiles through base_url. Single-cell UMAP/XY views can instead read AnnData Zarr through zarr_url. The browser loads the source files directly; optional adata supplies metadata, colors, and UMAP positions. See the Landscape guide and File Formats documentation for storage layouts.

Parameters:

Name Type Description Default
ini_x float

The initial x-coordinate of the view.

required
ini_y float

The initial y-coordinate of the view.

required
ini_zoom float

The initial zoom level of the view.

required
min_zoom float

Furthest zoom out. Default: one zoom level past the tissue-wide view.

required
max_zoom float

Closest zoom in. Default: about 10 µm across the map's shorter side.

required
max_tiles_to_view int

Tiles in view below which transcripts and cell boundaries load automatically (close-up). Default: 50.

required
intermediate_zoom_limit float

How far out the TRX button can still load transcripts and cell boundaries on demand, as a multiple of max_tiles_to_view. This counts tiles, so 9 allows a view 3 times wider than close-up. 1 turns this off. Default: 9.

required
rotation_orbit float

Rotating angle around orbit axis for point-cloud views.

required
rotation_x float

Rotating angle around X axis for point-cloud views.

required
token str

The token traitlet.

required
base_url str or list

DegaFiles URL(s), mutually exclusive with zarr_url. Can be a single string or a list of dicts with 'url' and 'label' keys for multiple datasets. Example: [{'url': 'http://...', 'label': 'Dataset1'}, ...] You can also pass a simple list of URL strings.

required
zarr_url str or Path

A single-cell AnnData Zarr store to read instead of DegaFiles (technology="Chromium", the default with zarr_url): an http(s) URL, e.g. on Hugging Face, or a local path under the working directory, served by a local server. Gene expression comes from a CSC matrix in the store, X or a layer such as adata.layers["counts_csc"] = adata.layers["counts"].tocsc(). Optional var["mean"] and var["max"] hold the gene statistics DegaFiles keep in meta_gene.parquet; cell attributes, cluster colors (uns[f"{cluster_attr}_colors"]), and obsm["X_umap"] come from the store unless adata is passed too. Consolidate the store's metadata (zarr.consolidate_metadata) so it opens in one request.

required
zarr_layer str

The zarr_url layer to read expression from, or "X". By default, X if it is CSC, else the store's only CSC layer.

required
gene_signature_url str or Path

Dense AnnData Zarr of cell-type mean expression for UMAP/XY viewport estimates. obs_names match the cell category labels and var_names are genes. The estimate reads nonnegative means from layers['counts'] (mean counts per cell) when present, else X; a layers['log1p'] of mean log1p expression can sit alongside for z-scored views. uns['viewport_signature'] is a JSON string with groupby (the cell attribute) and units, and optionally layer (the layer to read) and layers (units per layer).

required
adata_sig AnnData

The same cell-type means as an in-memory AnnData, read the same way, e.g. sc.get.aggregate(adata, by="leiden", func="mean", layer="counts") (whose "mean" layer is used when there is neither layers['counts'] nor X). Sent with the widget, so keep it to tens of MB; save larger signatures to Zarr for gene_signature_url. groupby defaults to cluster_attr and units to "mean expression per cell" unless uns['viewport_signature'] sets them. Spatial DegaFiles fall back to their own df_sig.parquet for their clusters.

required
dataset_names list

Short names for the datasets to display in the dropdown selector. Should match the length of base_urls. Example: ['Brain', 'Kidney'] for two datasets.

required
rotate float

Degrees to rotate the 2D landscape visualization.

required
adata AnnData

Cell metadata from obs, cluster colors from uns, and UMAP coordinates from obsm["X_umap"]. Overrides source metadata; obs_names must match source cell IDs. Expression is read from DegaFiles or Zarr, not from this object.

required
AnnData AnnData

Alias of adata.

required
cluster_attr str

Cell attribute used for cluster colors and composition bars. Default: "leiden".

required
cell_attr list of str

Cell attributes to expose. The cluster_attr is always included. Default: ["leiden"].

required
landscape_state str

"spatial", "umap", or "xy", depending on the available data. Single-cell data defaults to UMAP when supplied, otherwise XY.

required
xy_genes list of str

Genes for the X and Y expression axes. When empty at initialization, uses the two genes with the highest whole-dataset mean expression; ties/missing statistics use dataset gene order. Explicit axes and later saved-view restores take precedence.

required
xy_scale str

"linear" or "log1p". Default: "log1p".

required
nbhd GeoDataFrame

Neighborhood polygons, or an object exposing to_geodataframe(). Polygons retain their spatial/UMAP/XY coordinate-space metadata.

required
nbhd_edit bool

Enable neighborhood editing. Default: False.

required
dataset_name str

The name of the dataset to visualize. This will show up in the user interface bar.

required
cell_name_prefix bool

If True, cell names in adata.obs.index are assumed to have a dataset prefix (e.g., "dataset-name_cell-name") that should be trimmed when mapping to DegaFiles. Default: False.

required
use_adata_3d_centroids bool

For technology="point-cloud" views given an adata, render that AnnData's obsm["spatial"]/obs[z_key] centroids instead of the geometry baked into cell_metadata.parquet — no DegaFiles rewrite needed to preview a candidate alignment. Has no effect on 2D (non point-cloud) views, which always use the on-disk x/y. Default: True.

required
z_key str

adata.obs column holding the Z coordinate used for use_adata_3d_centroids (falls back to 0 if absent). Default: "Z".

required

use_adata_3d_centroids writes centroids to a small file next to base_url and fetches it over HTTP when base_url is a local celldega.viz.get_local_server() address (millions of per-cell centroids don't fit through the widget's comm channel); otherwise it falls back to syncing them directly through the widget state, which is fine for smaller datasets.

A point-cloud (3D) view requires a real, pre-built DegaFiles base_url like any other technology — build one with the celldega.pre module (e.g. celldega.pre.write_point_cloud_dataset for a 3D AnnData). adata here is only ever used for cell attributes/metadata, never for spatial positions.

The AnnData input automatically extracts cell attributes (e.g., leiden clusters), the corresponding colors (or derives them when missing), and any available UMAP coordinates.

nbhd_polygons property

All NBHDs with geometry, space, cell IDs and x/y vertex rings.

Physical polygons use native tissue coordinates; UMAP and XY retain their displayed coordinates and their saved embedding/axis metadata. Display Y increases downward; UMAP's axes.y.reversed marks that increasing the raw embedding's second coordinate is drawn upward. Each element of x/y is a polygon ring, including any interior holes. nbhd exposes the same frame, updated when browser edits arrive.

pins property writable

Points of interest on the tissue or the UMAP, one per Snapshot (PINS).

Set it to Snapshots to annotate the Landscape: a Snapshots collection, PNG paths, a folder of Snapshot PNGs, or a viewer's snap. Each Landscape Snapshot of the tissue or the UMAP becomes a pin at the center of its view, shown while the Landscape shows that space; hovering shows its name and memo, and clicking opens its view::

landscape.pins = dega.viz.Snapshots(landscape.snap)
landscape.show_pins = True  # or press PINS

Returns the pins (name, description, position and saved view).

apply_state(changes)

Change what the Landscape shows, as its controls would.

Input structure is validated here, so mistakes raise in the calling cell. Availability (names, layers, views) is checked in the browser, which then applies the changes; check get_apply_result with apply_request_id in a later cell, or observe apply_capture_id and apply_error. Runtime failures may leave partial changes.

Parameters:

Name Type Description Default
changes dict

Any of:

  • clusters: cluster names to select / highlight (exactly; [] clears the selection), like clicking cluster bars.
  • genes: genes to color cells by (up to 20; [] returns to cluster colors), like the comma-separated gene search.
  • view: {"target": [x, y], "zoom": z} camera position (orbit views also take rotationOrbit and rotationX).
  • zoom_to: {"clusters": [...]} or {"cells": [...]} to frame those cells (spatial view).
  • reset_view: True to return to the starting view.
  • space: "spatial", "umap" or "xy".
  • selected_cells: cell names to select ([] clears them).
  • xy: {"genes": [x_gene, y_gene], "scale": "linear" | "log1p"} for the XY expression view (up to two genes).
  • layers: booleans for image, cells, transcripts, neighborhoods.
  • channels: {name: {"visible": bool, "intensity": 0..100}}.
  • sliders: cell/nbhd values and trx: {"size": ..., "opacity": ...}.
  • image_source: "primary" or "he" (when available).
required

Returns:

Type Description
list[str]

list[str]: What was submitted; not confirmation that the browser applied it.

Raises:

Type Description
ValueError

For an unknown key or an invalid value (nothing changes).

get_selected_cells(adata=None)

Return selected IDs, or a copied AnnData subset when adata is supplied.

highlight_cells(cell_ids)

Highlight specific cells by their identifiers.

load_gates(path)

Restore NBHDs; only polygons matching the current coordinate space are drawn.

neighborhood_summary(max_clusters=8)

Drawn neighborhoods, with each one's cell count and cluster mix.

Reads nbhd_polygons (regions drawn in the Landscape, in any space) and this Landscape's per-cell clusters (meta_cell[cluster_attr]).

Returns:

Type Description
list[dict]

list[dict]: ``{"name", "space", "n_cells", "clusters": [{"name", "count",

list[dict]

"fraction"}, ...]}`` per neighborhood, largest clusters first.

request_state(max_bars=25)

Ask the browser for a snapshot of what this Landscape shows.

The snapshot holds the space (spatial / UMAP), the camera (target, zoom), how cells are colored ("cluster" or genes), the selected clusters and genes, and the cluster and gene counts in the current field of view (as in the bar charts). Asynchronous: the reply sets latest_state. Drawn neighborhoods are already in Python: see neighborhood_summary.

Parameters:

Name Type Description Default
max_bars int

Cap on the clusters and genes listed for the field of view.

25

Returns:

Name Type Description
int int

The id of this request.

save_gates(path)

Save named polygons, coordinate spaces and selected cell IDs as GeoJSON.

select_gate(name)

Restore a gate's view and select its saved cells (names must be unambiguous).

set_xy(x_gene=None, y_gene=None, *, scale='log1p')

Show source expression on X/Y, using linear or log1p scaling.

Both genes may be omitted to start with all cells overlapping. A gene for Y requires a gene for X. No UMAP is required. Return with landscape_state = 'spatial' (or 'umap' when available).

trigger_update(new_value)

Update the update_trigger traitlet with a new value.

update_cell_clusters(new_clusters)

Update cell clusters with new data.

NeighborhoodCloud

Bases: _SpatialWidget

3D orbit view of neighborhood alpha shapes (replaces Landscape(technology="neighborhood-cloud")).

Renders a pre-built neighborhood-cloud DegaFiles directory: one precomputed alpha-shape polygon per (cluster, slice), cheap to display regardless of dataset size, with real cell centroids loaded on demand when a cluster is selected. Build one with celldega.pre.write_nbhd_cloud_dataset from per-slice alpha shapes (celldega.nbhd.alpha_shape_cell_clusters_by_slice).

The neighborhood geometry lives entirely on disk under the DegaFiles nbhd_cloud/ tree and is fetched by the front-end; this widget carries only the shared spatial trait surface plus the 3D orbit camera. (The 2D neighborhood drawing editor is a Landscape feature and intentionally not part of NeighborhoodCloud.)

Parameters:

Name Type Description Default
base_url str or list

DegaFiles URL(s), as in Landscape.

required
adata AnnData

Source of cell attributes/metadata.

required

Screenshot

A screenshot being captured or saved; displays its status and preview.

Attributes:

Name Type Description
path Path | None

The PNG (written once done).

done

Whether the files are written (or capture failed: see error).

error

Why nothing was saved, if so.

wait(timeout=None)

Block until saved (only from another thread: in a notebook cell the browser can't reply until the cell finishes).

Snapshot

Bases: AnyWidget

Display a static PNG, name and memo, with expandable reproducibility metadata.

Pass a PNG path (plain PNGs work too), a captured snapshot dictionary, or a name in a linked viewer's snap collection. Linking a viewer adds a blue Show this view control when the image contains compatible replay metadata. The viewer must already be displayed in this kernel. Each card embeds its PNG in notebook widget state; it does not load the visualization renderer or data.

Examples::

Snapshot(landscape=landscape, snapshot="Glomerulus")
Snapshot("figures/glomerulus.png", landscape=landscape)
Snapshot(clustergram=cgm, snapshot="Markers")
Snapshot("figures/overview.png", name="Overview", description="My memo")

panel selects the replay panel in a composite PNG. allow_resize=True permits navigation into a differently sized viewer; data identity is always checked. Images alone cannot restore a view. Multiple cards coexist, including cards with the same name. Linking requires a live kernel; static previews and metadata remain available in saved widget state.

show_view()

Request navigation in the linked viewer; report its exact acknowledgement.

Snapshots

A named collection of Snapshots, e.g. points of interest to pin on a Landscape.

Give it PNG paths, a folder of Snapshot PNGs, a viewer's snap collection, or add Snapshots one at a time. Passed to a Landscape (Landscape(..., pins=...) or landscape.pins = ...), each Landscape Snapshot becomes a pin at the center of its view; the PINS button shows them, and clicking one opens its view.

Examples::

poi = dega.viz.Snapshots(["figures/glomerulus.png", "figures/medulla.png"])
poi = dega.viz.Snapshots("celldega_files/snapshots")   # every Snapshot PNG
poi = dega.viz.Snapshots(landscape.snap)
poi.card("Glomerulus", landscape=landscape)             # one postcard, by name
dega.viz.Landscape(base_url=..., snapshots=poi)         # pinned on the tissue
landscape.pins = poi                                    # or pin them later

add(snapshot, *, name=None)

Add a Snapshot; returns its name (repeated names get (2), etc.).

card(name, **kwargs)

A postcard for one of these Snapshots, chosen by name.

poi.card("Glomerulus", landscape=landscape) links it to a viewer, like Snapshot; other keyword arguments go to Snapshot too.

pins()

One pin per Landscape Snapshot of the tissue or the UMAP: name, memo, position, space and view.

A pin sits at the center of its Snapshot's view, in the space the Snapshot shows ("spatial" or "umap"), and appears while the Landscape shows that space. Snapshots of other widgets (a Clustergram or Yearbook), or of the XY view, are skipped: they are shown as cards instead.

save(folder)

Write the Snapshots kept only in memory (e.g. clerk.snapshots) to folder as Snapshot PNGs; returns the files written.

Snapshots already on disk are left where they are. Each written file reopens as before, e.g. Snapshots(folder) in a later session.

Yearbook

Bases: Screenshots, _RasterCapture, _StateSnapshots, CelldegaWidget

A widget for visualizing cell portraits in a yearbook-style grid layout.

This widget creates a grid of cell "portraits" - zoomed-in views centered on selected cells. All portraits share synchronized zoom state but display different spatial regions. The control panel works similarly to Landscape, showing gene and cell bars based on visible content.

Parameters:

Name Type Description Default
base_url str

The base URL for the dataset.

required
cells list

List of cell identifiers to display as portraits. If not provided and no query is given, random cells will be selected.

required
selected_cells list[str]

IDs checked in the portrait grid. Independent of the portrait candidates in cells and the input selection. Checked IDs persist across page and query changes. Assign a new list to update the checked portraits from Python.

required
selection Selection or dict or list

Ordered selection of cells to display as portraits. Accepts a selection object exposing to_json()/to_dict() (e.g. a celldega.select selection), a JSON-ready selection dict with ids, or a plain list of cell ids. Yearbook uses its ids as the portrait cell order and stores the JSON-ready payload for provenance. Pass either selection or cells, not both.

required
front_end_query dict

Stateless query evaluated in the browser against DegaFiles (no Python/AnnData required). Supports the following formats:

  • Cluster only: {"cluster": {"attr": "leiden", "value": "8"}} Returns random cells from the specified cluster.
  • Gene only: {"gene": "BRCA1"} Returns cells ranked by gene expression (highest first).
  • Cluster + Gene: {"cluster": {"attr": "leiden", "value": "8"}, "gene": "BRCA1"} Returns cells from the cluster ranked by gene expression.
  • Max cells: {"max_cells": 100} Limits the number of cells returned (default: num_rows * num_cols * 10).

(The former query argument is deprecated; it now maps to front_end_query.)

required
num_rows int

Number of rows in the portrait grid. Alias: rows.

required
num_cols int

Number of columns in the portrait grid. Alias: cols.

required
portrait_size_um float

Size of each portrait in micrometers.

required
portrait_gap int

Gap between portraits in pixels. Default is 4.

required
pixel_width float

Pixel width for scale bar calculation. If provided, a scale bar will be displayed.

required
token str

Authentication token for data access.

required
dataset_name str

Name to display in the UI.

required
width int

Widget width in pixels. 0 means 100%.

required
height int

Widget height in pixels.

required
segmentation str

Segmentation version to use. Default is "default".

required
adata AnnData

AnnData object for cell metadata.

required
cell_attr list

List of cell attributes to extract from adata.

required

Example::

# Using an explicit list of cell ids
yb = Yearbook(
    base_url="https://path-to-dataset",
    cells=["cell_1", "cell_2", "cell_3", "cell_4"],
    rows=2,
    cols=2,
    portrait_size_um=100,
)

# Using an ordered selection of cell ids from an AnnData
selection = adata.obs_names[adata.obs["leiden"] == "5"][:4].tolist()
yb = Yearbook(
    base_url="https://path-to-dataset",
    selection=selection,
    rows=2,
    cols=2,
)

# Using a stateless front-end query (no AnnData needed)
yb = Yearbook(
    base_url="https://path-to-dataset",
    front_end_query={"gene": "BRCA1", "max_cells": 50},
    rows=2,
    cols=2,
    portrait_size_um=100,
)

total_pages property

Calculate total number of pages based on cells and grid size.

get_selected_cells(adata=None)

Return checked IDs, or a copied AnnData subset in its original row order.

go_to_page(page)

Navigate to a specific page.

next_page()

Navigate to next page.

prev_page()

Navigate to previous page.

clustergram_enrich(cgm, *, row_enrich=True, col_enrich=False)

Display a Clustergram widget and an Enrich widget side by side.

Parameters:

Name Type Description Default
cgm Clustergram

A Clustergram widget.

required
row_enrich bool

If True (default), run enrichment analysis when row dendrogram clusters are selected.

True
col_enrich bool

If True, run enrichment analysis when column dendrogram clusters are selected.

False

Returns:

Name Type Description
HBox HBox

Visualization display containing both widgets.

from_png(path, *, panel=0, allow_resize=False, **overrides)

Construct an interactive visualization from a Celldega screenshot PNG.

The PNG supplies source references, construction options and supported replay settings. Data is loaded from its recorded location; it is not embedded in the image. Pass constructor overrides to relocate data or provide original in-memory inputs, e.g. matrix=mat or adata=adata. A composite screenshot has one widget per panel; select it with the zero-based panel argument.

Display the returned widget. It restores once its browser renderer is ready, checking the schema, data identity and canvas dimensions before replay. In a later notebook cell, inspect viz.get_apply_result(viz.apply_request_id); None means pending, and an apply_error reply explains a failed restore. allow_resize=True accepts a different canvas extent. This is a partial semantic restore, not a guarantee of identical pixels.

get_local_server(file_server_root=None)

Start a local HTTP server with CORS support and return the port number.

Parameters:

Name Type Description Default
file_server_root Optional

by default, files will be served from

None

Returns:

Name Type Description
int int

The port number on which the server is running.

get_proxy_server(remote_base_url=None, verbose=False)

Start a local proxy server that forwards requests to a remote URL.

This is useful for bypassing CORS restrictions when the remote server (like Hugging Face) doesn't support CORS for Range requests.

Security: The proxy validates all URLs to prevent SSRF attacks: - Only http/https schemes are allowed - Private/loopback IP addresses are blocked - When remote_base_url is set, /proxy/ requests are constrained to that host

Parameters:

Name Type Description Default
remote_base_url str | None

Optional base URL for the remote server. If provided, requests to the proxy will be forwarded to this URL. If not provided, use /proxy/FULL_URL format.

None
verbose bool

If True, print log messages.

False

Returns:

Name Type Description
int int

The port number on which the proxy server is running.

Example

port = get_proxy_server("https://huggingface.co/datasets/user/repo/resolve/main/folder")

Now use http://localhost:{port}/file.parquet

Or use http://localhost:{port}/proxy/https://huggingface.co/.../other/file.parquet

landscape_clerk(landscape, clerk, width='600px', height='650px', *, capture_on_select=True)

Convenience layout: a Landscape beside a portrait Clerk, wired via link_clerk.

For anything else, call link_clerk and arrange the widgets yourself.

Parameters:

Name Type Description Default
landscape Landscape

A Landscape widget.

required
clerk Clerk

A Clerk widget.

required
width str

Width of the Landscape widget.

'600px'
height str

Height of both widgets.

'650px'
capture_on_select bool

Re-capture the raster on each Landscape selection.

True

Returns:

Name Type Description
HBox HBox

Both widgets side by side.

landscape_clustergram(landscape, mat, width='600px', height='700px', *, enrich=False, row_enrich=True, col_enrich=False, enrich_kwargs=None)

Deprecated alias for spatial_clustergram, kept for backward compatibility. Prefer spatial_clustergram, which also works with CellCloud, NeighborhoodCloud, and Yearbook.

landscape_yearbook(landscape, yearbook, width='100%', height='400px', cluster_attr='leiden')

Display a Landscape widget above a Yearbook widget with linked queries.

When the user clicks on a cluster in the Landscape, the Yearbook automatically updates to show cells from that cluster. When a gene is selected, cells are ranked by gene expression.

Parameters:

Name Type Description Default
landscape Landscape

A Landscape widget.

required
yearbook Yearbook

A Yearbook widget.

required
width str

The width of the widgets.

'100%'
height str

The height of each widget.

'400px'
cluster_attr str

The cell attribute (adata.obs column) a clicked cluster value refers to (default "leiden"). If the click payload carries its own attr it takes precedence, so linked Clustergrams over non-leiden sets (cell types, domains) color the right cells.

'leiden'

Returns:

Name Type Description
VBox VBox

Visualization display containing both widgets stacked vertically.

Example::

landscape = dega.viz.Landscape(base_url="...", adata=adata)
yearbook = dega.viz.Yearbook(base_url="...", rows=2, cols=4)
display = dega.viz.landscape_yearbook(landscape, yearbook)

landscape_yearbook_clustergram(landscape, yearbook, cgm, width='600px', height='400px', cluster_attr=None)

Display a Landscape and Clustergram side by side, with a Yearbook below.

All three widgets are linked: - Clustergram clicks update both Landscape and Yearbook - Gene selections rank cells in Yearbook by expression - Cluster selections filter cells in Yearbook

Parameters:

Name Type Description Default
landscape Landscape

A Landscape widget.

required
yearbook Yearbook

A Yearbook widget.

required
cgm Clustergram

A Clustergram widget.

required
width str

The width of each widget in the top row.

'600px'
height str

The height of each widget.

'400px'

Returns:

Name Type Description
VBox VBox

Visualization display with Landscape+Clustergram on top, Yearbook below.

Example::

landscape = dega.viz.Landscape(base_url="...", adata=adata)
yearbook = dega.viz.Yearbook(base_url="...", rows=2, cols=4)
cgm = dega.viz.Clustergram(matrix=mat)
display = dega.viz.landscape_yearbook_clustergram(landscape, yearbook, cgm)

Link a standalone Clerk to whichever widgets you pass -- the integration point.

Clerk stands alone and only sees the widgets you pass it. Widgets are modular and swappable: pass any subset. The usual case is Landscape + Clustergram + Enrich. Each question from the chat box captures the linked views as they are at that moment:

  • landscape -> a screenshot of the current view (+ zoom/pan view state) in clerk.image_b64 / clerk.image_view_state.
  • clustergram -> a snapshot of what's on screen (Clustergram.request_state), plus any genes named in the question; its selected genes also flow into clerk.gene_list.
  • enrich -> the enrichment results on screen (Enrich.request_state). Clerk then stops fetching its own Enrichr terms.

  • yearbook -> the portraits on screen (its query, page and cells, and an image), shown with the question. Clerk can also choose which cells it shows: a cluster ranked by a gene (the Yearbook's own query), or, given a single-cell AnnData (Clerk(adata=...): an AnnData, or a link to one), any selection celldega.select can make.

This only wires state; lay the widgets out however you like. Returns clerk for chaining.

Parameters:

Name Type Description Default
clerk Clerk

The Clerk widget to link.

required
landscape Landscape | None

Source of raster / view-state evidence.

None
clustergram Clustergram | None

Source of matrix and gene-list evidence.

None
enrich Enrich | None

Source of enrichment-result evidence.

None
yearbook Yearbook | None

Source of single-cell portrait evidence.

None
capture_on_select bool

Re-capture the Landscape raster on each selection.

True

load_screenshot(path)

Read the record embedded in a screenshot PNG.

load_screenshots(folder)

Every screenshot PNG's record in a folder, oldest first.

Unrelated or malformed files are skipped.

screenshot(*widgets, description='', path=None, title='', metadata=None, author='you', max_size=2048, background='white')

Save a screenshot of one or more widgets with a description and provenance.

Pass widgets or containers of them (e.g. the linked row from dega.viz.spatial_clustergram): several widgets are placed side by side in one image, and each one's state is recorded.

Parameters:

Name Type Description Default
description str

What you're looking at and why it's interesting.

''
path str | Path | None

A .png file, or a folder for an auto-named file (default celldega_files/snapshots).

None
title str

Optional short title (also used in the file name).

''
metadata dict | None

Anything else to record, e.g. {"adata": "data/kidney.h5ad"}. Set widget.screenshot_metadata to record it with every screenshot of that widget, including ones taken with its SNAP button.

None
max_size int

Longest side of each widget's image, in pixels.

2048
background str | None

A CSS color behind areas the visualization leaves empty (white by default); None keeps them transparent.

'white'

Returns:

Name Type Description
Screenshot Screenshot

Displays its progress and a preview; .path once saved.

snapshot(*widgets, name='', **kwargs)

Save a Snapshot (PNG + Markdown memo) and register it in each viewer's snap.

name is the collection key and postcard title. Capture finishes after the notebook cell returns. See screenshot for capture options; that spelling remains a compatibility alias.

spatial_clustergram(spatial, mat, width='600px', height='700px', *, enrich=False, row_enrich=True, col_enrich=False, enrich_kwargs=None, cluster_attr=None, clerk=False, clerk_layout='sidecar', clerk_kwargs=None)

Display a spatial widget and a Clustergram widget side by side, linked so that clicking a Clustergram row/column updates the spatial widget.

Works with any of celldega's spatial widgets: Landscape, CellCloud, NeighborhoodCloud, or Yearbook. Landscape/CellCloud/ NeighborhoodCloud share an update_trigger trait and are linked via a front-end jslink (no round-trip through Python); Yearbook has no such trait and is instead linked by observing the Clustergram's click_info in Python and translating it into a front_end_query (same mechanism as landscape_yearbook_clustergram).

Parameters:

Name Type Description Default
spatial Landscape | CellCloud | NeighborhoodCloud | Yearbook

The spatial widget to link.

required
mat Clustergram

A Clustergram widget.

required
width str

The width of the spatial widget. The Clustergram panel is sized to the Clustergram's canvas (its width plus ~100px for labels), widened if needed so its control panel fits.

'600px'
height str

The total height of the spatial widget, including its control bar, and the default height of the Enrich widget. The Clustergram's height sets only its canvas; its controls and dendrogram add about 200px, so Clustergram(height=<height - 200>) lines the two up (e.g. the 700px default with height=500). The row stretches every widget to the tallest one.

'700px'
enrich bool | Enrich

If True, create an Enrich widget; if an Enrich instance is provided, use it directly. If False, no enrichment widget is shown. Ignored for a Yearbook spatial.

False
row_enrich bool

If True (default), run enrichment analysis when row dendrogram clusters are selected.

True
col_enrich bool

If True, run enrichment analysis when column dendrogram clusters are selected.

False
enrich_kwargs dict | None

Optional kwargs passed to Enrich when enrich=True.

None
cluster_attr str | None

The cell attribute (adata.obs column) a clicked cluster refers to. Only used when spatial is a Yearbook; defaults to the Clustergram's own col_entity attribute (see _clustergram_col_attr).

None
clerk bool | Clerk

If True, create a Clerk; if a Clerk is given, use it. Either way it is linked (link_clerk) to the spatial widget, the Clustergram and any Enrich here. If False, no Clerk.

False
clerk_layout str

"sidecar" (default) adds Clerk to the end of the row as a narrow column the row's height, like Enrich: it takes the room the row leaves (240-300 px), and the views keep their widths. A row wider than the notebook scrolls sideways. "wide" puts Clerk full width under the row.

'sidecar'
clerk_kwargs dict | None

Optional kwargs passed to Clerk when clerk=True, e.g. {"context_info": "..."}.

None

Returns:

Name Type Description
HBox HBox | VBox

The widgets side by side; with clerk_layout="wide", a VBox with

HBox | VBox

that row above the Clerk.