CyteType class#

CyteType annotates the clusters of one AnnData object. Creating it checks the inputs, summarizes each cluster and writes the upload files vars.h5 and obs.duckdb. run() uploads the files, submits the job, waits for it to finish and adds the results to the AnnData object. get_results() returns the stored results or fetches those of a finished job, and cleanup() deletes the upload files.

from cytetype import CyteType

annotator = CyteType(adata, group_key="leiden", rank_key="rank_genes_leiden")
adata = annotator.run(
    study_context="Peripheral blood mononuclear cells from a healthy human donor."
)
results = annotator.get_results()
annotator.cleanup()

Always use the AnnData object that run() returns. The Python quickstart runs these steps on a public dataset, Prepare your data describes the input requirements, and Results in AnnData and Seurat describes every column and key that run() adds.

class cytetype.CyteType(adata, group_key, rank_key='rank_genes_groups', gene_symbols_column=None, n_top_genes=50, aggregate_metadata=True, min_percentage=10, pcent_batch_size=5000, coordinates_key='X_umap', max_cells_per_group=1000, vars_h5_path='vars.h5', obs_duckdb_path='obs.duckdb', max_metadata_categories=500, api_url=None, auth_token=None, label_na=False)#

CyteType class for characterizing clusters from single-cell RNA-seq data.

This class provides an object-oriented interface for cluster characterization using the CyteType API. The expensive data preparation steps (validation, expression percentage calculation, and marker gene extraction) are performed during initialization, allowing for efficient reuse when making multiple requests with different parameters.

Initialization also writes the vars.h5 and obs.duckdb artifact files and adds a temporary __cytetype_gene_symbols column (with a numeric suffix if that name is taken) to adata.var holding the cleaned gene symbols. Call cleanup() after run() to delete the files and remove the column; a file whose build failed is deleted right away. After cleanup(), create a new CyteType object to run another job with artifacts.

Initialize CyteType with AnnData object and perform data preparation.

Parameters:
  • adata (AnnData) – The AnnData object to annotate. Must contain log1p-normalized gene expression data in adata.X and gene names in adata.var_names.

  • group_key (str) – The key in adata.obs containing the cluster labels. These clusters will receive cell type annotations.

  • rank_key (str, default: 'rank_genes_groups') – The key in adata.uns containing differential expression results from sc.tl.rank_genes_groups. Must use the same groupby as group_key. Defaults to “rank_genes_groups”.

  • gene_symbols_column (str | None, default: None) – Name of the column in adata.var that contains gene symbols. When None (default), auto-detects by checking well-known column names (feature_name, gene_symbols, etc.), then adata.var_names, then heuristic scan of all var columns. Defaults to None.

  • n_top_genes (int, default: 50) – Number of top marker genes per cluster to extract during initialization. Higher values may improve annotation quality but increase memory usage. Defaults to 50.

  • aggregate_metadata (bool, default: True) – Whether to aggregate metadata from the AnnData object. Defaults to True.

  • min_percentage (int, default: 10) – Minimum percentage of cells in a group to include in the cluster context. Defaults to 10.

  • pcent_batch_size (int, default: 5000) – Number of cells to process per chunk when calculating expression percentages. Defaults to 5000.

  • coordinates_key (str, default: 'X_umap') – Key in adata.obsm with 2D coordinates for the report’s visualization. This key is tried first, then “X_umap”, “X_tsne” and “X_pca”, all matched case-insensitively; the first array with adata.n_obs rows and at least 2 columns is used (only its first 2 columns). If none qualifies, visualization is disabled. Defaults to “X_umap”.

  • max_cells_per_group (int, default: 1000) – Maximum number of cells to sample per group for visualization. If a group has more cells than this limit, a random sample will be taken. Defaults to 1000.

  • vars_h5_path (str, default: 'vars.h5') – Path where the expression artifact (normalized and, when available, raw counts) is written during initialization and uploaded by run(). A relative path is written to the current working directory. cleanup() deletes the file. Defaults to “vars.h5”.

  • obs_duckdb_path (str, default: 'obs.duckdb') – Path where the cell metadata artifact (adata.obs and the visualization coordinates) is written during initialization and uploaded by run(). A relative path is written to the current working directory. cleanup() deletes the file. Defaults to “obs.duckdb”.

  • max_metadata_categories (int, default: 500) – Maximum number of unique values a categorical obs column may have to be included in cluster metadata aggregation. Columns with more unique values (e.g. cell barcodes, per-cell IDs) are skipped to avoid excessive memory usage. Defaults to 500.

  • api_url (str | None, default: None) – URL for the CyteType API endpoint. Defaults to CYTETYPE_API_URL when set, otherwise “https://cytetype.nygen.io”.

  • auth_token (str | None, default: None) – API key sent as a Bearer token. When None, the key saved by cytetype setup (or cytetype login) for api_url is read each time it is needed, and initialization logs a note if there is none. Defaults to None.

  • label_na (bool, default: False) – If True, cells with NaN values in the group_key column are assigned an 'Unknown' cluster label (or 'Unknown 2', etc. if that label already exists) in a new AnnData object, which run() returns; the labels in the original object’s obs are not changed. If False (default), a ValueError is raised instead.

Raises:
  • KeyError – If the required keys are missing in adata.obs or adata.uns

  • ValueError – If the data format is incorrect, there are validation errors, or api_url is not a valid server origin

cleanup()#

Delete the artifact files built during initialization.

Call this after run() completes to remove the vars.h5 and obs.duckdb files from disk and drop the temporary canonical gene-symbol column. Paths are cleared so repeated calls are safe. A later run() raises unless require_artifacts=False; create a new CyteType object to rebuild the artifacts.

Return type:

None

run(study_context, llm_configs=None, metadata=None, n_parallel_clusters=2, results_prefix='cytetype', poll_interval_seconds=10, timeout_seconds=7200, api_url=None, auth_token=None, save_query=True, query_filename='query.json', upload_timeout_seconds=3600, upload_max_workers=4, require_artifacts=True, show_progress=True, override_existing_results=False, visibility=None)#

Perform cluster characterization using the CyteType API.

Parameters:
  • study_context (str) – Biological context for the experimental setup. Required. For example, include information about ‘organisms’, ‘tissues’, ‘diseases’, ‘developmental_stages’, ‘single_cell_methods’, ‘experimental_conditions’.

  • llm_configs (list[dict[str, Any]] | None, default: None) – Configuration for the large language models to be used. Each dict must match the LLMModelConfig schema with required ‘provider’ and ‘name’ fields. Either ‘apiKey’ or all AWS credentials (‘awsAccessKeyId’, ‘awsSecretAccessKey’, ‘awsDefaultRegion’) must be provided. Defaults to None, using the API’s default model.

  • metadata (dict[str, Any] | None, default: None) – Custom metadata tags to include in the report header. Values must be strings; values that look like URLs will be made clickable in the report. A “title” key (case-insensitive) also names the job in the dashboard. Defaults to None.

  • n_parallel_clusters (int, default: 2) – Number of parallel requests to make to the model (1-50). Note that high values can lead to rate limit errors. Ignored when llm_configs is not provided; the server then uses its own setting. Defaults to 2.

  • results_prefix (str, default: 'cytetype') – Prefix for the keys added to adata.obs and adata.uns to store results (see Returns). Defaults to “cytetype”.

  • poll_interval_seconds (int, default: 10) – How often (in seconds) to check for results from the API. Defaults to 10.

  • timeout_seconds (int, default: 7200) – Maximum time (in seconds) to wait for API results before raising a timeout error. Defaults to 7200.

  • api_url (str | None, default: None) – URL for the CyteType API endpoint. If not provided, the API URL specified in the initialization will be used. If provided, it will override the API URL specified in the initialization.

  • auth_token (str | None, default: None) – API key sent as a Bearer token. If provided, it overrides the token specified in the initialization and is kept for later calls to the same API URL. If neither is provided, the key saved by cytetype setup (or cytetype login) for the API URL is read at each call. Defaults to None.

  • save_query (bool, default: True) – Whether to save the query to a file. Defaults to True.

  • query_filename (str, default: 'query.json') – Filename for saving the query when save_query is True. Defaults to “query.json”.

  • upload_timeout_seconds (int, default: 3600) – Socket read timeout used for each artifact upload. Defaults to 3600.

  • upload_max_workers (int, default: 4) – Number of parallel threads used to upload file chunks. Each worker holds one chunk in memory; the chunk size is set by the server. Defaults to 4.

  • require_artifacts (bool, default: True) – Whether to raise an error if artifact building or uploading fails, or if cleanup() already deleted the artifacts. When True (default), any artifact failure stops the run. Set to False to skip artifacts and continue with annotation only. Authentication and authorization errors always stop the run. Defaults to True.

  • show_progress (bool, default: True) – Whether to display progress updates with spinner and cluster status. Set to False to disable all visual progress output. Defaults to True.

  • override_existing_results (bool, default: False) – Whether to override existing results with the same results_prefix. If False (default) and results already exist, will raise an error to prevent accidental overwriting. Set to True to explicitly allow overwriting. Defaults to False.

  • visibility (Literal['private', 'org', 'public'] | None, default: None) – Who can view the report. Defaults to None, which uses the server default (“private”). “org” shares the report with your organization and needs an organization API key. With a key that looks like a personal key (starting with cyt_p_), a warning is logged before the artifacts are uploaded. The server rejects “org” for any key without an organization license, such as a personal key, when the job is submitted, after the upload. “public” makes the report viewable by anyone with the link, and any signed-in CyteType user can find it in Chat’s report search.

Return type:

AnnData

Returns:

anndata.AnnData – The AnnData object the results were added to. This is the object passed to CyteType(), except when label_na=True relabeled NaN cluster labels: then it is a new object and the obs columns exist only there, so use the returned object. It gets the following additions:

  • adata.obs[f"{results_prefix}_annotation_{group_key}"]: Cell type annotations

  • adata.obs[f"{results_prefix}_cellOntologyTerm_{group_key}"]: Cell Ontology term names

  • adata.obs[f"{results_prefix}_cellOntologyTermID_{group_key}"]: Cell Ontology term IDs

  • adata.obs[f"{results_prefix}_cellState_{group_key}"]: Cell states

  • adata.obs[f"{results_prefix}_reviewerConfidence_{group_key}"]: Reviewer confidence (“High”, “Moderate” or “Low”; “Unknown” when missing)

  • adata.uns[f"{results_prefix}_results"]: The job ID and the normalized results (see get_results()) as a JSON string under “result”

  • adata.uns[f"{results_prefix}_jobDetails"]: The job ID, report URL and API URL, plus the requested visibility when given

The obs columns are categorical. Cells in clusters without a result get “Unknown” (”” for the cell state).

Raises:
  • ValueError – If results with the same prefix already exist and override_existing_results is False, if api_url is not a valid server origin, if visibility is not a valid value, if upload_timeout_seconds is not positive, or if cleanup() deleted the artifacts and require_artifacts is True.

  • AuthenticationError – If no API key is available (including saved credentials that cannot be read) or the server rejects it.

  • pydantic.ValidationError – If llm_configs, metadata, n_parallel_clusters or the prepared input data are invalid.

  • RateLimitError – If the server’s rate limit for job submissions is exceeded.

  • QuotaExceededError – If the account’s quota is exceeded.

  • AuthorizationError – If the account may not submit jobs or upload files (for example, an expired license).

  • LLMValidationError – If a model in llm_configs fails the server’s validation.

  • APIError – For other errors returned by the server.

  • NetworkError – If the server cannot be reached or returns an unexpected response.

  • cytetype.api.exceptions.TimeoutError – If a request times out or the job does not complete within timeout_seconds (also importable as cytetype.CyteTypeTimeoutError).

  • JobFailedError – If the job fails on the server.

  • Exception – With require_artifacts=True, the original exception raised while building or uploading an artifact.

get_results(results_prefix='cytetype')#

Retrieve the CyteType results for this AnnData object.

Results stored in adata.uns[f"{results_prefix}_results"] are returned first. They are re-normalized, so results saved by older versions also get the filled fields and the reviewerConfidence, isHeterogeneous and heterogeneityType keys (obs columns are not added in this case). Otherwise, if adata.uns[f"{results_prefix}_jobDetails"] holds a job ID, the API is asked for the job status and, if the job has completed, for its results (up to two requests, no polling). Fetched results are written the same way as by run(), to the AnnData object that run() returns (self.adata; a new object if label_na=True relabeled NaN cluster labels).

Parameters:

results_prefix (str, default: 'cytetype') – The prefix used when storing results. Defaults to “cytetype”.

Return type:

dict[str, Any] | None

Returns:

dict[str, Any] | None – The normalized results with “annotations”, “summary”, “clusterCategories”, “studyContext” and “raw_annotations” (the API’s per-cluster results, unchanged). Each annotation has “clusterId”, “annotation”, “ontologyTerm”, “ontologyTermID”, “granularAnnotation”, “cellState”, “justification”, “supportingMarkers”, “conflictingMarkers”, “missingExpression”, “unexpectedExpression”, “reviewerConfidence” (“High”, “Moderate”, “Low” or None), “isHeterogeneous” (bool or None) and “heterogeneityType” (str or None). None if no results are stored and they could not be fetched (no job details, job not completed, or the request failed).

Raises:
  • ValueError – If the API URL stored in the job details is not a valid server origin.

  • AuthenticationError – If results must be fetched and no API key is available for the job’s API URL (including saved credentials that cannot be read).