Skip to content

Pre Module API Reference

Prepare instrument output for Landscape with the DegaFiles preparation and hosting guide. Examples include Atera preprocessing and custom segmentation.

See Add aligned H&E to DegaFiles for importing an optional histology background into Landscape and Yearbook.

For CellCloud, use write_point_cloud_dataset for compact indexed Parquet DegaFiles or write_point_cloud_zarr for an AnnData Zarr with sparse CSC expression. Both support rounded XYZ positions and named alignments; see the CellCloud preparation examples and mouse-brain workflow.

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

add_aligned_he(path_dega_files, image_path, *, alignment=None)

Tile H&E in the existing image coordinate system and register it in the manifest.

Run after pre.main() or on an existing DegaFiles directory. Without alignment, the RGB image must already have exactly the reference image's width, height, origin and pixel scale. No alignment is estimated here.

alignment may be a 3x3 array or a headerless CSV path. It maps H&E pixel coordinates to the existing DegaFiles image pixels: [x, y, 1] (column vectors). Xenium Explorer imagealignment.csv files use this convention. Translation, rotation, reflection, shear and scale are supported. The image is resampled onto the reference canvas; outside pixels are white.

Existing fluorescence, cells and transcripts are preserved. The new pyramid uses WebP and the reference tile size, with Parquet packing when DegaFiles use row groups. Requires the optional celldega[pre] dependency and libvips. An existing H&E pyramid is never overwritten. Returns the H&E manifest entry.

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'

Returns:

Type Description

dict or None: For Xenium, how each channel was scaled (see create_image_tiles_xenium); None for other technologies.

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.

Channels are read one at a time (CYX OME-TIFF) to limit memory use. Each channel is stretched to its instrument "Suggested LUT max" from the OME-XML, or to a tissue percentile when the bundle has none (see _tile_morphology_channel).

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'

Returns: dict: How each channel was scaled (method, lut_max), for recording in landscape_parameters.json.

Raises:

Type Description
FileNotFoundError

If the required input image file is not found.

ValueError

If the image layout is unexpected or 'all' is requested for a bundle that only has morphology.ome.tif.

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, image_scaling=None, microns_per_pixel=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
image_scaling dict

How image tiles were scaled (Xenium), as returned by create_image_tiles. Saved under "image_scaling" so a landscape can be audited later.

None
microns_per_pixel float

Image pixel size, saved under "microns_per_pixel" so the front end can size the scale bar without a per-technology lookup.

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 the neighborhood geometry (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.

Parameters

nbhd : GeoDataFrame or neighborhood-like object Per-slice neighborhoods with cluster_id, color, and cell_count columns (e.g. from alpha_shape_cell_clusters_by_slice). path_dega_files : str | Path DegaFiles root directory.

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)

Gene-coloring writer: a capped, top-expressing cell scatter per gene.

Selects each gene's top-expressing cells (_select_top_expressing_cells, an O(n) argpartition, no geometry at all), so "browse any gene" scales to a large gene list: a capped point scatter of real single-cell positions and expression values, colored by per-cell expression.

Reads each gene's expression directly from an already-loaded adata.X column.

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}, the manifest the frontend checks before fetching a gene's cells.

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_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-gene cell scatter (write_gene_cell_scatter), 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 a serial-slice alignment).

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 write_gene_cell_scatter), 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 a serial-slice alignment). nbhd : GeoDataFrame or neighborhood-like object Neighborhoods spanning all slices, e.g. alpha_shape_cell_clusters_by_slice(adata, ...). Needs unique ids (name) and slice_id, cluster_id, color, cell_count columns. 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 2D nbhd feature's GeoJSON already is.
  • nbhd_cloud/meta_neighborhood.parquet — neighborhood_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 per-gene cell scatter (write_gene_cell_scatter), and population proportions were never surfaced in the frontend.

Parameters

nbhd : GeoDataFrame or neighborhood-like object Neighborhoods spanning all slices, e.g. from alpha_shape_cell_clusters_by_slice(adata, ...), with unique ids (name), slice_id, cluster_id, color, and cell_count columns. path_dega_files : str | Path DegaFiles root directory.

write_point_cloud_dataset(adata, path_dega_files, *, name=None, z_key='Z', cluster_key=None, write_genes=None, write_base_metadata=None, overwrite=False, use_int_index=None, coordinate_resolution=None, compression='snappy', compression_level=None)

Write cell positions (and clusters/genes) to a point-cloud DegaFiles.

Parameters

adata : AnnData Cell-level AnnData. obsm["spatial"] provides x/y (its first two columns); z is taken from obs[z_key] if present, else from a third spatial column, else 0. Cell names come from obs_names. path_dega_files : str or Path Target point-cloud DegaFiles directory. If it already contains a manifest the writer appends a named position variant; otherwise it creates a fresh point-cloud directory. name : str, optional Name of a position variant (e.g. one alignment of the cells). Positions are written to cell_metadata_<name>.parquet and the name is listed under "alignments" in the manifest; view it with CellCloud(..., alignment="<name>"). Required in append mode. When omitted, only the base cell_metadata.parquet is written. z_key : str, optional, default "Z" obs column holding the z (depth) coordinate. cluster_key : str, optional Only used in create mode: obs column to export as clusters (with colors from uns[f"{cluster_key}_colors"] when available). write_genes : bool, optional Only used in create mode. Whether to export gene expression to cbg/ + meta_gene.parquet (keyed by cell name). Defaults to True when adata carries an expression matrix (layers['counts'] or X). write_base_metadata : bool, optional Whether to also (over)write the base cell_metadata.parquet with these positions. Defaults to True in create mode and False in append mode (so an append never clobbers the existing default positions). overwrite : bool, default False Allow overwriting an existing cell_metadata_<name>.parquet, or an existing dataset when no name is given.

bool, optional

Store original observation IDs once in cell_ids.parquet; use uint32 row positions in geometry, clustering and per-gene files. Defaults to False for a new dataset, or inherits the existing dataset on append. Appending requires exactly the same cells and preserves their original order even when the new AnnData is reordered.

coordinate_resolution : float, optional Round coordinates to this step in their physical units. Use 1.0 for nearest-micron positions (at most 0.5 microns of error on each axis). Integral steps use int32 coordinates; the default keeps float32. An appended alignment inherits the existing resolution. compression : str Parquet compression codec; defaults to "snappy". "zstd" with compression_level=6 provides compact storage. Integer IDs also use delta encoding. compression_level : int, optional Compression level, when supported by the chosen codec.

Returns

pathlib.Path Path to the written positions file (the named variant when name is given, else cell_metadata.parquet).

write_point_cloud_zarr(adata, store, *, z_key='Z', cluster_key=None, alignments=None, coordinate_resolution=1.0, obs_columns=None, chunk_rows=262144, expression_chunk_size=262144, overwrite=False)

Write a self-contained CellCloud AnnData Zarr store for HTTP hosting.

X is CSC, so selecting a gene reads only its sparse values and cell-row indices. obs_names retain the original cell IDs; expression is indexed by their zero-based row positions. obsm['spatial'] stores default XYZ coordinates and obsm['spatial_<name>'] stores each named alignment. Pass CellCloud(zarr_url=..., alignment='<name>') to choose one.

Coordinates remain in their physical units. With the default coordinate_resolution=1.0, micron coordinates are rounded to the nearest micron and saved as int32, with at most half a micron of error on each axis. Pass None to retain float32 positions. Original inputs are never modified. A new output path is required unless overwrite=True.

Parameters

adata : AnnData Cells, original observation IDs, gene IDs, and counts in layers['counts'] or X. Spatial positions follow the same rules as write_point_cloud_dataset. store : str or Path New local directory; upload its complete contents to a static host. cluster_key : str, optional Cluster observation column. Its palette is retained and missing colors are generated. Other requested observation columns remain available. alignments : mapping of str to array, optional Additional (n_cells, 3) XYZ arrays in exactly adata.obs_names order. These are rounded using the same coordinate resolution. obs_columns : sequence of str, optional Observation columns to keep; defaults to all columns. cluster_key is always retained when provided. chunk_rows : int Number of cells per coordinate chunk (default 262,144). expression_chunk_size : int Number of sparse expression entries per chunk (default 262,144). overwrite : bool Replace an existing local store only when explicitly requested.

Returns

pathlib.Path The completed Zarr v2 store. Numeric arrays use Zstandard compression with bit shuffle; consolidated metadata reduces HTTP round trips.

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.