Integration and metrics API reference#
Prefer the DataStore methods below in analysis code.
integration.modalities accepts two or more exact source refs. WNN is the default; it consumes neighbor
artifacts and follows each one’s named native reduction or batch-correction coordinates. SNN is
explicit and consumes connectivity-map artifacts. The returned integrated-graph reference is the
exact downstream graph argument.
WNN does not accept imported-coordinate ancestry. coordinates is a provenance input on neighbor
and ANN artifacts, not a separate artifact kind.
wnn = ds.integration.modalities([rna_neighbors, adt_neighbors])
snn = ds.integration.modalities([rna_graph, adt_graph], method="snn")
WNN also rejects neighbors built on normalized values, as an RNA pipeline run with
pca={"dims": 0} builds them, because it weighs each assay by its reduced coordinates; SNN
integrates such graphs.
ds.pipeline.multimodal([rna_run, adt_run]) runs this integration over completed pipeline runs of
the same cells, then embeds and clusters the integrated graph as a durable run (Analysis pipeline API reference).
Integration holds its inputs in memory: SNN every source graph with a float64 matrix of
shared-neighbor fractions per graph, about 16 * n_graphs + 20 bytes per edge, and WNN every
assay’s neighbors and coordinates with the integrated graph and its modality weights. Both
compare that estimate with the datastore’s memory budget before they load a graph or coordinate
and raise MemoryError over it, naming the bytes, the cells, the neighbors, the dimensions, and
the limit. reduction.harmony does the same before it reads coordinates, with the estimate of
harmony_peak_bytes(): it holds the float64 coordinates three
times, as its input, its original copy, and its corrected copy, and float64 soft cluster
assignments with n_clusters values per cell, about 1.5 KB per cell with 30 dimensions and 100
clusters, plus per-level regression sums of levels x n_clusters x dims floats, so n_clusters
in harmony_params and the dimensions set its memory. Its admission also counts the batch
labels, which it reads before it admits the fit and holds until the fit ends, at the size of their
text objects: about 60 bytes per cell for each batch column of short labels. These estimates are
counts of the arrays each step allocates;
the budget compares them with its limit, and they are not a cap on the memory of the process (see
Memory and execution).
The default WNN artifact stores one per-cell weight for each input assay. Plot those values with
cytearc.plotting.modality_weights() or the bound
ds.plots.modality_weights(graph=wnn, layout=wnn_layout) accessor. An explicit SNN artifact does
not contain modality weights.
Neighbor-based metrics require neighbors; graph metrics require graph; reduction metrics
require their exact coordinate artifact. Batch-mixing methods and biological-annotation cLISI or
graph connectivity intentionally read imported metadata columns over the rows selected by artifact
lineage. They are not an indirect path for scoring CyteArc-produced clusterings. Concordance instead
accepts two exact clustering refs with the same frozen cell selection. None accepts a storage path
or an omitted artifact input.
mixing = ds.integration.compute_ilisi("batch", rna_neighbors)
connectivity = ds.integration.compute_graph_connectivity("cell_type", snn)
agreement = ds.clusters.compute_concordance(rna_clusters, adt_clusters, metric="ari")
The metric methods return dataset-level scalar summaries such as iLISI, cLISI, and graph
connectivity. cytearc.metrics.compute_lisi() returns per-cell LISI values from KNN arrays.
Metric label columns must label every scored cell: masked, NaN, None, and blank labels raise
ValueError.
All LISI entry points resolve perplexity=None to floor(k / 3), where k is the
number of neighbors. Explicit values are capped at k / 3
with a warning when the graph is too small. With three to five neighbors, the default
is 1, so scores can approach 1 when the nearest distance is unique. Tied distances can
produce larger values.
Cluster separability summaries expose macro_f1_fold_sd, the sample standard deviation
of macro F1 across validation folds. Interpret it as fold variability.
DataStore methods#
Integrate explicit graph or neighbor artifacts across assays. |
|
|
Compute scIB integration LISI on a persisted KNN graph. |
|
Compute scIB cell-type LISI on a persisted KNN graph. |
|
Summarize batch LISI as a normalized neighborhood-mixing score. |
|
Score label connectivity on a persisted, symmetrized assay graph. |
|
Calculate modified silhouette scores for evaluating cluster separation. |
|
Compare two immutable clustering artifacts using ARI or NMI. |
|
Evaluate cluster-label separability in PCA coordinates. |
- IntegrationAccessor.modalities(sources, method='wnn', chunk_size=10000, invalidate_cache=False, l2_normalize=True)#
Integrate explicit graph or neighbor artifacts across assays.
SNN combines shared edge support across two or more assays. WNN accepts two or more assays and uses Hao-inspired per-cell modality weights. CyteArc WNN scores only the union of the existing self-free KNN rows and uses the distance span from the nearest to the k-th neighbor as its bandwidth, so it is not bit-identical to Seurat’s default wider search and SNN-far bandwidth. WNN neighbors of different counts give a graph of the smallest count, and a warning says so each time the graph is computed or reused.
- Parameters:
sources (
list[ArtifactRef]) – Connectivity-map refs for SNN or neighbor refs for WNN.method (
str) – Choose a method for modality integration. Available options: ‘wnn’: Hao-inspired weighted nearest neighbor integration and ‘snn’: shared nearest neighbor integration.chunk_size (
int) – Number of cells per stored chunk of the integrated edge, weight, and modality-weight arrays. It does not bound memory: integration holds every source graph, and for WNN every source’s coordinates, in memory.invalidate_cache (
bool) – Force a new integrated-graph artifact.l2_normalize (
bool) – L2-normalize modality coordinates during WNN scoring. This algorithmic setting is stored in artifact provenance.
- Return type:
- Returns:
Reference to the integrated-graph artifact. Pass it to embeddings.umap, embeddings.tsne, or the clustering methods as their
graphargument.- Raises:
MemoryError – If the integration exceeds the memory budget.
UnmeasuredCellsError – If a source assay did not measure a selected cell.
WNN modality weights remain in the returned immutable artifact.
- IntegrationAccessor.compute_ilisi(batch_colname, neighbors, *, perplexity=None, scale=True)#
Compute scIB integration LISI on a persisted KNN graph.
- Parameters:
batch_colname (
str) – Cell metadata column containing batch labels.neighbors (
ArtifactRef) – Explicit neighbor artifact to score.perplexity (
float|None) – Effective neighborhood size.Noneusesfloor(k / 3).scale (
bool) – Scale the median LISI by the number of observed batches.
- Return type:
float- Returns:
Median iLISI, scaled so higher values indicate better batch mixing when
scaleis true.
Notes
CyteArc persisted KNN graphs exclude self-neighbors, as required by this metric. The batch column is intentionally an imported metadata input.
- IntegrationAccessor.compute_clisi(annotation_column, neighbors, *, perplexity=None, scale=True)#
Compute scIB cell-type LISI on a persisted KNN graph.
- Parameters:
annotation_column (
str) – Cell metadata column containing imported biological annotations.neighbors (
ArtifactRef) – Explicit neighbor artifact to score.perplexity (
float|None) – Effective neighborhood size.Noneusesfloor(k / 3).scale (
bool) – Invert and scale the median LISI by the number of observed labels.
- Return type:
float- Returns:
Median cLISI, scaled so higher values indicate better label conservation when
scaleis true.
Notes
CyteArc persisted KNN graphs exclude self-neighbors, as required by this metric. The annotation column is intentionally an imported metadata input, not a CyteArc-produced clustering.
- IntegrationAccessor.compute_batch_mixing(label_colname, neighbors, *, perplexity=None)#
Summarize batch LISI as a normalized neighborhood-mixing score.
This computes batch LISI on the supplied KNN graph and rescales its mean against the mixing that perfectly integrated data would reach given the dataset’s batch sizes. Unlike raw LISI, the result is bounded in
[0, 1], which makes it easier to compare across graphs and datasets.- Parameters:
label_colname (
str) – Cell metadata column holding the batch assignment.neighbors (
ArtifactRef) – Explicit neighbor artifact to score.perplexity (
float|None) – Effective neighborhood size; None uses floor(k / 3).
- Return type:
float- Returns:
A value in
[0, 1]. Scores near 1 indicate that neighborhoods mix batches as well as the global composition allows, and scores near 0 indicate poorly mixed batches.- Raises:
ValueError – If KNN inputs are invalid or the column has fewer than two batches.
- IntegrationAccessor.compute_graph_connectivity(annotation_column, graph)#
Score label connectivity on a persisted, symmetrized assay graph.
- Parameters:
annotation_column (
str) – Cell metadata column containing imported biological annotations.graph (
ArtifactRef) – Explicit connectivity-map or integrated-graph artifact.
- Return type:
float- Returns:
Mean fraction of cells retained in the largest connected component for each label.
Notes
Persisted directed edges are treated as undirected. This follows the original scIB symmetrized-graph definition and intentionally differs from the directed strong-component calculation currently used by YosefLab
scib-metrics. The annotation column is an imported biological label, not a CyteArc-produced clustering.
- IntegrationAccessor.compute_graph_silhouette(neighbors, clusters, *, random_seed=4444, sample_size=11)#
Calculate modified silhouette scores for evaluating cluster separation.
This implements a graph-based silhouette score that measures how similar cells are to their own cluster compared to the nearest neighboring cluster.
- Parameters:
neighbors (
ArtifactRef) – Explicit neighbor artifact to score.clusters (
ArtifactRef) – Explicit cluster-label or Paris cluster-cut artifact.random_seed (
int) – Seed used for cluster sampling.sample_size (
int) – Maximum size of each sampled cluster group.
- Return type:
ndarray|None- Returns:
numpy array of silhouette scores for each cluster, or None if computation fails
- Raises:
ValueError – If graph, labels, sampling, or embedding data are invalid
Notes
Scores range from -1 to 1: - Near 1: Cluster is well-separated from neighboring clusters - Near 0: Cluster overlaps with neighboring clusters - Near -1: Cluster may be incorrectly assigned
Implementation uses sampling for efficiency with large datasets. NaN values indicate clusters that couldn’t be scored due to size constraints.
- ClustersAccessor.compute_concordance(first, second, metric='ari')#
Compare two immutable clustering artifacts using ARI or NMI.
Both clusterings must carry the exact same cell-selection reference. This allows clusterings from different assays to be compared without consulting mutable cell metadata.
- Parameters:
first (
ArtifactRef) – First cluster-label or Paris cluster-cut artifact.second (
ArtifactRef) – Second cluster-label or Paris cluster-cut artifact.metric (
Literal['ari','nmi']) –"ari"for the adjusted Rand index or"nmi"for normalized mutual information.
- Return type:
float- Returns:
Agreement between the two partitions. ARI ranges from -1 to 1 and NMI from 0 to 1, with higher values meaning stronger agreement.
- Raises:
ValueError – If the clusterings do not use the same frozen cell selection or the metric name is invalid.
- IntegrationAccessor.compute_cluster_separability(pca, clusters, *, n_folds=5, max_sample_cells=50000, max_silhouette_cells=10000, random_seed=4444, svm_c=1.0, svm_max_iter=10000)#
Evaluate cluster-label separability in PCA coordinates.
- Return type:
Harmony#
ds.reduction.harmony(reduction, batch_columns, harmony_params=...) corrects reduced coordinates
for one or more batch columns with CyteArc’s implementation of
Harmony2 (Patikas et al. 2026), which builds on
Harmony (Korsunsky et al. 2019). It was written from
the two papers and is not expected to reproduce other Harmony implementations number for number.
corrected = ds.reduction.harmony(pca, ["batch"], harmony_params={"theta": 1.0, "n_clusters": 50})
A fit repeats rounds of two steps:
Soft clustering. Each cell, scaled to unit length, is assigned softly to
n_clustersclusters whose centroids start from k-means++ seeds drawn from the cells.sigmasets how soft the assignments are, andthetapenalizes clusters whose mix of batch levels departs from that of all cells. The penalty takes Harmony2’s stabilized form: when a batch level has no cells in a cluster, the pull of the cluster on that level’s cells stays bounded, where in the 2019 form it grew with the cluster’s size. Cells are updated in blocks ofblock_sizeof the cells, each block against batch counts that leave its own cells out.Correction. For every cluster, a ridge regression weighted by the cells’ assignments to the cluster fits the original coordinates on an unpenalized intercept and one term per batch level. A cell’s corrected coordinates are its original coordinates minus the terms of its own batch levels, summed over the clusters with its assignments as weights; the intercepts, which hold the clusters’ positions, are not subtracted. By default the penalty of a level in a cluster is
ridge_alphatimes the level’s expected mass there, its share of all cells times the cluster’s total assignment, so a level with far less than its expected mass in a cluster gets almost no correction from that cluster. A level whose assignment mass in a cluster is belowprune_thresholdof its cells is left out of that cluster’s regression.
Each round runs clustering passes until the objective changes by at most epsilon_cluster of its value or max_iter_cluster passes have run, then corrects the coordinates. The fit has converged when the objective changes between rounds by at most epsilon_harmony of its value twice in a row, or, from the fifth round on, when it drifts by at most epsilon_harmony of its value per round once its alternation from round to round is averaged out. The second test ends fits whose clustering and correction settle into two states that take turns, so that the objective alternates between two close values instead of repeating one; asking for two small changes in a row keeps such an alternation from stopping a fit by chance. A fit stops as soon as it converges, so max_iter_harmony only bounds fits that settle slowly; its default of 40 rounds, where the 2019 paper used 10, leaves room for large, heterogeneous datasets. A fit that reaches max_iter_harmony rounds, two or more, while its objective is still drifting stops there and warns, each time the correction is computed or reused; raising max_iter_harmony gives it more rounds. With several batch columns, their penalties add and each regression has one term per level of every column.
harmony_params takes the keyword options of fit_harmony(), all but
nthreads, which the datastore sets:
Key |
Default |
Meaning |
|---|---|---|
|
the cell count divided by 30, rounded half to even, between 1 and 100 |
number of soft clusters; an explicit value lies between 1 and the cell count |
|
|
diversity penalty: one value, one per batch column, or one per batch level; finite and at least 0 |
|
|
softness of the assignments: one value or one per cluster; finite and positive |
|
|
multiplies each level’s |
|
|
a fixed ridge penalty for every cluster: one value, one per batch column, or one per batch level; finite and positive. With several batch columns it must be at least 1e-6 times each cluster’s assignment mass, or the fit raises |
|
|
scale of the dynamic penalty; positive. Passing it with |
|
|
smallest assignment mass in a cluster, as a fraction of a level’s cells, for the level to enter that cluster’s regression; at least 0 and below 1. With 0, only levels without mass are left out |
|
|
fraction of the cells updated together; above 0 and at most 1 |
|
|
most clustering passes per round; at least 1 |
|
|
most rounds of clustering and correction; at least 1. The fit stops as soon as it converges, so the limit only bounds slow fits; the 2019 paper used 10 |
|
|
relative change of the objective between consecutive passes that ends a round’s clustering, after at least two passes; at least 0 |
|
|
relative change of the objective per round that ends the fit: the objective changed by at most this fraction of its value in each of the last two rounds (in the one round when only two have run), or, from five rounds on, the average of two consecutive round objectives changes by at most this fraction per round. The second test ends fits whose clustering and correction settle into a cycle that returns to nearly the same state every other round; at least 0 |
|
|
seed of the cell update order and the k-means++ seeds; an integer of at least 0 |
Values given per batch level follow design order: the batch columns in their order and, within a
column, a categorical’s used categories in their declared order or the sorted values of any other
column. HarmonyResult.batch_levels lists that order, and HarmonyResult.parameters["phiColumns"]
names each level "{column}_{level}".
The datastore checks harmony_params with
validate_harmony_parameters() before it reads data, and a
pipeline recipe checks harmony={"harmony_params": ...} when it validates its call, before it
creates a run record. Keys of the earlier Harmony implementation raise ValueError:
Earlier key |
Use instead |
Message |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
nothing; clusters are seeded with k-means++ |
|
max_iter_harmony=0, which clustered without correcting, now raises max_iter_harmony must be at least 1, and ridge_penalty must be positive where lamb accepted 0. Other unknown keys raise
ValueError listing the supported keys. Passing an earlier key to fit_harmony itself raises
Python’s TypeError for an unexpected keyword argument.
A batch_correction artifact stores the corrected coordinates and the fitted state that
Symphony-style mapping references copy. The soft assignments are not stored.
Array or attribute |
Shape, dtype |
Contents |
|---|---|---|
|
cells by dims, float32 |
corrected coordinates |
|
clusters, float64 |
total assignment of each cluster |
|
clusters by dims, float64 |
assignment-weighted means of the uncorrected coordinates |
|
clusters by dims, float64 |
assignment-weighted means of the corrected coordinates |
|
dims by clusters, float64 |
unit-length centroids of the final clustering; a cluster whose cells cancel keeps a zero centroid |
|
clusters, float64 |
|
|
clusters by batch levels, float64 |
ridge penalties of the last correction |
|
clusters by batch levels, bool |
levels that entered each cluster’s last regression |
attribute |
one list of strings per batch column |
batch levels in design order |
attribute |
mapping |
|
attribute |
mapping |
the diagnostics behind the warning of a fit that stops before converging: |
HarmonyResult.parameters records the settings the fit used, with camelCase keys: algorithm
("harmony2"), nClusters, theta per batch level after tau, tau, sigma per cluster,
ridge ("dynamic" or "fixed") with ridgeAlpha or ridgePenalty, pruneThreshold,
blockSize, maxIterCluster, maxIterHarmony, epsilonCluster, epsilonHarmony,
randomState, initialization ("kmeans++"), and phiColumns. It also records how the fit ran:
rounds, converged, objective, the objective at the end of each round’s clustering, and
clusterPasses, the clustering passes of each round.
Reuse requires every array and the diagnostics in this table. A correction saved by the earlier implementation stored a ridge array instead of ridge_penalty and active_levels, so it stays listable, loadable, and traceable, but no request reuses it: the next request computes a new correction, and the ANN index, neighbors, graphs, embeddings, clusters, and mapping references built on it are computed again. Mapping references built from an earlier correction still load and map.
- cytearc.embeddings.fit_harmony(values, metadata, *, n_clusters=None, theta=2.0, sigma=0.1, tau=0.0, ridge_penalty=None, ridge_alpha=None, prune_threshold=1e-05, block_size=0.05, max_iter_cluster=200, max_iter_harmony=40, epsilon_cluster=1e-05, epsilon_harmony=0.0001, random_state=4466, nthreads=1)#
Correct batch effects in reduced coordinates with Harmony2.
Harmony alternates two steps. A soft clustering of the unit-normalized cells favors clusters in which every batch is represented in proportion to its size; then, within each cluster, a ridge regression of the original coordinates on the batch design estimates each batch’s offset, and every cell subtracts the offsets of its batches, weighted by its cluster assignments. The regression keeps an unpenalized intercept per cluster, so the cell-type structure stays. The two steps repeat until the clustering objective settles between rounds. This is CyteArc’s implementation of Harmony2: k-means++ seeding, the stabilized diversity penalty, a dynamic ridge penalty and batch pruning, with the online block updates of the 2019 method.
- Parameters:
values (
ndarray) –(dims, cells)real coordinates, usually principal components, one column per cell.metadata (
DataFrame) – One row per cell and one column per batch variable. A categorical column keeps the declared order of its used categories; any other column orders its values with Python’ssorted. A column’s values may mix number types, such as1and2.5, as long as they group as their text reads.n_clusters (
int|None) – Number of soft clusters. Default: the cell count over 30, rounded half to even, kept between 1 and 100.theta (
float|Sequence[float] |ndarray) – Diversity penalty, non-negative: a scalar, one value per batch column, or one value per batch level in design order. Larger values mix batches more strongly. Default 2.sigma (
float|Sequence[float] |ndarray) – Entropy weight of the soft assignments, positive: a scalar or one value per cluster. Larger values give softer assignments. Default 0.1.tau (
float) – Discounting of theta for small batches: each level’s theta is scaled by1 - exp(-(N_b / (n_clusters * tau))^2). Default 0, no discounting.ridge_penalty (
float|Sequence[float] |ndarray|None) – A fixed, positive ridge penalty of the batch coefficients: a scalar, one value per batch column, or one value per batch level. Default None: the dynamic penaltyridge_alpha * E_kbof Harmony2, the mass that batchbwould have in clusterkif batch and cluster were independent.ridge_penalty=1.0gives the fixed penalty of the 2019 method. With several batch columns, a fixed penalty must be at least 1e-6 times each cluster’s assignment mass (the summed assignments of its cells); a smaller one raisesValueError, because float64 cannot solve those regressions accurately. With one batch column any positive penalty is solved accurately.ridge_alpha (
float|None) – Scale of the dynamic ridge penalty, positive. Default None, which means 0.2. Cannot be combined withridge_penalty.prune_threshold (
float) – A batch level enters clusterk’s regression only when its mass there,O_kb, is positive and at least this fraction of its cell countN_b; in[0, 1). Default 1e-5.block_size (
float) – Fraction of the cells updated together in each online block of the clustering, in(0, 1]. Default 0.05.max_iter_cluster (
int) – Clustering passes per round, at most; at least 1. Default 200.max_iter_harmony (
int) – Rounds of clustering and correction, at most; at least 1. The fit stops as soon as it converges, so this only bounds fits that settle slowly. Default 40, where the 2019 paper used 10: large, heterogeneous datasets often need more than 10 rounds.epsilon_cluster (
float) – Relative change of the objective between consecutive passes that ends a round’s clustering, after at least two passes. Default 1e-5.epsilon_harmony (
float) – Relative change of the objective per round that ends the fit. The fit has converged when the objective changed by at most this fraction of its value in each of the last two rounds (in the one round when only two have run), or, from five rounds on, when the average of two consecutive round objectives changes by at most this fraction per round. Clustering and correction can settle into a cycle that returns to nearly the same state every other round, so consecutive objectives alternate around a settled level; the second test ends such fits, and asking for two small changes in a row keeps an alternating objective from stopping the fit by chance. Default 1e-4.random_state (
int) – Non-negative seed of the fit’s own random generator; the global NumPy state is never used. Default 4466.nthreads (
int) – Threads for BLAS and the Numba kernels. Results do not depend on it, up to the last bits of BLAS sums. Default 1.
- Return type:
- Returns:
The corrected coordinates with the soft clustering, centroids and penalties of the final round, and a record of the resolved options and the fit’s progress in
parameters.- Raises:
TypeError – If
valuesdoes not hold real numbers,metadatais not a DataFrame, or an option has the wrong type.ValueError – If an argument is out of range, the metadata does not describe the cells, a batch column holds values that would form one batch but print differently, such as
1,1.0andTrue, values that print alike but would form separate batches, such as1and"1", or values that cannot be ordered, such as text beside numbers, the values are not finite, a fixedridge_penaltyis too small for several batch columns, or the fit produces non-finite values or clusters without cells.numpy.linalg.LinAlgError – If a regression system is not positive definite.
References
Korsunsky I, et al. Fast, sensitive and accurate integration of single-cell data with Harmony. Nat Methods 16, 1289-1296 (2019). doi:10.1038/s41592-019-0619-0
Patikas N, Yao H, et al. Integration of large, complex single-cell datasets with Harmony2. bioRxiv (2026). doi:10.64898/2026.03.16.711825
- cytearc.embeddings.harmony.validate_harmony_parameters(parameters)#
Check Harmony parameters before any data is read; return a new dict equal to the input.
The checks need no data: the keys, the types, and the ranges of the values. Rules that depend on the data, such as the cluster count against the cell count or the length of per-level values, are checked by the fit.
- Parameters:
parameters (
Mapping[str,Any] |None) – A mapping of option names ofcytearc.embeddings.fit_harmony()to values, or None.- Return type:
dict[str,Any]- Returns:
A new dict equal to
parameters, with the values untouched;{}for None.- Raises:
TypeError – If
parametersis not a mapping with text keys, or a value has the wrong type.ValueError – If a key is not an option, was renamed or removed, or a value is out of range.
- cytearc.embeddings.harmony.harmony_cluster_count(n_cells, n_clusters=None)#
Return the cluster count a fit of n_cells cells uses: n_cells / 30 rounded half to even, kept in [1, 100], or the explicit count.
- Parameters:
n_cells (
int) – The number of cells.n_clusters (
int|None) – An explicit cluster count, or None for the default.
- Return type:
int- Returns:
The cluster count.
- Raises:
TypeError – If an argument is not an integer.
ValueError – If
n_cellsis below 1 orn_clusterslies outside[1, n_cells].
- cytearc.embeddings.harmony.harmony_peak_bytes(n_cells, dims, n_clusters, column_levels, *, n_combinations=None, block_size=0.05)#
Return the bytes that a Harmony2 fit holds at its peak, with its float64 input.
The bound covers the caller’s
(dims, cells)float64 input, which the DataStore fills before the fit, and the fit’s own arrays at the largest of its phases: encoding the batch design, k-means++ seeding, clustering, and correction. Per cell, the dominant terms are24 dims + 8 n_clustersbytes: the input, original and corrected coordinates, and the assignments.- Parameters:
n_cells (
int) – The number of cells.dims (
int) – The number of dimensions.n_clusters (
int) – The cluster count of the fit.column_levels (
Sequence[int]) – The number of levels of each batch column.n_combinations (
int|None) – The number of distinct level combinations among the cells; by default the largest it can be.block_size (
float) – The fit’sblock_size.
- Return type:
int- Returns:
The peak in bytes.
- Raises:
TypeError – If an argument has the wrong type.
ValueError – If an argument is out of range.
- class cytearc.embeddings.HarmonyResult(original, corrected, assignments, centroids, sigma, ridge_penalty, active_levels, batch_columns, batch_levels, parameters)#
Final Harmony2 state: corrected coordinates and the soft clustering that Symphony reference mapping needs.
The state is that of the last round, whether or not the objective settled;
parameters["converged"]records which.- original#
(dims, cells)float64, an independent copy of the input coordinates.
- corrected#
(dims, cells)float64, the batch-corrected coordinates.
- assignments#
(clusters, cells)float64 soft cluster assignments; each column sums to 1.
- centroids#
(dims, clusters)float64 cosine centroids of the corrected cells, unit or zero columns.
- sigma#
(clusters,)float64 entropy weight of each cluster.
- ridge_penalty#
(clusters, levels)float64 ridge penalty of the last correction round.
- active_levels#
(clusters, levels)bool, the batch levels that entered each cluster’s last regression.
- batch_columns#
The batch metadata columns, in the order of the design.
- batch_levels#
The levels of each batch column, as text, in design order.
- parameters#
JSON-compatible record of the resolved options and of the fit’s progress.
Metrics#
Methods and classes for evaluation
- class cytearc.metrics.ClusterSeparabilityResult(clustering_scores, cluster_scores, confusion, sample_indices)#
- cytearc.metrics.clisi_knn(distances, indices, cell_labels, perplexity=None, scale=True)#
Compute the median cell-type LISI score from a self-free KNN graph.
When scaled, higher values indicate better conservation of cell labels. This follows the cLISI aggregation and scaling used by scIB.
The KNN arrays must exclude each cell from its own neighbor row. CyteArc’s persisted KNN graphs satisfy this requirement. Self-including KNN arrays produce a different statistic and are not adjusted automatically.
- Return type:
float
References
Luecken et al. 2022 doi: 10.1038/s41592-021-01336-8
- cytearc.metrics.compute_lisi(distances, indices, metadata, label_colnames, perplexity=None)#
Score how mixed each cell’s KNN neighborhood is for each label column.
Each cell weights its neighbors with an exponential kernel on their distances, tuned per cell until the weights reach the requested perplexity. The score is the inverse Simpson index of the weighted label frequencies, the effective number of labels around the cell: 1 when all the weight falls on one label, rising to the number of labels when it is spread evenly.
- Parameters:
distances (
ndarray|Array) – KNN distances, one row per cell, as a NumPy or Zarr array.indices (
ndarray|Array) – KNN neighbor indices with the same shape asdistances.metadata (
DataFrame) – Cell table with one row per cell.label_colnames (
Iterable[str]) – Columns ofmetadatato score.perplexity (
float|None) – Effective neighborhood size; None uses floor(neighbor count / 3).
- Return type:
ndarray- Returns:
Scores with shape (n_cells, n_labels), one column per entry of
label_colnames.- Raises:
ValueError – If the KNN arrays are not two-dimensional of one shape, the metadata does not hold one row per cell, or a label column holds missing values, values that would form one label but print differently, such as
1,1.0andTrue, or values that print alike but would form separate labels, such as1and"1".
References
Korsunsky et al. 2019 doi: 10.1038/s41592-019-0619-0
- cytearc.metrics.graph_connectivity(edges, labels, batch_rows=100000, *, weights=None)#
Score label connectivity on a persisted, implicitly undirected graph.
Each directed edge is treated as an undirected connection. The result is the mean, across labels, of the fraction of cells in the largest connected component for that label. When weights are supplied, zero-weight edges do not connect cells.
This follows the original scIB symmetrized-graph definition. It does not match the directed strong-component calculation currently implemented by YosefLab
scib-metrics. Labels that would form one label but print differently, such as1,1.0andTrue, or that print alike but would form separate labels, such as1and"1", raiseValueError.- Return type:
float
References
Luecken et al. 2022 doi: 10.1038/s41592-021-01336-8
- cytearc.metrics.ilisi_knn(distances, indices, batch_labels, perplexity=None, scale=True)#
Compute the median integration LISI score from a self-free KNN graph.
When scaled, higher values indicate better batch mixing. This follows the iLISI aggregation and scaling used by scIB.
The KNN arrays must exclude each cell from its own neighbor row. CyteArc’s persisted KNN graphs satisfy this requirement. Self-including KNN arrays produce a different statistic and are not adjusted automatically.
- Return type:
float
References
Luecken et al. 2022 doi: 10.1038/s41592-021-01336-8
- cytearc.metrics.label_concordance_score(label_sets, metric='ari')#
Compare two label partitions using ARI or NMI.
- Parameters:
label_sets (
Sequence[ndarray]) – Two arrays of labels to compare.metric (
Literal['ari','nmi']) – Either"ari"or"nmi".
- Return type:
float- Returns:
Label agreement. ARI ranges from -1 to 1 and NMI from 0 to 1.
- Raises:
ValueError – If
label_setsdoes not hold two one-dimensional arrays of one length without missing values, an array holds values that would form one label but print differently, such as1,1.0andTrue, or values that print alike but would form separate labels, such as1and"1", ormetricis neither"ari"nor"nmi".
- cytearc.metrics.lisi_batch_mixing_score(lisi_scores, batch_labels)#
Normalize mean batch LISI against the dataset’s batch proportions.
Raw batch LISI depends on how many batches are present and how unevenly cells are split between them, so its values are hard to compare across datasets. This score rescales the mean batch LISI onto a fixed range by dividing the observed neighborhood mixing by the mixing that perfectly integrated data would reach. The reference point is the inverse Simpson index of the global batch proportions, which is the LISI a neighborhood would show if it mirrored the whole dataset.
- Parameters:
lisi_scores (
ndarray) – Per-cell batch LISI values, typically the array returned bycompute_lisi()for a batch label.batch_labels (
Sequence[object] |ndarray) – Batch assignment for each cell, aligned withlisi_scores.
- Return type:
float- Returns:
A value in
[0, 1]. Scores near 1 mean neighborhoods mix batches as well as the global composition allows, and scores near 0 mean batches stay separated.- Raises:
ValueError – If the inputs are misaligned, contain non-finite scores or missing labels, assign the cells to fewer than two batches, or the labels hold values that would form one batch but print differently, such as
1,1.0andTrue, or values that print alike but would form separate batches, such as1and"1".
- cytearc.metrics.silhouette_scoring(ds, graph, hvg_data, assay_type, res_label, *, cell_key='I', random_seed=4444, sample_size=11, distance_metric, neighbor_indices=None, neighbor_distances=None)#
Compute modified silhouette scores for clusters in single-cell data.
This implementation differs from the standard silhouette score by using a graph-based approach and comparing clusters to their nearest neighbors.
- Parameters:
ds (cytearc.datastore.datastore.DataStore) – DataStore object containing cell metadata
graph (
csr_matrix|None) – Optional CSR matrix representing the weighted KNN graphhvg_data (
ndarray|Array|ChunkedArray) – Cell-by-dimension matrix whose rows are compared, such as the coordinates behind the KNN graphassay_type (
str) – Type of assay (e.g., ‘RNA’, ‘ATAC’)res_label (
str) – Label for clustering resolutiondistance_metric (
Literal['l2','cosine','ip']) – Neighbor metric used to compare sampled rows: ‘l2’, ‘cosine’, or ‘ip’. Inner-product distances are one minus the inner product, clipped at zero, so rows whose inner products exceed one compare as identical.
- Returns:
Array of silhouette scores for each cluster, or None if cluster labels are not found
- Return type:
ndarray|None- Raises:
ValueError – If a selected cell has a missing cluster label, either a null value or a row that the column’s linked missing mask flags, or the labels hold values that would form one cluster but print differently, such as
1,1.0andTrue, or values that print alike but would form separate clusters, such as1and"1".
Notes
Scores are calculated using a sampling approach for efficiency. NaN values indicate clusters that couldn’t be scored due to size constraints.
CyteArc’s iLISI and cLISI use the scIB median and scaling definitions over CyteArc’s self-free persisted KNN arrays.
Graph connectivity follows the original scIB symmetrized-graph definition.
YosefLab scib-metrics currently uses directed strong components for graph connectivity, so those values need not match.
See Luecken et al. 2022, doi: 10.1038/s41592-021-01336-8.