Graph construction API reference#

These DataStore methods build a neighbor graph as explicit, provenance-backed stages. Each builder returns an ArtifactRef; pass that exact ref to the next stage.

Prefer a pipeline recipe, such as ds.pipeline.rna(), for a standard analysis (Analysis pipeline API reference). Use the individual methods for a partial workflow, an alternative branch, or a stage that the recipes do not run. See Build a neighbor graph stage by stage for an executable walkthrough.

Explicit chain#

Capture the live Boolean cell column once at the workflow boundary. The returned selection is immutable; later live changes do not alter it.

cells = ds.snapshot_cell_selection("I")
features = ds.features.hvgs(cells, top_n=1000, show_plot=False)

normalized = ds.features.normalize(cells, features)
pca = ds.reduction.pca(normalized, dims=21)
ann = ds.graph.ann_index(pca)
neighbors = ds.graph.neighbors(ann, k=11)
graph = ds.graph.connectivity(neighbors)
initialization = ds.embeddings.initialization(pca)

The full stage order is:

  1. snapshot_cell_selection() and an exact feature-selection ref

  2. normalize()

  3. pca(), lsi(), or custom(), or none; or coordinates computed elsewhere through import_coordinates()

  4. Optional harmony()

  5. ann_index()

  6. neighbors()

  7. connectivity()

Without a reduction, graph.ann_index(normalized) builds the graph on the normalized artifact itself: its float32 values of the selected features are the coordinates, one per feature, as in an RNA pipeline run with pca={"dims": 0}. Every later stage, including the embedding initialization and an SNN integration, accepts such a graph. Harmony corrects reduced coordinates only, and WNN integration, mapping references, and doublet scoring need them too, so each rejects normalized coordinates with an error that names a reduction such as reduction.pca. Because normalized values can be coordinates, features.normalize writes them with a checked writer: a value that is NaN or infinite once rounded to float32, such as one from a custom normalizer or the log1p of a negative count, raises NonFiniteArtifactError, a ValueError that names features.normalize, and no complete artifact is saved.

The hnswlib index holds every cell in memory, about 4 * dims + 8 * ann_m + 130 bytes per cell on x86-64 Linux (cytearc.neighbors.index.ann_index_peak_bytes), where dims is the number of coordinate dimensions: the PCA dimensions, or the selected features of normalized coordinates. graph.ann_index holds it while it adds the coordinate blocks and while it saves it, and graph.neighbors while it loads and queries it, beside the indices and distances of every cell’s neighbors, 8 bytes per neighbor. Each compares what it holds with the datastore’s memory budget before it creates or loads the index and raises MemoryError over it, naming the bytes, the cells, the dimensions, and the limit. The index moves between the store and memory through a temporary file of about 4 * dims + 8 * ann_m + 20 bytes per cell (cytearc.neighbors.index.ann_index_file_bytes) in the system’s temporary directory, which needs that much free space.

initialization() depends on explicit reduction, Harmony, imported, or normalized coordinates. It is needed for UMAP unless an initialization array is supplied, but is not part of connectivity construction.

graph.neighbors reads the coordinate ref named by the ANN artifact. Its optional coordinates= argument is only an equality check; it cannot redirect an index to different coordinates.

By default graph.ann_index builds the hnswlib index with ann_m=24 links per cell and a build candidate list of ann_efc=200, on one thread so that the index is reproducible. An ann_efc below 2 * ann_m builds an index whose searches can miss every true neighbor of some cells between well-separated clusters. The search depth only changes queries: graph.neighbors searches max(ann_ef, 2 * k) candidates by default, where ann_ef is the index’s recorded smallest depth, 200 by default, and its own ann_ef= argument sets another depth. The neighbors artifact records the depth that the query used as its ann_ef unless it is max(ann_ef, k + 1), the index’s own depth as hnswlib applies it; an artifact without ann_ef searched that depth. A query of the index’s depth therefore keeps the identity of earlier ones, and a changed depth computes new neighbors from the same index.

Queries run on the datastore’s nthreads threads, which never change the neighbors. Each query saves the percentage of cells that it returned among their own nearest neighbors as its selfHitRate diagnostic, and a rate below 99.5% warns each time the query is computed or reused; cells with identical coordinates also lower it. reduction.pca and reduction.harmony also save the numbers behind their warnings as diagnostics, which their entries below list.

External coordinates#

A latent space computed by another tool, such as scVI’s X_scVI or a Harmony correction saved as X_pca_harmony, becomes graph coordinates through import_coordinates(). Pass a pandas DataFrame indexed by cell ID, which is aligned to the selected cells by ID; rows of other cells are left out. An array raises TypeError, because its rows would land on cells by position, and a store’s cells need not be in the order of the tool’s cells:

cells = ds.snapshot_cell_selection("I")
latent = ds.reduction.import_coordinates(
    pd.DataFrame(adata.obsm["X_scVI"], index=adata.obs_names),
    cell_selection=cells,
    name="X_scVI",
    source={"tool": "scvi-tools", "version": "1.2.0", "parameters": {"n_latent": 30}},
)
ann = ds.graph.ann_index(latent)
graph = ds.graph.connectivity(ds.graph.neighbors(ann, k=11))

The result is an imported_coordinates artifact. Its identity records the name, the source record, a fingerprint of the values, and a fingerprint of the ordered cell IDs, so importing the same values again reuses it and ds.artifacts.lineage shows where the coordinates came from. H5adReader imports such an obsm array in the same form when its role is "coordinates", as in embedding_roles={"X_scVI": "coordinates"}.

Downstream consumers#

UMAP, LocalMAP, t-SNE, clustering, diffusion, trajectories, graph metrics, and graph-backed plots require an exact graph or neighbor artifact. Analytical producers return artifacts and do not add live metadata fields:

umap = ds.embeddings.umap(
    graph,
    initialization,
)
leiden = ds.clusters.leiden(
    graph,
    resolution=0.5,
)
ds.plots.embedding(layout=umap, color_by=leiden)

The scientific cell selection comes from graph lineage. Load a payload from its exact ref, or pass the ref to another consumer.

Graph consumers do not accept an independent feature selection. Named lineage edges identify the normalized feature selections used to construct a native graph. Imported-coordinate graphs have no such selection; integrated graphs preserve the ordered projections of their explicit sources.

Methods#

cytearc.DataStore.snapshot_cell_selection

Capture a live boolean cell column as an immutable selection.

cytearc.datastore.namespaces.FeaturesAccessor.normalize

Normalize explicit immutable cell and feature selections.

cytearc.datastore.namespaces.ReductionAccessor.pca

Fit or reuse PCA for a normalized artifact.

cytearc.datastore.namespaces.ReductionAccessor.lsi

Fit or reuse latent semantic indexing for normalized data.

cytearc.datastore.namespaces.ReductionAccessor.custom

Register custom feature loadings as a reusable reduction.

cytearc.datastore.namespaces.ReductionAccessor.harmony

Snapshot live batch columns, then fit or reuse Harmony correction.

cytearc.datastore.namespaces.ReductionAccessor.import_coordinates

Import an external latent space as graph coordinates.

cytearc.datastore.namespaces.GraphAccessor.ann_index

Build or reuse an approximate nearest-neighbor (hnswlib HNSW) index.

cytearc.datastore.namespaces.GraphAccessor.neighbors

Query an ANN artifact and persist compact neighbor matrices.

cytearc.datastore.namespaces.GraphAccessor.connectivity

Convert persisted neighbors into a weighted connectivity graph.

cytearc.datastore.namespaces.EmbeddingsAccessor.initialization

Build or reuse K-means initialization for explicit coordinates.

cytearc.datastore.namespaces.GraphAccessor.load

Load the cell neighborhood as a scipy sparse matrix.

DataStore.snapshot_cell_selection(cell_key='I')#

Capture a live boolean cell column as an immutable selection.

The returned reference is the explicit starting input for atomic graph construction methods such as normalize(). A complete matching snapshot is reused when possible.

Parameters:

cell_key (str) – Boolean cell metadata column to capture.

Return type:

ArtifactRef

Returns:

A complete datastore-scoped cell-selection artifact.

FeaturesAccessor.normalize(cell_selection, features, *, log_transform=None, renormalize_subset=None, invalidate_cache=False)#

Normalize explicit immutable cell and feature selections.

On a store merged from sources that called different peaks, as its feature columns measured_in_<source> record, an ATAC assay’s term frequencies divide each cell’s counts by its total over the peaks that every source of the selected cells measured, as a store of those peaks alone does, unless renormalize_subset takes it over the selected peaks. The artifact then records those peaks as measured_features_fingerprint.

Raises:
  • UnmeasuredCellsError – If the assay did not measure a selected cell.

  • ValueError – If the assay records that the source of a selected cell did not measure a selected feature, as the feature columns measured_in_<source> of a merged store record.

Return type:

ArtifactRef

ReductionAccessor.pca(normalized, *, dims=21, pca_cell_selection=None, feat_scaling=True, batch_size=None, local_cache='auto', show_elbow_plot=False, invalidate_cache=False)#

Fit or reuse PCA for a normalized artifact.

Up to 4096 features, PCA is exact: one pass over the selected cells accumulates their float64 covariance, whose leading eigenvectors are the loadings. Wider inputs are fitted with a randomized block Krylov solver that reads the selected cells once per pass, for up to 24 passes, and stops when the leading components move less than 0.1 degrees in a pass; the artifact then records solver="randomized". Neither result depends on batch_size beyond rounding. Besides the coordinates, loadings, and center, the artifact stores the variance of each component (variance) and its share of the total variance of the fitted values (variance_ratio) from release 1.3.0 on.

The fit saves its diagnostics, which ds.artifacts.inspect(ref).diagnostics returns: solverPasses, the passes of the randomized solver, None for the exact one, and componentShift, the degrees that its leading components moved in the last pass when it stopped at 24 passes, None otherwise. A fit that stopped there gives a DiagnosticWarning each time it is computed or reused.

Parameters:
  • normalized (ArtifactRef) – Normalized artifact to reduce.

  • dims (int) – Requested number of principal components. (Default: 21)

  • pca_cell_selection (ArtifactRef | None) – Optional stored cell-selection artifact used to fit PCA while projecting every cell in normalized.

  • feat_scaling (bool) – Whether to standardize features before fitting PCA.

  • batch_size (int | None) – Number of selected cells processed per block. When omitted, whole stored row bands are combined as needed to fit at least dims + 1 rows. An explicit smaller value is expanded to that aligned minimum with a warning.

  • local_cache (bool | str) – Local staging policy for normalized data on remote stores. Keep "auto" on a remote store so that the passes of the randomized solver read a local copy.

  • show_elbow_plot (bool) – Whether to display the explained variance of the dims components, read from the stored artifact when it is reused.

  • invalidate_cache (bool) – Force a new reduction artifact.

Return type:

ArtifactRef

Returns:

Reference to the PCA reduction artifact.

Raises:

MemoryError – When the fit needs more than the datastore memory budget, before the fit or the feature scaling starts.

ReductionAccessor.lsi(normalized, *, dims=11, skip_first=True, rand_state=4466, solver='streaming', n_iter=5, n_oversamples=10, batch_size=None, local_cache='auto', invalidate_cache=False)#

Fit or reuse latent semantic indexing for normalized data.

Parameters:
  • normalized (ArtifactRef) – Normalized artifact to reduce.

  • dims (int) – Requested number of retained LSI dimensions.

  • skip_first (bool) – Whether to omit the first singular component.

  • rand_state (int) – Seed of the randomized decomposition, at least 0, and at most 2**32 - 1 for the materialized solver.

  • solver (Literal['streaming', 'materialized']) – Memory-bounded streaming solver or materialized compatibility solver. The materialized solver holds the whole matrix and raises MemoryError before reading it when that exceeds the memory budget.

  • n_iter (int) – Power iterations used by randomized LSI.

  • n_oversamples (int) – Extra random vectors used to stabilize the fitted singular subspace.

  • batch_size (int | None) – Number of selected cells processed per block.

  • local_cache (bool | str) – Local staging policy for normalized data on remote stores.

  • invalidate_cache (bool) – Force a new reduction artifact.

Return type:

ArtifactRef

Returns:

Reference to the LSI reduction artifact.

ReductionAccessor.custom(loadings, normalized, *, batch_size=None, local_cache='auto', invalidate_cache=False)#

Register custom feature loadings as a reusable reduction.

Parameters:
  • loadings (ndarray) – Two-dimensional feature-by-dimension matrix of finite real loadings. Its row count must match the normalized feature selection.

  • normalized (ArtifactRef) – Normalized artifact associated with the loadings.

  • batch_size (int | None) – Number of selected cells processed per block.

  • local_cache (bool | str) – Local staging policy for normalized data on remote stores.

  • invalidate_cache (bool) – Force a new reduction artifact.

Return type:

ArtifactRef

Returns:

Reference to the custom reduction artifact.

ReductionAccessor.harmony(reduction, batch_columns, *, harmony_params=None, batch_size=None, invalidate_cache=False)#

Snapshot live batch columns, then fit or reuse Harmony correction.

The correction is CyteArc’s implementation of Harmony2. The stored batch_correction artifact holds the corrected coordinates and the fitted state that Symphony reference mapping needs.

The correction saves its diagnostics, which ds.artifacts.inspect(ref).diagnostics returns: rounds, the rounds of clustering and correction run; convergedRound, the round at which the fit converged, None when it stopped before; objectiveChange, the objective’s change in the last round as a share of its value; previousObjectiveChange, that change in the round before; and averageObjectiveChange, the change per round of the average of two consecutive round objectives, as a share of that average. A change is None until two, three and five rounds have run. A fit that ran two or more rounds without converging gives a DiagnosticWarning each time the correction is computed or reused.

Parameters:
  • reduction (ArtifactRef) – The reduction whose coordinates are corrected, such as a reduction.pca result.

  • batch_columns (list[str]) – Cell metadata columns whose levels are the batches; their live values are snapshotted before the fit.

  • harmony_params (dict[str, Any] | None) – Options of the fit: the keyword options of cytearc.embeddings.harmony.fit_harmony, such as n_clusters, theta, sigma and ridge_penalty. Renamed or removed keys raise an error that names their replacement.

  • batch_size (int | None) – Rows of each block read from the coordinates and the batch labels; by default the reduction’s own blocks.

  • invalidate_cache (bool) – Fit again even when a matching correction exists.

Return type:

ArtifactRef

Returns:

The reference of the batch_correction artifact.

Raises:
  • TypeError – If reduction is not an ArtifactRef or an option has the wrong type.

  • ValueError – If the arguments, the options or the batch labels are invalid, such as a missing batch label.

  • MemoryError – If the fit exceeds the memory budget.

  • numpy.linalg.LinAlgError – If a regression of the fit is not positive definite.

ReductionAccessor.import_coordinates(values, *, cell_selection, name, from_assay=None, source=None, invalidate_cache=False)#

Import an external latent space as graph coordinates.

The coordinates, such as an scVI latent space (X_scVI) or a Harmony correction computed elsewhere (X_pca_harmony), become an imported_coordinates artifact that graph.ann_index, embeddings.initialization, and mapping accept like a PCA. Its identity records name, the source record, a fingerprint of the values, which also serves as their source digest, and a fingerprint of the ordered cell IDs, so importing the same values again reuses the artifact, and lineage reports show where they came from.

Parameters:
  • values (Any) – A pandas DataFrame indexed by cell ID, such as pd.DataFrame(adata.obsm["X_scVI"], index=adata.obs_names), whose rows are aligned to the cells of cell_selection by ID; rows of other cells are left out. Integer and boolean values are stored as float64.

  • cell_selection (ArtifactRef) – Cell-selection artifact of the cells that the coordinates describe.

  • name (str) – Name of the coordinates, recorded as their source key, such as "X_scVI".

  • from_assay (str | None) – Assay that owns the artifact; the default assay when None.

  • source (Mapping[str, Any] | None) – Record of the tool that computed the coordinates, such as {"tool": "scvi-tools", "version": "1.2.0", "parameters": {"n_latent": 30}}, holding text, numbers, booleans, None, and lists or mappings of them.

  • invalidate_cache (bool) – Write a new artifact even when one matches.

Return type:

ArtifactRef

Returns:

Reference to the imported_coordinates artifact.

Raises:
  • TypeError – If an argument has the wrong type, the values are not numbers, or they are not a DataFrame indexed by cell ID, such as an array, whose rows would land on cells by position.

  • ValueError – If the DataFrame lacks a selected cell or repeats a cell ID, or a value is not finite.

  • PermissionError – If no matching result exists and the store is not opened with zarr_mode='r+'.

GraphAccessor.ann_index(coordinates, *, ann_metric='l2', ann_efc=200, ann_ef=200, ann_m=24, ann_parallel=False, rand_state=4466, batch_size=None, invalidate_cache=False)#

Build or reuse an approximate nearest-neighbor (hnswlib HNSW) index.

The index holds every cell in memory, about 4 * dims + 8 * ann_m + 130 bytes per cell on x86-64 Linux.

Parameters:
  • coordinates (ArtifactRef) – Reduction, batch-correction, imported-coordinate, or normalized artifact whose rows are indexed.

  • ann_metric (str) – Distance metric, "l2" or "cosine".

  • ann_efc (int) – Candidate list size while the index is built (ef_construction). Keep it at least 2 * ann_m: a smaller list builds a graph in which searches on well-separated clusters can miss a cell’s true neighbors.

  • ann_ef (int) – The smallest search depth (hnswlib ef) of the index’s queries. graph.neighbors searches max(ann_ef, 2 * k) candidates unless it is given its own ann_ef. It does not change the index, only the queries that read it.

  • ann_m (int) – Links per cell in each layer of the index (M); the lowest layer keeps twice as many. At least two.

  • ann_parallel (bool) – Insert the cells on the datastore’s threads. A parallel index can differ from run to run, so it is identified separately from a serial one, which is reproducible.

  • rand_state (int) – Non-negative seed of the index’s layer assignment.

  • batch_size (int | None) – Coordinate rows added per block; by default the stored row band.

  • invalidate_cache (bool) – Force a new index artifact.

Return type:

ArtifactRef

Returns:

Reference to the ANN index artifact.

Raises:

MemoryError – If the index exceeds the memory budget.

GraphAccessor.neighbors(ann_index, *, coordinates=None, k=11, ann_ef=None, batch_size=None, invalidate_cache=False)#

Query an ANN artifact and persist compact neighbor matrices.

Every cell is queried against the index for itself and its k nearest other cells, on the datastore’s nthreads threads; the neighbors do not depend on the thread count. The percentage of cells that the search returns among their own neighbors is saved as the selfHitRate diagnostic, which ds.artifacts.inspect(ref).diagnostics returns. A rate below 99.5% gives a DiagnosticWarning, each time the query is computed or reused, that the index or the search depth is too small for these coordinates.

Parameters:
  • ann_index (ArtifactRef) – ANN index artifact to query.

  • coordinates (ArtifactRef | None) – Optional check that the index was built on these coordinates; it cannot redirect the query.

  • k (int) – Neighbors per cell, excluding the cell itself; at most one fewer than the cells.

  • ann_ef (int | None) – Search depth (hnswlib ef) of the query. By default max(index_ef, 2 * k), where index_ef is the ann_ef that the index records, 200 by default. The search never covers fewer than k + 1 candidates. The artifact records the depth it used as its ann_ef unless that is max(index_ef, k + 1), the depth of the index’s own ann_ef as hnswlib applies it; an artifact without ann_ef searched that depth, so a default query with 2 * k at most index_ef keeps the identity of earlier queries.

  • batch_size (int | None) – Coordinate rows queried per block; by default the stored row band.

  • invalidate_cache (bool) – Force a new neighbors artifact.

Return type:

ArtifactRef

Returns:

Reference to the neighbors artifact.

Raises:

MemoryError – If the query exceeds the memory budget.

GraphAccessor.connectivity(neighbors, *, local_connectivity=1.0, bandwidth=1.5, invalidate_cache=False)#

Convert persisted neighbors into a weighted connectivity graph.

Parameters:
  • neighbors (ArtifactRef) – Neighbors artifact.

  • local_connectivity (float) – UMAP-style local-connectivity adjustment.

  • bandwidth (float) – Distance-kernel bandwidth multiplier.

  • invalidate_cache (bool) – Force a new connectivity artifact.

Return type:

ArtifactRef

Returns:

Reference to the connectivity-map artifact.

EmbeddingsAccessor.initialization(coordinates, *, n_centroids=1000, rand_state=4466, batch_size=None, kmeans_sampling=0.1, kmeans_batch_size=10000, invalidate_cache=False)#

Build or reuse K-means initialization for explicit coordinates.

Pass the returned reference explicitly to an embedding operation.

Parameters:
  • coordinates (ArtifactRef) – Coordinate artifact to cluster, such as a reduction.

  • n_centroids (int) – Requested number of K-means centroids, at least 2.

  • rand_state (int) – K-means random seed, from 0 to 2**32 - 1.

  • batch_size (int | None) – Number of cells processed per block.

  • kmeans_sampling (float) – Fraction of cells considered during centroid seeding.

  • kmeans_batch_size (int) – Number of cells per internal K-means update.

  • invalidate_cache (bool) – Force a new initialization artifact.

Return type:

ArtifactRef

Returns:

Reference to the embedding-initialization artifact.

Raises:
  • TypeError – If coordinates is not an ArtifactRef or a setting has the wrong type, such as text for kmeans_sampling.

  • ValueError – If a setting is out of range, such as n_centroids below 2, rand_state outside 0 to 2**32 - 1, or kmeans_sampling outside (0, 1].

  • MemoryError – If the fit exceeds the memory budget.

GraphAccessor.load(graph, *, symmetric=None, upper_only=None, use_k=None)#

Load the cell neighborhood as a scipy sparse matrix.

Parameters:
  • graph (ArtifactRef) – Connectivity-map or integrated-graph artifact.

  • symmetric (bool | None) – If True, returns the fuzzy union of the directed edge weights, A + A^T - A * A^T with * the elementwise product, so a pair of cells joined in both directions keeps a + b - a * b rather than the sum of its two weights.

  • upper_only (bool | None) – If True, then only the values from upper triangular of the matrix are returned. This is only used when symmetric is True.

  • use_k (int | None) – Number of top k-nearest neighbors to keep in the graph. It must be an integer from 1 to the graph’s k. By default, all neighbors are used. (Default value: None)

Return type:

csr_matrix

Returns:

A scipy sparse matrix representing cell neighborhood graph.