### Install from GitHub (base and GPU) Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy Installs panhumanpy directly from the GitHub repository. The first command installs the base version, the second includes GPU dependencies. ```bash # base pip install git+https://github.com/satijalab/panhumanpy.git # w/ GPU dependencies pip install git+https://github.com/satijalab/panhumanpy.git#egg=panhumanpy[gpu] ``` -------------------------------- ### Install base version from PyPI Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy Installs the base version of panhumanpy with CPU support only. ```bash pip install panhumanpy ``` -------------------------------- ### Command-line usage example Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Shows the command-line invocation for annotating an h5ad file using the module as a standalone script. The command takes a filepath and optional arguments. ```bash annotate /path/to/input.h5ad [options] ``` -------------------------------- ### Get help for AzimuthNN_base Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Displays documentation for the AzimuthNN_base class using help(). ```python # For documentation help(ph.AzimuthNN_base) ``` -------------------------------- ### Quickstart: Run minimal annotation pipeline Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy Shows the minimal usage of AzimuthNN: load an h5ad file, run the annotation pipeline, extract cell metadata, embeddings, UMAP, and save annotated results. ```python from panhumanpy import AzimuthNN obj = 'path/to/obj.h5ad' # Normalize obj = ... # Run minimal annotation pipeline azimuth = AzimuthNN(obj) # Get cell type annotations cell_metadata = azimuth.cells_meta # Extract embeddings embeddings = azimuth.azimuth_embed() # Generate UMAP umap = azimuth.azimuth_umap() # Save results obj_annotated = azimuth.pack_adata('obj_ANN.h5ad') ``` -------------------------------- ### Install AzimuthAPI from GitHub Source: https://satijalab.org/pan_human_azimuth/r/azimuthapi Installs the AzimuthAPI package using the remotes package, ensuring the remotes dependency is present first. ```R if (!requireNamespace("remotes", quietly = TRUE)) { install.packages("remotes") } # Install AzimuthAPI from GitHub remotes::install_github("satijalab/AzimuthAPI") ``` -------------------------------- ### Install GPU version from PyPI Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy Installs panhumanpy with GPU dependencies for enhanced performance on compatible hardware. ```bash pip install panhumanpy[gpu] ``` -------------------------------- ### Module docstring with usage examples Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate The module docstring includes usage examples for interactive annotation with AzimuthNN, including embedding extraction, UMAP generation, mapping to Cell Ontology, and saving results. Also shows how to access help for the main classes and functions. ```python >>> 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 ``` ```python >>> help(AzimuthNN) >>> help(AzimuthNN_base) >>> help(annotate_core) ``` -------------------------------- ### Install panhumanpy with conda and pip Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Commands to create a conda environment and install panhumanpy. For CPU use: pip install panhumanpy or from GitHub. For GPU use: pip install panhumanpy[gpu] or from GitHub with the gpu extra. ```bash # From the command line, to create and activate conda env: # conda create -n panhumanpy_env python=3.9 # conda activate panhumanpy_env # To install panhumanpy, # For CPU based use: # pip install panhumanpy # or from GitHub: # pip install git+https://github.com/satijalab/panhumanpy.git # For GPU based use: # pip install panhumanpy[gpu] # or from GitHub: # pip install git+https://github.com/satijalab/panhumanpy.git#egg=panhumanpy[gpu] ``` -------------------------------- ### Run annotate_core with Cell Ontology mapping Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate This example demonstrates how to execute the full annotation pipeline using annotate_core, including Cell Ontology mapping and UMAP embedding generation. ```python >>> 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'] ``` -------------------------------- ### Install bmcite Dataset from SeuratData Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Installs the bmcite dataset from SeuratData. This dataset contains human bone marrow mononuclear cells from Stuart, Butler et al Cell 2019. ```r bmcite <- InstallData("bmcite") ``` -------------------------------- ### Set Up Local Python Environment for Pan-human Azimuth Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Creates and activates a conda environment named 'pan-human-azimuth' with Python 3.9, then installs the panhumanpy Python package and its dependencies. This is required for the local annotation option. ```bash # Create a new conda environment for Pan-human Azimuth conda create -n pan-human-azimuth python=3.9 # Activate the environment conda activate pan-human-azimuth # Install Pan-human Azimuth and its dependencies # for more installation options, see https://satijalab.org/pan_human_azimuth/python/panhumanpy.html pip install panhumanpy ``` -------------------------------- ### Run CloudAzimuth for Cloud-Based Annotation Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Runs Pan-human Azimuth cell type annotation on a Seurat object using the cloud-based API deployed on AWS. This is the easiest option and requires no additional setup. ```r bmcite_ann <- CloudAzimuth(bmcite) ``` -------------------------------- ### Run CloudAzimuth annotation Source: https://satijalab.org/pan_human_azimuth/r/azimuthapi Demonstrates the workflow for loading data, normalizing, running cloud-based annotation, and extracting results. ```R library(AzimuthAPI) library(Seurat) # Load data obj <- ... # Normalize obj <- NormalizeData(obj) # Run annotation on the cloud obj <- CloudAzimuth(obj) # Get cell type annotations cell_metadata <- obj@meta.data # Extract embeddings embeddings <- Embeddings(obj, reduction = "azimuth_embed") # Generate UMAP obj <- RunUMAP(obj, dims = 1:128, reduction = "azimuth_embed", reduction.name = "azimuth_umap") ``` -------------------------------- ### Execute annotation pipeline with annotate Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Main entry point for command-line execution. It parses arguments, loads the h5ad file, runs the annotation pipeline, and saves the results with an '_ANN' suffix. ```python [docs] def annotate(): """ 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. """ args = arg_parse_in() arguments = arg_parse_out(args) for key, value in arguments.items(): globals()[key] = value query_obj = ReadQueryObj(query_filepath) X_query = query_obj.X_query() query_features = query_obj.query_features( feature_names_col=feature_names_col ) features_meta = query_obj.features_meta() cells_meta = query_obj.cells_meta() core_outputs = 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 = model_version ) azimuth_object = core_outputs['azimuth_object'] azimuth_object.features_meta = features_meta dir_path = os.path.dirname(query_filepath) filename = os.path.basename(query_filepath) filename, ext = os.path.splitext(filename) out_path = os.path.join(dir_path, f'{filename}_ANN{ext}') azimuth_object.pack_adata(save_path=out_path) #################################################################### if __name__=="__main__": annotate() ``` -------------------------------- ### Accessing help documentation Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Use the Python help function to retrieve detailed documentation for the primary classes and functions in the module. ```python >>> help(AzimuthNN) >>> help(AzimuthNN_base) >>> help(annotate_core) ``` -------------------------------- ### Access AzimuthNN documentation Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Use the help function to view documentation for the AzimuthNN class. ```python # For documentation help(ph.AzimuthNN) ``` -------------------------------- ### ANNotate function signature Source: https://satijalab.org/pan_human_azimuth/r/reference/annotate Function signature for running the Pan-human Azimuth model locally on a Seurat object. Requires the `panhumanpy` Python package installed and accessible via reticulate. Returns an annotated Seurat object. ```R ANNotate( query_obj, feature_names_col = NULL, annotation_pipeline = "supervised", eval_batch_size = 8192L, normalization_override = FALSE, norm_check_batch_size = 100L, output_mode = "minimal", refine_labels = TRUE, map_to_cl = NULL, include_cl_id = FALSE, extract_embeddings = TRUE, umap_embeddings = TRUE, n_neighbors = 30L, n_components = 2L, metric = "cosine", min_dist = 0.3, umap_lr = 1, umap_seed = 42L, spread = 1, verbose = TRUE, init = "spectral", model_version = "v1", process_obj = TRUE, cutoff_abs = 5, cutoff_frac = 0.001, assay = NULL ) ``` -------------------------------- ### Initialize AzimuthNN and extract data Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Basic workflow for initializing the AzimuthNN model with an AnnData object and extracting embeddings, UMAP projections, and metadata. ```python >>> 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 ``` -------------------------------- ### Initialize AzimuthNN with label refinement Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Configure label refinement levels during initialization of the AzimuthNN object. ```python azimuth = ph.AzimuthNN(query, feature_names_col = "gene_symbol", refine = ['medium']) ``` -------------------------------- ### annotate() Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate 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. ```APIDOC ## annotate() ### Description 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. ### Usage 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. ### Parameters No parameters. ### Returns No return values. ``` -------------------------------- ### Define UMAP parameter arguments for n_neighbors, n_components, metric, min_dist, learning_rate, seed, spread, verbosity, and init Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Adds a series of command-line arguments to configure UMAP parameters, each with a default value matching Seurat defaults. These include -nnbrs/--n_neighbors (default 30), -nc/--n_components (default 2), -me/--metric (default 'cosine'), -mdt/--min_dist (default 0.3), -ulr/--umap_lr (default 1.0), -useed/--umap_seed (default 42), -sp/--spread (default 1.0), -uv/--umap_verbose (store_false to hide progress), and -uin/--umap_init (default 'spectral', with 'random' as an option). ```python parser.add_argument( "-nnbrs", "--n_neighbors", default=30, help=( "n_neighbors param for umaps, defaults " "to Seurat default 30" ), type=int ) ``` ```python parser.add_argument( "-nc", "--n_components", default=2, help=( "n_components param for umaps, defaults " "to Seurat default 2" ), type=int ) ``` ```python parser.add_argument( "-me", "--metric", default='cosine', help=( "metric param for umaps, defaults to " "Seurat default 'cosine'" ), type=str ) ``` ```python parser.add_argument( "-mdt", "--min_dist", default=0.3, help=( "min_dist param for umaps, defaults to " "Seurat default 0.3" ), type=float ) ``` ```python parser.add_argument( "-ulr", "--umap_lr", default=1.0, help=("learning_rate param for umaps, defaults " "to Seurat default 1.0" ), type=float ) ``` ```python parser.add_argument( "-useed", "--umap_seed", default=42, help=( "random_state param for reproducibility of " "umaps, defaults to Seurat default 42" ), type=int ) ``` ```python parser.add_argument( "-sp", "--spread", default=1.0, help=( "spread param for umaps, defaults to " "Seurat default 1.0" ), type=float ) ``` ```python parser.add_argument( "-uv", "--umap_verbose", action="store_false", help="Hide UMAP progress" ) ``` ```python parser.add_argument( "-uin", "--umap_init", default="spectral", help=( "init param for umaps, defaults to " "'spectral', the other option is 'random'" ), type=str ) ``` -------------------------------- ### Calibrate AzimuthNN_base predictions Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Demonstrates the typical inference pipeline workflow, including initializing the model, running inference, and applying calibration to the raw outputs. ```python >>> 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 ``` -------------------------------- ### Initialize AzimuthNN without refinement Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Initialize the AzimuthNN model while skipping the refinement process entirely. ```python >>> azimuth = AzimuthNN(adata, refine=False) ``` -------------------------------- ### ANNotate Initialization Logic Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Initializes the annotation pipeline, validates output modes, and processes query data from AnnData or HDF5 files. ```python if output_mode not in ['minimal', 'detailed']: raise ValueError( "output_mode must be either 'minimal' or 'detailed'" ) self._refine_levels = self._parse_refine_arg(refine) self._query_arg = query_arg self._normalization_override = normalization_override self._norm_check_batch_size = norm_check_batch_size self._output_mode = output_mode super().__init__( annotation_pipeline, model_version, eval_batch_size ) if isinstance(self._query_arg, anndata.AnnData): self.query_adata( self._query_arg, feature_names_col = feature_names_col ) elif isinstance(self._query_arg, str): self.query_h5ad( self._query_arg, feature_names_col = feature_names_col ) self.process_query( normalization_override = self._normalization_override, norm_check_batch_size = self._norm_check_batch_size ) self._run_minibatched_pipeline() ``` -------------------------------- ### Initialize AzimuthNN with query data Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Load query data from an h5ad file or an AnnData object to prepare for annotation. ```python # file path to query h5ad query_path = "path/to/h5ad" # optional query = ad.read_h5ad(query_path) ``` -------------------------------- ### Initialize AzimuthNN with refinement Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Initialize the AzimuthNN model with specific refinement levels for cell type annotations. ```python >>> azimuth = AzimuthNN(adata, refine=['broad', 'fine']) ``` -------------------------------- ### Initialize AzimuthNN and Run Annotation Pipeline Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Initializes the AzimuthNN object with query data and pipeline parameters, optionally extracts embeddings or maps to cell ontology, and returns the core outputs. ```python azimuth = AzimuthNN( query_adata, annotation_pipeline = annotation_pipeline, model_version = model_version, eval_batch_size = eval_batch_size, normalization_override = normalization_override, norm_check_batch_size = norm_check_batch_size, output_mode = output_mode, refine = refine_labels ) if extract_embeddings: if umap_embeddings: azimuth.azimuth_embed_and_umap( n_neighbors=n_neighbors, n_components=n_components, metric=metric, min_dist=min_dist, umap_lr=umap_lr, umap_seed=umap_seed, spread=spread, verbose=verbose, init=init ) else: azimuth.azimuth_embed() if map_to_cl is not None: for col in map_to_cl: azimuth.map_to_cell_ontology( src_col=col, include_cl_id=include_cl_id ) core_outputs = { 'azimuth_object' : azimuth, 'embeddings_dict' : azimuth.embeddings, 'umap_dict' : azimuth.umaps, 'cells_meta' : azimuth.cells_meta } return core_outputs ``` -------------------------------- ### Run inference and process outputs Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Runs inference on the query and processes outputs. For model_version 'v1', a confidence calibration step is recommended (commented out). ```python # Inference azimuth.process_query() azimuth.run_inference_model() # If using model_version = 'v1', we recommend adding the confidence calibration step here # _ = azimuth.calibrate_predictions() _ = azimuth.process_outputs() ``` -------------------------------- ### AzimuthNN.__init__ Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Initializes the AzimuthNN object with an AnnData object and optional refinement levels. Refinement is performed during initialization as part of the minibatched pipeline. ```APIDOC ## AzimuthNN.__init__ ### Description Initializes the AzimuthNN object with an AnnData object and optional refinement levels. Refinement is performed during initialization as part of the minibatched pipeline. ### Parameters - **adata** (anndata.AnnData) - Required - The AnnData object containing the single-cell data. - **refine** (list or bool, optional) - Optional - List of refinement levels to perform. Can be ['broad', 'fine'] or ['broad', 'medium', 'fine']. Set to False to skip refinement entirely. Default is None, which checks all three levels ['broad', 'medium', 'fine']. ### Example ```python >>> import anndata >>> adata = anndata.read_h5ad('my_data.h5ad') >>> azimuth = AzimuthNN(adata) >>> azimuth = AzimuthNN(adata, refine=['broad', 'fine']) >>> azimuth = AzimuthNN(adata, refine=False) ``` ``` -------------------------------- ### AzimuthNN_base.__init__ Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Constructor for the AzimuthNN_base class. Initializes the annotation pipeline with specified parameters. ```APIDOC ## AzimuthNN_base.__init__ ### Description Initializes the AzimuthNN_base class with the given annotation pipeline, model version, and evaluation batch size. ### Method Constructor ### 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. ### 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. ``` -------------------------------- ### query_h5ad method Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Loads query data from an H5AD file on disk. Uses ReadQueryObj to extract components for inference. ```python def query_h5ad( self, query_filepath, feature_names_col=None ): """ 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. """ query_obj = ReadQueryObj(query_filepath) self.X_query = query_obj.X_query() if self.X_query.dtype != np.float64: self.X_query = self.X_query.astype(np.float64) self.query_features = query_obj.query_features( feature_names_col=feature_names_col ) self.features_meta = query_obj.features_meta() self.cells_meta = query_obj.cells_meta() self.num_cells = self.X_query.shape[0] ``` -------------------------------- ### AzimuthNN_base.query_h5ad Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Loads query data from an H5AD file on disk. ```APIDOC ## AzimuthNN_base.query_h5ad ### Description Loads query data from an H5AD file on disk. ### Method query_h5ad ### 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. ``` -------------------------------- ### Pack AnnData Object Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Packages results into an AnnData object, optionally saving it to disk. Metadata is coerced to h5ad-compatible types. ```python [docs] def pack_adata(self, save_path = None): """ 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.AnnData AnnData object containing all query data and results. 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. """ cells_meta_coerced = coerce_metadata_types(self.cells_meta) features_meta_coerced = coerce_metadata_types(self.features_meta) all_embeddings = {**self.embeddings, **self.umaps} adata_obj = create_anndata( self.X_query, cells_meta_coerced, features_meta_coerced, embeddings = all_embeddings ) ``` -------------------------------- ### ANNotate _run_minibatched_pipeline Method Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Executes the inference, calibration, and refinement pipeline in minibatches to manage memory usage. ```python def _run_minibatched_pipeline(self): """ Run inference, calibration, output processing, and optional refinement in minibatches. After each minibatch, intermediate softmax arrays and unprocessed outputs are released via the _scoped_slice context manager on AzimuthNN_base. Internal print messages from run_inference_model, calibrate_predictions, and refine_labels are suppressed during minibatched processing. """ n_cells = self._inference_input_matrix.shape[0] n_batches = ( (n_cells + self._eval_batch_size - 1) // self._eval_batch_size ) if self._refine_levels: refine_str = ', '.join(self._refine_levels) else: refine_str = 'none' print( f"Splitting query data into {n_batches} " f"evaluation batch(es) of up to \n" f"{self._eval_batch_size} cells.\n" ) if refine_str != 'none': print( "Interpreting label predictions for consistent granularity " f"at {refine_str} level(s).\n" ) # accumulators for results across minibatches all_processed_outputs = {} all_refined_labels = {} # suppress internal prints during minibatched processing self._verbose = False print("Running model:") for batch_idx in range(n_batches): start = batch_idx * self._eval_batch_size end = min( (batch_idx + 1) * self._eval_batch_size, n_cells ) with MemoryContext(): with self._scoped_slice(start, end): _ = self.run_inference_model() _ = self.calibrate_predictions() _ = self.process_outputs(mode=self._output_mode) for level in self._refine_levels: _ = self.refine_labels(refine_level=level) ``` -------------------------------- ### Use map_to_cell_ontology independently Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Demonstrates various ways to use map_to_cell_ontology, including processing lists, DataFrames, AnnData objects, and files on disk. It supports optional CL ID inclusion and model version specification. ```python from panhumanpy.ANNotate_tools import map_to_cell_ontology # Apply to a list of labels directly — returns a list cl_labels = map_to_cell_ontology(['B cell', 'T cell', 'NK cell']) # With CL IDs — returns a tuple (cl_labels, cl_ids) cl_labels, cl_ids = map_to_cell_ontology( ['B cell', 'T cell'], include_cl_id=True ) # Apply to a pandas DataFrame (e.g. the obs from an existing AnnData) # Returns the DataFrame with a new column added immediately after src_col df = map_to_cell_ontology(df, src_col='cell_type') # Apply to an AnnData object directly # Returns the AnnData with the new column added to .obs adata = map_to_cell_ontology(adata, src_col='cell_type') # Apply to an h5ad file on disk # Reads, annotates, writes a new file with '_CL' appended to the filename # e.g. my_data.h5ad -> my_data_CL.h5ad adata = map_to_cell_ontology('my_data.h5ad', src_col='cell_type') # Apply to a CSV metadata file on disk # e.g. my_metadata.csv -> my_metadata_CL.csv df = map_to_cell_ontology('my_metadata.csv', src_col='cell_type') # Optionally specify a model version explicitly (defaults to the package default) cl_labels = map_to_cell_ontology(['B cell'], model_version='v1') ``` -------------------------------- ### Instantiate AzimuthNN_base Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Creates an AzimuthNN_base instance with an optional model_version argument. The query is not passed at instantiation; it is provided later via query_adata. ```python azimuth = ph.AzimuthNN_base(model_version=model_version) # model_version arg is optional # Note that this class is not instantiated with a query, the query is only passed to it later. ``` -------------------------------- ### Retrieve session information Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Displays the current R session environment details. ```R sessionInfo() ``` -------------------------------- ### Import panhumanpy and anndata Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Import the panhumanpy package and optionally anndata for use in the annotation pipeline. ```python import panhumanpy as ph import anndata as ad #optional ``` -------------------------------- ### annotate command Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate The annotate command is a standalone script that takes an input h5ad file and produces an annotated h5ad file. It supports various options for feature names, annotation pipeline, batch size, normalization, output mode, label refinement, cell ontology mapping, embedding extraction, and UMAP generation. ```APIDOC ## annotate /path/to/input.h5ad [options] ### Description Annotates single-cell data in an h5ad file using a pre-trained model. The annotated data is 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) is appended to prevent overwriting. ### Usage annotate /path/to/input.h5ad [options] ### Arguments #### Positional Arguments - **filepath** (string) - Required - Path to input h5ad file containing single-cell data. #### Optional Arguments - **-fn, --feature_names_col** (string) - Optional - Column in query.var containing gene names (default: None). - **-ap, --annotation_pipeline** (string) - Optional - Annotation pipeline to use (default: 'supervised'). - **-ebs, --eval_batch_size** (integer) - Optional - Batch size for model inference (default: 8192). - **-norm, --normalization_override** (boolean) - Optional - Skip normalization check (default: False). - **-ncbs, --norm_check_batch_size** (integer) - Optional - Number of cells to sample for normalization check (default: 100). - **-om, --output_mode** (string) - Optional - Output verbosity, 'minimal' or 'detailed' (default: 'minimal'). - **-rf, --refine_labels** (boolean) - Optional - Skip hierarchical label refinement (default: use refinement). - **-mcl, --map_to_cl** (string) - Optional - 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** (boolean) - Optional - 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** (boolean) - Optional - Skip neural network embeddings extraction (default: extract embeddings). - **-umap, --umap_embeddings** (boolean) - Optional - Skip UMAP projection generation (default: generate UMAP). #### UMAP Parameters - **-nnbrs, --n_neighbors** (integer) - Optional - Neighbors per point in UMAP (default: 30). - **-nc, --n_components** (integer) - Optional - UMAP dimensionality (default: 2). - **-me, --metric** (string) - Optional - Distance metric for UMAP (default: 'cosine'). - **-mdt, --min_dist** (float) - Optional - Minimum distance in UMAP (default: 0.3). - **-ulr, --umap_lr** (float) - Optional - UMAP learning rate (default: 1.0). - **-useed, --umap_seed** (integer) - Optional - Random seed for reproducibility (default: 42). - **-sp, --spread** (float) - Optional - UMAP spread parameter (default: 1.0). - **-uv, --umap_verbose** (boolean) - Optional - Hide UMAP progress (default: show progress). - **-uin, --umap_init** (string) - Optional - UMAP initialization method (default: 'spectral'). ### Output Annotated data is 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) is automatically appended to prevent overwriting. ### Example Commands ``` annotate my_cells.h5ad -fn feature_name -ebs 4096 -nc 3 annotate my_cells.h5ad -mcl azimuth_broad azimuth_fine -clid ``` ``` -------------------------------- ### pack_adata(save_path=None) Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Creates an AnnData object with all results and optionally saves to disk. Packages expression data, metadata, embeddings, and UMAP coordinates into a unified AnnData object. ```APIDOC ## pack_adata(save_path=None) ### Description Creates an AnnData object with all results and optionally saves to disk. This method packages all results (expression data, metadata, embeddings, and UMAP coordinates) into a unified AnnData object for further analysis or visualization. ### Method pack_adata ### Parameters - **save_path** (str, optional) - Optional - Path to save the AnnData object as an H5AD file. If None, the object is created but not saved. ### Returns - **anndata.AnnData** - AnnData object containing all query data and results. ### 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. ``` -------------------------------- ### Load AzimuthAPI and Required Packages Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Loads the required R packages for using AzimuthAPI and processing Seurat objects. Includes AzimuthAPI, Seurat, SeuratData, ggplot2, and dplyr. ```r library(AzimuthAPI) library(Seurat) library(SeuratData) library(ggplot2) library(dplyr) ``` -------------------------------- ### query_h5ad Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Loads query data from an H5AD file on disk, reading and extracting necessary components for inference. ```APIDOC ## query_h5ad ### Description Load query data from an H5AD file on disk. ### Method query_h5ad ### Parameters - **query_filepath** (str) - Required - Path to the H5AD file containing the query data. - **feature_names_col** (str, optional) - 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. ``` -------------------------------- ### Define -mcl/--map_to_cl argument for mapping metadata columns to Cell Ontology labels Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Adds a command-line argument that accepts one or more column names from cell metadata to map to Cell Ontology labels. The argument is optional and defaults to None, with a type of string. ```python parser.add_argument( "-mcl", "--map_to_cl", default=None, nargs='+', help=( "One or more column names in the cell " "metadata to map to Cell Ontology labels. " "e.g. -mcl azimuth_broad azimuth_fine" ), type=str ) ``` -------------------------------- ### Perform manual label refinement Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Legacy method for performing label refinement in versions prior to 0.3.0. ```python azimuth.azimuth_refine() cell_metadata = azimuth.cells_meta ``` -------------------------------- ### process_query method Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Prepares query expression data for inference by applying normalization and alignment based on the annotation pipeline. It requires that query data is loaded and validates the normalization_override and norm_check_batch_size parameters. ```python def process_query( self, normalization_override=False, norm_check_batch_size=100 ): """ 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. """ if not isinstance(normalization_override, bool): raise TypeError("normalization override must be a bool") if not isinstance(norm_check_batch_size, int): raise TypeError("norm_check_batch_size must be an integer") query_processing_class = InferenceInputData( self.X_query, self.query_features, self.inference_feature_panel, normalization_override = normalization_override, norm_check_batch_size = norm_check_batch_size ) self._inference_input_matrix = query_processing_class.inference_input( annotation_pipeline = self._annotation_pipeline ) ``` -------------------------------- ### Run AzimuthNN workflow Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Perform embedding, UMAP calculation, and retrieve cell metadata using the AzimuthNN class. ```python #azimuth = ph.AzimuthNN(query_path) # if passing the filepath azimuth = ph.AzimuthNN(query, model_version = model_version) # model_version arg is optional embeddings = azimuth.azimuth_embed() umap = azimuth.azimuth_umap() cell_metadata = azimuth.cells_meta ``` -------------------------------- ### Visualize medium granularity labels Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Creates a DimPlot using the azimuth_medium column for a consistent medium level of granularity. ```R p5 <- DimPlot(bmcite_qc, group.by = "azimuth_medium", label.size = 3, label = T, reduction = "azimuth_umap") + NoLegend() p5 ``` -------------------------------- ### Interactive annotation with AzimuthNN Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Demonstrates the high-level AzimuthNN interface to load data, generate embeddings and UMAP, map to Cell Ontology, and save the annotated results. ```python >>> 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 ``` -------------------------------- ### Set default values for arguments and parse command-line arguments Source: https://satijalab.org/pan_human_azimuth/_modules/panhumanpy/annotate Sets default values for normalization_override, refine_labels, include_cl_id, extract_embeddings, umap_embeddings, and umap_verbose, then parses the command-line arguments and returns the resulting namespace. ```python parser.set_defaults( normalization_override=False, refine_labels=True, include_cl_id=False, extract_embeddings=True, umap_embeddings=True, umap_verbose=True ) ``` ```python args = parser.parse_args() return args ``` -------------------------------- ### Visualize softmax probabilities Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Creates a histogram to visualize the distribution of model confidence scores across cells. ```R ggplot(md, aes(x = final_level_confidence)) + geom_histogram(bins = 20, fill = "skyblue") + labs(x = "Softmax probability", y = "Count", title = "Histogram of Softmax Probabilities") + theme_bw() ``` -------------------------------- ### AzimuthNN_base.process_query Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Processes the query data to prepare it for inference. ```APIDOC ## AzimuthNN_base.process_query ### Description Processes the query data to prepare it for inference according to the specified annotation pipeline. ### Method process_query ### 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. ### Notes 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. ``` -------------------------------- ### Run ANNotate for Local Annotation Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Runs Pan-human Azimuth cell type annotation locally using the ANNotate function. The initial run may take longer because model weights are downloaded and cached locally. ```r bmcite_ann <- ANNotate(bmcite) ``` -------------------------------- ### Initialize AzimuthNN with custom feature column Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Specify the column name in query.var where gene names are stored if they are not in the index. ```python azimuth = ph.AzimuthNN(query, feature_names_col = "gene_symbol") ``` -------------------------------- ### Visualize fine granularity labels Source: https://satijalab.org/pan_human_azimuth/r/articles/intro_azimuthapi_vignette Creates a DimPlot using the azimuth_fine column for a consistent high level of granularity. ```R p6 <- DimPlot(bmcite_qc, group.by = "azimuth_fine", label.size = 3, label = T, reduction = "azimuth_umap") + NoLegend() p6 ``` -------------------------------- ### CloudAzimuth function signature Source: https://satijalab.org/pan_human_azimuth/r/reference/cloudazimuth The CloudAzimuth function takes a Seurat object and optional parameters for assay, server IP, port, and scheme. Defaults are 'RNA' for assay, 'azimuthapi.satijalab.org' for IP, NULL for port, and 'https' for scheme. Additional arguments are passed to the API. ```r CloudAzimuth( object = object, assay = "RNA", ip = "azimuthapi.satijalab.org", port = NULL, scheme = NULL, ... ) ``` -------------------------------- ### make_QC_heatmap function signature Source: https://satijalab.org/pan_human_azimuth/r/reference/make_qc_heatmap The function signature for generating a QC heatmap, including all available parameters for customization. ```R make_QC_heatmap( seurat_obj, group.by = NULL, cells.order = NULL, n_downsample = 200, save_folder_path = NULL, logfc_cutoff = log(2), n_markers = 10, text.size = 5, text.angle = 90, min.size = NULL, max.size = NULL, min.pct = 0.1, reorder = TRUE, switch_id = NULL, identity = "" ) ``` -------------------------------- ### Pack metadata and low-dimensional representations into anndata Source: https://satijalab.org/pan_human_azimuth/python/tutorial_panhumanpy Packs metadata updated with annotations and any low-dimensional representations into an anndata object. ```python # To pack metadata updated with annotations, and any low dimensional representations computed into an anndata obj annotated_query = azimuth.pack_adata() ``` -------------------------------- ### AzimuthNN_base.query_stripped Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Loads query data directly from an expression matrix and metadata, bypassing the need for an AnnData object. ```APIDOC ## AzimuthNN_base.query_stripped ### Description Loads query data directly from an expression matrix and metadata. Useful for integration with custom preprocessing pipelines. ### Method query_stripped ### 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. ``` -------------------------------- ### AzimuthNN_base.query_adata Source: https://satijalab.org/pan_human_azimuth/python/panhumanpy.annotate Loads query data from an AnnData object. ```APIDOC ## AzimuthNN_base.query_adata ### Description Loads query data from an AnnData object containing expression data and metadata. ### Method query_adata ### 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. ```