Skip to content

Pre Module API Reference

Module for pre-processing to generate LandscapeFiles from ST data.

add_clustering_from_adata(adata, path_dega_files, cluster_key='leiden', segmentation_name=None)

Add cell clustering data from an AnnData object to LandscapeFiles.

This function exports clustering assignments and associated colors from an AnnData object to the LandscapeFiles format, enabling the Landscape and Yearbook widgets to use custom clustering results.

Parameters

adata : AnnData AnnData object containing clustering results in obs[cluster_key]. Colors can be provided in uns[f"{cluster_key}_colors"]. path_dega_files : str or Path Path to the LandscapeFiles directory. cluster_key : str, default "leiden" Column name in adata.obs containing cluster assignments. segmentation_name : str, optional Name for this segmentation/clustering result. If provided, files will be saved as cell_clusters_{segmentation_name}/. If None, files are saved to the default cell_clusters/ directory.

Returns

None

Examples

import scanpy as sc import celldega as dega

Load and cluster your data

adata = sc.read_h5ad("my_data.h5ad") sc.tl.leiden(adata, resolution=0.5)

Add clustering to LandscapeFiles

dega.pre.add_clustering_from_adata( ... adata, ... path_dega_files="./my_landscape_files", ... cluster_key="leiden" ... )

For a custom segmentation with a specific name

dega.pre.add_clustering_from_adata( ... adata, ... path_dega_files="./my_landscape_files", ... cluster_key="leiden", ... segmentation_name="cellpose2" ... )

Notes

The Landscape widget can use the custom clustering by setting the segmentation parameter to match the segmentation_name.

add_custom_segmentation(technology, path_dega_files, path_segmentation_files, image_scale=1, tile_size=250)

Add custom segmentation to existing landscape files.

Parameters: - technology: Technology type (e.g., "Xenium", "MERSCOPE", "custom") - path_dega_files: Path to landscape files - path_segmentation_files: Path to segmentation files - image_scale: Image scale factor - tile_size: Tile size for processing

cluster_gene_expression(technology, path_dega_files, cbg, data_dir=None, segmentation_approach='default')

Calculates cluster-specific gene expression signatures for Xenium data.

Parameters:

Name Type Description Default
technology str

The technology used (e.g., "Xenium" or "MERSCOPE"). Currently, only "Xenium" is supported.

required
data_dir str

Path to the directory containing the Xenium data.

None
path_dega_files str

Path to the directory where the gene expression signature file will be saved.

required
cbg DataFrame

A cell-by-gene matrix where rows represent cells and columns represent genes. The index of the DataFrame should match the cell IDs in the Xenium metadata.

required

Raises:

Type Description
ValueError

If the specified technology is not supported.

FileNotFoundError

If the required input files are not found.

create_cluster_and_meta_cluster(technology, path_dega_files, data_dir=None, segmentation_approach='default')

Creates cell clusters and meta cluster files for visualization. Currently supports only Xenium.

Parameters:

Name Type Description Default
technology str

The technology used (e.g., "Xenium" or "MERSCOPE"). Currently, only "Xenium" is supported.

required
data_dir str

Path to the directory containing the Xenium data.

None
path_dega_files str

Path to the directory where the cluster and meta cluster files will be saved.

required

Raises:

Type Description
ValueError

If the specified technology is not supported.

FileNotFoundError

If the required input files are not found.

create_image_tiles(technology, data_dir, path_dega_files, image_tile_layer='dapi')

Creates image tiles for visualization from the Xenium morphology image.

Parameters:

Name Type Description Default
technology str

The technology used (e.g., "Xenium", "MERSCOPE", "VisiumHD", "H&E").

required
data_dir str

Path to the directory containing the data (e.g., morphology_focus_0000.ome.tif).

required
path_dega_files str

Path to the directory where the image tiles and pyramid will be saved.

required
image_tile_layer str

Specifies which image layers to process. Options for Xenium are

'dapi'

Raises:

Type Description
ValueError

If the specified technology is not supported or if the image_tile_layer is invalid.

FileNotFoundError

If the required input image file is not found.

create_image_tiles_h_and_e(data_dir, path_dega_files, image_tile_layer)

Creates image tiles for visualization from the H&E image.

Parameters:

Name Type Description Default
data_dir str

Path to the directory containing the data (e.g., morphology_focus_0000.ome.tif).

required
path_dega_files str

Path to the directory where the image tiles and pyramid will be saved.

required
image_tile_layer str

Specifies the name of the h&e image to process.

required

Raises: FileNotFoundError: If the required input image file is not found.

create_image_tiles_merscope(data_dir, path_dega_files, image_tile_layer='dapi')

Creates image tiles for visualization from the Xenium morphology image.

Parameters:

Name Type Description Default
data_dir str

Path to the directory containing the data (e.g., morphology_focus_0000.ome.tif).

required
path_dega_files str

Path to the directory where the image tiles and pyramid will be saved.

required
image_tile_layer str

Specifies which image layers to process. Options are 'dapi' (default) or 'all'.

'dapi'

Raises: FileNotFoundError: If the required input image file is not found.

create_image_tiles_xenium(data_dir, path_dega_files, image_tile_layer='dapi')

Creates image tiles for visualization from the Xenium morphology image.

Parameters:

Name Type Description Default
data_dir str

Path to the directory containing the data (e.g., morphology_focus_0000.ome.tif).

required
path_dega_files str

Path to the directory where the image tiles and pyramid will be saved.

required
image_tile_layer str

Specifies which image layers to process. Options are 'dapi' (default) or 'all'.

'dapi'

Raises: FileNotFoundError: If the required input image file is not found.

get_image_info(technology, image_tile_layer='dapi')

Retrieve image information for a given technology and image tile layer.

Parameters:

Name Type Description Default
technology str

The technology for which image information is requested. Currently supports 'Xenium' and 'MERSCOPE'.

required
image_tile_layer str

The type of image tile layer to retrieve information for. Options are 'dapi' or 'all'. Defaults to 'dapi'.

'dapi'

Returns:

Type Description
list[dict]

A list of dictionaries containing image information, including name,

list[dict]

button name, and color.

Raises:

Type Description
ValueError

If the technology is not supported or the image_tile_layer is invalid.

get_max_zoom_level(path_image_pyramid)

Returns the maximum zoom level based on the highest-numbered directory in the specified path.

Parameters:

Name Type Description Default
path_image_pyramid str

Path to the directory containing zoom level directories.

required

Returns:

Name Type Description
int

The maximum zoom level.

make_chromium_from_anndata(adata, path_dega_files)

Generate minimal LandscapeFiles from a Chromium AnnData object.

Parameters

adata : anndata.AnnData AnnData object containing scRNA-seq count data. path_dega_files : str or Path Directory where LandscapeFiles will be written.

Raises

ValueError If the expression matrix contains non-integer values.

make_deepzoom_pyramid(image_path, output_path, pyramid_name, tile_size=512, overlap=0, suffix='.jpeg')

Creates a DeepZoom image pyramid from a JPEG image.

Parameters:

Name Type Description Default
image_path str

Path to the JPEG image file.

required
output_path str

Directory to save the DeepZoom pyramid.

required
pyramid_name str

Name of the pyramid directory.

required
tile_size int

Tile size for the DeepZoom pyramid. Defaults to 512.

512
overlap int

Overlap size for the DeepZoom pyramid. Defaults to 0.

0
suffix str

Suffix for the DeepZoom pyramid tiles. Defaults to ".jpeg".

'.jpeg'

Returns:

Type Description

None

make_meta_cell_image_coord(technology, path_transformation_matrix, path_meta_cell_micron, path_meta_cell_image, image_scale=1, sample=None, paths=None, dataset=None)

Applies an affine transformation to cell coordinates in microns and saves the transformed coordinates in pixels.

Parameters

technology : str The technology used to generate the data, Xenium and MERSCOPE are supported. path_transformation_matrix : str Path to the transformation matrix file path_meta_cell_micron : str Path to the meta cell file with coordinates in microns path_meta_cell_image : str Path to save the meta cell file with coordinates in pixels

Returns

None

Examples

make_meta_cell_image_coord( ... technology='Xenium', ... path_transformation_matrix='data/transformation_matrix.csv', ... path_meta_cell_micron='data/meta_cell_micron.csv', ... path_meta_cell_image='data/meta_cell_image.parquet' ... ) Args: technology (str): The technology used to generate the data (e.g., "Xenium" or "MERSCOPE"). path_transformation_matrix (str): Path to the transformation matrix file. path_meta_cell_micron (str): Path to the meta cell file with coordinates in microns. path_meta_cell_image (str): Path to save the meta cell file with coordinates in pixels. image_scale (float): Scaling factor to convert micron coordinates to pixel coordinates.

Returns:

Type Description

None

make_meta_gene(cbg, path_output)

Creates a DataFrame with genes and their assigned colors.

Parameters:

Name Type Description Default
cbg DataFrame

A sparse DataFrame with genes as columns and barcodes as rows..

required
path_output str

Path to save the meta gene file.

required

Returns:

Type Description

None

make_trx_tiles(technology, path_trx, path_transformation_matrix=None, path_trx_tiles=None, coarse_tile_factor=10, tile_size=250, chunk_size=1000000, verbose=False, image_scale=1, max_workers=1, streaming_tile_assignment=None)

Processes transcript data by dividing it into coarse-grain and fine-grain tiles, applying transformations, and saving the results in a parallelized manner.

Parameters

technology : str The technology used for generating the transcript data (e.g., "MERSCOPE" or "Xenium"). path_trx : str Path to the file containing the transcript data. path_transformation_matrix : str Path to the file containing the transformation matrix (CSV file). path_trx_tiles : str Directory path where the output files (Parquet files) for each tile will be saved. coarse_tile_factor : int, optional Scaling factor of each coarse-grain tile comparing to the fine tile size. tile_size : int, optional Size of each fine-grain tile in microns (default is 250). chunk_size : int, optional Number of rows to process per chunk for memory efficiency (default is 1000000). verbose : bool, optional Flag to enable verbose output (default is False). image_scale : float, optional Scale factor to apply to the transcript coordinates (default is 1.0). max_workers : int, optional Maximum number of parallel workers for processing tiles (default is 1). streaming_tile_assignment : bool or None, optional If True, stream transformed coordinates to Parquet shards and spill per spatial tile (same strategy as row-group mode) instead of concatenating all rows and using partition_by / coarse filters on one huge frame. If None, enable automatically when row count is at least STREAMING_TILE_ASSIGN_ROW_THRESHOLD.

Returns

dict A dictionary containing the bounds of the processed data in both x and y directions.

pack_image_tiles_to_parquet(pyramid_dir, channel_name, output_path, image_format='.webp', delete_source_tiles=True, max_row_groups_per_file=2000)

Pack all image tiles from a DeepZoom pyramid into chunked parquet files with row groups.

Each zoom level's tiles are stored as row groups, allowing efficient range-based access. The formula for row group index is: row_group_index = sum of tiles in previous zoom levels + tile_x * num_tiles_y + tile_y

For large datasets, tiles are split across multiple parquet files, each containing at most max_row_groups_per_file row groups.

Parameters:

Name Type Description Default
pyramid_dir str

Path to the pyramid_images directory.

required
channel_name str

Name of the image channel (e.g., "dapi").

required
output_path str

Path to the output directory (will contain chunk_X.parquet files).

required
image_format str

Image file extension (default ".webp").

'.webp'
delete_source_tiles bool

If True, delete the original tile files after packing.

True
max_row_groups_per_file int

Maximum row groups per file (default 400).

2000

Returns:

Name Type Description
dict

Image tile metadata including grid info per zoom level and image dimensions.

read_cbg_mtx(base_path, barcodes_name='barcodes', features_name='features', technology=None)

Read the cell-by-gene matrix from the mtx files.

Parameters

base_path : str The base path to the directory containing the mtx files.

Returns

cbg : pandas.DataFrame A sparse DataFrame with genes as columns and barcodes as rows.

remove_intermediate_files(path_dega_files)

Remove intermediate image files.

Parameters: - path_dega_files: Path to landscape files directory

resolve_xenium_morphology_ome_path(data_dir)

Locate the morphology OME-TIFF for Xenium-class bundles (including Atera WTA preview).

Standard Xenium output uses morphology_focus/morphology_focus_0000.ome.tif. Some v4-compatible and Atera preview bundles use other names under morphology_focus/ or ship morphology.ome.tif at the bundle root.

Resolution order:

. morphology_focus/morphology_focus_0000.ome.tif (classic Xenium)

. First morphology_focus/morphology_focus_*.ome.tif (lexicographic sort)

. First morphology_focus/*.ome.tif if no morphology_focus_* match

. morphology.ome.tif at bundle root

Parameters

data_dir Path to the outs directory (e.g. containing experiment.xenium).

Returns

Path Path to an existing .ome.tif file.

Raises

FileNotFoundError If no supported morphology TIFF is found.

save_landscape_parameters(technology, path_dega_files, image_name='dapi_files', tile_size=1000, image_info=None, image_format='.webp', use_int_index=True, segmentation_approach='default', use_row_groups=False, tile_grid_info=None, image_tile_info=None, trx_chunk_info=None, cell_chunk_info=None, cbg_chunk_info=None)

Saves the landscape parameters to a JSON file.

Parameters:

Name Type Description Default
technology str

The technology used to generate the data.

required
path_dega_files str

Path to the directory where landscape files are stored.

required
image_name str

Name of the image directory. Defaults to "dapi_files".

'dapi_files'
tile_size int

Tile size for the image pyramid. Defaults to 1000.

1000
image_info dict

Additional image metadata. Defaults to None.

None
image_format str

Format of the image files. Defaults to ".webp".

'.webp'
use_int_index bool

Use integer name for cell_tile and trx_tile.

True
use_row_groups bool

If True, tiles are stored as row groups. Defaults to False.

False
tile_grid_info dict

Tile grid metadata when using row groups.

None
image_tile_info dict

Image tile metadata from pack_image_tiles_to_parquet.

None
trx_chunk_info dict

Chunk info for transcript parquet files.

None
cell_chunk_info dict

Chunk info for cell segmentation parquet files.

None
cbg_chunk_info dict

Chunk info for CBG parquet files.

None

Returns:

Type Description

None

write_cell_clusters_meta(nbhd, path_dega_files)

Write cell_clusters/meta_cluster.parquet (cluster, color, count).

This is the same file/column convention every other technology already writes and that set_cluster_metadata (js/global_variables/meta_cluster.js) fetches unconditionally to populate viz_state.cats.color_dict_cluster and the cluster bar graph — neither of which is specific to neighborhood-cloud. Derived from nbhd.gdf (color per cluster is already consistent across slices; count is summed across a cluster's neighborhoods) rather than requiring the caller to supply it separately.

write_gene_cell_scatter(adata, gene_list, path_dega_files, slice_attr='slice_id', z_attr=None, min_expression=2.0, min_cells=4, max_cells=50000, progress_every=500)

Cheap gene-coloring writer: a capped, top-expressing cell scatter per gene — no alpha shape.

A gene's real alpha shape (write_gene_shapes_streaming) is expensive (a Delaunay triangulation + verification per slice) — expensive enough that it only makes sense for a small, deliberately curated marker-gene list. This function writes only the cheap half of that computation: the capped, top-expressing cell selection (celldega.nbhd._select_top_expressing_cells, an O(n) argpartition, no geometry at all), so "browse any gene" scales to a much larger gene list than gene-nbhds ever could — a plain capped point scatter instead of a filled polygon, but real single-cell positions and expression values, colored the same way (per-cell expression, red-alpha scheme) as gene-nbhds' own "peppered" cells.

Reads each gene's expression directly from an already-loaded adata.X column, same as write_gene_shapes_streaming requires.

Writes nbhd_cloud/cells/by_gene/<gene>.parquet (columns: cell_id, gene, slice_id, x, y, z, expression) plus nbhd_cloud/cells/by_gene/available_gene_scatter.json{gene: max_expression}, a separate manifest from available_genes.json (shape-backed genes) so the frontend can distinguish "this gene has its own alpha shape" from "this gene only has a cell scatter."

Parameters

adata : AnnData Cell-level AnnData with spatial coordinates in obsm["spatial"], a slice_attr (and, if given, z_attr) column in obs, and every gene in gene_list present in adata.var_names. gene_list : Sequence[str] Genes to write a cell scatter for. path_dega_files : str | Path DegaFiles root directory. slice_attr, z_attr : str, str | None See write_meta_slice. min_expression : float A cell counts as "expressing" a gene when its value is at least this. min_cells : int Minimum number of expressing cells (before capping) required to write a gene's scatter at all; genes with fewer are silently skipped. max_cells : int Cap on the number of top-expressing cells written per gene (across all slices combined). progress_every : int Print a progress line every this many genes processed (0 disables).

Returns

int Number of genes that had enough expressing cells and were written.

write_gene_shapes(gdf_gene_alpha, path_dega_files)

Write nbhd_cloud/shapes/by_gene/<gene>.parquet, one file per gene (every slice).

A curated-gene-list companion to write_nbhd_cloud_shapes_and_features — same geometry_geojson string-column convention (no GeoParquet/WKB), but keyed by gene instead of (slice, cluster), and one file per gene (covering every slice) rather than one file per slice (covering every cluster), since the frontend always wants "this gene's shapes across the whole tissue" as a unit, never a single-slice subset. Sibling to shapes/by_slice/ (see write_nbhd_cloud_shapes_and_features) — both are alpha-shape geometry, grouped under one shapes/ parent, partitioned along different axes. Takes an already fully-materialized gdf_gene_alpha (the output of alpha_shape_gene_expression_by_slice), so it's meant for a small, curated/bounded gene list where holding every gene's shapes for every slice in memory at once is fine. For a whole-transcriptome gene list (~40k genes), use write_gene_shapes_streaming instead, which writes each gene's parquet as soon as it's computed rather than requiring the whole result set up front.

Each row: gene, slice_id, mean_expression, max_expression, area, cell_count, inv_alpha, geometry_geojson. Also writes nbhd_cloud/shapes/by_gene/available_genes.json{gene: max_expression}, both the manifest the frontend checks before treating a selected gene as having its own alpha shapes, and the normalization reference for that gene's fill opacity (mirroring the per-cell gene-coloring convention).

Parameters

gdf_gene_alpha : gpd.GeoDataFrame Output of celldega.nbhd.alpha_shape_gene_expression_by_slice. path_dega_files : str | Path DegaFiles root directory.

write_gene_shapes_streaming(adata, gene_list, path_dega_files, slice_attr='slice_id', z_attr=None, alphas=(150,), min_expression=2.0, min_cells=4, z_jitter=0.1, max_cells=50000, shape_max_cells=50000, random_state=0, progress_every=500)

Whole-transcriptome variant of write_gene_shapes — writes as it computes.

alpha_shape_gene_expression_by_slice + write_gene_shapes together require every gene's shapes for every slice to be held in memory before a single file is written — fine for a small curated marker-gene list, not for a whole gene panel (~40k genes). This streams celldega.nbhd.iter_gene_alpha_shapes_by_slice one gene at a time: as soon as a gene's shapes across every slice are ready, its parquet is written and that gene's in-memory result is dropped before moving to the next gene, so peak memory is bounded by one gene's shapes, not len(gene_list) genes' worth.

Requires an AnnData with every gene in gene_list already loaded into .X.

Writes the same nbhd_cloud/shapes/by_gene/<gene>.parquet files and available_genes.json manifest as write_gene_shapes, plus nbhd_cloud/cells/by_gene/<gene>.parquet — up to max_cells of that gene's own highest-expressing cells (real centroids to "pepper" the alpha shape with in the frontend). Genes with no usable shape in any slice (below min_cells everywhere, or every candidate shape failed verification / GEOS choked — see celldega.nbhd.alpha_shape) are silently skipped, same as the non-streaming path.

Parameters

adata : AnnData Cell-level AnnData, same requirements as celldega.nbhd.alpha_shape_gene_expression_by_slice. gene_list : Sequence[str] Genes to compute shapes for — typically a curated marker panel (tens to ~100 genes), though this streams one gene at a time so it scales to a whole-transcriptome list too. path_dega_files : str | Path DegaFiles root directory. slice_attr, z_attr, alphas, min_expression, min_cells, z_jitter, max_cells : Forwarded to iter_gene_alpha_shapes_by_slice — see its docstring. shape_max_cells, random_state : Forwarded to iter_gene_alpha_shapes_by_slice — cap (via uniform random subsample) on the expressing cells that feed each shape's own geometry computation, and the seed for that subsampling. This is what actually bounds the expensive part for a broadly-expressed gene; min_expression alone does not, since a gene can still be at/above any fixed threshold in far more cells than needed to describe its spatial footprint. progress_every : int Print a progress line every this many genes processed (0 disables).

Returns

int Number of genes that produced at least one shape and were written.

write_identity_transform(path_dega_files)

Write an identity transform matrix for IST data.

write_meta_gene_for_nbhd_cloud(adata, path_dega_files)

Write a dataset-root meta_gene.parquet (mean, std, max, non-zero, color).

Every technology's gene search box and gene bar graph fetch this file unconditionally (set_meta_gene/set_color_dict_gene, neither gated on technology) — neighborhood-cloud is no exception, even though its actual gene-expression coloring comes from the per-neighborhood expression/<gene>.parquet files (§write_nbhd_cloud_shapes_and_features), not this file. Reuses the existing make_meta_gene writer (same one every other technology uses) rather than duplicating its color-palette logic.

write_meta_slice(adata, path_dega_files, slice_attr='slice_id', z_attr=None)

Write nbhd_cloud/meta_slice.parquet, one row per slice.

Columns: slice_id, z, centroid_x, centroid_y, centroid_z, cell_count. z/centroid_z are 0.0 when z_attr is not given.

Parameters

adata : AnnData Cell-level AnnData with spatial coordinates in obsm["spatial"] and a slice_attr (and, if given, z_attr) column in obs. path_dega_files : str | Path DegaFiles root directory; nbhd_cloud/ is created if missing. slice_attr : str Column in adata.obs identifying each slice. z_attr : str | None Column in adata.obs with each cell's Z coordinate (expected constant per slice, e.g. from celldega.align.serial_slices).

Returns

pd.DataFrame The table written to meta_slice.parquet.

write_nbhd_cloud_cells(adata, path_dega_files, cluster_attr='cluster', slice_attr='slice_id', z_attr=None, max_cells=None, random_state=0)

Write nbhd_cloud/cells/by_cluster/cluster_<id>.parquet, one file per cluster.

Each row: cell_id, x, y, z, cluster_id, slice_id. Cluster selection (not per-neighborhood) is the frontend's cell-display trigger — picking a cluster shows its cells across every slice, optionally narrowed to one slice client-side (the slice_id column is already there) when the slice bar has isolated one slice. A per-cluster file is the natural fit for that: one bounded fetch per selection, not one per slice.

Parameters

adata : AnnData Cell-level AnnData with spatial coordinates in obsm["spatial"] and cluster_attr / slice_attr (and, if given, z_attr) columns in obs. path_dega_files : str | Path DegaFiles root directory. cluster_attr, slice_attr, z_attr : str, str, str | None See write_meta_slice. max_cells : int | None Cap on the number of cells written per cluster (across all its slices combined). Above this many, a uniform random subsample is written instead of every cell -- unlike a gene's top-expressing cell cap (max_cells on the gene-shapes writers below), there's no per-cell ranking signal within a cluster (every member is equally "in" the cluster), so random is the only choice that doesn't bias toward an arbitrary subset. None (default) writes every cell, matching this function's original, uncapped behavior. random_state : int Seed for the subsampling RNG, so results are reproducible run to run.

write_nbhd_cloud_dataset(adata, nbhd, path_dega_files, cluster_attr='cluster', slice_attr='slice_id', z_attr=None, max_cells=None, random_state=0, write_meta_gene=True)

Write the full neighborhood-cloud DegaFile layout for one dataset.

Orchestrates write_meta_slice, write_nbhd_cloud_cells, and write_nbhd_cloud_shapes_and_features, then writes landscape_parameters.json.

Parameters

adata : AnnData Aligned 3D cell-level AnnData: obsm["spatial"] (x, y), obs[cluster_attr], obs[slice_attr], optionally obs[z_attr] (e.g. from celldega.align.serial_slices.align_serial_slices). nbhd : NeighborhoodCollection Caller-built neighborhood collection spanning all slices — e.g. NeighborhoodCollection.from_gdf(alpha_shape_cell_clusters_by_slice(adata, ...)). Must have a slice_id column in nbhd.gdf. path_dega_files : str | Path Output DegaFiles root directory. cluster_attr, slice_attr, z_attr See write_meta_slice / write_nbhd_cloud_cells. max_cells, random_state Forwarded to write_nbhd_cloud_cells — cap (via uniform random subsample) on cells written per cluster. max_cells=None (default) writes every cell, unchanged from this function's original behavior. write_meta_gene : bool Whether to write meta_gene.parquet (the dataset-root per-gene stats). True (default) preserves the original behavior; False skips it for a clusters-only cloud with no gene-expression data.

write_nbhd_cloud_shapes_and_features(nbhd, path_dega_files)

Write shapes and neighborhood metadata:

  • nbhd_cloud/shapes/by_slice/slice_<id>.parquet — one file per slice, every cluster's polygon, with a geometry_geojson string column (a JSON geometry, e.g. MultiPolygon with XYZ coordinates) rather than GeoParquet/WKB, since it's fed straight into a deck.gl GeoJsonLayer the same way the legacy 2D nbhd feature's GeoJSON already is. Sibling to shapes/by_gene/ (see write_gene_shapes) — both are alpha-shape geometry, partitioned along different axes (this one by slice, the other by gene), grouped under one shapes/ parent rather than as unrelated-looking top-level directories.
  • nbhd_cloud/meta_neighborhood.parquetneighborhood_id, cluster_id, slice_id, color, area, cell_count, inv_alpha.
  • cell_clusters/meta_cluster.parquet (via write_cell_clusters_meta).

Per-neighborhood gene expression and population proportions are intentionally not computed/written here: gene coloring comes from the curated marker-gene alpha shapes instead (alpha_shape_gene_expression_by_slice / write_gene_shapes), and population proportions were never surfaced in the frontend. Both would need the same expensive per-slice spatial join this writer used to do just to produce data nothing read.

Parameters

nbhd : NeighborhoodCollection Caller-built neighborhood collection spanning all slices, e.g. from NeighborhoodCollection.from_gdf(alpha_shape_cell_clusters_by_slice(adata, ...)). path_dega_files : str | Path DegaFiles root directory.

write_xenium_transform(data_dir, path_dega_files, transform_fname='micron_to_image_transform.csv')

Extracts the transformation matrix from the Xenium cells.zarr.zip file and saves it as a CSV file.

Parameters:

Name Type Description Default
data_dir str

Path to the directory containing the Xenium data (e.g., cells.zarr.zip).

required
path_dega_files str

Path to the directory where the transformation matrix CSV will be saved.

required
transform_fname str

Name of the output CSV file. Defaults to "micron_to_image_transform.csv".

'micron_to_image_transform.csv'

Returns:

Type Description

numpy.ndarray: The full transformation matrix extracted from the Xenium cells.zarr.zip file.

Raises:

Type Description
FileNotFoundError

If the cells.zarr.zip file does not exist in the specified data_dir.

KeyError

If the transformation matrix is not found in the Zarr file under the expected path.

Exception

If an unexpected error occurs while processing the Zarr file.