Skip to content

Neighborhood Module API Reference

See Atera breast cancer neighborhoods for hextile niches and alpha-shape comparisons, and pancreas islet gradients for a complete gradient-analysis and NeighborhoodCollection workflow.

Neighborhoods are GeoDataFrames with one row per neighborhood and an id column (name by default, falling back to neighborhood_id / nbhd_id). They come from alpha shapes, hextiles, gradient rings, or your own polygons, and are summarized against cell-level AnnData or MuData into new neighborhood-level AnnData objects:

import celldega as dega

gdf_hex = dega.nbhd.generate_hextile(adata, diameter=100)

# neighborhoods x genes (mean expression of the cells inside each hexagon)
adata_nbg = dega.nbhd.calc_nbhd_by_gene(gdf_hex, "cell", adata)

# neighborhoods x cell types (proportions)
adata_nbp = dega.nbhd.calc_nbhd_by_pop(adata, gdf_hex, category="leiden")

# neighborhoods x neighborhoods relations (e.g. between cluster alpha shapes)
gdf_alpha = dega.nbhd.alpha_shape_cell_clusters(adata, cat="leiden", alphas=[150])
gdf_alpha = dega.nbhd.filter_alpha_shapes(gdf_alpha, alpha=150)
adata_overlap = dega.nbhd.calc_nbhd_overlap(gdf_alpha, metric="iou")

# every result is ready for a Clustergram
mat = dega.clust.Matrix(adata_nbp)

With a MuData (e.g. RNA + protein), calc_nbhd_by_gene aggregates every modality and returns a MuData of neighborhood-level modalities; pass modality= to aggregate just one. In the calc_nbhd_* functions and calc_gradient, any object exposing to_geodataframe() can stand in for the neighborhood GeoDataFrame.

alpha_shape returns Shapely geometry and calc_gradient returns a GeoDataFrame of rings. With coordinates in microns:

footprint = dega.nbhd.alpha_shape(adata.obsm["spatial"][seed_mask], inv_alpha=40)
rings = dega.nbhd.calc_gradient(
    footprint, direction="both", bin_width=25, max_dist=200,
    clip_reference=adata,
)
adata_rings = dega.nbhd.calc_nbhd_by_pop(adata, rings, category="leiden", min_cells=1)

Multiple footprints are unioned before buffering. Cells are assigned to rings with a within spatial join, so a cell lying exactly on a ring boundary is not counted in either ring.

Storing results in a NeighborhoodCollection

NeighborhoodCollection is a MuData-backed container that keeps neighborhood geometry, per-neighborhood modalities, and neighborhood-by-neighborhood relations aligned on one observation axis. It stores data only: pass it to the functions above in place of the GeoDataFrame, then store what they return.

nc = dega.nbhd.NeighborhoodCollection(gdf=gdf_alpha, nbhd_type="alpha_shape")

pop = dega.nbhd.calc_nbhd_by_pop(adata, nc, category="leiden", min_cells=5)
nc.subset(pop.obs_names)             # optional: drop neighborhoods below min_cells
nc.add_mod("population", pop)
nc.add_mod("gene", dega.nbhd.calc_nbhd_by_gene(nc, adata=adata))
nc.add_relation("overlap", dega.nbhd.calc_nbhd_overlap(nc, metric="iou"))

trx = dega.nbhd.read_transcripts(data_dir)
nc.obs = nc.obs.join(dega.nbhd.calc_nbhd_transcript_assignment(nc, trx))

mat = dega.clust.Matrix(mdata=nc, color_by="population")

Neighborhood generation and calculation.

Neighborhoods are GeoDataFrame objects (one row per neighborhood) built from cells (alpha shapes, hextiles, gradient rings) and summarized against cell-level AnnData/MuData into new neighborhood-level AnnData.

NeighborhoodCollection

Bases: CelldegaCollection

Neighborhood-level or spatial-region MuData collection.

Observations are neighborhoods or spatial regions. Feature modalities live in mod and global observation relations live in relations/mdata.obsp. Geometry is kept as a live GeoDataFrame in memory; durable geometry storage can be layered on later with WKB columns or GeoParquet sidecars.

The collection only stores data. Computation lives in celldega.nbhd functions, which accept the collection wherever they take a neighborhood GeoDataFrame and return plain objects to store back::

nc = NeighborhoodCollection(gdf=gdf_alpha)
pop = dega.nbhd.calc_nbhd_by_pop(adata, nc, category="leiden")
nc.subset(pop.obs_names)  # optional: drop neighborhoods below min_cells
nc.add_mod("population", pop)
nc.add_mod("gene", dega.nbhd.calc_nbhd_by_gene(nc, adata=adata))
nc.add_relation("overlap", dega.nbhd.calc_nbhd_overlap(nc))
rings = NeighborhoodCollection(
    gdf=dega.nbhd.calc_gradient(nc.gdf.loc[["9"]]), nbhd_type="gradient"
)

geometry property

Neighborhood geometry. Alias of gdf (single source of truth).

__init__(obs=None, mod=None, mdata=None, gdf=None, nbhd_type=None, data_dir=None, source=None, name=None, meta=None, nbhd_col='name', geometry=None, relations=None, provenance=None, uns=None, memberships=None, transformation_matrix=None)

Build a neighborhood / spatial-region collection.

The observation axis (one row per neighborhood) is established from a neighborhood GeoDataFrame (gdf — the usual path, produced by alpha_shape / generate_hextile / etc.), from an explicit obs table paired with geometry, or from a pre-built mdata. When built from gdf, per-neighborhood area/area_um2 and centroid columns are derived and the neighborhood-id column is normalized.

Parameters:

Name Type Description Default
obs DataFrame | None

Pre-built neighborhood observation table (use with geometry, not with gdf).

None
mod dict[str, AnnData] | None

Feature-space modalities to attach up front.

None
mdata MuData | None

Pre-built MuData to wrap (e.g. from read).

None
gdf GeoDataFrame | None

Neighborhood geometry; each row becomes an observation. Mutually exclusive with obs/geometry.

None
nbhd_type str | None

Label for how the neighborhoods were made (e.g. "hextile", "alpha_shape"); defaults to "neighborhood".

None
data_dir str | None

DegaFiles/instrument directory used as the default source for load_transformation_matrix.

None
source str | dict[str, Any] | None

Source descriptor recorded in provenance.

None
name str | None

Optional collection name.

None
meta dict[str, Any] | None

Extra metadata merged into uns["celldega"].

None
nbhd_col str

Column in gdf identifying each neighborhood (falls back to neighborhood_id / nbhd_id).

'name'
geometry GeoDataFrame | None

Neighborhood geometry paired with an explicit obs (alternative to gdf).

None
relations dict[str, spmatrix] | None

Square neighborhood-by-neighborhood matrices for mdata.obsp.

None
provenance dict[str, Any] | None

Free-form provenance metadata.

None
uns dict[str, Any] | None

Extra Celldega metadata.

None
memberships dict[str, spmatrix] | None

Membership matrices (e.g. cell-to-neighborhood); kept in memory only (not persisted by write).

None
transformation_matrix Any | None

Optional micron-to-pixel affine (see set_transformation_matrix).

None

Raises:

Type Description
ValueError

If gdf is combined with obs or geometry.

add_relation(key, relation)

Store a square neighborhood-by-neighborhood relation in relations[key].

Parameters:

Name Type Description Default
key str

Name for the relation in relations (mdata.obsp).

required
relation Any

A square AnnData labelled by neighborhood id on both axes (e.g. from celldega.nbhd.calc_nbhd_overlap or calc_nbhd_bordering), aligned to this collection's obs by id with absent neighborhoods as zero rows/columns; or a matrix already in obs order.

required

Returns:

Type Description
csr_matrix

The stored sparse relation matrix.

Raises:

Type Description
ValueError

If a matrix is not (n_obs, n_obs).

from_gdf(gdf, nbhd_type='neighborhood', **kwargs) classmethod

Create a NeighborhoodCollection from a neighborhood GeoDataFrame.

Convenience wrapper for NeighborhoodCollection(gdf=gdf, nbhd_type=nbhd_type, **kwargs).

Parameters:

Name Type Description Default
gdf GeoDataFrame

Neighborhood geometry; each row becomes an observation.

required
nbhd_type str

Label for how the neighborhoods were made.

'neighborhood'
**kwargs Any

Forwarded to the constructor.

{}

Returns:

Type Description
NeighborhoodCollection

A new NeighborhoodCollection.

load_transformation_matrix(data_dir=None)

Load the micron-to-pixel transformation matrix from DegaFiles.

Reads micron_to_image_transform.csv and stores it via set_transformation_matrix. Later this matrix can instead be supplied directly (e.g. from SpatialData).

Parameters:

Name Type Description Default
data_dir str | None

Directory containing the transform CSV; defaults to self.data_dir.

None

Returns:

Type Description
ndarray

The loaded matrix as a float ndarray.

Raises:

Type Description
ValueError

If no data_dir is available.

set_transformation_matrix(matrix)

Set the micron-to-pixel affine transformation matrix.

Parameters:

Name Type Description Default
matrix Any

Affine mapping micron coordinates (the geometry's native space) to image/pixel space, as a (2, 3) or (3, 3) array.

required

Returns:

Type Description
ndarray

The stored matrix as a float ndarray. It is also mirrored into

ndarray

uns so it round-trips through write/read.

subset(obs_names)

Keep only the neighborhoods in obs_names, in that order (in place).

Modalities, geometry, square relations and memberships are subset together so they stay aligned to the observation axis. Use it to drop neighborhoods a celldega.nbhd function filtered out, e.g. nc.subset(pop.obs_names) after calc_nbhd_by_pop(..., min_cells=5).

Parameters:

Name Type Description Default
obs_names Any

Neighborhood ids to keep.

required

Raises:

Type Description
ValueError

If any id is not in the collection.

to_geodataframe()

Return the neighborhood geometry, one row per neighborhood.

This is the hook Celldega uses to accept a collection wherever it takes a neighborhood GeoDataFrame (e.g. celldega.nbhd functions, Landscape(nbhd=...)).

to_pixel_gdf()

Return the neighborhood geometry ready for pixel-space visualization.

Adds a geometry_pixel column (micron geometry transformed to image space via the stored transformation matrix) and leaves the original micron geometry intact. The result can be passed straight to Landscape(nbhd=...), which renders geometry_pixel directly when present rather than applying its own transform.

Returns:

Type Description
GeoDataFrame

A copy of gdf with an added geometry_pixel column.

Raises:

Type Description
ValueError

If geometry or the transformation matrix is not set.

alpha_shape(points, inv_alpha)

Compute the alpha shape (concave hull) of a 2D point set.

Parameters

points : np.ndarray Point coordinates, shape (n_points, 2). inv_alpha : float Inverse alpha; larger values trace the points more loosely.

Returns

MultiPolygon The verified alpha-shape polygons (empty when none could be computed).

alpha_shape_cell_clusters(adata, cat='cluster', alphas=(100, 150, 200, 250, 300, 350), meta_cluster=None, *, modality=None, spatial_key='spatial')

Compute alpha shapes for each cluster of cells.

Parameters

adata : AnnData or MuData Cell-level data with spatial coordinates in obsm[spatial_key] and cluster labels in obs[cat]. For a MuData, cat is looked up in the global obs and then in the modalities' own obs. cat : str Column with cluster/category labels. alphas : Sequence[float] Inverse alpha values to compute shapes for. meta_cluster : pd.DataFrame | None Optional cluster metadata with a 'color' column, indexed by cluster. If not provided, colors come from uns[f'{cat}_colors'] when available, otherwise default to black. modality : str, optional For a MuData input, the modality to take coordinates and labels from. spatial_key : str, default "spatial" Key of the cell coordinates in obsm.

Returns

gpd.GeoDataFrame Alpha shapes for each cluster at each alpha value, indexed (and named) f"{cluster}_{inv_alpha}", with columns name, cat, geometry, inv_alpha, color, and area, sorted by area.

alpha_shape_cell_clusters_by_slice(adata, cluster_attr='cluster', slice_attr='slice_id', z_attr=None, alphas=(150,), meta_cluster=None, z_jitter=0.1, progress_every=0, *, modality=None, spatial_key='spatial')

Compute one alpha shape per (slice, cluster) pair, each stamped with its slice's Z.

For each slice, computes alpha_shape_cell_clusters / filter_alpha_shapes at a single alpha resolution, then stamps every resulting polygon with that slice's Z (from z_attr, or 0.0 if not given) plus a small per-cluster jitter (via stamp_z) so overlapping, coplanar cluster polygons within a slice don't z-fight.

Parameters

adata : AnnData or MuData Cell-level data with spatial coordinates in obsm[spatial_key] and cluster_attr / slice_attr (and, if given, z_attr) columns in obs. cluster_attr : str Column with cluster/category labels. slice_attr : str Column identifying each slice. z_attr : str | None Column with each cell's Z coordinate (expected to be one constant value per slice). If None, every slice is stamped at Z=0. alphas : Sequence[float] Must contain exactly one inverse-alpha resolution (see alpha_shape) — this function computes a single resolution per (slice, cluster), unlike alpha_shape_cell_clusters which can sweep several. meta_cluster : pd.DataFrame | None Optional cluster metadata with a 'color' column. Defaults to the colors in uns[f"{cluster_attr}_colors"], or a distinct fallback palette when none are stored, so every slice shares one palette. z_jitter : float Per-cluster Z offset within a slice, to avoid z-fighting between coplanar cluster polygons that would otherwise sit at the exact same Z. progress_every : int Print a progress line every this many slices processed (0, the default, disables it). Each alpha shape involves a Delaunay triangulation plus verification, so this is the slow part of a neighborhood-cloud pre-processing run on a dataset with many slices. modality : str, optional For a MuData input, the modality to take coordinates and labels from. spatial_key : str, default "spatial" Key of the cell coordinates in obsm.

Returns

gpd.GeoDataFrame One row per (slice, cluster) neighborhood, with columns name (f"{slice_id}__{cluster_id}"), cluster_id, slice_id, geometry (3D), color, area, inv_alpha, cell_count.

calc_gradient(source, direction='both', bin_width=10, max_dist=50, *, technology=None, scale_um_per_pixel=None, is_pixel_space=False, clip_boundary=None, clip_reference=None, clip_alpha=100, add_colors=True, nbhd_col='name')

Generate gradient bands around a region of interest as a GeoDataFrame.

Starting from the boundary of the merged source geometry, this builds fixed-width bands every bin_width microns out to max_dist:

  • Outward bands grow away from the ROI (positive distance). Use clip_boundary/clip_reference to stop them from running off the tissue.
  • Inward bands erode into the ROI (negative distance) and stop automatically once the geometry erodes to nothing.

Each band is one row of the returned GeoDataFrame, ordered inner-most to outer-most, with a signed distance so you can spatially join cells to bands (gpd.sjoin) and correlate composition or expression against distance from the ROI edge.

Parameters:

Name Type Description Default
source GeoDataFrame | GeoSeries | BaseGeometry | Any

The ROI. May be a GeoDataFrame/GeoSeries (all rows are dissolved into one shape), a bare shapely (Multi)Polygon, or a neighborhood-like object exposing to_geodataframe().

required
direction str

"outward", "inward", or "both" (default).

'both'
bin_width float

Width of each ring in microns (default 10).

10
max_dist float

Maximum distance from the ROI boundary in microns (default 50). Applied symmetrically to outward and inward bands.

50
technology str | None

Imaging platform (e.g. "Xenium") used to look up scale_um_per_pixel when the geometry is in pixel space. Ignored if scale_um_per_pixel is given.

None
scale_um_per_pixel float | None

Microns per pixel. Required (directly or via technology) when is_pixel_space=True.

None
is_pixel_space bool

True if source geometry is in pixel units; False (default) if it is already in microns. Controls how micron ring widths are converted to the geometry's units and how areas are reported.

False
clip_boundary Any | None

Optional precomputed tissue boundary (GeoDataFrame/GeoSeries/geometry) to clip outward rings to. Takes precedence over clip_reference. Use this to pass your own whole-tissue alpha shape at an alpha of your choosing.

None
clip_reference Any | None

Optional source of cell positions from which a tissue alpha shape is computed on the fly to clip outward rings. Accepts an AnnData (uses obsm["spatial"] or x/y centroid obs columns), a GeoDataFrame/GeoSeries of cells, or an (N, 2) array. Must be in the same coordinate space as source.

None
clip_alpha float

Inverse-alpha value for the on-the-fly alpha shape (default 100). Larger values trace tissue boundaries more loosely.

100
add_colors bool

If True (default), add a color column (Blues for outward bands, Reds for inward) for visualization.

True
nbhd_col str

Name of the band-identifier column in the output (default "name"), matching the neighborhood functions' default nbhd_col.

'name'

Returns:

Type Description
GeoDataFrame

A GeoDataFrame with one row per ring, ordered inner-most to

GeoDataFrame

outer-most, and columns:

GeoDataFrame
  • name / ring_range_um — band label, e.g. "out (+0~+10) µm".
GeoDataFrame
  • direction — "outward" or "inward".
GeoDataFrame
  • dist_start_um / dist_end_um — signed band edges in microns.
GeoDataFrame
  • area / area_um2 / area_px2 — band areas.
GeoDataFrame
  • color — hex color (when add_colors).
GeoDataFrame
  • geometry — the band polygon, in the source coordinate space.

Raises:

Type Description
ValueError

If direction is invalid, or is_pixel_space=True without a resolvable scale_um_per_pixel.

Examples:

Build bands from an alpha-shape GeoDataFrame in micron coordinates::

>>> rings = dega.nbhd.calc_gradient(
...     footprints, direction="both", bin_width=25, max_dist=200,
...     clip_reference=adata,
... )

adata.obsm["spatial"] supplies tissue coordinates for clipping. Multiple footprints are unioned before buffering, so adjacent regions do not produce overlapping band interiors. Shared band boundaries still require a tie-breaking rule when assigning cells with gpd.sjoin.

calc_img_zonal_stats(polygon_src, img, unique_polygon_col_name='name', channel_names=None, stats_funcs=None)

Calculate zonal statistics for each polygon from a multi-channel image. Returns a DataFrame with columns: polygon_id, {channel}_{stat}, geometry (if GeoDataFrame).

calc_nbhd_bordering(gdf_nbhd, metric='border_ratio', nbhd_col='name', category='leiden')

Calculate pairwise border relationships between neighborhoods.

Parameters

gdf_nbhd : GeoDataFrame or neighborhood-like object Neighborhood geometries with an identifier column (nbhd_col). metric : str, default "border_ratio" The border metric to compute: - "border_ratio": shared border length over the row neighborhood's perimeter (asymmetric). - "border_length": raw shared border length (symmetric). - "binary": 1 if the neighborhoods touch, 0 otherwise (symmetric). nbhd_col : str, default "name" Column with neighborhood identifiers. category : str, default "leiden" Name of the category the neighborhoods represent (e.g. "leiden"); used for the category column in obs/var and the colors in uns.

Returns

AnnData Square neighborhoods x neighborhoods matrix with obs["perimeter"], uns["metric"], and the neighborhood category/colors when the geometry has cat/color columns.

Notes

Shared border length is the length of the intersection of the two neighborhood boundaries, so this suits neighborhoods that touch without overlapping. For overlapping neighborhoods use calc_nbhd_overlap.

Examples

adata_border = dega.nbhd.calc_nbhd_bordering(gdf_hex_niche) mat = dega.clust.Matrix(adata_border)

calc_nbhd_by_gene(gdf_nbhd, by='cell', adata=None, data_dir=None, nbhd_col='name', min_cells=1, *, include_variance=False, modality=None, layer=None, feature_type=None, spatial_key='spatial', gdf_trx=None)

Calculate a neighborhood-by-gene expression matrix.

Computes gene expression for each neighborhood, either from cell-level expression (mean expression of the cells within each neighborhood) or from raw transcript counts (cell-free mode).

Parameters

gdf_nbhd : GeoDataFrame or neighborhood-like object Neighborhood geometries with an identifier column (nbhd_col). Objects exposing to_geodataframe() are accepted too. by : str, default "cell" - "cell": mean expression of cells within each neighborhood (requires adata) - "cell-free": transcript counts within each neighborhood (requires gdf_trx or data_dir) adata : AnnData or MuData, optional Cell-level data with spatial coordinates in obsm[spatial_key]. Required when by="cell". For a MuData, every modality is aggregated (one output modality per input modality) unless modality is given. data_dir : str, optional Directory containing transcripts.parquet, used for by="cell-free" when gdf_trx is not given. nbhd_col : str, default "name" Column in gdf_nbhd with neighborhood identifiers (falls back to neighborhood_id/nbhd_id). min_cells : int, default 1 Minimum cells (or, for by="cell-free", transcripts) a neighborhood needs to be included. With by="cell", neighborhoods without any cells are never included. include_variance : bool, default False With by="cell", also store per-neighborhood, per-gene variance (population variance) in layers["variance"]. modality : str, optional For a MuData input, aggregate only this modality and return an AnnData. layer : str, optional Aggregate this layer instead of X. feature_type : str, optional Entity type of the features (written to var["entity_type"] and uns["axis_entities"]). Defaults to "gene" for AnnData and gene-like modalities (rna, gene, expression), else the modality name. spatial_key : str, default "spatial" Key of the cell coordinates in obsm. gdf_trx : GeoDataFrame, optional Transcript points with a feature_name column (see read_transcripts), for by="cell-free".

Returns

AnnData or MuData Neighborhoods x features, with obs["n_cells"] (or obs["n_transcripts"]), uns["by"], uns["axis_entities"], and the neighborhood cat/color columns when the geometry has them. A MuData input without modality returns a MuData with one modality per input modality.

calc_nbhd_by_pop(adata, gdf_nbhd, category='leiden', nbhd_col='name', min_cells=5, output='proportion', *, modality=None, spatial_key='spatial')

Calculate the cell population distribution of each neighborhood.

Computes a neighborhood-by-population matrix showing the distribution of cell categories (e.g., clusters, cell types) within each neighborhood.

Parameters

adata : AnnData or MuData Cell-level data with spatial coordinates in obsm[spatial_key] and the category column in obs. For a MuData, category is looked up in the global obs (also as "<modality>:<category>") and then in the modalities' own obs. gdf_nbhd : GeoDataFrame or neighborhood-like object Neighborhood geometries with an identifier column (nbhd_col). category : str, default "leiden" Cell category column (e.g. "leiden", "cell_type"). nbhd_col : str, default "name" Column in gdf_nbhd with neighborhood identifiers. min_cells : int, default 5 Minimum number of cells a neighborhood needs to be included. output : str, default "proportion" - "proportion": fraction of cells per category (sums to 1 per neighborhood) - "counts": raw cell counts per category modality : str, optional For a MuData input, the modality to take coordinates and category from. spatial_key : str, default "spatial" Key of the cell coordinates in obsm.

Returns

AnnData Neighborhoods x categories with obs["n_cells"], uns["category"], uns["output"], var["entity_type"] = "cell_population", and category colors (var["color"], uns[f"{category}_colors"]) when the cell data has them.

calc_nbhd_overlap(gdf_nbhd, metric='iou', nbhd_col='name', category='leiden')

Calculate pairwise overlap between all neighborhoods.

Parameters

gdf_nbhd : GeoDataFrame or neighborhood-like object Neighborhood geometries with an identifier column (nbhd_col). metric : str, default "iou" The overlap metric to compute: - "iou": intersection over union; symmetric, from 0 (no overlap) to 1 (identical geometries). - "ioa": intersection over the row neighborhood's area; asymmetric, useful for containment analysis. - "intersection": raw intersection area in square units. nbhd_col : str, default "name" Column with neighborhood identifiers. category : str, default "leiden" Name of the category the neighborhoods represent (e.g. "leiden"); used for the category column in obs/var and the colors in uns.

Returns

AnnData Square neighborhoods x neighborhoods matrix with obs["area"], uns["metric"], and the neighborhood category/colors when the geometry has cat/color columns.

Examples

adata_iou = dega.nbhd.calc_nbhd_overlap(gdf_alpha, metric="iou") mat = dega.clust.Matrix(adata_iou)

calc_nbhd_transcript_assignment(gdf_nbhd, gdf_trx=None, *, data_dir=None, nbhd_col='name')

Per-neighborhood transcript counts and cell-assignment proportion.

A transcript counts as assigned when its cell_id is not "UNASSIGNED".

Assumption: transcript-to-cell assignment is not computed here — it must already be present in the instrument data, with unassigned transcripts marked by the "UNASSIGNED" sentinel (Xenium convention). A missing cell_id column raises ValueError; a complete absence of the sentinel warns (it may be genuinely fully assigned, or use a different convention).

Parameters

gdf_nbhd : GeoDataFrame or neighborhood-like object Neighborhood geometries with an identifier column (nbhd_col). gdf_trx : GeoDataFrame, optional Transcript points with a cell_id column (see read_transcripts). data_dir : str, optional Directory containing transcripts.parquet, used when gdf_trx is not given. nbhd_col : str, default "name" Column in gdf_nbhd with neighborhood identifiers.

Returns

pd.DataFrame Indexed by neighborhood id with columns total_transcripts, unassigned_transcripts, and transcript_assignment_proportion (assigned / total; 0.0 when a neighborhood has no transcripts).

filter_alpha_shapes(gdf_alpha, alpha, min_area=0, clean_names=True)

Filter alpha shapes by a specific alpha value and optionally clean up names.

Alpha shapes computed by alpha_shape_cell_clusters have names in the format {category}_{alpha} (e.g., "cluster_0_150"). This function filters to a specific alpha value and removes the trailing _{alpha} suffix from names.

Parameters

gdf_alpha : gpd.GeoDataFrame GeoDataFrame of alpha shapes with 'inv_alpha', 'area', 'name', and 'cat' columns. Typically the output of alpha_shape_cell_clusters. alpha : float The inverse alpha value to filter for (must match values in 'inv_alpha' column). min_area : float, default 0 Minimum area threshold. Shapes with area <= min_area are excluded. clean_names : bool, default True If True, removes the trailing _{alpha} suffix from the 'name' column, leaving just the category name (e.g., "cluster_0" instead of "cluster_0_150").

Returns

gpd.GeoDataFrame Filtered GeoDataFrame with optionally cleaned names.

Examples

gdf_alpha = dega.nbhd.alpha_shape_cell_clusters(adata, cat="leiden") gdf_filtered = dega.nbhd.filter_alpha_shapes(gdf_alpha, alpha=150)

Names are now just category names without the alpha suffix

print(gdf_filtered["name"].tolist()[:3]) ['0', '1', '2']

generate_hextile(adata, diameter=100, *, modality=None, spatial_key='spatial')

Generate a hexagonal grid over the bounding box of cell spatial coordinates.

Parameters

adata : AnnData, MuData, GeoDataFrame, or array Cell-level data with spatial coordinates in obsm[spatial_key], a GeoDataFrame (its total bounds are used), or an (n, 2) coordinate array. diameter : float, default 100 Diameter of each hexagon in the same units as the spatial coordinates (typically microns). modality : str, optional For a MuData input, the modality to take coordinates from. spatial_key : str, default "spatial" Key of the cell coordinates in obsm.

Returns

gpd.GeoDataFrame GeoDataFrame with hexagon geometries covering the spatial extent. Columns: "name" (hex_0, hex_1, ...), "geometry" (Polygon).

Examples

gdf_hex = dega.nbhd.generate_hextile(adata, diameter=100) gdf_hex.shape (1234, 2)

hextile_niche(gdf_hex, adata_hex, category='leiden', dissolve=True)

Create niche polygons from hextiles based on clustering results.

Takes hexagon geometries and assigns them to niches based on clustering (e.g., Leiden clustering of hexagon population distributions). Optionally dissolves adjacent hexagons of the same niche into unified polygons.

Parameters

gdf_hex : gpd.GeoDataFrame GeoDataFrame of hexagon geometries. Must be indexed by hexagon name (matching adata_hex.obs.index). adata_hex : AnnData or MuData Hexagon-level data containing clustering results in obs[category]. The index must match the hexagon names in gdf_hex. Colors can be provided in uns[f"{category}_colors"]. category : str, default "leiden" Column name in adata_hex.obs containing the niche/cluster assignment. dissolve : bool, default True If True, dissolve adjacent hexagons of the same niche into unified MultiPolygon geometries. If False, return individual hexagons with their niche assignment.

Returns

gpd.GeoDataFrame If dissolve=True: GeoDataFrame with dissolved niche polygons. Columns: "name", "cat", "geometry", "color", "area". If dissolve=False: GeoDataFrame with individual hexagons and niche assignment. Columns: "name", "cat", "geometry", "color".

Examples

Generate hexagons and compute population distribution

gdf_hex = dega.nbhd.generate_hextile(adata, diameter=100) adata_hex = dega.nbhd.calc_nbhd_by_pop(adata, gdf_hex, category="leiden")

Cluster hexagons by population similarity (e.g., using scanpy)

import scanpy as sc sc.pp.pca(adata_hex) sc.pp.neighbors(adata_hex) sc.tl.leiden(adata_hex)

Create dissolved niche polygons

gdf_niche = dega.nbhd.hextile_niche(gdf_hex, adata_hex, category="leiden")

Or keep individual hexagons with niche assignment

gdf_hex_niche = dega.nbhd.hextile_niche(gdf_hex, adata_hex, dissolve=False)

read_transcripts(data_dir, *, cell_id=True)

Load transcripts.parquet as a GeoDataFrame of transcript points.

No CRS is set since coordinates are in micron imaging space, not geospatial.

Parameters

data_dir : str Directory containing transcripts.parquet (Xenium column names feature_name, x_location, y_location, cell_id). cell_id : bool, default True Also load the cell_id column (needed for transcript assignment).

Returns

gpd.GeoDataFrame Columns feature_name (and cell_id) plus point geometry.

stamp_z(geometry, z)

Stamp a constant Z onto every vertex of a 2D geometry.

Used to place a 2D alpha-shape polygon (or any other geometry) at a fixed height in a 3D scene, e.g. one alpha shape per (slice, cluster) placed at its slice's Z coordinate. Any desired per-geometry offset (e.g. a small jitter to avoid z-fighting between coplanar overlapping polygons within a slice) should already be folded into z.

Parameters

geometry : Shapely geometry object (e.g., Polygon, MultiPolygon), or None. z : float Constant Z value to assign to every vertex.

Returns

Shapely geometry with a Z ordinate on every vertex, or None.