Mapping API reference#
A mapping workflow retains every boundary explicitly:
reference_ref = reference_ds.mapping.build_reference(neighbors_ref)
reference = reference_ds.mapping.load_reference(reference_ref)
query_cells = query_ds.snapshot_cell_selection("I")
result_ref = query_ds.mapping.run(reference, query_cells)
result = query_ds.mapping.load_result(result_ref, reference=reference)
transfer_ref = query_ds.mapping.transfer_labels(
result_ref,
reference=reference,
reference_labels="cell_type",
)
transfer = query_ds.mapping.load_label_transfer(transfer_ref)
MappingReference pins the exact feature selection and reference model. Query overlap is another
feature-selection artifact. mapping.run returns only the projection ref; loaders, label transfer,
score readers, and score plots require that ref plus the explicit reference. There is no named
mapping registry, live cell_key routing, omitted-result lookup, or reference fallback.
A handle is validated against its store in full when mapping.load_reference loads it. Every later
operation that takes the handle checks the stored artifact record and its attributes against the
handle, validates the cell selection against the current ordered cell IDs, and recomputes the digest
of the handle’s arrays. Repeated label transfer and score calls
avoid reading the reference model payload, index and neighbors. Each operation also compares the
prepared dataset fingerprint stored on the reference assay with the fingerprint the handle carries;
an unprepared or different reference dataset is rejected. Reading
reference cell metadata also validates the stored selection against the current ordered cell IDs.
A handle whose arrays or references changed is rejected with does not match its stored artifact;
reload it with mapping.load_reference.
A query projection records the prepared dataset fingerprint of the query assay and reuses a complete
projection only for the same query dataset, cells, overlap, reference, and options. A query cell is
uninformative when its raw counts are zero in every reference feature that the query measured. Such
a cell keeps its projection row but is flagged in uninformative; it receives no transferred label,
adds no mapping score, and does not enter Symphony query-batch statistics or
queryScaledDispersion. diagnostics["uninformativeCellCount"] counts these cells.
queryScaledDispersion averages the squared reference-scaled deviation of informative cells over
the measured reference features only, so it does not depend on missing_feature_policy.
Projections written before this contract are rejected with an instruction to re-run mapping.run.
mapping.run matches query features to the reference features by exact feature ID. A query that names the same genes with another ID scheme, such as gene symbols against a reference of Ensembl IDs, maps with feature_key="names", which matches them by exact feature name. The reference features’ names are read from the reference assay at the reference’s feature selection, so every saved reference can map by name. A reference whose features share a name is refused with the names and their IDs, since one query feature would then match several reference features. Query features that share a name add their counts, as DataStoreMerge(feature_key="names") sums them. The projection and its overlap selection record feature_key only when it is "names", so a match by name is a separate artifact and a match by ID keeps its identity. featureCoverage is the share of reference features that some query feature matches.
Label transfer#
mapping.transfer_labels saves a label transfer as two query-owned artifacts. It first reads
reference_labels, a cell-metadata column of the reference datastore or a cell-label artifact in
it such as cluster_labels, cluster_cut, or clusters.relabel_by_overlap, and freezes those labels into the
query datastore as a datastore-scoped reference_labels artifact. That artifact holds the
reference classes and one class code per selected reference cell. Its identity records the mapping
reference, the source column or the source artifact as an ExternalArtifactRef, and a fingerprint
of the labels, so unchanged labels reuse one frozen copy and changed labels create another. A
missing, blank, or masked reference label never votes.
It then saves a label_transfer artifact in the projection’s assay. Its inputs are the projection,
the frozen reference labels, and the projection’s query cell selection; its parameters are
threshold_fraction, max_distance, and the vote algorithm version. Each query cell takes the
label with the largest share of its neighbors’ inverse-distance weight. A cell abstains when it is
uninformative, has no labeled neighbor, ties between labels, falls below threshold_fraction, or
has its nearest reference neighbor beyond max_distance. Abstention is stored as the linked
missing mask of the labels array, never as a placeholder string, so a reference class named
"NA" stays a class. The artifact also stores the reference classes, each cell’s neighbor votes,
and the evidence below, and a payload fingerprint that loading verifies.
A complete transfer with the same projection, frozen labels, and decision rule is reused. A
read-only query datastore raises PermissionError before anything is computed or written when no
match exists. mapping.load_label_transfer reads only the query datastore, so a saved transfer loads
without the reference and never changes when the reference annotations change. Because
label_transfer is a cell-label artifact, it can color an embedding, group statistical tests and
plots, and seed select_cells like a clustering; consumers that need a label for every cell reject
it while it contains abstentions. DataStore.artifacts.lineage(transfer_ref, references=reference) follows
the transfer into the reference datastore.
LabelTransferResult.evidence has one row per projected query cell, in the order of
cell_selection, with these columns:
Column |
Meaning |
|---|---|
|
Transferred label, missing where the cell abstained |
|
Label the vote favored before the threshold and distance rules |
|
Share of neighbor weight that supports the winning label |
|
Winning share minus the runner-up share |
|
Entropy of the vote among labeled neighbors |
|
Distance to the nearest reference neighbor |
|
Percentile of that distance among reference nearest-neighbor distances |
|
Whether the cell received no label |
|
|
Vote metrics are NaN for uninformative cells. Projection-level diagnostics such as
featureCoverage and queryScaledDispersion stay in mapping.load_result(...).diagnostics.
label_vote_shares(labels) takes the label of each cell as a pandas Series indexed by cell ID, such as pd.Series(values, index=transfer.cell_ids), where cell_ids holds the IDs of the transfer’s cells in the order of its evidence, and returns a NumPy array of each cell’s vote share for its label, in that order. prediction_sets(calibration_nonconformity, alpha) forms split-conformal prediction sets from the saved votes, calibrated with one minus those shares on held-out cells. Both need the per-neighbor vote matrices, which hold one column per saved neighbor, so mapping.load_label_transfer loads them only with load_votes=True. Each array that a load reads is checked against the digest recorded when the transfer was written.
- class cytearc.MappingReference(datastore, ref, assay_name, reduction, ann_index, neighbors, cell_selection, feature_selection, batch_correction, dataset_fingerprint, selected_cell_count, model, symphony_state, feature_ids, metadata, reference_distance_quantiles, reference_distance_values, payload_fingerprint, model_digest, normalization_arrays=<factory>)#
An immutable scaled-PCA reference loaded from a CyteArc Zarr store.
payload_fingerprintis the stored payload fingerprint the handle was loaded against andmodel_digestthe digest of the arrays it was given;validate_mapping_reference_bindingcompares both with the store and with the handle instead of re-reading the payload.- current_model_digest()#
Recompute the digest of the arrays this handle holds.
- Return type:
str
- fetch_cell_column(column)#
Fetch one reference cell column through the stored cell selection.
- Return type:
ndarray
- property size_factor: float | None#
The size factor of library-size values, or None for other values.
- validate_dataset_fingerprint()#
Check the reference assay against the fingerprint the handle carries.
- Return type:
None
- validate_frozen_axes()#
Validate the exact stored cell and feature axes used by the reference.
- Return type:
None
- class cytearc.MappingResult(ref, n_cells, correction_method, diagnostics, reference, indices=None, distances=None, uninformative=None)#
One loaded query projection and its optional neighbor arrays.
uninformativemarks query cells whose raw counts are zero in every reference feature that the query measured. Their neighbor rows are stored but carry no query evidence, so label transfer and mapping scores skip them.- property cell_selection: ArtifactRef#
Exact frozen query-row selection for this loaded projection.
- property feature_selection: ArtifactRef#
Exact frozen query-feature selection for this loaded projection.
- class cytearc.LabelTransferResult(ref, projection, reference_labels, reference_label_source, cell_selection, cell_idx, cell_ids, threshold_fraction, max_distance, categories, evidence, vote_class_codes=None, vote_class_fractions=None)#
One loaded label transfer: transferred query labels and their evidence.
evidencehas one row per projected query cell, in the order ofcell_selection;cell_idxgives the matching query cell rows andcell_idstheir cell IDs, which key the per-cell values thatlabel_vote_shares()and the mapping plots take.labelis the transferred label and is missing where the cell abstained.abstentionReasonsays why a cell abstained:uninformative_cell(no counts in any measured reference feature),no_labeled_neighbors,tied_vote,below_threshold(voteFractionbelowthreshold_fraction), orbeyond_max_distance(nearestDistanceabovemax_distance).candidateLabelis the label that the vote favored before the threshold and distance rules, so other thresholds can be compared without a new transfer.reference_labelsis the frozen copy of the reference labels in the query datastore, andreference_label_sourcenames where they were read: a reference cell-metadata column, or a reference label artifact.vote_class_codesandvote_class_fractionshold, for each cell, the reference classes that its neighbors voted for, as positions incategories, padded with -1, and each class’s share of the neighbor weight. These matrices hold one column per saved neighbor, so they are loaded only when requested, withmapping.load_label_transfer(transfer, load_votes=True);label_vote_shares()andprediction_sets()need them.Return each cell’s share of neighbor vote weight for a given label.
labelsholds the label of each projected query cell, such as the known labels of held-out calibration cells, as a pandas Series indexed by cell ID; labels of other cells are left out. A label that is not a reference class has a share of zero. Missing labels and uninformative cells give NaN. One minus these shares is the nonconformity thatprediction_sets()calibrates with.- Raises:
TypeError – If
labelsis not a Series indexed by cell ID, such as an array, whose labels would land on cells by position.ValueError – If
labelslacks a cell of the transfer or repeats a cell ID.
- Return type:
ndarray
- property labels: Series#
Transferred labels, missing where a cell abstained.
- property n_cells: int#
Number of projected query cells.
- prediction_sets(calibration_nonconformity, alpha=0.1)#
Return split-conformal prediction sets from the stored votes.
calibration_nonconformityholds one minus the vote share of the true label for held-out calibration cells, which must be exchangeable with these query cells;label_vote_shares()computes those shares. A class joins a cell’s set when its nonconformity is not exceeded by more than a fractionalphaof the calibration cells. Cells without labeled votes get an empty set.- Return type:
Series
DataStore methods#
|
Package a PCA neighbor chain as an immutable artifact. |
Load one mapping reference from an explicit artifact. |
|
Map selected query cells into an immutable prepared reference. |
|
Load one complete query-owned mapping projection. |
|
Return an iterator of reference-sized mapping scores, one per query group. |
|
|
Transfer reference labels to projected query cells and save the result. |
|
Load one complete label transfer from this query datastore. |
- MappingAccessor.build_reference(neighbors, *, invalidate_cache=False)#
Package a PCA neighbor chain as an immutable artifact.
The PCA may scale its features or not, and its values may come from any built-in RNA normalizer:
norm_lib_size,norm_lib_size_log,norm_pearson_residuals,norm_clrornorm_dummy. Queries are normalized as the reference’s cells were. Pearson residuals and CLR fit numbers over those cells, each feature’s share of their counts or its scale; the reference fits them from the cells’ counts, with the function that normalized them, when it is written, and saves them. A read-only store returns a saved reference of the same chain and refuses only to write a new one.- Raises:
ValueError – If the PCA’s values come from a custom normalizer.
PermissionError – If the reference must be written and the store is not opened with
zarr_mode='r+'.
- Return type:
- MappingAccessor.load_reference(reference)#
Load one mapping reference from an explicit artifact.
- Return type:
- MappingAccessor.run(reference, cell_selection, *, query_assay=None, save_k=3, missing_feature_policy='reference_mean', feature_key='ids', query_batches=None, invalidate_cache=False)#
Map selected query cells into an immutable prepared reference.
Query features match the reference features by exact feature ID.
feature_key="names"matches them by exact feature name instead, for a query that names the same genes with another ID scheme, such as gene symbols against Ensembl IDs. Query features that share a name then add their counts, asDataStoreMergesums them. The projection and its overlap selection recordfeature_keyonly when it is"names", so a match by name is a separate artifact.A query cell whose raw counts are zero in every reference feature that the query measured is recorded as uninformative. It keeps a projection row but is excluded from label transfer, mapping scores, Symphony query-batch statistics, and
queryScaledDispersion. A read-only query store returns a saved projection of the same request.A query store merged from sources that measured different genes records which genes each source measured in its feature columns
measured_in_<source>. Each query cell is then projected on the reference features that its own source measured; the others are missing for that cell and take the fill ofmissing_feature_policy, as when the source’s own store is mapped, and itsqueryScaledDispersionreads the features that the source measured. The projection records what each source measured asmeasured_features_fingerprint, only when some source did not measure some reference feature that the query holds.query_batches, for a Symphony reference only, holds the technical batch of each selected query cell, one column per batch variable, as a pandas DataFrame indexed by cell ID; rows of other cells are left out.- Raises:
UnmeasuredCellsError – If the query assay did not measure a selected cell.
TypeError – If
query_batchesis not a DataFrame indexed by cell ID, such as one with aRangeIndex, whose rows would land on cells by position, or the reference normalizes with Pearson residuals or CLR, which need counts, and the query assay holds values normalized before import.ValueError – If
feature_keyis"names"and reference features share a name, before anything is written, orquery_batcheslacks a selected query cell, repeats a cell ID, or holds in a column values that would form one batch but print differently, such as1,1.0andTrue, or values that print alike but would form separate batches, such as1and"1", or the reference normalizes withnorm_dummyand the query assay holds another kind of values than the reference’s, counts or values normalized before import, ormissing_feature_policyis"error"and a source of the selected query cells did not measure a reference feature that the query holds.PermissionError – If the projection or its overlap selection must be written and the query store is not opened with
zarr_mode='r+', before any query cell is projected.
- Return type:
- MappingAccessor.load_result(result, *, reference, load_arrays=False)#
Load one complete query-owned mapping projection.
- Return type:
- MappingAccessor.compute_scores(result, target_groups=None, *, reference, log_transform=True, multiplier=1000, weighted=True, fixed_weight=0.1)#
Return an iterator of reference-sized mapping scores, one per query group.
target_groupsnames the group of each projected query cell, as a pandas Series indexed by cell ID; values of other cells are left out. Without it, every query cell forms one group.The call checks its arguments,
target_groupsamong them, before it returns; the scores are computed as the groups are taken.- Raises:
TypeError – If
target_groupsis not a Series indexed by cell ID, such as an array, whose values would land on cells by position.ValueError – If
target_groupslacks a projected query cell or repeats a cell ID.
- Return type:
Generator[tuple[Any,ndarray],None,None]
- MappingAccessor.transfer_labels(projection, *, reference, reference_labels, threshold_fraction=0.5, max_distance=None, invalidate_cache=False)#
Transfer reference labels to projected query cells and save the result.
The reference labels are first frozen into this query datastore as a
reference_labelsartifact, so a later change to the reference cannot change a saved transfer. Each query cell then takes the label with the largest share of its neighbors’ inverse-distance weight. A cell abstains, and its label is missing, when it is uninformative, no neighbor has a usable label, two labels tie, the winning share is belowthreshold_fraction, or its nearest reference neighbor is farther thanmax_distance. A high vote share means that the neighbors agree; it is not a calibrated probability.A complete transfer with the same projection, reference labels, and decision rule is reused.
- Parameters:
projection (
ArtifactRef) – Query projection returned byrun().reference (
MappingReference) – The mapping reference that the projection used.reference_labels (
str|ArtifactRef) – A cell-metadata column of the reference datastore, or a cell-label artifact in it, such ascluster_labels,cluster_cut, orsmart_label.threshold_fraction (
float) – Smallest winning vote share that assigns a label.max_distance (
float|None) – Largest distance to the nearest reference neighbor that assigns a label.Nonesets no distance limit.invalidate_cache (
bool) – Compute a new transfer even when a matching one exists. Frozen reference labels with the same fingerprint are still reused, because they are an exact copy.
- Return type:
- Returns:
Reference to the immutable
label_transferartifact. Load it withload_label_transfer(), or use it wherever a cell-label artifact is accepted, such ascolor_byof an embedding plot.- Raises:
PermissionError – If no matching transfer exists and the query datastore is not opened with
zarr_mode='r+'.
- MappingAccessor.load_label_transfer(transfer, *, load_votes=False)#
Load one complete label transfer from this query datastore.
Loading reads only this datastore, so the reference datastore is not needed and later changes to it do not change the result.
- Parameters:
transfer (
ArtifactRef) – Label transfer returned bytransfer_labels().load_votes (
bool) – Also load each cell’s neighbor votes, whichlabel_vote_sharesandprediction_setsneed. The vote matrices hold one column per saved neighbor, so they are skipped by default.
- Return type:
- Returns:
The transferred labels, their evidence, and the exact inputs.
Mapping diagnostics are documented in the Plotting API reference API reference.