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:
- An explicit id list —
cells=["cell_1", "cell_2", ...]. The simplest path: you already know the cells you want. - A back-end selection —
selection=.... Accepts acelldega.select.Selection, a JSON-ready selection dict, or a plain id list. This is the recommended way to drive the grid from a PythonAnnDataobject, because it carries the query, sampler, scores, and provenance with the cells. See the select module docs for the full query/sampling algebra. - A stateless front-end query —
front_end_query=.... Evaluated in the browser against the dataset's DegaFiles, so it needs only abase_urland no PythonAnnData.
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 |
required |
zarr_url
|
str or Path
|
Self-contained AnnData Zarr instead
of |
required |
zarr_layer
|
str
|
CSC expression layer, or |
required |
adata
|
AnnData
|
Source of cell attributes/metadata (clusters,
colors, UMAP). Never used for spatial positions — those come from the
DegaFiles — except when |
required |
alignment
|
str
|
Named alignment variant; cell positions are
read from |
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 |
required |
z_key
|
str
|
|
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
|
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. |
required |
effort
|
str
|
Reasoning effort, |
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 withdega.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
|
None
|
html
|
bool
|
Also render |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
What was saved: |
dict
|
and |
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 |
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 |
-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 |
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
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
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:
|
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: What was submitted, e.g. |
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'
|
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 |
()
|
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 ( |
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
|
|
required |
axis
|
str
|
|
'col'
|
attribute
|
str | None
|
The manual attribute, e.g. |
None
|
colors
|
dict | None
|
Optional |
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'
|
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 |
None
|
Returns:
| Type | Description |
|---|---|
Series
|
A |
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 |
required |
modality
|
str
|
Modality key on a MuData (default |
'population'
|
groupby
|
str | None
|
With cell-level |
None
|
category
|
str | None
|
Population |
None
|
colors
|
dict[str, str] | None
|
Optional |
None
|
adata
|
Any
|
Optional source cell-level |
None
|
group_attrs
|
list[str] | None
|
Group-level |
None
|
normalized
|
bool | None
|
Column-normalize each bar to 100%. Defaults to |
None
|
col_weights
|
dict[str, float] | None
|
Optional |
None
|
cluster
|
bool
|
Run hierarchical clustering before display (default |
True
|
row_entity
|
str | dict[str, str] | None
|
Population selection identity. Defaults to
|
None
|
col_entity
|
str | dict[str, str] | None
|
Group selection identity. Defaults to
|
None
|
name
|
str
|
Clustergram registry name. |
'composition'
|
width / height
|
Widget size in pixels. |
required | |
**kwargs
|
Any
|
Forwarded to |
{}
|
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 |
None
|
slice_attr
|
str | None
|
For a single combined |
None
|
slices
|
Sequence[Any] | None
|
The initial |
None
|
cluster_key
|
str | None
|
Optional |
None
|
slice_labels
|
dict[Any, str] | None
|
Optional |
None
|
landmarks
|
DataFrame | None
|
An optional pre-existing landmark table to load —
|
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 |
required | |
landscapes
|
Any
|
Not implemented yet — planned future alternative to
|
None
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
ValueError
|
If |
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 |
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 ( |
required |
zarr_layer
|
str
|
The |
required |
gene_signature_url
|
str or Path
|
Dense AnnData Zarr of cell-type
mean expression for UMAP/XY viewport estimates. |
required |
adata_sig
|
AnnData
|
The same cell-type means as an in-memory
AnnData, read the same way, e.g. |
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 |
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 |
required |
z_key
|
str
|
|
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:
|
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 |
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 |
Whether the files are written (or capture failed: see |
|
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 |
required |
selection
|
Selection or dict or list
|
Ordered selection of
cells to display as portraits. Accepts a selection object exposing
|
required |
front_end_query
|
dict
|
Stateless query evaluated in the browser against DegaFiles (no Python/AnnData required). Supports the following formats:
(The former |
required |
num_rows
|
int
|
Number of rows in the portrait grid. Alias: |
required |
num_cols
|
int
|
Number of columns in the portrait grid. Alias: |
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 |
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 |
required |
clerk
|
Clerk
|
A |
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 |
required |
yearbook
|
Yearbook
|
A |
required |
width
|
str
|
The width of the widgets. |
'100%'
|
height
|
str
|
The height of each widget. |
'400px'
|
cluster_attr
|
str
|
The cell attribute ( |
'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 |
required |
yearbook
|
Yearbook
|
A |
required |
cgm
|
Clustergram
|
A |
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_clerk(clerk, *, landscape=None, clustergram=None, enrich=None, yearbook=None, capture_on_select=True)
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) inclerk.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 intoclerk.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 selectioncelldega.selectcan 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 |
None
|
title
|
str
|
Optional short title (also used in the file name). |
''
|
metadata
|
dict | None
|
Anything else to record, e.g. |
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); |
'white'
|
Returns:
| Name | Type | Description |
|---|---|---|
Screenshot |
Screenshot
|
Displays its progress and a preview; |
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 |
required |
width
|
str
|
The width of the spatial widget. The Clustergram panel is
sized to the Clustergram's canvas (its |
'600px'
|
height
|
str
|
The total height of the spatial widget, including its
control bar, and the default height of the |
'700px'
|
enrich
|
bool | Enrich
|
If True, create an |
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 |
None
|
cluster_attr
|
str | None
|
The cell attribute ( |
None
|
clerk
|
bool | Clerk
|
If True, create a |
False
|
clerk_layout
|
str
|
|
'sidecar'
|
clerk_kwargs
|
dict | None
|
Optional kwargs passed to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
HBox |
HBox | VBox
|
The widgets side by side; with |
HBox | VBox
|
that row above the Clerk. |