panhumanpy.ANNotate

Azimuth Cell Annotation: Neural network-based hierarchical cell type annotation for single-cell RNA-seq data.

This module provides tools for hierarchical cell type annotation and interpretation based on single-cell RNA-seq data using the Azimuth neural network model trained on annotated panhuman scRNA-seq data.

Key Components

AzimuthNN_baseClass

Low-level class providing fine-grained control over the annotation process. Suitable for advanced users who need detailed control or are processing data in batches to optimize memory usage.

AzimuthNNClass

High-level interface that wraps around AzimuthNN_base for interactive analysis. Provides a streamlined workflow for cell annotation with sensible defaults. Recommended for most interactive analysis sessions and notebooks.

annotate_coreFunction

Core function for script-based automated annotation. Designed for batch processing and integration into analysis pipelines.

Usage Examples

Interactive usage with high-level interface:
>>> import anndata
>>> from panhumanpy import AzimuthNN
>>> adata = anndata.read_h5ad('my_data.h5ad')
>>> # Run minimal annotation pipeline with calibration
>>> azimuth = AzimuthNN(adata)
>>> embeddings = azimuth.azimuth_embed()  # Extract embeddings
>>> umap = azimuth.azimuth_umap()  # Generate UMAP
>>> # Optionally map annotations to Cell Ontology terms
>>> azimuth.map_to_cell_ontology('azimuth_fine')
>>> azimuth.map_to_cell_ontology('azimuth_broad', include_cl_id=True)
>>> adata_annotated = azimuth.pack_adata('output.h5ad')  # Save results
For more detailed documentation on specific classes and functions:
>>> help(AzimuthNN)
>>> help(AzimuthNN_base)
>>> help(annotate_core)

Command-line Usage

This module can be run as a standalone script to annotate h5ad files:

annotate /path/to/input.h5ad [options]

Required positional argument:
filepath Path to input h5ad file containing

single-cell data

Optional arguments:
-fn, --feature_names_col
Column in query.var containing gene

names (default: None)

-ap, --annotation_pipeline

Annotation pipeline to use (default: ‘supervised’)

-ebs, --eval_batch_size

Batch size for model inference (default: 8192)

-norm, --normalization_override

Skip normalization check (default: False)

-ncbs, --norm_check_batch_size

Number of cells to sample for normalization check (default: 100)

-om, --output_mode

Output verbosity, ‘minimal’ or ‘detailed’ (default: ‘minimal’)

-rf, --refine_labels

Skip hierarchical label refinement (default: use refinement)

-mcl, --map_to_cl

One or more column names in the cell metadata to map to Cell Ontology labels after annotation. Multiple columns can be provided as a space-separated list. e.g. -mcl azimuth_broad azimuth_fine (default: None, no mapping applied)

-clid, --include_cl_id

If set, also adds CL ID columns (e.g. CL:0000236) alongside CL label columns produced by –map_to_cl. Has no effect if –map_to_cl is not specified. (default: False)

-em, --extract_embeddings

Skip neural network embeddings extraction (default: extract embeddings)

-umap, --umap_embeddings

Skip UMAP projection generation (default: generate UMAP)

UMAP parameters:
-nnbrs, --n_neighbors

Neighbors per point in UMAP (default: 30)

-nc, --n_components

UMAP dimensionality (default: 2)

-me, --metric

Distance metric for UMAP (default: ‘cosine’)

-mdt, --min_dist

Minimum distance in UMAP (default: 0.3)

-ulr, --umap_lr

UMAP learning rate (default: 1.0)

-useed, --umap_seed

Random seed for reproducibility (default: 42)

-sp, --spread

UMAP spread parameter (default: 1.0)

-uv, --umap_verbose

Hide UMAP progress (default: show progress)

-uin, --umap_init

UMAP initialization method (default: ‘spectral’)

Output: The annotated data will be saved as a new h5ad file in the same directory as the input file, with ‘_ANN’ appended to the filename. If a file with that name already exists, a timestamp (YYYYMMDD_HHMMSS) will be automatically appended to prevent overwriting existing results.

Example commands:

annotate my_cells.h5ad -fn feature_name -ebs 4096 -nc 3 annotate my_cells.h5ad -mcl azimuth_broad azimuth_fine -clid

AzimuthNN_base

class panhumanpy.ANNotate.AzimuthNN_base(annotation_pipeline='supervised', model_version='v1', eval_batch_size=8192)[source]

Bases: AutoloadInferenceTools

Base class for low-level interactive usage of the Azimuth neural network annotation pipeline.

This class provides a comprehensive framework for single-cell RNA-seq annotation using neural network models. It handles the complete workflow from data loading and preprocessing to inference, confidence calibration, post-processing, and result visualization.

This includes functionality for extracting embeddings, generating UMAP visualizations, and refining annotations at different levels of

granularity.

Parameters:
  • annotation_pipeline (str, default='supervised') – The type of annotation pipeline to use.

  • model_version (str, default set to match package major version.) – Model version to use.

  • eval_batch_size (int, default=8192) – Batch size for inference and embedding generation.

query

The AnnData object if loaded.

Type:

anndata.AnnData or None

X_query

Expression matrix in CSR format.

Type:

scipy.sparse.csr_matrix or None

query_features

List of feature names.

Type:

list or None

features_meta

Feature metadata.

Type:

pandas.DataFrame or None

cells_meta

Cell metadata.

Type:

pandas.DataFrame or None

num_cells

Number of cells in the query.

Type:

int or None

processed_outputs

Processed inference results.

Type:

dict or None

embeddings

Dictionary of extracted embeddings.

Type:

dict

umaps

Dictionary of generated UMAP coordinates.

Type:

dict

Raises:
  • TypeError – If input parameters are not of the correct type.

  • RuntimeError – If model metadata fails to load.

Notes

This class is designed for programmatic use and provides fine-grained control over each step of the annotation pipeline. Consider using a higher-level interface for convenience if a standard workflow is sufficient for your needs.

query_stripped(X_query, query_features, cells_meta)[source]

Load query data directly from expression matrix and metadata.

This method allows for direct loading of pre-processed expression data without requiring an AnnData object. This is useful for integration with custom preprocessing pipelines.

Parameters:
  • X_query (scipy.sparse.csr_matrix) – Expression matrix with cells as rows and features as columns.

  • query_features (list of str) – List of feature names corresponding to columns in X_query.

  • cells_meta (pandas.DataFrame) – Cell metadata with rows corresponding to cells in X_query.

Raises:
  • TypeError – If inputs are not of correct type.

  • ValueError – If dimensions of inputs don’t match.

Notes

This method creates a minimal features_meta DataFrame based on the provided feature names.

query_adata(query_arg, feature_names_col=None)[source]

Load query data from an AnnData object.

Parameters:
  • query_arg (anndata.AnnData) – AnnData object containing expression data and metadata.

  • feature_names_col (str, optional) – Column in var DataFrame to use for feature names. If None, uses the var_names index.

Notes

This method extracts the expression matrix, feature names, and metadata from the provided AnnData object.

query_h5ad(query_filepath, feature_names_col=None)[source]

Load query data from an H5AD file on disk.

Parameters:
  • query_filepath (str) – Path to the H5AD file containing the query data.

  • feature_names_col (str, optional) – Column in var DataFrame to use for feature names. If None, uses the var_names index.

Raises:

ValueError – If the file is not in H5AD format.

Notes

This method reads the H5AD file from disk and extracts the necessary components for inference.

process_query(normalization_override=False, norm_check_batch_size=100)[source]

Process the query data to prepare it for inference.

This method prepares the expression data for the inference model according to the specified annotation pipeline. The processing steps vary depending on the pipeline type, potentially including normalization, feature selection, dimensionality reduction, or other transformations.

Parameters:
  • normalization_override (bool, default=False) – If True, bypasses normalization entirely regardless of whether the values are integers or not.

  • norm_check_batch_size (int, default=100) – Batch size for checking normalization status.

Raises:

TypeError – If parameters are not of the correct type.

Notes

This method must be called after loading query data and before running inference or extracting embeddings. The specific processing steps depend on the annotation_pipeline specified during initialization.

Currently, only the ‘supervised’ annotation pipeline is implemented, which normalizes the expression data and aligns it with a reference feature panel.

run_inference_model()[source]

Run the inference model on the processed query data.

This method executes the neural network inference to generate cell type predictions.

Returns:

Dictionary of raw inference outputs including hierarchical label predictions and probabilities.

Return type:

dict

Raises:

AssertionError – If input matrix has not been initialized by calling process_query().

Notes

The raw outputs should be calibrated using calibrate_predictions() and then processed using process_outputs() before further use downstream. The typical workflow is: 1. run_inference_model() 2. calibrate_predictions() 3. process_outputs()

calibrate_predictions()[source]

Apply calibration to softmax outputs using trained calibrators.

This method calibrates the softmax probability outputs from each hierarchical level using the corresponding trained calibration models, if available. Calibration improves the reliability and trustworthiness of prediction confidence scores by adjusting for overconfidence or underconfidence in the original model outputs.

Returns:

Updated inference outputs dictionary with calibrated results. Contains the same keys as the original inference outputs but with calibrated values:

  • ’softmax_vals_all’: List of calibrated softmax probability arrays,

one per hierarchical level - ‘probability_of_preds’: Updated maximum probability values from the calibrated softmax distributions - Other keys remain unchanged from the original inference outputs

Return type:

dict

Notes

  • Only applies calibration if calibration method is specified in model

metadata and calibrator models are available - If no calibration is configured (calibration method is None), the method returns the original inference outputs unchanged - Each hierarchical level is calibrated independently using its own trained calibrator model - Memory management is applied during processing to handle large datasets efficiently by cleaning up intermediate results after each level

Raises:

AssertionError – If calibration method is not None but the number of available calibrator models doesn’t match the expected number of hierarchical levels (max_depth).

Examples

The method is typically called as part of the inference pipeline:

>>> azimuth = AzimuthNN_base()
>>> # ... load data and run inference ...
>>> raw_outputs = azimuth.run_inference_model()
>>> calibrated_outputs = azimuth.calibrate_predictions()
>>> # Calibrated outputs now have adjusted confidence scores

The calibration process transforms prediction confidence scores:

  • Before calibration: Model might be over(/under)-confident

(high probabilities for uncertain predictions or vice-versa) - After calibration: Probabilities better reflect true prediction confidence and uncertainty

process_outputs(mode='minimal')[source]

Process raw inference outputs into usable predictions.

This method organizes the raw inference outputs into a structured dictionary of predictions at various hierarchical levels.

Parameters:

mode (str, default='minimal') – Processing mode: ‘minimal’ provides essential outputs, ‘detailed’ includes additional information for all levels.

Returns:

Dictionary of processed outputs including hierarchical labels, level-specific labels, and confidence scores.

Return type:

dict

Raises:

AssertionError – If mode is not ‘minimal’ or ‘detailed’.

Notes

This method should be called after run_inference_model() and calibrate_predictions(). The calibration step improves confidence score reliability by correcting for model overconfidence or underconfidence using trained calibration models.

refine_labels(refine_level)[source]

Refine hierarchical labels to a consistent level of granularity.

This method applies post-processing rules to standardize annotations at the specified level of granularity (broad, medium, or fine).

Parameters:

refine_level (str) – Level of refinement: ‘broad’, ‘medium’, or ‘fine’.

Returns:

List of refined labels at the specified level.

Return type:

list

Raises:

AssertionError – If refine_level is not valid or inference hasn’t been run.

Notes

For ‘broad’ level, this returns the top-level annotations. For ‘medium’ and ‘fine’ levels, specialized refinement is applied.

inference_model_embeddings(embedding_layer_name)[source]

Extract embeddings from an intermediate layer of the inference model.

Parameters:

embedding_layer_name (str) – Name of the layer to extract embeddings from.

Returns:

Embeddings from the specified layer for all query cells.

Return type:

numpy.ndarray

Raises:
  • RuntimeError – If inference model is not found.

  • AssertionError – If input matrix has not been initialized.

Notes

The embeddings are stored in the embeddings dictionary with a key that combines the model name and layer name.

inference_model_umaps(embedding_layer_name, n_neighbors=30, n_components=2, metric='cosine', min_dist=0.3, umap_lr=1.0, umap_seed=42, spread=1.0, verbose=True, init='spectral')[source]

Generate UMAP coordinates from existing embeddings.

Parameters:
  • embedding_layer_name (str) – Name of the layer whose embeddings should be used.

  • n_neighbors (int, default=30) – Number of neighbors for UMAP.

  • n_components (int, default=2) – Number of dimensions for UMAP output.

  • metric (str, default='cosine') – Distance metric for UMAP.

  • min_dist (float, default=0.3) – Minimum distance parameter for UMAP.

  • umap_lr (float, default=1.0) – Learning rate for UMAP.

  • umap_seed (int, default=42) – Random seed for reproducibility.

  • spread (float, default=1.0) – Spread parameter for UMAP.

  • verbose (bool, default=True) – Whether to display progress during UMAP calculation.

  • init (str, default='spectral') – Initialization method for UMAP.

Returns:

UMAP coordinates for all query cells.

Return type:

numpy.ndarray

Raises:

AssertionError – If the specified embeddings have not been generated.

Notes

This method requires that embeddings have already been generated using inference_model_embeddings().

inference_embeddings_and_umap(embedding_layer_name, n_neighbors=30, n_components=2, metric='cosine', min_dist=0.3, umap_lr=1.0, umap_seed=42, spread=1.0, verbose=True, init='spectral')[source]

Generate both embeddings and UMAP coordinates in one operation.

This is a convenience method that combines the functionality of inference_model_embeddings() and inference_model_umaps().

Parameters:
  • embedding_layer_name (str) – Name of the layer to extract embeddings from.

  • n_neighbors (int, default=30) – Number of neighbors for UMAP.

  • n_components (int, default=2) – Number of dimensions for UMAP output.

  • metric (str, default='cosine') – Distance metric for UMAP.

  • min_dist (float, default=0.3) – Minimum distance parameter for UMAP.

  • umap_lr (float, default=1.0) – Learning rate for UMAP.

  • umap_seed (int, default=42) – Random seed for reproducibility.

  • spread (float, default=1.0) – Spread parameter for UMAP.

  • verbose (bool, default=True) – Whether to display progress during UMAP calculation.

  • init (str, default='spectral') – Initialization method for UMAP.

Returns:

Tuple containing (embeddings, umap_coordinates).

Return type:

tuple

Raises:
  • RuntimeError – If inference model is not found.

  • ValueError – If input matrix has not been initialized.

Notes

This method may be more efficient than calling the two component methods separately, depending on usage, as it avoids storing intermediate results in memory twice.

update_cells_meta()[source]

Update cells_meta DataFrame with inference results.

This method adds or updates columns in the cell metadata DataFrame with inference results, including predictions and refined labels.

Returns:

Updated cell metadata DataFrame.

Return type:

pandas.DataFrame

Raises:
  • TypeError – If cells_meta is not a pandas DataFrame.

  • RuntimeError – If num_cells attribute is not set.

  • ValueError – If the number of values doesn’t match the number of cells.

Notes

If both broad level annotations and level_zero_labels exist, the latter is dropped to avoid duplication.

pack_adata(save_path=None)[source]
Create an AnnData object with all results and optionally save to

disk.

This method packages all results (expression data, metadata, embeddings, and UMAP coordinates) into a unified AnnData object for further analysis or visualization.

Parameters:

save_path (str, optional) – Path to save the AnnData object as an H5AD file. If None, the object is created but not saved.

Returns:

AnnData object containing all query data and results.

Return type:

anndata.AnnData

Notes

If the specified save_path already exists, a timestamp is appended to the filename to prevent overwriting. Metadata is automatically coerced to h5ad-compatible types.

map_to_cell_ontology(src_col, include_cl_id=False)[source]

Map annotation labels in cells_meta to Cell Ontology terms.

Applies the versioned cell ontology map for the model version used in this run to the specified column in cells_meta, adding one (or two) new columns immediately after src_col. Unmapped labels are set to ‘unmapped’ and a single warning is emitted listing all unique labels that could not be mapped.

Parameters:
  • src_col (str) – Name of the column in cells_meta carrying the source annotation labels to be mapped.

  • include_cl_id (bool, default False) – If True, also adds a column named {src_col}_CL_ID containing the CL identifier string (e.g. ‘CL:0000236’), or ‘unmapped’.

Returns:

  • pandas.DataFrame – Updated cells_meta with new column(s) added.

  • New columns added

  • —————–

  • {src_col}_CL – CL label string for each cell, or ‘unmapped’.

  • {src_col}_CL_ID (only if include_cl_id=True) – CL identifier string, or ‘unmapped’.

Raises:
  • TypeError – If cells_meta is not a pandas DataFrame.

  • ValueError – If src_col is not present in cells_meta.

Warns:

UserWarning – Emitted once, listing all unique labels that could not be mapped to a CL term.

Examples

>>> azimuth = AzimuthNN(adata)
>>> azimuth.map_to_cell_ontology('azimuth_fine')
>>> azimuth.map_to_cell_ontology('azimuth_broad', include_cl_id=True)

AzimuthNN

class panhumanpy.ANNotate.AzimuthNN(query_arg, feature_names_col=None, annotation_pipeline='supervised', model_version='v1', eval_batch_size=8192, normalization_override=False, norm_check_batch_size=100, output_mode='minimal', refine=True)[source]

Bases: AzimuthNN_base

AzimuthNN: A high-level interface for a cell annotation pipeline based on the Azimuth neural network.

This class wraps around the AzimuthNN_base class to provide a simplified workflow for hierarchical cell type annotation based on single-cell RNA-seq data, handling data loading, preprocessing, model inference, and visualization in a streamlined manner.

The pipeline automatically applies confidence calibration to improve the reliability of prediction confidence scores using trained calibration models.

As of v0.3.0, inference, calibration, output processing, and label refinement are performed in minibatches to reduce peak memory usage. Softmax arrays and intermediate inference outputs are released after each minibatch is processed.

For more fine-grained control over the annotation process, users should directly use the AzimuthNN_base class.

Parameters:
  • query_arg (Union[str, anndata.AnnData]) – Either an AnnData object containing single-cell data or a path to an h5ad file.

  • feature_names_col (str, optional) – Column in the anndata_object.var dataframe that contains the gene names to use for model input. If None, assumes var_names are already the correct gene identifiers.

  • annotation_pipeline (str, default='supervised') – Type of annotation pipeline to use for cell type prediction.

  • model_version (str, default set to match package major version.) – Model version to use.

  • eval_batch_size (int, default=8192) – Batch size to use during model inference and minibatched annotation pipeline.

  • normalization_override (bool, default=False) – If True, skips normalization check and forces processing to continue.

  • norm_check_batch_size (int, default=1000) – Number of cells to sample for normalization check.

  • output_mode (str, default='minimal') – Controls the verbosity of output in the cell meta dataframe. Options are ‘minimal’ or ‘detailed’.

  • refine (list, bool, or None, default=True) – Which refinement levels to apply during initialization. Accepts a list containing one or more of ‘broad’, ‘medium’, ‘fine’. If ‘medium’ or ‘fine’ is included without ‘broad’, ‘broad’ is added automatically as it is a prerequisite. Also accepts True (equivalent to [‘broad’, ‘medium’, ‘fine’]), False or None (no refinement), or an empty list (no refinement). As of v0.3.0, refinement is performed by default within the minibatched pipeline.

cells_meta

Cell metadata.

Type:

pandas.DataFrame or None

embeddings

Contains embeddings extracted from the model.

Type:

dict

umaps

Contains UMAP projections of the embeddings.

Type:

dict

Raises:
  • TypeError – If query_arg is not an AnnData object or a string path, if normalization_override is not a bool, or if norm_check_batch_size is not an integer.

  • ValueError – If output_mode is not ‘minimal’ or ‘detailed’, or if refine contains invalid refinement levels.

Examples

>>> import anndata
>>> adata = anndata.read_h5ad('my_data.h5ad')
>>> azimuth = AzimuthNN(adata)
>>> embeddings = azimuth.azimuth_embed()
>>> umap = azimuth.azimuth_umap()
>>> cell_metadata = azimuth.cells_meta

Refine only at broad and fine levels: >>> azimuth = AzimuthNN(adata, refine=[‘broad’, ‘fine’])

Skip refinement entirely: >>> azimuth = AzimuthNN(adata, refine=False)

azimuth_refine(refine=None)[source]

Refine cell type annotations at multiple granularity levels.

Deprecated since version 0.3.0: Label refinement is now performed during initialization as part of the minibatched pipeline. This method is retained for backwards compatibility and will be removed in a future release. Use the refine parameter in AzimuthNN initialization instead.

If a refinement level was not included at initialization, re-initialization is required since softmax arrays are no longer held in memory after the pipeline completes.

Parameters:

refine (list, optional) – List of refinement levels to check. If None, checks all three levels [‘broad’, ‘medium’, ‘fine’].

azimuth_embed()[source]

Extract embeddings from the Azimuth model’s embedding layer.

This method extracts cell embeddings from a pre-defined layer in the inference model and stores them in the embeddings dictionary under the key ‘azimuth_embed’, replacing the original model-specific key.

To extract embeddings from a different layer in the model, use AzimuthNN_base class for more fine grained control.

Returns:

The extracted embeddings, with shape (n_cells, embedding_dimension).

Return type:

numpy.ndarray

Raises:

AssertionError – If inference model hasn’t been run yet.

azimuth_umap(n_neighbors=30, n_components=2, metric='cosine', min_dist=0.3, umap_lr=1.0, umap_seed=42, spread=1.0, verbose=True, init='spectral')[source]

Generate UMAP projection from Azimuth embeddings.

This method creates a UMAP projection from previously extracted Azimuth embeddings and stores it in the umaps dictionary.

Parameters:
  • n_neighbors (int, default=30) – Number of neighbors to consider for each point in UMAP.

  • n_components (int, default=2) – Dimensionality of the UMAP projection.

  • metric (str, default='cosine') – Distance metric to use for UMAP.

  • min_dist (float, default=0.3) – Minimum distance between points in the UMAP projection.

  • umap_lr (float, default=1.0) – UMAP learning rate.

  • umap_seed (int, default=42) – Random seed for UMAP for reproducibility.

  • spread (float, default=1.0) – Scales the effective scale of embedded points.

  • verbose (bool, default=True) – Whether to display progress during UMAP computation.

  • init (str, default='spectral') – Initialization method for UMAP.

Returns:

The UMAP projection, with shape (n_cells, n_components).

Return type:

numpy.ndarray

Raises:

AssertionError – If ‘azimuth_embed’ embeddings haven’t been generated yet.

azimuth_embed_and_umap(n_neighbors=30, n_components=2, metric='cosine', min_dist=0.3, umap_lr=1.0, umap_seed=42, spread=1.0, verbose=True, init='spectral')[source]

Extract embeddings and generate UMAP projection in one step.

This method provides a convenient wrapper that combines the functionality of azimuth_embed() and azimuth_umap() methods. It extracts embeddings from the inference model and immediately computes a UMAP projection, storing both results.

Parameters:
  • n_neighbors (int, default=30) – Number of neighbors to consider for each point in UMAP.

  • n_components (int, default=2) – Dimensionality of the UMAP projection.

  • metric (str, default='cosine') – Distance metric to use for UMAP.

  • min_dist (float, default=0.3) – Minimum distance between points in the UMAP projection.

  • umap_lr (float, default=1.0) – UMAP learning rate.

  • umap_seed (int, default=42) – Random seed for UMAP for reproducibility.

  • spread (float, default=1.0) – Scales the effective scale of embedded points.

  • verbose (bool, default=True) – Whether to display progress during UMAP computation.

  • init (str, default='spectral') – Initialization method for UMAP.

Returns:

A tuple containing:
  • numpy.ndarray: The extracted embeddings

  • numpy.ndarray: The UMAP projection

Return type:

tuple

Raises:

AssertionError – If inference model hasn’t been run yet.

annotate_core

panhumanpy.ANNotate.annotate_core(X_query, query_features, cells_meta, annotation_pipeline, eval_batch_size, normalization_override, norm_check_batch_size, output_mode, refine_labels, map_to_cl, include_cl_id, extract_embeddings, umap_embeddings, n_neighbors, n_components, metric, min_dist, umap_lr, umap_seed, spread, verbose, init, model_version='v1')[source]

Core function for cell type annotation using the Azimuth neural network, designed primarily for script-based usage.

While AzimuthNN and AzimuthNN_base classes provide interactive functionality for exploratory analysis, this function offers a one-step method for automated annotation via Python or R scripts. It performs the complete annotation workflow in a single function call: data preprocessing, model inference, confidence calibration, label generation, optional label refinement, optional Cell Ontology mapping, and optional embedding/UMAP generation.

As of v0.3.0, this function uses the AzimuthNN class internally, which performs inference, calibration, and refinement in minibatches for improved memory efficiency.

Parameters:
  • X_query (scipy.sparse.csr_matrix) – Expression matrix with cells as rows and genes as columns.

  • query_features (list of str) – List of feature names (gene identifiers) corresponding to columns in X_query.

  • cells_meta (pandas.DataFrame) – Metadata for cells, with rows corresponding to cells in X_query.

  • annotation_pipeline (str) – Type of annotation pipeline to use for cell type prediction.

  • eval_batch_size (int) – Batch size to use during model inference.

  • normalization_override (bool) – If True, skips normalization check and forces processing to continue.

  • norm_check_batch_size (int) – Number of cells to sample for normalization check.

  • output_mode (str) – Controls the verbosity of output in the cell meta dataframe. Options are ‘minimal’ or ‘detailed’.

  • refine_labels (bool) – Whether to perform label refinement at broad, medium, and fine levels.

  • map_to_cl (list of str or None) – List of column names in cells_meta to map to Cell Ontology terms after annotation is complete. Each named column must exist in cells_meta at the time of mapping, so columns produced by the annotation pipeline (e.g. ‘azimuth_broad’, ‘azimuth_fine’) are valid targets. If None, no mapping is applied.

  • include_cl_id (bool) – If True, also adds a CL identifier column (e.g. ‘CL:0000236’) alongside each CL label column produced by map_to_cl. Has no effect if map_to_cl is None.

  • extract_embeddings (bool) – Whether to extract embeddings from the model.

  • umap_embeddings (bool) – Whether to generate UMAP projections from the embeddings. Requires extract_embeddings=True.

  • n_neighbors (int) – Number of neighbors to consider for each point in UMAP.

  • n_components (int) – Dimensionality of the UMAP projection.

  • metric (str) – Distance metric to use for UMAP.

  • min_dist (float) – Minimum distance between points in the UMAP projection.

  • umap_lr (float) – UMAP learning rate.

  • umap_seed (int) – Random seed for UMAP for reproducibility.

  • spread (float) – Scales the effective scale of embedded points.

  • verbose (bool) – Whether to display progress during UMAP computation.

  • init (str) – Initialization method for UMAP.

  • model_version (str) – Model version to use, e.g. ‘v0’ or ‘v1’. Defaults to model_version_default as defined in this module.

Returns:

A dictionary containing: - ‘azimuth_object’: The instantiated AzimuthNN object - ‘embeddings_dict’: Dictionary of computed embeddings - ‘umap_dict’: Dictionary of computed UMAP projections - ‘cells_meta’: Updated cell metadata with annotations and,

if map_to_cl was specified, Cell Ontology columns

Return type:

dict

Raises:
  • TypeError – If normalization_override, extract_embeddings, umap_embeddings, refine_labels, or include_cl_id are not boolean values, if norm_check_batch_size is not an integer, or if map_to_cl is not a list of strings or None.

  • ValueError – If output_mode is not ‘minimal’ or ‘detailed’, or if umap_embeddings is True but extract_embeddings is False.

Notes

This function is designed to be the core engine for script-based automated annotation workflows. Unlike the interactive AzimuthNN and AzimuthNN_base classes which allow step-by-step exploration and visualization, this function executes the entire annotation pipeline in one call.

It’s particularly useful for: - Batch processing of multiple datasets - Integration into automated analysis pipelines - Creating wrappers for other languages (like R)

Cell Ontology mapping (map_to_cl) is applied after the full annotation pipeline completes, so columns added by the pipeline (e.g. ‘azimuth_broad’, ‘azimuth_fine’) can be specified directly.

Examples

>>> from scipy.sparse import csr_matrix
>>> import pandas as pd
>>> import numpy as np
>>>
>>> X = csr_matrix(np.random.rand(100, 1000))
>>> features = [f"gene_{i}" for i in range(1000)]
>>> meta = pd.DataFrame(index=range(100))
>>>
>>> # Run annotation with Cell Ontology mapping
>>> results = annotate_core(
...     X, features, meta,
...     annotation_pipeline='supervised',
...     eval_batch_size=8192,
...     normalization_override=False,
...     norm_check_batch_size=100,
...     output_mode='minimal',
...     refine_labels=True,
...     map_to_cl=['azimuth_broad', 'azimuth_fine'],
...     include_cl_id=True,
...     extract_embeddings=True,
...     umap_embeddings=True,
...     n_neighbors=30,
...     n_components=2,
...     metric='cosine',
...     min_dist=0.3,
...     umap_lr=1.0,
...     umap_seed=42,
...     spread=1.0,
...     verbose=True,
...     init='spectral'
... )
>>> annotated_meta = results['cells_meta']
>>> embeddings = results['embeddings_dict']['azimuth_embed']
>>> umap_coords = results['umap_dict']['azimuth_umap']

annotate

panhumanpy.ANNotate.annotate()[source]

Main entry point for command-line execution of the Azimuth cell annotation pipeline.

Parses command line arguments, loads the specified h5ad file, runs the annotation pipeline including confidence calibration via annotate_core(), and saves the results as a new h5ad file in the same directory as the input file with ‘_ANN’ appended to the filename.

This function is intended to be called when the module is executed directly as a script and provides a complete workflow from argument parsing to saving results.

No parameters or return values as this function is designed to be the executable entry point for command-line usage.