DataStore API reference#
DataStore is the primary analyst-facing object.
It inherits graph, mapping, and assay helpers from the classes below.
Use this page for analyst-facing methods and consult the inheritance appendix when extending CyteArc.
A DataStore is not designed for concurrent use from several threads; call its methods from one thread at a time.
Several processes can save results into one store at once; Several processes on one store lists the calls that need the store to themselves.
Graph-construction methods are documented on Graph construction API reference.
Artifact and run inspection, including the metadata-only DataStore.summary(), is documented on Artifacts, lineage, and summaries API reference.
Mapping methods are on Mapping API reference, and integration metrics are on Integration and metrics API reference.
Those methods are excluded here rather than repeated.
summary is reserved for DataStore.summary() and cannot be used as an assay name.
Writers and DataStore opening reject that name before mutating store-level state.
Assays are also available as attributes such as ds.RNA; an assay named like a DataStore
attribute, such as cells, or starting with an underscore is available only through get_assay(name).
Opening also rejects the removed {assay}/state group. Rebuild such a store with the current
release; CyteArc does not read or migrate its former analysis state.
Analysis namespaces#
For a standard analysis, start with a pipeline recipe, such as ds.pipeline.rna(label=...),
ds.pipeline.atac(...), ds.pipeline.adt(...), ds.pipeline.multimodal(...), or
ds.pipeline.perturbation(...)
(Analysis pipeline API reference). Use the namespaces below when selecting individual analysis steps. Each method
keeps its scientific defaults, return type, and saved-result identity. Cell metadata stays on
ds.cells, and ds.get_assay(name) provides access to every assay, including one whose name
matches a namespace.
ds.artifacts#
find resolves one complete saved result. It searches computed results by default; use
ds.artifacts.find("embedding", imported="X_umap", from_assay="RNA") for an imported embedding.
See Artifacts, lineage, and summaries API reference for supported filters and ambiguity handling.
ds.qc#
QC bounds are exclusive: qc.filter(["RNA_nFeatures"], lows=[200], highs=[None]) removes a
cell with exactly 200 detected genes, which scanpy’s filter_cells(min_genes=200) and CyteArc’s
features.detected(min_cells=...) keep. Pass keep_bounds=True to qc.filter or
select_cells for inclusive bounds; the bounds of qc.auto_filter are always exclusive, and a
writable open with min_features_per_cell=k removes cells with at most k features.
qc.auto_filter chooses each metric’s MAD policy from what CyteArc wrote and warns when it
falls back to a column’s name; pass metric_policies for imported columns such as scanpy’s
total_counts or pct_counts_mt.
qc.hto_demultiplexing, qc.call_cells, qc.ambient_contamination and qc.doublets save the numbers behind their warnings as diagnostics, which their entries below list, and warn from them each time their artifact is computed or reused.
qc.call_cells calls cells in an unfiltered droplet matrix with EmptyDrops (Cell calling). Import every barcode with counts, such as CrH5Reader(path, is_filtered=False, filtering_cutoff=0): the barcodes with at most lower counts form the ambient pool that the other barcodes are tested against. It reads every barcode that the assay measured, never the live I column, so a writable open’s min_features_per_cell floor cannot remove the ambient pool; open raw stores with min_features_per_cell=-1 to keep I complete too. It saves the statistics of every barcode as an assay-scoped cell_calling artifact (operation run_cell_calling; arrays total, log_probability, p_value, fdr, limited, and the feature-length ambient profile; attributes retain, knee, inflection, alpha, and n_ambient; diagnostic goodTuringSlope) and returns a cell_selection (operation call_cells, parameter fdr) whose inputs are that artifact and the tested barcodes (a select_all_cells selection, narrowed by select_measured_cells when the assay did not measure every barcode). Another fdr reuses the statistics. qc.load_cell_calls reads them, and qc.barcode_ranks gives the barcode-rank curve from the prepared <assay>_nCounts totals without reading counts.
- class cytearc.datastore.namespaces.QcAccessor(store)#
- auto_filter(attrs=None, min_p=0.01, max_p=0.99, *, cell_selection=None, artifact_metrics=None, invalidate_cache=False, method='mad', sample_column=None, sample_artifact=None, n_mads=3.0, min_cells_per_sample=20, metric_policies=None)#
Create an immutable automatically filtered cell selection.
Defaults to median absolute deviation (MAD) bounds. Each metric’s policy sets the scale of its bounds and which bounds apply:
Counts and feature counts use log1p values and two-sided bounds.
Percentages use raw values and an upper bound only, kept within 0 to 100.
metric_policiessets the policy of named metrics explicitly.
The kind of a metric comes from what CyteArc wrote, not from its name: the
<assay>_nCountsand<assay>_nFeaturescolumns and the percentage columns that an assay’s preparation wrote, and thequality_metricartifacts ofqc.feature_percentage, which are percentages. Any other metric, such as an importedtotal_countsorpct_counts_mtcolumn, gets the policy that its name suggests: counts for names ending innCountsornFeatures, percentages for names ending inpercentMitoorpercentRibo, and raw two-sided bounds otherwise, with a warning that names those metrics. The resolved policies are recorded asmetric_policies.Bounds are exclusive: a cell whose value equals a bound is removed. MAD thresholds are pooled unless a sample source is supplied. Use
method="gaussian"for pooled median/std Gaussian quantiles instead.Requested columns are read from current cell metadata when this method is called. Exact quality-metric artifacts can be supplied alongside metadata metrics. Metadata values are fingerprinted and artifact references are stored in provenance.
These are the pipeline filtering rules. A cell whose metric is recorded as missing never passes and does not inform the bounds; the fingerprints of metadata-column missing-value masks are recorded in provenance. Non-finite metrics among the remaining active cells, missing sample labels among active cells, and an empty result raise
ValueError.Bounds assume one population of cells. A warning says when automatic bounds remove more than half of the selected cells, or when the MAD bounds of a log1p metric miss a second population: a separate group of cells above the upper bound, or a strongly bimodal metric whose low group the bounds keep. Both happen when empty droplets of a raw, unfiltered droplet matrix set the bounds; call cells or import the filtered matrix first.
- Parameters:
attrs (
Iterable[str] |None) – Column names to be used for filtering.min_p (
float) – Quantile used for the lower threshold (Gaussian path only).max_p (
float) – Quantile used for the upper threshold (Gaussian path only).cell_selection (
ArtifactRef|None) – Optional prior cell-selection artifact.artifact_metrics (
Iterable[NamedCellArtifact] |None) – Named exactquality_metricartifact vectors.method (
Literal['mad','gaussian']) – MAD bounds by default, or explicit pooled Gaussian bounds.sample_column (
str|None) – Optional cell-metadata column with sample labels. When set, MAD bounds are calculated within each sample.sample_artifact (
NamedCellArtifact|None) – Optional named exacthto_identitysample vector.n_mads (
float) – Number of scaled MADs used for bounds.min_cells_per_sample (
int) – Groups with fewer active cells than this are retained without MAD filtering and emit a warning.metric_policies (
dict[str,dict[str,str]] |None) – MAD policies of named metrics (MAD only). Each maps"transform"to"log1p"or"identity"and"bound_direction"to"two_sided","lower", or"upper", for example{"total_counts": {"transform": "log1p", "bound_direction": "lower"}}. Unnamed metrics keep their default policies.
- Return type:
- Returns:
A complete datastore-scoped
cell_selectionartifact.- Raises:
TypeError – If
metric_policiesor one of its policies is not a mapping.ValueError – If
metric_policiesnames a metric that is not filtered, holds an unknown key or value, or is given withmethod="gaussian".UnmeasuredCellsError – If a metric’s assay did not measure a selected cell.
- barcode_ranks(from_assay=None, *, cell_selection=None, lower=100)#
Locate the knee and inflection of the barcode-rank curve.
The curve ranks barcodes by their prepared
<assay>_nCountstotal, so it reads no counts and writes nothing.qc.call_cellsretains the barcodes with at least the knee’s total by default.- Parameters:
from_assay (
str|None) – Assay of the totals (default: the default assay).cell_selection (
ArtifactRef|None) – Barcodes to rank. None ranks every barcode that the assay measured, whatever the liveIcolumn holds.lower (
int) – Totals at or below this value are left out of the fit.
- Return type:
- Returns:
The curve with its knee and inflection totals, which are NaN when fewer than five distinct totals exceed
lower.- Raises:
TypeError – If
cell_selectionis not an ArtifactRef orloweris not an integer.ValueError – If
loweris negative.UnmeasuredCellsError – If the assay did not measure a barcode of
cell_selection.
- call_cells(from_assay=None, *, cell_selection=None, lower=100, retain=None, n_iter=10000, alpha=None, fdr=0.001, random_seed=0, invalidate_cache=False)#
Call cells in an unfiltered droplet matrix with EmptyDrops.
EmptyDrops (Lun et al. 2019, Genome Biology 20:63) tells cells from empty droplets. Barcodes with at most
lowercounts form the ambient pool, whose profile is smoothed with Good-Turing estimation. Every other barcode is tested against that profile under a Dirichlet-multinomial model whose precision is estimated from the pool, with Monte Carlo p-values. Barcodes with at leastretaincounts are cells, and the barcodes whose Benjamini-Hochberg adjusted p-value is at mostfdrare the called cells.The per-barcode statistics are saved as an assay-scoped
cell_callingartifact, whichqc.load_cell_callsreads, and the called cells as acell_selectionthat records it as its inputcell_calling. Anotherfdrreuses the statistics. The counts are read in row blocks within the memory budget; totals come from the prepared<assay>_nCountscolumn.The statistics save their diagnostics, which
ds.artifacts.inspect(statistics).diagnosticsreturns for thecell_callingartifact:goodTuringSlope, the slope of the Good-Turing frequency fit that smooths the ambient profile. A slope of -1 or more gives aDiagnosticWarningthat the smoothed profile may be unreliable, each time the statistics are computed or reused.Import every barcode of the droplet run, such as Cell Ranger’s raw matrix with
CrH5Reader(path, is_filtered=False, filtering_cutoff=0): the ambient pool is made of the barcodes with low totals. Cell calling reads every barcode of the assay, never the liveIcolumn, so barcodes that a writable open removes fromIwithmin_features_per_cellstay in the pool; open raw stores withmin_features_per_cell=-1to keepIcomplete as well.With the same
alphaandretain, the calls agree with DropletUtils’emptyDrops. Two defaults differ from DropletUtils 1.30:alphais estimated by maximum likelihood, which isemptyDrops(alpha = NULL), where DropletUtils defaults to the multinomialalpha = Inf; and the defaultretainis the knee of a smoothing spline’s curvature, where DropletUtils now traces the curve, so the two knees differ.- Parameters:
from_assay (
str|None) – Assay of the counts (default: the default assay).cell_selection (
ArtifactRef|None) – Barcodes of one droplet run to call. None uses every barcode that the assay measured. Run each sample of a merged store separately.lower (
int) – Barcodes with at most this many counts form the ambient pool and are not tested (default 100).retain (
int|None) – Barcodes with at least this many counts are cells with p-value 0. None uses the total at the knee of the barcode-rank curve (qc.barcode_ranks).n_iter (
int) – Monte Carlo iterations (default 10,000). The smallest p-value is1 / (n_iter + 1);qc.load_cell_callsmarks barcodes that more iterations could make significant aslimited.alpha (
float|None) – Dirichlet-multinomial precision of the ambient model. None estimates it by maximum likelihood over the ambient pool.fdr (
float) – Largest adjusted p-value of a called cell (default 0.001).random_seed (
int) – Seed of the simulations. A seed gives the same p-values on any number of threads.invalidate_cache (
bool) – Compute again instead of reusing saved results.
- Return type:
- Returns:
A datastore-scoped
cell_selectionof the called cells.- Raises:
TypeError – If an argument has the wrong type, or the assay stores counts that are not non-negative integers.
ValueError – If an argument is out of range,
cell_selectionselects no barcode, no barcode exceedslower, there is no ambient pool, the knee cannot be located for a defaultretain, or no barcode is called.UnmeasuredCellsError – If the assay did not measure a barcode of
cell_selection.PermissionError – If the store is read-only and the results are not saved yet.
MemoryError – If the computation does not fit the memory budget.
- doublets(clusters, graph, *, from_assay=None, cluster_sample_fraction=1.0, max_cells_per_cluster=None, sample_column=None, simulation_ratio=2.0, heterotypic_fraction=0.0, save_k=30, expected_doublet_rate=0.05, threshold=None, smoothing_t=0, normalize_scores=False, random_seed=4444, invalidate_cache=False)#
Score and call doublets from simulated doublets, within each sample.
Doublets are simulated by adding the counts of two cells of one sample, every cell of the sample by default, so their cell types are as common as in the sample. They are normalized like the graph’s cells and projected onto its reduction: the PCA of an RNA assay, or the LSI of an ATAC assay, whose doublets are weighted by TF-IDF with each peak’s document frequency among the graph’s cells. Every cell and simulated doublet is then scored on its
knearest neighbors among the cells and simulated doublets of its own sample, withk = round(save_k * (1 + r))forrsimulated doublets per cell: the score is the probability that the cell is a doublet given the fraction of simulated doublets among those neighbors andexpected_doublet_rate, Scrublet’s doublet score (Wolock, Lopez and Klein, 2019). A cell is a predicted doublet when its score is above its sample’s threshold:threshold, or one chosen from the sample’s simulated-doublet scores. An automatic threshold is taken only when the doublet rate that it estimates, the share of cells above it over the share of simulated doublets above it, is at most 50%: the minimum between their two modes when it leaves at least 5% of them on each side, else Otsu’s threshold. A sample where neither is taken, as in a sample of one cell type, whose doublets look like its cells, has no threshold and calls no cell, as Scrublet calls none when it finds no threshold.Each sample’s index takes the settings of the graph’s ANN index and its metric, except that an ATAC assay’s cells are always scored by Euclidean distances in the LSI, whatever the metric of its graph. Samples are scored at once on the store’s workers, as many as the memory budget holds. A sample of 50,000 cells and simulated doublets or more is indexed in 4 parts that each hold every fourth point, built at once, each searched to the graph’s
ann_efdivided among the parts, and at least as deep as the neighbors it returns; a point’s neighbors are its nearest points across the parts. Every index is built on one thread, whatever the graph’sann_parallel, so a sample’s scores depend only on its cells andrandom_seed, and are the same for anynthreads.The
doublet_scoreartifact holds, for each cell of the graph’s selection, the score invalues, the fraction of simulated doublets among its neighbors inraw_scores, and the call inpredicted_doublets;ds.select_cells(ref, value="predicted_doublets", include=[False])keeps the predicted singlets.simulated_scoresholds the score of each simulated doublet andsimulated_parentsthe positions of its two parents among the selected cells, sample after sample. Thesamplesattribute lists each sample’s labels, cells, simulated doublets, neighbors, threshold and its method, calls, the fraction of simulated doublets above the threshold, and Scrublet’s estimate of the doublet rate. The method is"minimum","otsu","manual"for a giventhreshold, or"none"for a sample without a threshold, whose threshold and estimate are None.A sample whose cells share one cluster label cannot pair two clusters, so with
heterotypic_fractionabove 0 its doublets pair any two of its cells. The scores save their diagnostics, whichds.artifacts.inspect(ref).diagnosticsreturns:oneClusterSamples, the samples that formed none of the heterotypic doublets asked for, andoneClusterSampleExamples, up to five of them, such as(sample='A'). Such samples give aDiagnosticWarningeach time the scores are computed or reused, and so do samples without a threshold, whosethresholdMethodin thesamplesattribute is"none"and which the warning counts asnoThresholdSamples, and samples whose automatic threshold leaves fewer than 1% of their simulated doublets above it, which call almost no cell, as theirdetectableDoubletFractionsays.- Parameters:
clusters (
ArtifactRef) – Cluster labels over the graph’s cell selection. They matter only withheterotypic_fractionabove 0 or a parent pool smaller than every cell.graph (
ArtifactRef) – For an RNA assay, a connectivity map built on a PCA, with or without feature scaling, of values that a built-in RNA normalizer gave:norm_lib_size,norm_lib_size_log,norm_pearson_residuals,norm_clrornorm_dummy. The simulated doublets are normalized as the graph’s cells were, with what the normalizer fitted over them, and projected onto that PCA. For an ATAC assay, a map built on an LSI of values thatnorm_tf_idfnormalized. A map built on a Harmony correction of either needssample_column.from_assay (
str|None) – The RNA or ATAC assay of the graph; required for an integrated graph.cluster_sample_fraction (
float) – The fraction of each cluster of a sample that may parent doublets, drawn at random.max_cells_per_cluster (
int|None) – The most cells of each cluster of a sample that may parent doublets, or None for no limit. A limit makes rare clusters parent more doublets than their share of cells.sample_column (
str|None) – A cell metadata column naming each cell’s capture (10x channel or lane), or None to treat every cell as one sample. Doublets form only within one capture, so they are simulated from, and scored against, cells of the same sample. Cells hashed into one capture share it: do not pass hashtag identities.simulation_ratio (
float) – Simulated doublets per cell of each sample.heterotypic_fraction (
float) – The share of simulated doublets forced to pair cells of two clusters; 0 pairs any two cells of a sample.save_k (
int) – The neighbors that the scaling above starts from. A sample counts at most its other cells, and the artifact records the most that any sample uses.expected_doublet_rate (
float) – The prior doublet rate of each sample, above 0 and below 1.threshold (
float|None) – The doublet score from 0 to 1 above which a cell is a predicted doublet in every sample, or None to choose one per sample.smoothing_t (
int) – Diffusevaluesthis many steps over the graph; 0 keeps each cell’s own score.normalize_scores (
bool) – Scalevaluesto [0, 1]. Neither option changesraw_scores, the calls, or the thresholds.random_seed (
int) – The seed of the simulation and of each sample’s neighbor index.invalidate_cache (
bool) – Create a fresh result instead of reusing a match.
- Return type:
- Returns:
A complete assay-scoped
doublet_scoreartifact.- Raises:
TypeError – If the graph’s assay is neither an RNA nor an ATAC assay.
ValueError – If the graph of an RNA assay was built on values of a custom normalizer or on a reduction other than a PCA, or the graph of an ATAC assay on values of a normalizer other than
norm_tf_idfor on a reduction other than an LSI, which is checked before anything is planned. Also ifheterotypic_fractionis above 0 with one cluster, a sample has fewer than two cells or a missing label, or an argument is out of range.UnmeasuredCellsError – If the assay did not measure a cell of the graph.
MemoryError – If a sample’s simulation or neighbor index exceeds the memory budget.
- feature_percentage(cell_selection, features, *, invalidate_cache=False)#
Persist the percentage of counts assigned to selected features.
On a store merged from sources that measured different features, as its feature columns
measured_in_<source>record, a selected feature that some source of the selected cells did not measure is left out, through a feature selection of the others, with a warning that names such features. Each cell’s percentage is of its own total, as its source’s own store gives it.- Parameters:
cell_selection (
ArtifactRef) – Exact datastore-scoped cell-selection artifact.features (
ArtifactRef) – Exact assay-scoped feature-selection artifact.invalidate_cache (
bool) – Recompute instead of reusing an exact artifact.
- Return type:
- Returns:
A complete assay-scoped
quality_metricartifact.- Raises:
UnmeasuredCellsError – If the assay did not measure a selected cell.
ValueError – If no selected feature was measured by every source of the selected cells.
- filter(attrs, lows, highs, *, cell_selection=None, keep_bounds=False, invalidate_cache=False)#
Create an immutable selection from metadata thresholds.
The requested columns are read from current cell metadata when this method is called. Their values are fingerprinted in provenance, and the resulting immutable selection is stored. The live
Icolumn is snapshotted whencell_selectionis omitted. Pass a prior selection explicitly to compose multiple filtering steps.Cells whose value is recorded as missing in a nullable column never pass its bounds. The fingerprint of such a column’s missing-value mask is also recorded in provenance.
Bounds are exclusive unless
keep_boundsis True:lows=[200]keeps cells whose value is greater than 200 and removes a cell with exactly 200. Scanpy’sfilter_cells(min_genes=200)and CyteArc’sfeatures.detectedkeep values equal to their thresholds; passkeep_bounds=Truefor the same inclusive bounds.- Parameters:
attrs (
Iterable[str]) – Names of distinct columns to be used for filteringlows (
Iterable[float|None]) – Lower bounds, in the same order asattrs. Each bound is a finite number for a numeric or boolean column, text for a text column, or None.highs (
Iterable[float|None]) – Upper bounds, in the same order asattrs. A lower bound cannot exceed its upper bound.cell_selection (
ArtifactRef|None) – Optional prior cell-selection artifact.keep_bounds (
bool) – Retain values exactly equal to a bound, which makes both bounds inclusive.
- Return type:
- Returns:
A complete datastore-scoped
cell_selectionartifact.- Raises:
TypeError – If a bound or
keep_boundshas an invalid type, or a bound does not match its column, such as text for a numeric column. Bound types are checked before any column is read.ValueError – If a bound is invalid, the input selection is empty, or no cell passes the filter.
UnmeasuredCellsError – If a column’s assay did not measure a selected cell.
- hto_demultiplexing(cell_selection, *, from_assay=None, random_seed=0, positive_quantile=0.99, hashtags=None, sample_column=None, invalidate_cache=False)#
Demultiplex HTO counts into an immutable identity artifact.
The method follows Seurat’s
HTODemux: a count is positive when it exceeds thepositive_quantilequantile of the negative-binomial distribution fitted to its HTO’s background cluster. A cell with no positive HTO isNegative, one with several isDoublet, and a singlet takes the one HTO called positive. UnlikeHTODemux, which names a singlet after its highest normalized (CLR) value, a singlet is therefore never assigned an HTO that its cutoff called negative.The artifact’s
valuesarray holds the identities. Diagnostic arrays hold, for each cell, the HTOs with the highest and the second highest CLR value (max_idandsecond_id, Seurat’smaxIDandsecondID) and the difference of those values (margin). With one HTO,second_idis empty andmarginis NaN.sample_columnnames the cell metadata column of each cell’s sample, such as the pool of a lane, and each sample is demultiplexed on its own, as a separate call on its cells would.hashtagsnames the hashtags to demultiplex, by default every hashtag of the assay: one list for every sample, or a mapping from each sample’s label to its own hashtags. A hashtag without a count in a sample’s cells, such as one that another pool used, is left out rather than refused. The artifact’ssamplesattribute records, for each sample, itslabel(None withoutsample_column), its cells, the hashtags demultiplexed, each one’s cutoff and those left out.A background cluster that holds only zero counts, or whose fit gives a cutoff of 0, calls every nonzero count of its hashtag positive. That is accepted only for counts without ambient tags, in which no background cluster holds counts of its hashtag in most of its cells and at most half of the cells hold counts of more than one hashtag, as doublets do. Otherwise the hashtag is unused in the cells of its background, as when pools of cells use different hashtags, and the call is refused, naming each such hashtag. Demultiplex each pool with its own hashtags, through
sample_column.An HTO’s positive calls overlap its background when fewer than half of its positive cells have counts that the background fit exceeds with probability
(1 - positive_quantile) ** 3, one in a million for the default. Such calls, for example of an unused tag or of pure background, may be background. The identities save their diagnostics, whichds.artifacts.inspect(ref).diagnosticsreturns:overlappingHtos, the HTOs whose calls overlap, each counted in every sample where it does, andoverlappingHtoExamples, up to five of them with their sample, such as'HTO3' in sample 'a' of 'pool' (2 of 40 positive cells). Overlapping HTOs give aDiagnosticWarningthat names them each time the identities are computed or reused.- Parameters:
from_assay (
str|None) – HTO assay name (default:'HTO').cell_selection (
ArtifactRef) – Explicit cell-selection artifact.random_seed (
int) – Seed used for HTO demultiplexing, from 0 to 2**32 - 1.positive_quantile (
float) – Quantile of each HTO’s background distribution that a count must exceed to be positive, Seurat’spositive.quantile(default 0.99). It must be greater than 0 and less than 1. A higher quantile, such as 0.999, calls fewer background counts positive, and so fewer false doublets, but can miss weakly stained tags. The artifact records the quantile, so each quantile has its own artifact.hashtags (
Sequence[str] |Mapping[str,Sequence[str]] |None) – The hashtag IDs to demultiplex, or None for every hashtag of the assay. A mapping from each sample’s label, as text, to its hashtag IDs needssample_columnand an entry for every sample of the selected cells. The artifact records them, each list in the assay’s order.sample_column (
str|None) – Cell metadata column of each cell’s sample, or None to demultiplex every selected cell together. Every selected cell needs a label. The artifact records the column and the cells’ samples, so other labels make another artifact.invalidate_cache (
bool) – Recompute even when matching provenance exists.
- Return type:
- Returns:
A complete
hto_identityartifact.- Raises:
TypeError – If
random_seedis not an integer orpositive_quantileis not a real number.ValueError – If
random_seedis outside 0 to 2**32 - 1,positive_quantileis not finite or not between 0 and 1,sample_columnis not a cell column or leaves a selected cell without a label,hashtagsnames no hashtag of the assay or maps samples withoutsample_columnor other than the selected cells’, a sample has too few cells or no chosen hashtag with a count, or a hashtag’s background gives a cutoff of 0 in counts that carry ambient tags.UnmeasuredCellsError – If the HTO assay did not measure a selected cell.
- load_cell_calls(calls)#
Load the EmptyDrops statistics of every barcode of a cell calling.
- Parameters:
calls (
ArtifactRef) – The cell selection thatqc.call_cellsreturned, or itscell_callingartifact.- Return type:
- Returns:
The statistics of every barcode, with the barcode ids.
- Raises:
TypeError – If
callsis not an ArtifactRef.ValueError – If
callsis neither acell_callingartifact nor a selection of called cells, or is incomplete.
The same computation runs on an in-memory matrix:
- cytearc.quality_control.empty_drops(counts, *, lower=100, retain=None, n_iter=10000, alpha=None, random_seed=0, nthreads=None, barcodes=None)#
Test every barcode of an unfiltered count matrix against ambient RNA.
Implements EmptyDrops (Lun et al. 2019) on an in-memory matrix: see the module documentation for the method.
DataStore.qc.call_cellsruns the same computation over a stored matrix in bounded memory. A Good-Turing fit of the ambient pool whose slope is not below -1 logs the warning ofgood_turing_proportions(), once the barcodes are tested.- Parameters:
counts (
Any) – Barcodes by features matrix of non-negative integer counts, a NumPy array or SciPy sparse matrix, with every barcode of the droplet run, empty droplets included.lower (
int) – Barcodes with at most this many counts form the ambient pool and are not tested.retain (
int|None) – Barcodes with at least this many counts are cells with p-value 0. None uses the knee of the barcode-rank curve.n_iter (
int) – Monte Carlo iterations; the smallest p-value is1 / (n_iter + 1).alpha (
float|None) – Dirichlet-multinomial precision of the ambient model. None estimates it by maximum likelihood over the ambient pool.random_seed (
int) – Seed of the simulations; a seed gives the same p-values on any number of threads.nthreads (
int|None) – Threads for the simulations. None uses Numba’s thread count.barcodes (
Any) – Optional identifiers of the barcodes, one per row.
- Return type:
- Returns:
The statistics of every barcode.
- Raises:
TypeError – If an argument has the wrong type.
ValueError – If an argument is out of range, no barcode exceeds
lower, or the ambient pool is too small to smooth.
- cytearc.quality_control.barcode_ranks(totals, *, lower=100)#
Locate the knee and inflection of the barcode-rank curve.
Barcodes are ranked by decreasing total. The function fits a cubic smoothing spline to
log10(total)againstlog10(rank)over the distinct totals abovelowerand evaluates its derivatives at those totals. The inflection point is where the curve falls most steeply; the knee is where the signed curvature is lowest among the totals at or above the inflection, following the knee point definition of Lun et al. (2019).- Parameters:
totals (
Any) – Total count of each barcode, such as a raw matrix’sRNA_nCounts.lower (
int) – Totals at or below this value, mostly empty droplets, are left out of the fit.
- Return type:
- Returns:
The curve, with NaN for the knee and inflection when fewer than five distinct totals exceed
lower.- Raises:
TypeError – If
totalsis not numeric orlowernot an integer.ValueError – If
totalsis not one-dimensional, finite, and non-negative, orloweris negative.
- cytearc.quality_control.good_turing_proportions(counts)#
Estimate species proportions from counts with Simple Good-Turing.
Implements the Simple Good-Turing method of Gale and Sampson (1995). For each count
robserved forN_rspecies, the averaging transformZ_r = N_r / (0.5 * (t - q)), withqandtthe neighboring observed counts, is fitted by least squares aslog Z = a + b log r. The adjusted countr*is the Turing estimate(r + 1) N_{r+1} / N_rwhile it differs from the smoothed estimate(r + 1) (1 + 1/r)^bby more than 1.96 standard deviations, and the smoothed estimate from the first count where it does not, or whereN_{r+1}is 0. Observed species share1 - N_1 / Nin proportion tor*, and species with a count of 0 shareN_1 / Nequally. When every species was observed, the proportions are scaled to sum to 1. A fit whose slopebis not below -1 logs a warning that its smoothed proportions may be unreliable.- Parameters:
counts (
Any) – Non-negative integer count of each species.- Return type:
ndarray- Returns:
A float64 proportion for each species, summing to 1.
- Raises:
TypeError – If
countsis not an array of integers.ValueError – If
countsis not one-dimensional and non-negative, or holds fewer than two distinct positive counts.
Ambient RNA#
These methods estimate and remove ambient RNA as SoupX describes it (Young and Behjati, 2020, GigaScience, doi:10.1093/gigascience/giaa151); see Ambient RNA removal. qc.ambient_profile saves an assay-scoped ambient_profile artifact: the summed counts of each feature over the chosen empty droplets and each feature’s fraction of them. qc.ambient_contamination saves an assay-scoped, cell-aligned ambient_contamination artifact over its cell selection, whose values hold each cell’s contamination fraction and, for an estimate from gene sets, whose observed, expected, p_values, expressing, and used arrays hold one column per gene set, in name order. It records the profile, the clustering, and the resolved feature indices of each gene set. An estimate of exactly 0, whose cells hold no counts of their gene sets although pure soup would give them some, is saved as computed: a correction with it leaves those cells uncorrected. Its diagnostics count such estimates as zeroEstimates and give up to five as zeroEstimateExamples, each with its cells, the pure-soup count and the one-sided 95% Poisson upper bound of the fraction, about 3 divided by that count, and largestEstimate holds the largest of the global and cluster estimates. A DiagnosticWarning names the estimates of 0, and another an estimate above max_contamination, each time the estimate is computed or reused. Loading or correcting an estimate saved without these diagnostics, as earlier releases saved them, raises ValueError naming the call that estimates it anew. All three methods read RNA assays of raw UMI counts, which CyteArc stores as unsigned integers, and raise TypeError for other assays.
qc.correct_ambient writes a derived RNA assay, published atomically like the assays of
add_grouped_assay. It keeps the source’s features and count dtype, holds integer counts that
never exceed the source’s, and measures only the cells of the estimate: when they are not every
cell, its membership column <assay_label>_I marks them and the other rows hold no counts. Its
attributes record ambient_source_assay, the ambient_contamination and ambient_profile
artifacts, ambient_random_seed, ambient_corrected_cells, and ambient_removed_counts. Each
cell loses its fraction of its total, or every count of its genes that the soup holds when they
are fewer, rounded down or up, so a cell’s removed counts are its <source>_nCounts minus its
<assay_label>_nCounts. Each gene’s share of that removal is rounded at random, as in the paper,
by systematic sampling with one draw per cell: a gene is rounded up with a probability equal to
the fractional part of its share, so summed over cells every gene loses its share of the soup on
average. A cell’s draw depends only on random_seed (0 by default) and the cell’s row in the
store, so the counts are reproducible, do not depend on the memory budget, and are the same for
a cell whichever other cells are corrected with it; another seed gives other counts and another
assay identity. The correction streams the cells in bounded row bands.
- QcAccessor.ambient_profile(empty_droplets=None, *, total_counts=None, from_assay=None, invalidate_cache=False)#
Estimate the ambient RNA (soup) profile from empty droplets.
The soup profile is the share of each gene among the summed counts of droplets that hold no cell, equation S1 of Young and Behjati (2020), “SoupX removes ambient RNA contamination from droplet-based single-cell RNA sequencing data”, GigaScience 9:giaa151. The counts are summed in one bounded pass over the droplets’ rows.
Choose the droplets with exactly one of
empty_droplets, a cell selection of empty barcodes, ortotal_counts, the inclusive range of total counts of the droplets to use, such as(2, 10), which the paper uses. A range selects among the barcodes that the assay measured, so the store must hold unfiltered droplets, as a raw Cell Ranger matrix imported withfiltering_cutoff=0or1does.- Parameters:
empty_droplets (
ArtifactRef|None) – A cell-selection artifact of empty droplets.total_counts (
tuple[float,float] |None) – Inclusive(low, high)bounds on the droplets’<assay>_nCounts, with0 <= low <= high.from_assay (
str|None) – RNA assay of raw UMI counts. Defaults to the default assay.invalidate_cache (
bool) – Recompute instead of reusing a saved profile.
- Return type:
- Returns:
A complete assay-scoped
ambient_profileartifact. Itscountsarray holds the summed count of each feature, itsfractionarray the soup fractions, and its attributes the number of droplets (n_droplets) and their total count (n_counts). Read it withload_ambient_profile().- Raises:
TypeError – If the assay is not an RNA assay of unsigned integer counts, or an argument has the wrong type.
ValueError – If both or neither of
empty_dropletsandtotal_countsare given, the range is invalid, or the droplets select no droplet or hold no counts.UnmeasuredCellsError – If the assay did not measure an empty droplet.
PermissionError – If no saved profile matches and the store is read-only.
- QcAccessor.load_ambient_profile(profile)#
Read a saved soup profile as a table.
- Parameters:
profile (
ArtifactRef) – Anambient_profileartifact fromambient_profile().- Return type:
DataFrame- Returns:
One row per feature, in assay order and indexed by feature
ids, with the featurename, the summedcountsof the empty droplets, and the soupfraction.attrsholds the number of droplets (n_droplets) and their total count (n_counts).- Raises:
TypeError – If
profileis not an ArtifactRef.ValueError – If
profileis not anambient_profileartifact, or its features no longer match its assay.
- QcAccessor.ambient_contamination(cell_selection, profile, *, gene_sets=None, fraction=None, clusters=None, level='global', max_contamination=1.0, fdr=0.05, invalidate_cache=False)#
Estimate the ambient RNA contamination fraction of each cell.
The contamination fraction is the share of a cell’s counts that come from the soup. Following Young and Behjati (2020), “SoupX removes ambient RNA contamination from droplet-based single-cell RNA sequencing data”, GigaScience 9:giaa151, it is measured with
gene_sets: sets of genes that some cells do not express, such as hemoglobin genes outside erythroid cells or immunoglobulin genes outside B and plasma cells. In such a cell, every count of the set comes from the soup.A cell expresses a set when its count of the set is significantly larger than a droplet of pure soup with its total would hold: the Poisson probability of at least that count, with a mean of
max_contaminationtimes the pure-soup count, has a Benjamini-Hochberg adjusted value belowfdr. Each gene set leaves out the cells that express it and, withclusters, every cell of a cluster that holds one, as the paper recommends. The fraction is the observed count of the gene sets in the remaining cells divided by the count of pure soup with their totals.level="global"gives every cell that estimate, which the paper finds sufficient in most cases;level="cluster"gives each cluster the estimate from its own cells. Alternatively, pass a knownfractionfor every cell. The paper’s automatic estimate and its cell-level hierarchical model are not implemented.An estimate is exactly 0 when its cells hold no count of the gene sets they measure although pure soup would give them some. A count of 0 only bounds the fraction below about 3 divided by the pure-soup count, with 95% confidence, so a correction with it would leave those cells uncorrected. The estimate is saved as computed.
The estimate saves its diagnostics, which
ds.artifacts.inspect(ref).diagnosticsreturns:largestEstimate, the largest of the global estimate and the cluster estimates;zeroEstimates, the estimates of 0, whether global, of a gene set, or of a cluster; andzeroEstimateExamples, up to five of them with their cells, pure-soup count and bound, such asgene set 'rare' (no count in 85 cells where pure soup would give 46.2, so below 0.0649). A suppliedfractionsaves None for both numbers. An estimate abovemax_contaminationgives aDiagnosticWarning, and so do estimates of 0, each time the estimate is computed or reused.- Parameters:
cell_selection (
ArtifactRef) – Cells to estimate, such as called cells.profile (
ArtifactRef) – The soup profile fromambient_profile(). Its assay is the one estimated.gene_sets (
Mapping[str,Iterable[str]] |None) – Gene-set names mapped to gene names. Names match feature names without regard to case; unmatched names are logged, a set without a match raises, and a gene may belong to one set only. The artifact stores the sets in name order.fraction (
float|None) – A contamination fraction between 0 and 1 for every cell, instead ofgene_sets.clusters (
ArtifactRef|None) – A cell-label artifact, such as a clustering, that labels every cell ofcell_selection.level (
Literal['global','cluster']) –"global"or"cluster";"cluster"needsclusters.max_contamination (
float) – The largest plausible contamination fraction, greater than 0 and at most 1 (the paper’s default is 1).fdr (
float) – The false discovery rate of the expression test, greater than 0 and less than 1.invalidate_cache (
bool) – Recompute instead of reusing a saved estimate.
- Return type:
- Returns:
A complete assay-scoped
ambient_contaminationartifact overcell_selection. Itsvalueshold each cell’s fraction, whichartifacts.load_valuesandselect_cellsread; read the estimates and their evidence withload_ambient_contamination().- Raises:
TypeError – If an argument has the wrong type, or the assay is not an RNA assay of unsigned integer counts.
ValueError – If an argument is invalid, a gene set holds no soup counts, no cell can measure the contamination, or with
level="cluster", a cluster has no such cell.UnmeasuredCellsError – If the assay did not measure a selected cell.
PermissionError – If no saved estimate matches and the store is read-only.
- QcAccessor.load_ambient_contamination(contamination)#
Read a saved contamination estimate with its evidence.
- Parameters:
contamination (
ArtifactRef) – Anambient_contaminationartifact fromambient_contamination().- Return type:
- Returns:
The per-cell fractions, the global, per-gene-set, and per-cluster estimates, and the per-cell evidence of each gene set.
- Raises:
TypeError – If
contaminationis not an ArtifactRef.ValueError – If it is not an
ambient_contaminationartifact, or an estimate saved without its diagnostics, as earlier releases saved them; the error names the call that estimates it anew.MemoryError – If its values do not fit the datastore memory budget.
- QcAccessor.correct_ambient(contamination, *, assay_label, random_seed=0)#
Add an assay of counts with the ambient RNA removed.
Each cell of the contamination estimate loses its contamination fraction of its counts, as Young and Behjati (2020), “SoupX removes ambient RNA contamination from droplet-based single-cell RNA sequencing data”, GigaScience 9:giaa151, describe: the most likely removal under a multinomial model with the soup profile’s probabilities that never removes more of a gene than the cell holds. Genes are emptied in increasing order of their count divided by their soup fraction, and the rest is taken from the other genes in proportion to their soup fraction; genes absent from the soup are never reduced. A cell whose soup genes hold fewer counts than its share loses all of them.
As in the paper, each gene’s removal is rounded to whole counts at random, up with a probability equal to its fractional part, so its expected removal is the removal itself: summed over cells, every gene loses its share of the soup on average, however small its share in each cell. The draws follow systematic sampling with probabilities proportional to size (Madow 1949, doi:10.1214/aoms/1177729988), one draw per cell, so a cell with fraction
rhoand totalNlosesmin(rho * N, S)counts rounded down or up, whereSis its count of the genes that the soup holds. A cell’s draw depends only onrandom_seedand the cell’s row in the store, so a seed gives the same counts in any memory budget, and a cell gets the same counts whichever other cells the estimate corrects with it.The new assay is an RNA assay with the source’s features and count dtype, whose counts never exceed the source’s. It has a row for every cell but measures only the cells of the estimate, which its membership column
<assay_label>_Irecords when they are not every cell; the other rows hold no counts. Its counts are written in bounded row bands withcountsT, so every operation can use it by name, and its attributes record thecontaminationandprofileartifacts, therandom_seed, and the counts removed. It normalizes by library size with its source’s size factor: the session’ssfof the source, or the factor that the source stores when the session setssfto None. The assay becomes visible only after its counts are complete. If the write fails or is interrupted, the partial assay is removed or left pending untildiscard_interrupted_assay()removes it.- Parameters:
contamination (
ArtifactRef) – Anambient_contaminationartifact fromambient_contamination().assay_label (
str) – Name of the new assay.random_seed (
int) – Seed of the rounding draws, a non-negative integer.
- Return type:
None- Returns:
None
- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
contaminationis not anambient_contaminationartifact or was saved without its diagnostics, as earlier releases saved them,assay_labelis taken or invalid,random_seedis negative, or the session’ssfof the source is not a finite positive number.PermissionError – If the store is not opened with
zarr_mode='r+'.MemoryError – If one row band of the new assay and its correction do not fit the datastore memory budget.
- class cytearc.quality_control.ambient.AmbientContamination(fractions, estimate, method, level, set_estimates, cluster_estimates, evidence)#
A saved ambient RNA contamination estimate and its evidence.
- fractions#
The contamination fraction of each cell, indexed by cell
ids. Correction removes this fraction of each cell’s counts, or all of the cell’s counts of the genes that the soup holds when they are fewer.
- estimate#
The global estimate over every gene set and cell used, or the fraction that was supplied.
- method#
"gene_sets"for an estimate from gene sets,"fixed"for a supplied fraction.
- level#
"global"when every cell has the global estimate,"cluster"when each cell has its cluster’s estimate.
- set_estimates#
The estimate from each gene set alone, None for a set that no used cell measures.
- cluster_estimates#
The estimate of each cluster, keyed by the cluster label as text; empty unless
levelis"cluster".
- evidence#
One row per cell and gene set, with the cell
ids, thegene_set, itsobservedcounts, theexpectedcounts of a droplet of pure soup with the cell’s total, the Poissonp_valueof the observed counts at the largest plausible contamination,expressing, whether the cell expresses the set at the false discovery rate, andused, whether the cell measured the fraction. None for a supplied fraction.
ds.features#
- class cytearc.datastore.namespaces.FeaturesAccessor(store)#
- detected(cell_selection, *, from_assay=None, min_cells=20, invalidate_cache=False)#
Select features detected in at least
min_cellsselected cells.A read-only store returns a saved selection and refuses only to compute one, before it reads the counts. On a store merged from sources that measured different features, a feature that some source of the selected cells did not measure is left out, with a warning, and the selection records the features that every such source measured as
measured_features_fingerprint.- Raises:
UnmeasuredCellsError – If the assay did not measure a selected cell.
PermissionError – If the selection or its feature summary must be computed and the store is not opened with
zarr_mode='r+'.ValueError – If no feature was measured by every source of the selected cells.
- Return type:
- hvgs(cell_selection, *, from_assay=None, min_cells=None, top_n=1000, min_var=-inf, max_var=inf, min_mean=-inf, max_mean=inf, n_bins=200, lowess_frac=0.1, blacklist='^MT-|^RPS|^RPL|^MRPS|^MRPL|^CCN[A-Z]|^HLA-|^H2-|^HIST|^H1-[1-6]$|^H1F[1-6]$|^H2AC\\\\d+$|^H2BC\\\\d+$|^H3C\\\\d+$|^H4C\\\\d+$|^H2AW$|^H3-4$|^H4-16$|^XIST$|^DDX3Y$|^USP9Y$|^EIF1AY$|^KDM5D$|^SRY$|^ZFY$|^UTY$|^TMSB4Y$|^NLGN4Y$', keep_bounds=False, show_plot=True, max_cells=None, bin_strategy='adaptive', flavor='cytearc', batch=None, span=0.3, theta=100.0, clip=None, invalidate_cache=False, **plot_kwargs)#
Persist highly variable genes as an immutable feature selection.
Every flavor scores each gene’s variability among the selected cells, keeps the candidates that pass the filters below, and selects the
top_ncandidates with the highest scores, ties broken by lower feature index, or every candidate when fewer pass. The filters apply before the ranking, so they never shrink the selection belowtop_nwhile enough candidates pass.flavorsets the score:"cytearc"(default): the variance of library-size normalized values,sf * count / totalwith the assay’s size factor (1,000 by default) and no logarithm, divided by an expression-dependent background, the lower quartile of the variances of genes with a similar mean (fit_lowess). A corrected variance of 1 lies on the background."seurat_v3": the variance-stabilizing transformation of Stuart et al. (2019) on raw counts, scanpy’sflavor="seurat_v3". A local quadratic regression of log10 variance on log10 mean withspangives each gene an expected variance, counts are standardized with it and clippedsqrt(n)standard deviations above the mean, and the score is the variance of the standardized values."pearson_residuals": the variance of analytic Pearson residuals of the raw counts with overdispersiontheta, clipped atcliporsqrt(n), Lause, Berens and Kobak (2021), scanpy’s experimentalflavor="pearson_residuals". The expected count of a gene in a cell is the cell’s prepared total times the gene’s share of the counts.
seurat_v3 and pearson_residuals read the counts and the prepared cell totals and ignore the assay’s
normMethod. Each passes over the counts twice, seurat_v3 reading again only genes with a count above their clip.With
batch, every batch is scored on its own, each batch’stop_ncandidates are highly variable in it, and genes are selected by the number of batches in which they are highly variable, most first, then by their median rank in those batches. This is the order of Seurat’sSelectIntegrationFeaturesand of scanpy’sflavor="seurat_v3_paper"; scanpy’sflavor="seurat_v3"sorts by median rank first. The storedcorrected_varianceis then the mean score over the batches, and the selection also stores each gene’sbatch_countandmedian_batch_rank(NaN for a gene that no batch ranks among itstop_n). The cytearc flavor scores each batch’s values under the assay’snormMethodandsf, which the selection records as thenormalization_methodandsize_factorof its parameters, so a call under another normalizer or size factor computes a selection of its own.On a store merged from sources that measured different genes, as its feature columns
measured_in_<source>record, a gene that some source of the selected cells did not measure is left out, with a warning that names such genes, since its zero counts in that source’s cells are not measurements. Every flavor then scores the other genes as a store of them alone scores them, each cell’s total taken over them, its prepared total less its counts of the other genes, and the cytearc flavor reads the counts as batch-aware selections do; the left-out genes score 0, hold no statistics and are never selected. The selection records the genes that every source of the cells measured, as the fingerprintmeasured_features_fingerprintof its parameters, and a cytearc selection also thenormalization_methodandsize_factorof the values it reads.The artifact holds the
valuesmask and each gene’scorrected_variance(the flavor’s score). seurat_v3, pearson_residuals, and batch-aware selections also store each gene’smean_nonzeroanddetectedcount, which their plot shows.The selection saves its diagnostics, which
ds.artifacts.inspect(ref).diagnosticsreturns:selectedFeatures, the genes selected;selectedDetectionRatio, the median number of selected cells that detect a selected gene over the same median for the genes it could select (detected, within the detection bounds and outside the blacklist), or None when none is detected and for a selection that CyteArc 1.4.0 saved, which did not measure it; and withbatch,batches,batchesBelowTopN, the batches with fewer candidates thantop_n, andbatchBelowTopNExamples, up to five of them with their candidate counts. When fewer thantop_ngenes are selected, or some batch holds fewer candidates thantop_n, aDiagnosticWarningsays so each time the selection is computed or reused.Extra keyword arguments are options of
cytearc.plotting.highly_variable_features(), used whenshow_plotis True. Any other keyword raisesTypeError, and an option value that the plot refuses raises the plot’s error, before anything is computed or saved; without matplotlib, which looks up the plot’s colormaps, only the keywords are checked. A read-only store returns a saved selection and refuses only to compute one.- Parameters:
cell_selection (
ArtifactRef) – The cells whose variability is scored.from_assay (
str|None) – The RNA assay; the default assay when None.min_cells (
int|None) – Keep genes detected in at least this many selected cells. None uses the flavor’s default: for cytearc, the cube root of the number of selected cells rounded up and at least 20 (47 at 100,000 cells, 100 at 1,000,000), or for a selection of fewer than 381 cells, 5% of them rounded up and at least 5; for the other flavors, 0.top_n (
int) – The number of genes to select, and withbatchthe number that each batch ranks as highly variable.min_var (
float) – cytearc only. The log2 of the smallest corrected variance to keep: a gene stays only if its corrected variance exceeds2**min_var.-np.infsets no bound.max_var (
float) – cytearc only. The log2 of the largest corrected variance to keep,2**max_var.np.infsets no bound.min_mean (
float) – cytearc only. The log2 of the smallest mean normalized value to keep, where the mean is over the selected cells in which the gene is detected, not over all of them: a gene stays only if that mean exceeds2**min_mean.min_mean=0keeps genes whose mean over detected cells exceeds 1 normalized count.-np.infsets no bound.max_mean (
float) – cytearc only. The log2 of the largest such mean,2**max_mean.np.infsets no bound.n_bins (
int) – cytearc only. The number of points at which the adaptive background is evaluated, or of bins of the fixed one.lowess_frac (
float) – cytearc only. The background’s window radius as a fraction of the log-mean range.blacklist (
str) – A case-insensitive regular expression; genes whose names match it from their start are never selected. The default excludes every family ofcytearc.features.gene_families;""excludes none.keep_bounds (
bool) – Keep genes equal to a bound, which every bound excludes otherwise.show_plot (
bool) – Plot the mean-variance diagnostic. Without matplotlib, a warning says so and the selection is returned unplotted.max_cells (
float|None) – Keep genes detected in fewer than this many selected cells (at most this many withkeep_bounds). None uses the flavor’s default: for cytearc, exclude genes detected in more than 99.5% of the selected cells; for the other flavors, no bound.np.infsets no bound.bin_strategy (
Literal['fixed','adaptive']) – cytearc only."adaptive"local quantile regression or"fixed"LOWESS over the minimum-variance gene of each bin.flavor (
Literal['cytearc','seurat_v3','pearson_residuals']) –"cytearc","seurat_v3", or"pearson_residuals".batch (
str|ArtifactRef|None) – A cell metadata column, whose current values are snapshotted, or a label artifact such as a clustering or HTO identities, whose labels are the batches. Every selected cell needs a label, and every batch at least two selected cells. The detection bounds count the detections over every selected cell; the mean and variance bounds apply within each batch.span (
float) – seurat_v3 only. The fraction of genes in each local fit of the trend.theta (
float) – pearson_residuals only. The negative binomial overdispersion.clip (
float|None) – pearson_residuals only. The largest absolute residual; None clips at the square root of each batch’s cell count.invalidate_cache (
bool) – Compute again even when a matching selection exists.**plot_kwargs (
Any) – Options of the plot.
- Return type:
- Returns:
The reference of the
feature_selectionartifact. Its provenance records the resolvedmin_cellsandmax_cells.- Raises:
TypeError – If an option has the wrong type or a keyword is unknown.
ValueError – If an option is invalid or does not apply to the flavor, a batch is missing or too small, or no gene passes the filters.
KeyError – If the plot’s
themenames no theme.UnmeasuredCellsError – If the assay did not measure a selected cell.
PermissionError – If the selection, its feature summary, or its feature-name snapshot must be saved and the store is not opened with
zarr_mode='r+', before any of them is computed.
- prevalent_peaks(cell_selection, *, from_assay=None, top_n=10000, invalidate_cache=False)#
Feature selection method for ATACassay type assays.
This method first calculates prevalence of each peak by computing sum of TF-IDF normalized values for each peak and then marks top_n peaks with the highest prevalence as prevalent peaks. Peaks whose prevalence ties at the cutoff are kept in feature order, on every platform. On a store merged from sources that called different peaks, as its feature columns
measured_in_<source>record, the peaks that some source of the selected cells did not measure are left out, with a warning that names them, and every remaining peak is marked when fewer than top_n remain. The remaining peaks’ prevalence then divides each cell’s counts by its total over them, as a store of those peaks alone does: its prepared total less its counts of the other peaks.- Parameters:
from_assay (
str|None) – Assay to use for peak selection. If no value is provided then defaultAssay will be usedcell_selection (
ArtifactRef) – Explicit cells used to calculate peak prevalence.top_n (
int) – Number of top prevalent peaks to be selected, from 1 to one fewer than the number of peaks. (Default: 10000)
- Return type:
- Returns:
The persisted prevalent-peak feature-selection artifact.
- Raises:
UnmeasuredCellsError – If the assay did not measure a selected cell.
PermissionError – If the selection or its feature summary must be computed and the store is not opened with
zarr_mode='r+'. A read-only store returns a saved selection.
- snapshot(*, from_assay=None, mask=None, feature_indexes=None, invalidate_cache=False)#
Persist an explicit feature mask as an immutable artifact.
A read-only store returns a saved selection of the same mask and refuses only to create one.
- Return type:
- universe(*, from_assay=None)#
Create or reuse the canonical all-true feature universe.
The universe is an artifact only. It is never mirrored into feature metadata or registered under a mutable label. A read-only store returns a saved universe and refuses only to create one.
- Return type:
ds.reduction#
- class cytearc.datastore.namespaces.ReductionAccessor(store)#
ds.graph#
- class cytearc.datastore.namespaces.GraphAccessor(store)#
ds.embeddings#
- class cytearc.datastore.namespaces.EmbeddingsAccessor(store)#
- localmap(graph, initialization, *, localmap_dims=2, n_mid_near=5, n_further=20, iterations=(100, 100, 250), learning_rate=1.0, max_distance=10.0, random_seed=4444, nthreads=None, invalidate_cache=False)#
Lay out cells with LocalMAP and return the immutable embedding artifact.
LocalMAP extends PaCMAP. Each cell is attracted by its neighbors in
graph, attracted weakly by mid-near cells, the second closest of six random cells in the coordinates the graph was built on, and repelled by random further cells. In its last phase LocalMAP draws further pairs from the cells near each cell in the layout, which separates clusters that sit next to each other. Each edge of the graph attracts its two cells in proportion to its weight, scaled so that all edges attract as much as PaCMAP’s 10 neighbor pairs per cell. The layout does not depend on the number of threads.- Parameters:
graph (
ArtifactRef) – Explicit connectivity map to embed. Its lineage names the coordinates of the mid-near pairs, which the layout reads whole.initialization (
ArtifactRef|DataFrame) – Explicit initialization artifact from embeddings.initialization, or a DataFrame of finite real coordinates indexed by cell ID, aligned to the graph’s cells by ID; rows of other cells are left out. LocalMAP centers it and scales it to a standard deviation of 1e-4, keeping its proportions.localmap_dims (
int) – Dimensions of the layout. (Default value: 2)n_mid_near (
int) – Mid-near pairs per cell. More pairs hold the global arrangement more firmly in the first two phases. (Default value: 5)n_further (
int) – Further pairs per cell, which push cells apart. (Default value: 20)iterations (
tuple[int,int,int]) – Iterations of the three phases, each at least 1: the mid-near weight falls from 1000 to 3 over the first, stays at 3 over the second, and is 0 over the third, in which LocalMAP adjusts the pairs locally. (Default value: (100, 100, 250))learning_rate (
float) – Learning rate of the Adam optimizer. (Default value: 1.0)max_distance (
float) – Layout distance within which the last phase draws further pairs, and the scale of its neighbor attraction. (Default value: 10.0)random_seed (
int) – Seed of the mid-near and further pairs. (Default value: 4444)nthreads (
int|None) – Threads of the layout; by default the datastore’s. The layout does not depend on it.
- Return type:
- Returns:
Reference to the immutable embedding artifact.
- Raises:
ValueError – If
graphis not a connectivity map, an argument is out of range,initializationis a reference to another kind of artifact, or the graph has too few cells for the pairs.MemoryError – If the coordinates, the graph and the layout exceed the memory budget. The check runs before they are read.
PermissionError – If a new embedding is needed and the store is not opened with
zarr_mode='r+'. The check runs before the graph is read.
- tsne(graph, initialization, *, symmetric_graph=False, graph_upper_only=False, tsne_dims=2, lambda_scale=1.0, max_iter=500, early_iter=200, alpha=10, box_h=0.7, verbose=True, invalidate_cache=False)#
Run SGtSNE-pi (Read more here: fcdimitr/sgtsnepi). This is an implementation of tSNE that runs directly on graph structures. We use connectivity graphs generated by graph-construction methods to create a layout of cells using tSNE algorithm. This function uses the
sgtsnepipackage. To get a better understanding of how the parameters affect the embedding, check this out: http://t-sne-pi.cs.duke.edu/- Parameters:
graph (
ArtifactRef) – Explicit connectivity map or integrated graph to embed.initialization (
ArtifactRef|DataFrame) – Explicit initialization artifact from embeddings.initialization, or a DataFrame of coordinates indexed by cell ID, aligned to the graph’s cells by ID; rows of other cells are left out. Its values must be finite real numbers.symmetric_graph (
bool) – Forwarded to graph.load: if True, t-SNE embeds the fuzzy union of the directed edge weights. (Default value: False)graph_upper_only (
bool) – Forwarded to graph.load: keep the upper triangle of the symmetrized graph. It requires symmetric_graph=True. (Default value: False)tsne_dims (
int) – Number of tSNE dimensions to compute (Default value: 2)lambda_scale (
float) – λ rescaling parameter (Default value: 1.0)max_iter (
int) – Maximum number of iterations (Default value: 500)early_iter (
int) – Number of early exaggeration iterations (Default value: 200)alpha (
int) – Early exaggeration multiplier (Default value: 10)box_h (
float) – Grid side length (accuracy control). Lower values might drastically slow down the algorithm (Default value: 0.7)verbose (
bool) – If True (default) then the full log from SGtSNEpi algorithm is shown. If False, the log is discarded and the process’s standard output and error are restored afterwards.
- Return type:
- Returns:
Reference to the immutable embedding artifact.
- Raises:
ValueError – If
graph_upper_onlyis True withoutsymmetric_graph, or ifinitializationis a reference to another kind of artifact.ImportError – If
sgtsnepicannot be imported for a new embedding.MemoryError – If loading the graph and the arrays passed to sgtsnepi exceed the memory budget. sgtsnepi’s own working memory is not counted.
PermissionError – If a new embedding is needed and the store is not opened with
zarr_mode='r+'. The check runs before the graph is read.
- umap(graph, initialization, *, symmetric_graph=False, graph_upper_only=False, umap_dims=2, spread=2.0, min_dist=1, n_epochs=300, repulsion_strength=1.0, initial_alpha=1.0, negative_sample_rate=5, use_density_map=False, dens_lambda=2.0, dens_frac=0.3, dens_var_shift=0.1, random_seed=4444, parallel=False, nthreads=None, invalidate_cache=False)#
Build and return an immutable UMAP embedding artifact.
The embedding saves its diagnostics, which
ds.artifacts.inspect(ref).diagnosticsreturns:densityRadiusSpan, the span of densMAP’s log local radii, their largest minus their smallest, None without densMAP. Radii whose logarithms span at most 1e-6 are equal to float32 resolution, so densMAP adds no density term, and aDiagnosticWarningsays so each time the embedding is computed or reused.- Parameters:
graph (
ArtifactRef) – Explicit connectivity map or integrated graph to embed.initialization (
ArtifactRef|DataFrame) – Explicit initialization artifact from embeddings.initialization, or a DataFrame of coordinates indexed by cell ID, aligned to the graph’s cells by ID; rows of other cells are left out. Its values must be finite real numbers; UMAP optimizes a C-ordered float32 copy and leaves the caller’s DataFrame unchanged.symmetric_graph (
bool) – Must be False. UMAP optimizes the fuzzy union of the graph’s directed edge weights,w_ij + w_ji - w_ij * w_ji, which it forms itself, so a graph symmetrized by graph.load would be united twice. True raisesValueError. (Default value: False)graph_upper_only (
bool) – Must be False: the union of the upper triangle of the symmetrized graph is the union of the graph, so the flag has no effect of its own. True raisesValueError. (Default value: False)umap_dims (
int) – Number of dimensions of UMAP embedding (Default value: 2)spread (
float) – Same as spread in UMAP package. The effective scale of embedded points. In combination withmin_distthis determines how clustered/clumped the embedded points are.min_dist (
float) – Same as min_dist in UMAP package. The effective minimum distance between embedded points. Smaller values will result in a more clustered/clumped embedding where nearby points on the manifold are drawn closer together, while larger values will result on a more even dispersal of points. The value should be set relative to thespreadvalue, which determines the scale at which embedded points will be spread out, from 0 tospread. (Default value: 1)n_epochs (
int) – Same as n_epochs in UMAP package. The number of epochs to be used in optimizing the low dimensional embedding. Larger values may result in more accurate embeddings. (Default value: 300)repulsion_strength (
float) – Same as repulsion_strength in UMAP package. Weighting applied to negative samples in low dimensional embedding optimization. Values higher than one will result in greater weight being given to negative samples. (Default value: 1.0)initial_alpha (
float) – Same as learning_rate in UMAP package. The initial learning rate for the embedding optimization. (Default value: 1.0)negative_sample_rate (
float) – Same as negative_sample_rate in UMAP package. The number of negative samples to select per positive sample in the optimization process. Increasing this value will result in greater repulsive force being applied, greater optimization cost, but slightly more accuracy. (Default value: 5)use_density_map (
bool) – If True, run densMAP (density-preserving UMAP) instead of standard UMAP.dens_lambda (
float) – densMAP density preservation strength (Default value: 2.0).dens_frac (
float) – The fraction of the epochs, at the end of the layout, in which densMAP adds its density term, as umap-learn’sdens_frac. (Default value: 0.3)dens_var_shift (
float) – Variance shift for density correction (Default value: 0.1).random_seed (
int) – The seed of the layout, from 0 to 2**32 - 1. (Default value: 4444)parallel (
bool) – Whether to run UMAP in parallel mode. Setting value to True will use nthreads threads. The results are not reproducible in parallel mode. A serial layout runs on one thread and releases the GIL during each epoch, so the process’s other Python threads keep running. (Default value: False)nthreads (
int|None) – If parallel=True then this number of threads will be used to run UMAP. By default, the nthreads attribute of the class is used. (Default value: None)
- Return type:
- Returns:
Reference to the immutable embedding artifact.
- Raises:
ValueError – If
symmetric_graphorgraph_upper_onlyis True, if a setting is out of the range that umap-learn’sUMAPtakes:spreadnot above 0,min_dist,repulsion_strength,initial_alpha,negative_sample_rate,dens_lambdaordens_var_shiftbelow 0, ordens_fracoutside 0 to 1, ifinitializationis a reference to another kind of artifact, or if densMAP finds a cell whose local radius is not finite.MemoryError – If loading the graph and laying it out exceed the memory budget. The check runs before the graph is read.
PermissionError – If a new embedding is needed and the store is not opened with
zarr_mode='r+'. The check runs before the graph is read.
ds.integration#
- class cytearc.datastore.namespaces.IntegrationAccessor(store)#
ds.clusters#
clusters.leiden runs CyteArc’s own Leiden implementation, backend="cytearc", by default
(Leiden clustering). It uses the datastore’s nthreads and
returns the same labels for any thread count, numbered from 1 with the largest cluster first.
backend="igraph" and backend="leidenalg" call the GPL-licensed igraph and leidenalg packages,
which CyteArc does not install
(Optional GPL Leiden backends); without them, computing
a new clustering with either backend raises ImportError that explains how to install them. The
backend is part of the artifact identity: a clustering saved with "igraph", the default of
earlier releases, is reused only by a call that passes backend="igraph", and reusing it does not
need the packages.
clusters.connectivity(graph, groups) sums the graph’s weight between each pair of clusters and returns the tables that plots.cluster_connectivity draws, without a layout or a figure, as a ClusterConnectivity: nodes holds each cluster’s cells and incident weight, and edges each pair’s rawWeight and normalizedWeight. It needs no plotting dependencies and saves nothing, so a diagnostic can call it once per clustering, such as each Leiden resolution. groups is a clustering or another categorical cell artifact, read for the graph’s cells as the plot reads it, or a cell metadata column read over the graph’s cells. Its filters keep every pair by default, while the plot’s minimum_edge_weight defaults to 0.02; pass the plot’s filters to get the edges it draws.
- class cytearc.datastore.namespaces.ClustersAccessor(store)#
- connectivity(graph, groups, *, minimum_edge_weight=0.0, max_edges_per_node=None)#
Sum a cell graph’s weight between each pair of clusters, as tables.
Compare cluster structure across resolutions, or report which clusters the graph joins, without drawing a figure.
nodesholds each cluster’s cells and incident weight, the summed weighted degree of its cells, andedgeseach pair of clusters that the graph joins:rawWeightsums the weights of the edges between their cells, each undirected edge once, andnormalizedWeightdivides it bysqrt(incidentWeight[source] * incidentWeight[target]). The graph is read asgraph.load(symmetric=True)returns it, andplots.cluster_connectivitydraws the same weights on a layout. Nothing is saved.- Parameters:
graph (
ArtifactRef) – Connectivity-map or integrated-graph artifact.groups (
ArtifactRef|str) – The clusters: a categorical cell artifact, such as a clustering, or a user-owned cell metadata column. Labels are read for the graph’s cells, which an artifact’s own cells must include, so labels of more cells serve.minimum_edge_weight (
float) – Keep the pairs whosenormalizedWeightis at least this. The default, 0, keeps every pair.max_edges_per_node (
int|None) – Keep at most this many pairs for each cluster, the largestnormalizedWeightfirst, or every pair with None, the default.
- Return type:
- Returns:
The
nodesandedgestables, asClusterConnectivity, with the clusters in the natural order of their labels.- Raises:
TypeError – If
graphis not an ArtifactRef, orgroupsis neither an ArtifactRef nor a column name.ValueError – If a filter is invalid, which is checked before anything is read,
groupsbelongs to another assay thangraphor holds no label for some of the graph’s cells, or a label is missing: NaN, None, blank, or flagged by a linked missing mask.
- leiden(graph, *, resolution=1.0, backend='cytearc', symmetric_graph=False, graph_upper_only=False, random_seed=4444, invalidate_cache=False)#
Build and return immutable Leiden cluster labels.
resolutionmust be a finite positive number and is recorded as a float, so1and1.0identify the same artifact.random_seedmust be a non-negative integer because stored labels are reused.backendselects the Leiden implementation:"cytearc", CyteArc’s own multi-threaded implementation, is the default;"igraph"and"leidenalg"need those GPL-licensed packages, which CyteArc does not install, and are kept to reproduce earlier results. The thread count is not part of the artifact identity and never changes the labels.symmetric_graphpartitions the fuzzy union of the directed edge weights, andgraph_upper_only, which keeps its upper triangle, requiressymmetric_graph=True.- Raises:
MemoryError – If loading the graph and, for the
"cytearc"backend, partitioning it exceed the memory budget, before the graph is read.PermissionError – If new labels are needed and the store is not opened with
zarr_mode='r+', before the graph is read.
- Return type:
- load_paris(ref)#
Load a Paris result from an explicit completed cut artifact.
- Return type:
- membership_strength(clusters, graph, *, invalidate_cache=False)#
Store per-cell cluster membership strength as an artifact.
For each cell, computes the fraction of KNN neighbors sharing its own cluster label.
- Parameters:
clusters (
ArtifactRef) – Explicit axis-aligned cluster-label artifact over the cell selection ofgraph, with a label for every cell. Labels that its linked missing mask flags raiseValueError.graph (
ArtifactRef) – Explicit connectivity-map or integrated-graph artifact.
- Return type:
- Returns:
Reference to the immutable membership-strength artifact.
- Raises:
ValueError – If
graphis not a connectivity map or integrated graph.PermissionError – If no matching result exists and the store is not opened with
zarr_mode='r+'.
- paris(graph, *, n_clusters='auto', min_cluster_size=None, invalidate_cache=False)#
Build and return an immutable Paris cut artifact.
A fixed integer
n_clustersmust be 1 or at least the number of connected components ingraph, and the hierarchy must split into exactly that many clusters at one height. Otherwise aValueErrornames the alternatives, such asn_clusters='auto'.- Return type:
- relabel_by_overlap(to_relabel, base_label, *, invalidate_cache=False)#
Relabel one cell-label artifact using another label artifact.
Values in artifact A are relabeled from their overlap with artifact B. For each unique value in A, the most frequently occurring value in B is found. If two or more values in A have maximum overlap with the same value in B, then they all get the same label as B along with different suffixes: ‘a’ to ‘z’, then ‘aa’, ‘ab’, and so on. The suffixes are ordered based on where the largest fraction of the B label lies. If one label from A takes up multiple labels from B then all the labels from B are included, and they are delimited by hyphens. Both artifacts need one cell selection and a label for every cell; labels that a linked missing mask flags raise
ValueError.- Parameters:
to_relabel (
ArtifactRef) – Explicit axis-aligned label artifact to relabel.base_label (
ArtifactRef) – Explicit axis-aligned base-label artifact.
- Return type:
- Returns:
Reference to the immutable relabeled-values artifact.
- Raises:
ValueError – If two labels of A would receive the same new name, which hyphen-joined base labels can cause.
PermissionError – If no matching result exists and the store is not opened with
zarr_mode='r+'.
ds.markers#
- class cytearc.datastore.namespaces.MarkersAccessor(store)#
- export_csv(marker, csv_filename, *, min_score=None, min_frac_exp=0.2, min_auc=0.6, max_p_adj=0.05, sort_by='score')#
Export markers of each cluster/group to a CSV file where each column contains the marker names in
sort_byorder, best first. Columns follow the natural order of the group labels, as inmarkers.load, and a group thatmarkers.searchskipped has an empty column. This function does not export the statistics of markers, asmarkers.loadreturns them. A table of operation revision 1 exports asmarkers.loadreads it: with its five-decimal statistics, its asymptotic p-values, and its derivedneg_log10_p_value.- Parameters:
marker (
ArtifactRef) – Exact marker-table artifact returned bymarkers.search.csv_filename (
str) – Required parameter. Name, with path, of CSV file where the marker table is to be saved.min_score (
float|None) – Smallestscorekept, orNone(default) to keep every score, as formarkers.load.min_frac_exp (
float|None) – Smallestfrac_expkept (default 0.2), orNone.min_auc (
float|None) – Smallestauckept (default 0.6), orNone.max_p_adj (
float|None) – Largestp_value_adjustedkept (default 0.05), orNone.sort_by (
Literal['score','auc','p_value','fold_change']) – Statistic that orders each column, as formarkers.load.
- Raises:
TypeError – If a filter is neither
Nonenor a real number.ValueError – If a filter is NaN,
sort_byis unknown, or the marker table records nofold_change_policyor breaks the layout of its revision.
- Return type:
None
- load(marker, *, group_id=None, min_score=None, min_frac_exp=0.2, min_auc=0.6, max_p_adj=0.05, sort_by='score')#
Return marker features from markers.search.
When
group_idisNone(default), markers for every group under the artifact are returned in one long table with agroup_idcolumn. Groups follow the natural order of their labels, as in plots: numeric labels come first by value, so'2'precedes'10', and other labels follow in natural text order. Rows of a group followsort_by. Pass a specificgroup_idto return markers for that group only. For a wide export of marker names only, usemarkers.export_csv.A row is kept when it passes every filter that is not
None. By default, a marker is expressed in at least 20% of its group’s cells, has an AUC of at least 0.6 against the rest of the cells, and an adjusted p-value of at most 0.05.score, a group’s share of the summed mean dense ranks, falls as groups multiply and is capped by the group’s size, so it ranks markers by default but filters none: a perfect marker of a small group, or of one group of many, can score far below 0.25. PassNonefor every filter to get every tested feature of every group. A group thatmarkers.searchskipped because it had fewer than two cells gives no rows, with a warning.A table of operation revision 1, written before release 1.3.0, records neither
neg_log10_p_valuenorp_value_policy. It loads, from a read-only store too, with the statistics it stored: rounded to five decimals, except for the p-values, which come from the tie- and continuity-corrected normal approximation, the p-value policy"asymptotic_tie_and_continuity_corrected"that the load logs. Itsneg_log10_p_valueis derived as-log10(p_value), +inf wherep_valueunderflowed to 0, and the filters andsort_byapply as to any table.markers.searchnever reuses such a table: on a writable store it recomputes it at revision 2.- Parameters:
marker (
ArtifactRef) – Exact marker-table artifact returned bymarkers.search.group_id (
str|int|None) – One group label, orNonefor all groups. An integer is matched by its string form.min_score (
float|None) – Smallestscorekept, orNone(default) to keep every score.min_frac_exp (
float|None) – Smallest fraction of the group’s cells with a nonzero value,frac_exp, kept (default 0.2), orNone.min_auc (
float|None) – Smallestauckept (default 0.6): the probability that a cell of the group ranks above a cell of the rest, ties counting one half.Nonealso keeps negative markers, whose AUC is below 0.5.max_p_adj (
float|None) – Largestp_value_adjustedkept (default 0.05), orNone.sort_by (
Literal['score','auc','p_value','fold_change']) – Statistic that orders the rows of each group, best first:"score"(default),"auc", or"fold_change"descending, or"p_value"ascending. Ties fall to the p-value (to the AUC for"p_value"), then to the feature name and index.
- Return type:
DataFrame- Returns:
Pandas dataframe with a string
group_idcolumn, each row’sfeature_name,feature_id, andfeature_index, and its marker statistics.feature_idis the ID that the marker table froze, which tells apart features that share a name.fold_changemay be +inf or NaN, and theneg_log10_p_valueof a table of revision 1 may be +inf.- Raises:
TypeError – If a filter is neither
Nonenor a real number.ValueError – If
group_idis not a group of the marker artifact, a filter is NaN,sort_byis not one of the orders above, the table records nofold_change_policy, or it breaks the layout of its revision.
- search(clusters, *, from_assay=None, features, nthreads=None, invalidate_cache=False, **norm_params)#
Persist marker tables for an explicit clustering artifact.
Raw counts of any storage dtype are ranked. Library-size markers require finite non-negative counts and cell totals. On a store merged from sources that measured different features, the search ranks only the selected features that the source of every labeled cell measured, as the assay’s
measured_in_<source>feature columns record, and warns of those that it leaves out.- Parameters:
from_assay (
str|None) – Name of the assay to be used. If no value is provided then the default assay will be used.clusters (
ArtifactRef) – Completecluster_labelsorcluster_cutartifact with a label for every cell. Labels that its linked missing mask flags raiseValueError, as do blank labels, which CyteArc’s groupings count as missing. Any other label names a group,'T/NK'and'.'included. To compare the groups of a cell metadata column, or only some cells or clusters, freeze the labels over those cells withsnapshot_cluster_labels.features (
ArtifactRef) – Explicit feature-selection artifact.nthreads (
int|None) – Threads for marker search.**norm_params (
Any) – Extra keyword arguments forwarded tonormed.
- Return type:
- Returns:
A complete immutable marker-table artifact.
- Raises:
ValueError – If a library-size normalized value of a selected cell and feature, or the total of a selected cell (its
<assay>_nCountsvalue, or withrenormalize_subset=Trueits sum over the selected features), is negative or not finite. Nothing is written.PermissionError – If no matching result exists and the store is not opened with
zarr_mode='r+'. The check runs before the search.UnmeasuredCellsError – If the assay did not measure a labeled cell.
ValueError – If no selected feature was measured by the source of every labeled cell.
ds.scores#
chromvar scores peak sets, such as motif matches or CUT&RUN peaks of one factor, on an
ATAC assay; see Regulons API reference for building those networks.
- class cytearc.datastore.namespaces.ScoresAccessor(store)#
- aucell(net, cell_selection, *, from_assay=None, features, tmin=5, n_up=None, tie_seed=0, ambiguous_targets='drop', invalidate_cache=False)#
Score gene sets by recovery among each cell’s top-ranked RNA features.
AUCell ranks every feature selected by
featuresfrom raw counts. Network weights are ignored. Targets are matched without case sensitivity, then sources with fewer thantminmatched targets are removed. On a store merged from sources that measured different genes, as its feature columnsmeasured_in_<source>record, the genes offeaturesthat some source of the selected cells did not measure are left out, through a feature selection of the others, with a warning that names them.- Parameters:
net (
DataFrame) – Network withsourceandtargetcolumns.from_assay (
str|None) – RNA assay to score. The default assay is used when omitted.cell_selection (
ArtifactRef) – Explicit cells to score.features (
ArtifactRef) – Explicit feature-selection artifact.tmin (
int) – Minimum number of matched targets required per source.n_up (
int|None) – Number of top-ranked features used for recovery. When omitted, five percent of the ranking universe is used, clipped to its valid range.tie_seed (
int) – Seed for the global feature permutation used to resolve ties.ambiguous_targets (
Literal['drop','error']) – Handling of a target that matches several active features, such as a gene symbol shared by two feature ids."drop"removes its edges beforetminpruning, logs a warning, and records the target in the artifact’sdropped_ambiguous_targetsattribute."error"raises.
- Return type:
- Returns:
A complete
enrichment_scoresartifact.- Raises:
PermissionError – If the store is not opened with
zarr_mode='r+'.UnmeasuredCellsError – If the assay did not measure a selected cell.
ValueError – If no selected feature was measured by every source of the selected cells.
Note
Cache identity covers selections, method parameters, and the prepared network, whose digest hashes only the retained edges. It assumes the stored count matrix is immutable.
- cell_cycle(cell_selection, *, from_assay=None, s_genes=None, g2m_genes=None, ctrl_size=None, log_transform=None, n_bins=50, rand_seed=4466, invalidate_cache=False)#
Computes S and G2M phase scores by taking into account the average expression of S and G2M phase genes respectively. Following steps are taken for each phase:
Gene names match feature names without case, and a name matches every feature with it. A gene that its listed symbol misses matches by another HGNC symbol of the same gene in
cytearc.quality_control.cell_cycle_previous_symbols, such as FAM64A for PIMREG; the artifact records such genes asgene_aliasesand the log names them. A gene matched more than once counts once.cytearc.quality_control.match_gene_namesmatches a list of genes to feature names the same way.Normalized expression is log1p transformed when log_transform is True.
Every feature’s mean over the selected cells sets its expression bin, as in scanpy’s
score_genes: withNfeatures a bin holdsk = round(N / (n_bins - 1))of them, and a feature whose mean ranksr(from 1, tied means sharing the lowest rank) falls in binr // k. All features with a mean of 0 share the lowest bin, which can leave the next bins empty.For each bin that holds a phase gene,
ctrl_sizecontrol genes are drawn from all genes of the bin (the whole bin when it holds no more), and phase genes among them are dropped. Controls are drawn once per bin rather than for each phase gene as in Tirosh et al. (2016), and the S and G2M draws each start fromRandomState(rand_seed).The average expression of phase genes (Ep) and control genes (Ec) is calculated per cell.
A phase score is calculated as
Ep - Ec.G1 is assigned when both scores are negative.
G2M is assigned when the G2M score exceeds the S score.
S is assigned otherwise, including tied non-negative scores.
On a store merged from sources that measured different genes, as its feature columns
measured_in_<source>record, a gene that some source of the selected cells did not measure is left out of the phase genes, the bins and the controls, with a warning that names such genes, and each cell’s total, which library-size values divide by, is its total over the other genes, as a store of them alone scores them.- Parameters:
from_assay (
str|None) – Name of assay to be used. If no value is provided then the default assay will be used.cell_selection (
ArtifactRef) – Explicit cells to score.s_genes (
list[str] |None) – A list of S phase genes. If not provided then CyteArc loads pre-saved genes accessible at cytearc.quality_control.s_phase_genesg2m_genes (
list[str] |None) – A list of G2M phase genes. If not provided then CyteArc loads pre-saved genes accessible at cytearc.quality_control.g2m_phase_genesctrl_size (
int|None) – Controls sampled per bin. None uses the shorter input gene list.log_transform (
bool|None) – Apply log1p before binning and scoring. None applies it only fornorm_lib_size.n_bins (
int) – Number of bins into which average expression of genes is divided.rand_seed (
int) – A random seed for sampling control genes, from 0 to 2**32 - 1. (Default value: 4466)
- Return type:
- Returns:
A complete
cell_cycleartifact containing S, G2M, and phase values.- Raises:
UnmeasuredCellsError – If the assay did not measure a selected cell.
PermissionError – If the scores or their feature summary must be computed and the store is not opened with
zarr_mode='r+'. A read-only store returns saved scores.ValueError – If no gene of a phase list was measured by every source of the selected cells.
- chromvar(net, cell_selection, *, from_assay=None, features, gc=None, genome=None, n_backgrounds=50, background_seed=0, kernel_width=0.1, bins=50, tmin=1, ambiguous_targets='drop', invalidate_cache=False)#
Score peak-set accessibility deviations of cells with chromVAR.
For each source of
net, such as a motif with its matching peaks or a transcription factor with the peaks a CUT&RUN experiment bound, a cell’s deviation is its fragments in the source’s peaks minus the fragments expected from the cell’s depth and the peaks’ share of all fragments, relative to that expectation. It is corrected by the same deviation of background peak sets matched in GC content and accessibility, and the z-score divides it by the background deviations’ standard deviation, as chromVAR’scomputeDeviationsdoes. A cell expecting fewer than one fragment in a set has no value for it (NaN). Raw ATAC counts are read twice: once for the peak totals that define expectations and background peaks, once to score. On a store merged from sources that called different peaks, as its feature columnsmeasured_in_<source>record, the peaks offeaturesthat some source of the selected cells did not measure are left out, through a feature selection of the others, with a warning that names them, since that source’s cells hold no fragments in them.- Parameters:
net (
DataFrame) – Network withsourceandtargetcolumns whose targets are peak ids (chrom:start-end), such asmatch_motifsoutput.cell_selection (
ArtifactRef) – Explicit cells to score.from_assay (
str|None) – ATAC assay to score. The default assay when omitted.features (
ArtifactRef) – Explicit selection of the peaks that define fragment totals, expectations, and backgrounds. Every selected peak needs a fragment among the selected cells.gc (
ndarray|None) – GC content of every assay feature in feature order. Pass this orgenome.genome (
str|PathLike[str] |None) – Uncompressed FASTA of the genome the peak coordinates (ids,chrom:start-end) refer to; GC content is read from it.n_backgrounds (
int) – Background peak sets per source.background_seed (
int) – Seed of the background peak draws.kernel_width (
float) – Width of the kernel that matches background peaks, in whitened units.bins (
int) – Grid points per axis of the background model.tmin (
int) – Minimum number of selected peaks per source.ambiguous_targets (
Literal['drop','error']) – Handling of a target that matches several selected peaks:"drop"removes it,"error"raises.invalidate_cache (
bool) – Recompute even when a matching result exists.
- Return type:
- Returns:
A complete
enrichment_scoresartifact whose scores are z-scores and whosedeviationsarray holds the bias-corrected deviations.- Raises:
MemoryError – If the background model does not fit the budget.
PermissionError – If the store is not opened with
zarr_mode='r+'.UnmeasuredCellsError – If the assay did not measure a selected cell.
ValueError – If no selected peak was measured by every source of the selected cells.
- load(enrichment, *, sources=None)#
Load an explicit enrichment artifact without materializing scores.
- Parameters:
enrichment (
ArtifactRef) – Artifact returned byscores.waggr,scores.aucell, orscores.chromvar.sources (
Sequence[str] |None) – Optional source names to select and order.
- Return type:
- Returns:
The stored metadata and a lazy cells-by-sources score matrix.
- load_potency(potency)#
Load potency scores from an explicit completed artifact.
- Parameters:
potency (
ArtifactRef) – Acell_potencyartifact frompotency().- Return type:
- Returns:
The cells’ differentiation, potency and raw measures, in the order of the artifact’s cell selection, with the measure, the network and its coverage.
- Raises:
TypeError – If
potencyis not an ArtifactRef.ValueError – If it is not a complete
cell_potencyartifact ofds.scores.potency, or its record does not match the contract.
- potency(cell_selection, *, measure='ccat', graph=None, smoothing=0.9, species=None, network=None, from_assay=None, invalidate_cache=False)#
Score how differentiated each cell is from its expression on a protein network.
Less differentiated cells score higher potency. The measure ranks the cells, and
differentiation, one minus that rank, rises along the process, so the artifact directsfate()as itsdirectionwithout naming a source. Both measures are written from their papers and computed in one pass over the counts:"ccat", the default, of Teschendorff et al. (2021), Bioinformatics 37:1528-1534, doi:10.1093/bioinformatics/btaa987: the Pearson correlation of a cell’s expressionxwith each gene’s degree in the network, whether the cell expresses the network’s hubs."signaling_entropy", the signaling entropy rate of Teschendorff and Enver (2017), Nature Communications 8:15599, doi:10.1038/ncomms15599: how evenly a cell’s expression lets a walk spread over the network. The expressionxdefines the walkp_ij = A_ij x_j / (Ax)_i, whose entropy rate,sum_i pi_i log((Ax)_i / x_i)withpi_i = x_i (Ax)_i / x'Ax, is divided by the largest of any walk on the network,log lambda_max(A).
xislog2(10,000 * counts / total + 1.1)over the network’s genes, with each cell’s prepared total of all its counts,<assay>_nCounts, and the papers’ pseudocount, so a network gene without counts enters atlog2(1.1). Only the network’s genes are read, in blocks that fit the memory budget.On a store merged from sources that measured different genes, as its feature columns
measured_in_<source>record, a gene that some source of the selected cells did not measure holds zero counts in that source’s cells, which are no measurement. Such genes are left out, with a warning that names them: the network matches the others alone, and each cell’s total is its total over them, as a store of those genes alone holds it. The artifact then records those genes asmeasured_features_fingerprint.The network is STRING v12.5’s for the species, its links without STRING’s
databasechannel at a recombined score of at least 0.700 (Szklarczyk et al. (2025), Nucleic Acids Research 53:D730-D737, doi:10.1093/nar/gkae1113, CC BY 4.0). The first call downloads it from Nygen’s publicNygen/cytebasebucket into$XDG_CACHE_HOME/cytearc/networks, and every call checks the file against the size and SHA-256 digest that CyteArc records for it. Network genes match features by Ensembl gene ID when the feature IDs are those of the species, and by symbol otherwise; the scores use the largest connected part of the genes matched.The scores do not order every process. On fifteen systems of known order, compared on the methods page, CCAT ordered 12 better than the signaling entropy rate, which left the mouse and human thymus unordered (Spearman’s rho -0.08 and 0.06) where CCAT ordered them (0.37 and 0.26). The signaling entropy rate ordered the mouse small intestine better (0.84 against 0.52). Both measures ranked spinous keratinocytes above basal ones (rho -0.42 and -0.37), and neither ordered the oligodendrocyte lineages. Within a stage, both measures follow a cell’s sequencing depth, CCAT more closely (mean rho with the cell’s total counts 0.66 against 0.54), so the cells of one population are ranked largely by depth. Compare the orders of the stored
ccatandsignaling_entropyarrays, which every artifact holds, and check where potency peaks against known markers before trusting a direction.- Parameters:
cell_selection (
ArtifactRef) – Explicit cells to score; at least two.measure (
Literal['ccat','signaling_entropy']) –"ccat", the default, or"signaling_entropy": the measure that ranks the cells.graph (
ArtifactRef|None) – Explicit connectivity-map or integrated-graph artifact built on the cells ofcell_selection. With it, the measure is smoothed before it ranks the cells: each step keepssmoothingof the neighbors’ values and restarts at the cell’s own,d <- smoothing * P d + (1 - smoothing) * scorewithPthe row-normalized graph, until it is within 1e-12 of its fixed point. Without it the measure ranks the cells as it is.smoothing (
float) – The share of each step taken from the neighbors, above 0 and at most 0.99; used only withgraph.species (
str|None) –"human"or"mouse". None takes the species whose Ensembl gene IDs the features carry; an assay whose feature IDs are not Ensembl gene IDs needs it.network (
str|PathLike[str] |None) – A local copy of the species’ network file, which is checked like a downloaded one, for a machine without network access.from_assay (
str|None) – Name of the RNA assay to score. None uses the default assay.invalidate_cache (
bool) – Recompute rather than reuse a saved artifact.
- Return type:
- Returns:
A
cell_potencyartifact. Its canonical array isdifferentiation;potency,signaling_entropyandccatsit beside it, andload_potency()loads them with the network’s coverage.- Raises:
TypeError – If an argument has the wrong type, or the assay is not an RNAassay.
ValueError – If
measureorspeciesis unknown,smoothingis out of range,graphis built on other cells, the selection holds fewer than two cells, a cell has no counts or none on the network’s genes, or the assay’s features match fewer than 5,000 of the network’s genes.FileNotFoundError – If the network is not cached and cannot be downloaded; the message names the file and the way to supply it.
UnmeasuredCellsError – If the assay did not measure a selected cell.
MemoryBudgetError – If the scores or the smoothing do not fit the memory budget.
PermissionError – If the scores must be computed and the store is not opened with
zarr_mode='r+'. A read-only store returns saved scores.
- waggr(net, cell_selection, *, from_assay=None, features, mode='wmean', tmin=5, log_transform=False, ambiguous_targets='drop', invalidate_cache=False)#
Score weighted gene sets from streamed normalized RNA counts.
Targets are matched to active feature names without case sensitivity. Sources with fewer than
tminmatched non-zero edges are removed. Results are written to the assay’s enrichment group and returned lazily. On a store merged from sources that measured different genes, as its feature columnsmeasured_in_<source>record, the genes offeaturesthat some source of the selected cells did not measure are left out, through a feature selection of the others, with a warning that names them, and each cell’s library size is its total over the genes that every such source measured, as a store of those genes alone holds it: its prepared total less its counts of the other genes. The scores then record those genes asmeasured_features_fingerprint.- Parameters:
net (
DataFrame) – Network withsourceandtargetcolumns. An optionalweightcolumn supplies signed numeric edge weights. Missing weights default to one.from_assay (
str|None) – RNA assay to score. The default assay is used when omitted.cell_selection (
ArtifactRef) – Explicit cells to score.features (
ArtifactRef) – Explicit feature-selection artifact.mode (
Literal['wmean','wsum']) –"wmean"divides each weighted sum by the sum of absolute source weights."wsum"returns the weighted sum.tmin (
int) – Minimum number of matched targets required per source.log_transform (
bool) – Applylog1pafter library-size normalization.ambiguous_targets (
Literal['drop','error']) – Handling of a target that matches several active features, such as a gene symbol shared by two feature ids."drop"removes its edges beforetminpruning, logs a warning, and records the target in the artifact’sdropped_ambiguous_targetsattribute."error"raises.
- Return type:
- Returns:
A complete
enrichment_scoresartifact.- Raises:
PermissionError – If the store is not opened with
zarr_mode='r+'.UnmeasuredCellsError – If the assay did not measure a selected cell.
ValueError – If no selected feature was measured by every source of the selected cells.
Note
Cache identity covers selections, method parameters, normalization, and the prepared network, whose digest hashes only the retained edges. It assumes the stored count matrix is immutable.
scores.potency scores how differentiated each cell is from its expression on a STRING protein network, by CCAT, the default, or the signaling entropy rate, and saves a cell_potency artifact whose canonical array, differentiation, rises along the process, so ds.trajectory.fate(direction=...) takes it as it stands. The first call downloads the species’ network into $XDG_CACHE_HOME/cytearc/networks and checks it against the size and digest that CyteArc records; on a machine without network access, pass a copy as network=. Methods and limitations gives the definitions, the comparison on fifteen systems and where the scores fail.
scores.cell_cycle scores the S-phase and G2M-phase genes of cytearc.quality_control, s_phase_genes and g2m_phase_genes, unless a call passes its own lists, such as s_phase_genes_mouse and g2m_phase_genes_mouse, and matches them to the assay’s feature names with match_gene_names. The same call on a store’s names, match_gene_names(ds.RNA.feats.fetch_all("names"), s_phase_genes), shows which features a run will score, which genes match by a previous symbol, and which match none.
- cytearc.quality_control.match_gene_names(feature_names, genes)#
Match gene names to features without case, falling back to renames.
A gene matches every feature whose name equals it without case. A gene that matches none matches the features named by another symbol of the same gene in
cell_cycle_previous_symbols: a previous symbol for a current one, or the current symbol for a previous one, in that order.- Parameters:
feature_names (
Sequence[object] |ndarray) – The name of each feature.genes (
Sequence[str]) – Gene names to match.
- Return type:
- Returns:
The matched feature indices, the aliases used, and the genes that matched nothing.
- class cytearc.quality_control.cell_cycle_genes.GeneMatch(indices, aliases, unmatched)#
The features that a list of gene names matched.
- indices#
Feature indices in the order of the genes. A gene matches every feature with its name, so a gene listed twice, or names that differ only in case, repeat indices.
- aliases#
Genes matched by another symbol of the same gene, mapped to the feature name they matched.
- unmatched#
Genes that matched no feature.
ds.regulons#
grn infers transcription-factor to target importances with GRNBoost2 on the assay’s stored values, its raw counts or the values of an assay imported from normalized values; the functions in Regulons API reference turn them into regulons. specificity and connection_specificity give the regulon specificity scores of each group of cells and the connection specificity index of each pair of regulons from a stored score artifact, such as AUCell’s, reading its scores a block of cells at a time, so their memory follows a block of scores and the groups and regulons rather than every cell’s scores. They save nothing.
- class cytearc.datastore.namespaces.RegulonsAccessor(store)#
- connection_specificity(scores, *, margin=0.05, cell_selection=None)#
Score how specifically each pair of regulons is active in the same cells.
Gives the connection specificity index (CSI) of
regulons.connection_specificityfrom a stored score artifact, such asscores.aucellwrites, without reading its scores whole: one pass over the scores in blocks of cells merges each block’s sums of products of deviations into the regulons’ correlation matrix. The call holds one block of scores, as float64 too, and the correlations, then the index, two numbers for each pair of regulons, beside a position for each cell. A block holds the cells of one stored chunk of scores, or fewer when the memory budget leaves less room. Nothing is saved.- Parameters:
scores (
ArtifactRef) – Anenrichment_scoresartifact, such as AUCell’s.margin (
float) – Correlation margin: a regulon counts for a pair whose correlation isrwhen it correlates belowr - marginwith both.cell_selection (
ArtifactRef|None) – The cells to read, whichscoresmust hold. Every scored cell when omitted.
- Return type:
DataFrame- Returns:
A symmetric regulons-by-regulons DataFrame, indexed and labeled by the regulons of
scores. A regulon of constant scores correlates 0 with every regulon. The indices equal those ofconnection_specificityfor the same cells’ scores, except where rounding moves a correlation acrossr - margin.- Raises:
TypeError – If
scoresorcell_selectionis not an ArtifactRef, ormarginis not a real number.ValueError – If
marginis not finite,scoresis not anenrichment_scoresartifact, orcell_selectionholds a cell thatscoresdid not score.MemoryBudgetError – If the memory budget cannot hold the cells’ positions, the correlations of every pair of regulons twice over, and a block of one cell’s scores beside one stored chunk’s decode.
- grn(cell_selection, *, features, tfs, from_assay=None, random_seed=0, learning_rate=0.01, max_stages=5000, max_features=0.1, subsample=0.9, early_stop_window=25, early_stopping='stage', nthreads=None, invalidate_cache=False)#
Infer transcription-factor to target importances with GRNBoost2.
For each selected gene, a stochastic gradient boosting regressor predicts its stored values across the selected cells from those of the selected transcription factors, as arboreto’s GRNBoost2 does for pySCENIC: the same regressor settings and early stopping, the same seed for every target, a factor never predicting itself, and importances scaled by the number of fitted stages. The Pearson correlation of each linked factor and target is stored with it. The stored values are raw counts, or the values of an assay imported from normalized values, and the artifact’s
valuesparameter records which:"raw_counts"or"normalized_values".The values of the selected cells and genes are held in memory as float32, so select a representative subset of cells for large data.
- Parameters:
cell_selection (
ArtifactRef) – Cells whose counts are modeled.features (
ArtifactRef) – Feature selection of the genes modeled as targets; the factors among them are the regulators. Genes whose name occurs more than once in the selection are left out, because regulons name genes. On a store merged from sources that measured different genes, as its feature columnsmeasured_in_<source>record, a gene that some source of the selected cells did not measure is left out too, through a feature selection of the others, with a warning that names such genes.tfs (
Iterable[str]) – Candidate transcription factor names, such as a species TF list. Names are matched exactly to feature names.from_assay (
str|None) – RNA assay to model. The default assay when omitted.random_seed (
int) – Random state of every target’s regressor.learning_rate (
float) – Shrinkage of each boosting stage.max_stages (
int) – Most boosting stages per target.max_features (
float) – Fraction of the regulators drawn at each split.subsample (
float) – Fraction of cells drawn for each stage, below 1.early_stop_window (
int) – Stop a target once the mean out-of-bag improvement of this many latest stages is negative.early_stopping (
Literal['stage','consecutive']) –"stage"measures each stage’s improvement on its own out-of-bag cells, as GRNBoost2 does in the pySCENIC 0.12.1 container;"consecutive"compares consecutive stages, as arboreto does with scikit-learn 1.3 and later.nthreads (
int|None) – The most targets fitted at once. The store’s thread count when omitted. Targets are fitted in this process, and withnthreadsabove 1, those left after about two seconds of fitting go to that many worker processes, fewer when the memory budget holds fewer of their copies of the regulators and their fits. Worker processes start as new interpreters that import the main module, so a script keeps its own work underif __name__ == "__main__":. It does not change the result.invalidate_cache (
bool) – Recompute even when a matching result exists.
- Return type:
- Returns:
A complete
grn_adjacenciesartifact.- Raises:
MemoryError – If the counts do not fit the memory budget.
PermissionError – If the store is not opened with
zarr_mode='r+'.UnmeasuredCellsError – If the assay did not measure a selected cell.
ValueError – If no selected gene was measured by every source of the selected cells.
- load_grn(grn)#
Load a GRN artifact as a table of named links.
- Parameters:
grn (
ArtifactRef) – Artifact returned byregulons.grn.- Return type:
- Returns:
The links with factor and target names, and the inputs they were inferred from.
- profiles(groups, *, from_assay=None, cell_selection=None)#
Log counts per million of the summed raw counts of each cell group.
Summing small groups of similar cells, such as a fine clustering (metacells), averages out the sampling noise of single cells. Gene programs and region-to-gene links read such profiles.
- Parameters:
groups (
ArtifactRef|str) – Clustering artifact or cell metadata column that groups the cells, as forcompare.compute_bulk.from_assay (
str|None) – Assay to read. The default assay when omitted.cell_selection (
ArtifactRef|None) – Cells to read, as forcompare.compute_bulk.
- Return type:
DataFrame- Returns:
A groups-by-features DataFrame of
log1pcounts per million, indexed by the group labels, as the columns ofcompare.compute_bulkare. Columns are peak ids (chrom:start-end) for an ATAC assay and feature names otherwise; names that several features share are left out.- Raises:
UnmeasuredCellsError – If the assay did not measure a cell that is read.
- specificity(scores, groups, *, cell_selection=None)#
Score how specific each regulon’s activity is to each group of cells.
Gives the regulon specificity scores (RSS) of
regulons.regulon_specificityfrom a stored score artifact, such asscores.aucellwrites, without reading its scores whole: one pass over the scores in blocks of cells sums each regulon’s activity, and a second sums, for each group, the regulon’s share of activity in the group’s cells and their terms of the Jensen-Shannon divergence. The call holds one block of scores and three numbers for each group and regulon, beside a position, a label, and a code for each cell. A block holds the cells of one stored chunk of scores, or fewer when the memory budget leaves less room. Nothing is saved.- Parameters:
scores (
ArtifactRef) – Anenrichment_scoresartifact of finite, non-negative scores, such as AUCell’s. chromVAR’s z-scores, which can be negative, are refused.groups (
ArtifactRef|str) – Clustering artifact or user-owned cell metadata column that groups the cells, read for the scored cells ascompare.compute_bulkreads it. An artifact’s own cells must include them.cell_selection (
ArtifactRef|None) – The cells to score, whichscoresmust hold. Every scored cell when omitted.
- Return type:
DataFrame- Returns:
A groups-by-regulons DataFrame of the scores, indexed by the group labels in their natural order, named
group, with a column for each regulon ofscores. A regulon without activity in the cells scores NaN. Up to rounding, these are the scores thatregulon_specificitygives for the same cells’ scores and labels.- Raises:
TypeError – If
scoresorcell_selectionis not an ArtifactRef, orgroupsis neither an ArtifactRef nor a column name.ValueError – If
scoresis not anenrichment_scoresartifact,cell_selectionholds a cell thatscoresdid not score,groupsholds no label, or a missing label, for a cell to score, or a score is negative or not finite.MemoryBudgetError – If the memory budget cannot hold the cells’ positions, labels, and codes, the sums, and a block of one cell’s scores beside one stored chunk’s decode.
ds.perturbation#
ds.perturbation analyzes a pooled CRISPR screen: it calls the guides of each cell or imports Cell Ranger’s calls, labels each cell by the genes that its guides target, measures each perturbation’s effect on its target gene and its E-distance from the control cells, separates knocked-out cells from escapers with Mixscape, tests which genes each perturbation changes, and clusters the perturbations whose profiles agree. Each method saves an artifact, which a load_* method reads as a record of cytearc.perturbation. Perturbation API reference explains each method, its settings and checks, and its record.
- class cytearc.datastore.namespaces.PerturbationAccessor(store)#
- associations(labels, *, from_assay='RNA', pairs='trans', features=None, positive_controls='targets', id_column='target_gene_id', integration='union', moi='low', resampling=None, sample_column=None, covariates=None, side='both', n_resamples=(499, 4999, 24999), stage_threshold=0.02, approximation='skew_normal', min_nonzero=7, n_calibration_pairs=None, alpha=0.1, seed=0, invalidate_cache=False)#
Test whether each perturbation changes each gene, with calibrated p-values.
SCEPTRE’s low-MOI test (Barry et al. 2024), the default, compares, for each pair of a perturbation and a gene, the cells that carry the perturbation alone with the control cells of the labels;
moi="high"runs its high-MOI test, described below. A negative binomial regression of the gene’s counts on the cells’ covariates, fitted on those cells together under the null hypothesis, scores each cell, and the pair’s statistic is the perturbed cells’ standardized score. The fit takes Poisson coefficients and the size that maximizes the likelihood with the Poisson means held fixed. Its p-value comes from the same statistic over random sets of as many cells drawn from the perturbed and control cells:n_resamples[0]sets first; for a pair whose p-value is then at moststage_threshold,n_resamples[1]fresh sets whose statistics a skew-normal fit extends to far smaller p-values; and when the fit’s tail beyond those statistics’ 99th percentile holds less than half of their own share there,n_resamples[2]fresh sets (approximation="none"keeps the second round’s p-values). The fit does not depend on which of the pair’s cells carry the perturbation, so the test is exact when those cells are exchangeable under the null hypothesis.The covariates are log detected features and log UMIs of each cell in
from_assay, indicators of the samples ofsample_column, and the numeric cell columns ofcovariates. Only the tested cells, the control cells and the cells of the tested targets or guides, need a sample label and covariate values that are not missing. A pair is tested when at leastmin_nonzeroperturbed andmin_nonzerocontrol cells express the gene, and p-values are adjusted by Benjamini-Hochberg within each set of pairs. A pair that passes QC has no statistic when the covariates determine which of its cells carry the perturbation, as they do when a target’s cells are exactly the cells of samples, or of a binary covariate, that hold no control cell: it gets no p-value or fold change,stage0, and is not significant or counted as tested, and a warning names its target. The p-values count only the random sets that have a statistic. The fold change is log2 of the perturbed cells’ counts over their means under the pair’s fit, the estimator of the SCEPTRE book.Three sets of pairs are tested:
Discovery pairs: with
pairs="trans", every target with every feature offeatures; or the rows of a DataFrame oftargetandfeature.Calibration pairs: up to 100 distinct groups of control guides, drawn at random with as many guides as the median target and possibly sharing guides, paired at random with features of the whole assay that pass QC; as many pairs as the discovery pairs that pass QC by default. A group’s treatment cells are the control cells whose one guide is in the group, and every other control cell is its comparison: the cells of the other control guides, and the control cells with several control guides, even guides of the group, since under the null hypothesis no control guide has an effect. The pairs should give no discovery; the grade of their false discoveries follows the SCEPTRE book: excellent (0 or 1), mild (up to 6), moderate (up to 14) or severe. The grade is
"none"when no check runs: withn_calibration_pairs=0; with fewer than 2 control guides that are the one guide of a control cell; by default, when no discovery pair passes QC; when no pair of a group and a feature passes QC; or when no calibration pair has a statistic. A warning says why in all but the first case.Positive-control pairs: with
positive_controls="targets", each target with its own gene, matched asefficiency()matches them; or a DataFrame oftargetandfeature.
With
integration="singleton", each guide is tested alone instead of the guides of a target together, and the calibration groups hold one control guide each.In a high-MOI screen each cell carries several guides, so few cells carry a target alone and almost none carry control guides only. With
moi="high", as in SCEPTRE’s high-MOI test (Barry et al. 2021, 2024), a target’s treatment cells are the labeled cells whose guides target it, or with"singleton"the cells that carry the guide, whatever else they carry, and every other labeled cell is its comparison: cells of other targets or of sibling guides, cells with control guides and cells without a called guide. Every labeled cell is tested, so each one needs a sample label, covariate values, and guide UMIs, since the covariates add log detected guides and log guide UMIs of the guide assay. Each gene is fitted once on all labeled cells, and all of its pairs share that fit.resampling="conditional", the default at high MOI, fits a logistic regression of each group’s cells on the covariates and draws every cell into a random set with its fitted probability, the conditional randomization test, which stays valid when sequencing depth drives both the detection of guides and the expression of genes;"permutation"draws as many cells as the group uniformly from all cells. The calibration groups take any control guide called in a labeled cell, as many guides as the median target or all of them when fewer, and their treatment cells, the cells that carry any guide of the group, are compared with all other labeled cells, so one control guide is enough; the grade is"none"when no labeled cell carries one. QC counts the expressing cells of each group against all other cells, and a target whose cells are exactly the cells of samples, or of a binary covariate, has no statistic.The tests save their diagnostics, which
ds.artifacts.inspect(tests).diagnosticsreturns:calibrationStatus,"checked","off"or why no check ran;controlGuides, the control guides that the calibration groups draw from;calibrationGrade;falseDiscoveriesamong thenegativeControlPairs; androwsWithoutStatisticandcalibrationGroupsWithoutStatistic, the tested targets or guides and the calibration groups whose pairs pass QC without a statistic, with up to five of each inrowWithoutStatisticExamplesandcalibrationGroupWithoutStatisticExamples. Each warning of the calibration check and of pairs without a statistic is aDiagnosticWarningthat comes again each time the tests are reused. Withpositive_controls="targets", a warning names the targets or guides whose target matches no feature each time the tests are called.On a store merged from sources that measured different features, as its feature columns
measured_in_<source>record, the tests read only the features that every source of the compared cells measured. The compared cells are the control cells and the cells that carry one target or guide alone, or at high MOI every labeled cell. Trans pairs leave the other features offeaturesout, through a feature selection of the rest, and the positive controls of the targets leave out the targets’ genes among them, each with a warning that names them; the calibration pairs draw from those features alone; and each cell’s UMIs and detected features, the covariates, cover them alone, as a store of those features holds them. A table of pairs or of positive controls that names another feature is refused. The tests then record those features asmeasured_features_fingerprint.- Parameters:
labels (
ArtifactRef) – Aperturbation_labelsartifact.from_assay (
str) – The expression assay, whose counts are tested.pairs (
str|DataFrame) –"trans", or a DataFrame with columnstargetandfeature(feature IDs, or names that one feature has).features (
ArtifactRef|None) – Afeature_selectionartifact offrom_assaywhose features trans pairs test, such as highly variable genes.positive_controls (
str|DataFrame|None) –"targets", a DataFrame likepairs, or None.id_column (
str|None) – The feature column of the guide assay that holds each guide’s target feature ID, or None to match targets by name.integration (
str) –"union"or"singleton".moi (
str) –"low"for a screen of one guide per cell, or"high"for a screen of several guides per cell.resampling (
str|None) –"conditional"or"permutation"at high MOI, or None for"conditional"there and"permutation", the only choice, at low MOI.sample_column (
str|None) – A cell metadata column whose samples get indicators, or None.covariates (
Sequence[str] |None) – Numeric cell metadata columns to adjust for, or None.side (
str) –"both","left"for a decrease, or"right"for an increase.n_resamples (
Sequence[int]) – The random sets of the three rounds, a sequence of three integers such as a tuple or a list.stage_threshold (
float) – The p-value at or below which a pair takes the second round: 0, which keeps the first round’s p-values, or at least the smallest first-round p-value, 2 / (n_resamples[0]+ 1) withside="both"and 1 / (n_resamples[0]+ 1) otherwise, so 99 or 49 first-round sets for the default of 0.02.approximation (
str) –"skew_normal"or"none".min_nonzero (
int) – The fewest perturbed and control cells that express a tested gene.n_calibration_pairs (
int|None) – The calibration pairs, None for as many as the discovery pairs that pass QC, or 0 for no calibration check. A positive number runs the check without discovery pairs too.alpha (
float) – The false discovery rate ofsignificant.seed (
int) – The seed of the random sets and the calibration pairs.invalidate_cache (
bool) – Test again instead of reusing saved tests.
- Return type:
- Returns:
A complete
perturbation_associationsartifact scoped tofrom_assay, with one row per pair. Read it withload_associations().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
labelsis not aperturbation_labelsartifact, an assay, column, target or feature is unknown, a number is out of range, a positivestage_thresholdis below the smallest first-round p-value,resampling="conditional"goes withmoi="low", trans pairs have nofeatures, a table of pairs is malformed or names a feature that some source of the compared cells did not measure, every feature offeatureswas left out, at low MOI no labeled cell carries control guides only, or a tested cell has no sample label, a covariate value that is missing or not finite, or at high MOI no guide UMIs.PermissionError – If the store is read-only and the tests are not saved yet.
MemoryError – If one feature’s counts over the tested cells, or at high MOI the tests of one gene, do not fit the memory budget; the message names the smallest budget that runs the tests.
- call_guides(cell_selection, *, from_assay=None, method='poisson_gaussian', min_umi=None, fraction_threshold=None, sample_column=None, invalidate_cache=False)#
Call the guides of each cell from its guide counts.
Every cell holds a few ambient guide molecules, so a guide is called in a cell only when its UMIs stand out. Four methods decide:
"poisson_gaussian"(default) fits each guide’s UMI counts in the cells that hold any, as a Poisson background and a Gaussian on log2 counts (Replogle et al. 2022, as crispat and pertpy fit it), and calls the guide from the smallest count whose Gaussian posterior exceeds one half.min_umidefaults to 1."gaussian"fits two Gaussians with one shared variance to log10(count + 1) of every cell, as Cell Ranger describes, and calls from the smallest count where the higher one wins.min_umidefaults to 3, Cell Ranger’s floor. When most cells hold no UMI of a guide, the fit can split them from the cells with ambient UMIs and call those; a warning names this case."fixed"calls every guide frommin_umiUMIs, which it needs."top_guide"calls each cell’s top guide when the cell holdsmin_umiguide UMIs (default 5) and the top guide’s share of them exceedsfraction_threshold(default 0.8), as the maximum rule of the SCEPTRE book does. A cell gets at most one call; a cell with fewer guide UMIs, or whose top guide holds a smaller share, is labeled"Negative".
The fitted methods fit each guide in each sample of
sample_columnseparately and save the fits, the thresholds and each guide’s histogram of counts as aguide_thresholdsartifact, which the calls record as an input.min_umiraises each threshold and belongs to the calls, so calling again with another floor reuses the fits and reads the counts once. The counts are read in row blocks within the memory budget: once to count each guide’s UMIs and once to call. The histograms grow with the distinct UMI counts of each guide in each sample, many more in a screen whose cells carry many guides, and take what the counts leave of the budget once they stream in blocks of the rows of a stored chunk. Each step is charged to one memory ledger before it allocates, the calling pass before it reads a count: each cell’s detected guides bound its calls underfixedand the fitted methods, whose fits give the number of calls, andtop_guidemakes at most one call per cell. A refusal names the step and the budget that passes it. When the histograms stop while counts remain to be read, their refusal says so and names what the histograms of every row need, estimated from the rows read of each sample, with a sample not read yet taking the counts of the sample read most. That budget gets past the histograms unless the cells read later hold more distinct counts per cell than those read, as a deeper-sequenced sample stored after the others can; the calling pass after the fits names its own. The fits are saved once the calls that they make have passed their steps.The calls are saved as a
guide_callsartifact, asimport_guide_calls()saves Cell Ranger’s:valueslabels each cell with its one called guide,"Negative"or"Multiple", beside each cell’s number of calls, top guide, top UMIs, share and total guide UMIs, and its called guides with their UMIs.A fit whose status is not
"fitted"calls no cell. The calls save their diagnostics, whichds.artifacts.inspect(calls).diagnosticsreturns:guideFits, the fits of each guide in each sample;fitsCallingNoCell, those that call no cell;fitsNoCells,fitsTooSparse,fitsNoFitandfitsNoPositive, those of each such status;fitCallingNoCellExamples, up to five of them, such as'CRISPR3' in sample 'L2'; the fit counts are None and the examples empty for"fixed"and"top_guide".cellsWithCallcounts the cells with a call andcellsWithSeveralGuidesthose of them with several guides. Fits that call no cell, and with"gaussian"a majority of called cells with several guides, each give aDiagnosticWarningevery time the calls are computed or reused.- Parameters:
cell_selection (
ArtifactRef) – The cells to call.from_assay (
str|None) – The guide assay, declared with typeCRISPR, or None for the store’s only assay declaredCRISPR, whatever its name.method (
str) –"poisson_gaussian","gaussian","fixed"or"top_guide".min_umi (
int|None) – The UMI floor: the fewest UMIs of a called guide for the fitted methods and"fixed", and the fewest guide UMIs of a called cell for"top_guide". None takes the method’s default;"fixed"needs a value.fraction_threshold (
float|None) – For"top_guide"only, the share of the cell’s guide UMIs that its top guide must exceed, at least 0 and below 1. None takes 0.8.sample_column (
str|None) – For the fitted methods only, a cell metadata column whose labels split the cells into samples that are fitted separately, such as GEM wells. Every selected cell needs a label. None fits all selected cells together.invalidate_cache (
bool) – Compute again instead of reusing saved fits and calls.
- Return type:
- Returns:
A complete assay-scoped
guide_callsartifact. Read it withload_guide_calls(), read its fits withload_guide_thresholds(), and plot them withds.plots.guide_thresholds.- Raises:
TypeError – If an argument has the wrong type, or the assay is not declared
CRISPRor does not store unsigned integer counts.ValueError – If
from_assayis not an assay of the store, or without it, if the store holds no assay declaredCRISPR, or several.ValueError – If an argument is out of range or does not apply to the method, a sample column is unknown or lacks a label for a selected cell, or a guide ID is empty, repeated, or reserved.
UnmeasuredCellsError – If the guide assay did not measure a selected cell.
PermissionError – If the store is read-only and the calls are not saved yet.
MemoryError – If the histograms or the calls do not fit the memory budget. The histograms raise it while the counts are read, before they would hold more than the counts leave them.
- cluster(profiles, *, perturbations=None, metric='correlation', min_cluster_size=4, min_samples=2, selection='eom', seed=0, invalidate_cache=False)#
Cluster the perturbations whose profiles change expression alike.
As Replogle et al. (2022) did, the distance between two profiles is 1 minus their Pearson correlation over the features, which ignores how strongly each perturbation acts;
metric="euclidean"keeps it. HDBSCAN finds the clusters on these distances, through scikit-learn’sHDBSCAN(metric="precomputed")withalpha=1and without a single cluster, and a perturbation it cannot place gets the cluster -1.min_samplesfollows scikit-learn, which counts the point itself, so themin_samples=1of thehdbscanpackage, which Replogle et al. ran withmin_cluster_size=4andselection="eom", is 2 here, the default. Average linkage of the same distances orders the perturbations for a heatmap. A UMAP layout of each perturbation’s 15 nearest perturbations by the same distances places them in two dimensions, from the first two principal components of the profiles, on one thread, so that it depends only onseed.- Parameters:
profiles (
ArtifactRef) – Aperturbation_profilesartifact fromprofiles().perturbations (
Sequence[str] |None) – The names of the perturbations to cluster, in any order, such as those with a significant E-distance and a low remaining fraction, or None for every profile.metric (
str) –"correlation"or"euclidean".min_cluster_size (
int) – The fewest perturbations of a cluster, at least 2.min_samples (
int) – The perturbations within a perturbation’s core distance, itself included, at least 1.selection (
str) –"eom"to select clusters by excess of mass, or"leaf"to take the leaves of HDBSCAN’s cluster tree.seed (
int) – The seed of the layout, from 0 to 2**32 - 1.invalidate_cache (
bool) – Cluster again instead of reusing saved clusters.
- Return type:
- Returns:
A complete
perturbation_clustersartifact scoped to the assay of the profiles, with one row per clustered perturbation. Read it withload_clusters().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
profilesis not aperturbation_profilesartifact or was saved without its diagnostics, as earlier releases saved them,perturbationsnames a perturbation without a profile, fewer than 3 perturbations or 2 features remain,min_samplesexceeds the perturbations, or a setting is unknown or outside its range.PermissionError – If the store is read-only and the clusters are not saved yet.
MemoryError – If the profiles and the distances between them, with their working copies, do not fit the memory budget.
- edistance(labels, coordinates, *, by='target', n_permutations=1000, random_seed=0, invalidate_cache=False)#
Measure how far each perturbation moves cells from the control cells.
The E-distance of Peidli et al. (2024, scPerturb) compares the cells that carry a target alone, or a guide alone with
by="guide", with the control cells of the labels in a coordinate space such as a PCA: twice the mean squared distance between the groups, minus the mean squared distance within each group over distinct pairs. Its expected value is twice the squared distance between the group means, so it grows as a perturbation moves the center of its cells away from the controls, and a change in their spread alone leaves it near 0. A permutation test drawsn_permutationsgroups of the perturbed group’s size from the pooled cells, and the p-value is the share of draws, counting the observed groups, whose E-distance reaches the observed one, adjusted across rows by Benjamini-Hochberg. Each row draws from its own seed, derived fromrandom_seedand the row.The coordinates can be any reduction, batch correction, imported coordinates or normalized values. Cells of the labels without coordinates are left out and counted in a log message. A row with fewer than two perturbed cells has no E-distance and the status
"too_few_cells".- Parameters:
labels (
ArtifactRef) – Aperturbation_labelsartifact fromlabels().coordinates (
ArtifactRef) – The coordinate artifact.by (
str) –"target"for one row per target gene, or"guide"for one row per guide.n_permutations (
int) – The permutations of each test, from 0, which skips the tests, to 1,000,000.random_seed (
int) – The seed of the permutations, at least 0.invalidate_cache (
bool) – Measure again instead of reusing a saved table.
- Return type:
- Returns:
A complete
perturbation_edistanceartifact scoped to the assay of the coordinates. Read it withload_edistance().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
labelsis not aperturbation_labelsartifact,coordinatesis not a coordinate artifact,byis unknown, a number is out of range, or fewer than two control cells have coordinates.PermissionError – If the store is read-only and the table is not saved yet.
MemoryError – If the measurement does not fit the memory budget.
- efficiency(labels, *, from_assay='RNA', by='target', id_column='target_gene_id', invalidate_cache=False)#
Measure how strongly each perturbation changes its target gene.
For each target gene, or each guide with
by="guide", the target gene’s expression in the cells that carry the perturbation alone is compared with its expression in the control cells of the labels. A cell carries a target alone when its called guides target that gene and no other, with or without control guides, and a guide alone when it is the cell’s one called guide. The comparison reports the mean UMIs of the gene in each group, as Cell Ranger’s perturbation efficiency does, the mean expression after scaling each cell to the median library size of the compared cells that hold a UMI offrom_assay, the fraction of the control expression that remains, its base-2 logarithm, and a two-sided Mann-Whitney test on the scaled expression with Benjamini-Hochberg adjustment. The test’s p-value is the normal approximation with the corrections for ties and for continuity, which is unreliable for groups of a few cells. A knockdown leaves a fraction below 1 and an activation a fraction above 1. A row whose control cells hold no UMI of the gene has no fraction and the status"no_control_expression", but keeps its p-value, which counts in the adjustment.Each target is matched to a feature of
from_assayby the feature ID thatid_columnof the guide assay gives its guides, which 10x imports fill from Cell Ranger’s feature reference, when its guides give one ID and the feature IDs are unique; otherwise by the one feature whose name equals the target, when no other feature shares that name. Only the target genes are read, feature-major when that reads less. A target that matches no feature is kept with the status"no_feature". The table saves its diagnostics, whichds.artifacts.inspect(efficiency).diagnosticsreturns:rowsWithoutFeature, the rows whose target matches no feature, androwWithoutFeatureExamples, up to five of them, by guide each guide with its target, such asguide 'CRISPR2' (target 'ENH1'). Such rows give aDiagnosticWarningeach time the table is measured or reused.On a store merged from sources that measured different features, as its feature columns
measured_in_<source>record, a target whose gene some source of the compared cells, the cells that carry a perturbation alone and the control cells, did not measure has the status"no_feature", since its zero counts in that source’s cells are not measurements, as in a store of the genes that every such source measured, and aDiagnosticWarningthat names the gene and the sources that lack it each time the table is measured or reused. Each cell’s library size is its total over the features that every such source measured, as a store of those features alone holds it, and the table then records those features asmeasured_features_fingerprint.- Parameters:
labels (
ArtifactRef) – Aperturbation_labelsartifact fromlabels().from_assay (
str) – The expression assay.by (
str) –"target"for one row per target gene, or"guide"for one row per guide.id_column (
str|None) – The feature column of the guide assay that holds each guide’s target feature ID, or None to match by name only.invalidate_cache (
bool) – Measure again instead of reusing a saved table.
- Return type:
- Returns:
A complete
perturbation_efficiencyartifact scoped tofrom_assay. Read it withload_efficiency().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
labelsis not aperturbation_labelsartifact,from_assayis not an assay,byis unknown,id_columnis not a feature column of the guide assay, no labeled cell carries control guides only, or no compared cell holds a UMI offrom_assay.PermissionError – If the store is read-only and the table is not saved yet.
MemoryError – If the comparison does not fit the memory budget.
- import_guide_calls(path, *, cell_selection, from_assay=None, barcode_prefix=None, barcode_suffix=None, barcode_pattern=None, invalidate_cache=False)#
Import Cell Ranger’s guide calls for a set of cells.
Cell Ranger’s CRISPR Guide Capture analysis calls the guides of each cell and writes them to
crispr_analysis/protospacer_calls_per_cell.csv. The import joins each row’s barcode to a selected cell and saves the calls as aguide_callsartifact, which CyteArc’s own guide calling writes too. A selected cell absent from the file has no call, as Cell Ranger leaves out cells without a confident call. The guide counts of the assay give each cell’s top guide, its UMIs, and the cell’s total guide UMIs, read in row blocks within the memory budget.A cell’s ID is
barcode_prefix, the barcode andbarcode_suffix, matched exactly;barcode_patternkeeps the part of each barcode that itsbarcodegroup matches first. The barcodes join the cells through the join that every importer of barcodes shares. A merged store prefixes each sample’s barcodes with its name and two underscores, so import each sample’s file with its own prefix and a cell selection of that sample; a selection whose cells the file cannot reach is refused, since its other cells would be labeled"Negative". A sample’s name may end with_: the IDs of the cells ofpool_, such aspool___AAAC-1, also start withpool__, so their prefix ispool___, and a prefix that ends with__refuses cells whose IDs go on from it with_. Without a prefix, the cells’ samples are those of the store’s cell column of sources, which a merge writes when its sources measured different features; a store without one refuses cells whose IDs go on with_after their first__. The artifact’s diagnostics, whichds.artifacts.inspect(calls).diagnosticsreturns, count the file’s barcodes by the cell ID they name infileBarcodes, those that match no cell of the store inunmatchedBarcodes, which a warning names, and those of cells outside the selection, such as cells that QC filtering removed, inunselectedBarcodes, which a log message names;unmatchedBarcodeExamplesandunselectedBarcodeExamplesshow up to five of each beside the cell ID it derives. A reused import reports both again. Two barcodes that name one cell raiseValueError.Each step is charged to one memory ledger before it allocates, from the file’s rows,
|separators and bytes, counted in one streamed pass before the file is parsed: the parsed file, the selected cells’ IDs, the cell IDs that the prefix, suffix and pattern derive and the join’s matching of them, the padded calls, as wide as the most calls of one row, the guide counts that stream to summarize each cell, and the text of the labels. A refusal names the step and the budget that passes it, before anything is written.The artifact’s
valueshold the called guide’s ID for a cell with one call,"Negative"for a cell with none, and"Multiple"for a cell with several. Its other per-cell arrays aren_guides,top_guide(the guide with the most UMIs, an empty string for a cell with no guide UMIs),top_umi,top_fraction(the top guide’s share of the cell’s guide UMIs, NaN without UMIs) andtotal_umi, and the two-dimensionalguide_codesandguide_umis, which hold each cell’s called guides, most UMIs first, as positions among the assay’s guides, padded with -1 and 0.guidesholds the guide IDs in assay order.select_cellsreads the one-dimensional arrays, andartifacts.load_valuesreads every per-cell array.- Parameters:
path (
str|PathLike[str]) – Cell Ranger’sprotospacer_calls_per_cell.csv, plain or gzip-compressed, whatever its name.cell_selection (
ArtifactRef) – The cells that the calls label.from_assay (
str|None) – The guide assay, declared with typeCRISPR, or None for the store’s only assay declaredCRISPR, whatever its name.barcode_prefix (
str|None) – Text that precedes each barcode in the cell IDs, such as"lane1__"in a merged store. None, or an empty text, adds nothing.barcode_suffix (
str|None) – Text that follows each barcode in the cell IDs, such as"-1". None, or an empty text, adds nothing.barcode_pattern (
str|None) – A regular expression whose named groupbarcodeis the part of each barcode that names the cell, found asre.searchfinds it, such asr"^(?P<barcode>[ACGT]{16})"; a barcode it does not match names no cell. None keeps the whole barcode.invalidate_cache (
bool) – Import again instead of reusing saved calls.
- Return type:
- Returns:
A complete assay-scoped
guide_callsartifact. Read it withload_guide_calls()or plot it withds.plots.guide_calls.- Raises:
TypeError – If an argument has the wrong type, or the assay is not declared
CRISPRor does not store unsigned integer counts.ValueError – If
from_assayis not an assay of the store, or without it, if the store holds no assay declaredCRISPR, or several.ValueError – If the call file is malformed, a guide ID is empty, repeated, or a label reserved for cells without one guide, a called guide is not a feature of the assay, a guide count exceeds the uint32 maximum,
barcode_patternhas nobarcodegroup, two barcodes name one cell, or the file’s barcodes cannot reach every selected cell: withbarcode_prefix, a cell whose ID does not start with it or goes on with_from a prefix that ends with__, withbarcode_suffix, a cell whose ID does not end with it, and without a prefix, cells from several samples of a merged store or whose IDs do not tell their sample.UnmeasuredCellsError – If the guide assay did not measure a selected cell.
PermissionError – If the store is read-only and the calls are not saved yet.
MemoryBudgetError – If a step of the import does not fit the memory budget; the refusal names the step and the budget that passes it.
- labels(calls, *, controls, target_column='target_gene_name', targets=None, policy='single', invalidate_cache=False)#
Label each cell by the genes that its called guides target.
Each guide targets one gene, and control guides, such as non-targeting guides, target none. A cell’s label is
"Negative"without a called guide,"control"with control guides only, the gene when its guides target one gene, with or without control guides, and"Multiple"when they target several. Withpolicy="combinations", a cell whose guides target several genes is labeled with the genes, sorted and joined by"+", such as"GENE1+GENE2".Each guide’s target comes from
target_columnof the guide assay’s features, which 10x imports fill from Cell Ranger’s feature reference (target_gene_name, with"Non-Targeting"for non-targeting guides), andtargetsreplaces the column’s target of the guides it names. Control guides are named by their target, never guessed.The labels are saved as a
perturbation_labelsartifact for the cells of the calls:valuesholds the labels besideguide_label(the cells’ labels in the calls),is_control,n_targets, andtarget_codes, which holds each cell’s genes as positions in the artifact’stargets, padded with -1, so a cell’s full set of genes is kept under either policy.select_cellsreads the one-dimensional arrays, andartifacts.load_valuesreads every per-cell array.- Parameters:
calls (
ArtifactRef) – Aguide_callsartifact, imported from Cell Ranger or made bycall_guides().controls (
Sequence[str]) – The targets of control guides, such as["Non-Targeting"].target_column (
str|None) – The feature column of the guide assay that holds each guide’s target, or None to take every target fromtargets.targets (
Mapping[str,str] |None) – Targets by guide ID that replace the column’s, or None.policy (
str) –"single"or"combinations".invalidate_cache (
bool) – Label again instead of reusing saved labels.
- Return type:
- Returns:
A complete assay-scoped
perturbation_labelsartifact. Read it withload_labels().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
callsis not aguide_callsartifact or was saved without its diagnostics, as earlier releases saved called guides,controlsnames no target or a blank one, neithertarget_columnnortargetsis given, the target column is not a feature column,targetsnames a guide that is not in the assay or gives an empty target, a target that is not a control is a reserved label or, with"combinations", holds"+", a control matches no target, a called guide has no target, orpolicyis unknown.PermissionError – If the store is read-only and the labels are not saved yet.
MemoryError – If the labeling does not fit the memory budget.
- load_associations(tests)#
Read saved association tests.
- Parameters:
tests (
ArtifactRef) – Aperturbation_associationsartifact fromassociations().- Return type:
- Returns:
The discovery, calibration and positive-control pairs.
- Raises:
TypeError – If
testsis not an ArtifactRef.ValueError – If it is not a
perturbation_associationsartifact, or tests saved without their diagnostics, as earlier releases saved them; the error names the call that tests anew.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
MemoryError – If the tables of its pairs do not fit the datastore memory budget.
- load_clusters(clusters)#
Read saved perturbation clusters with the distances between their profiles.
The distances are computed again from the saved profiles, as the clustering computed them.
- Parameters:
clusters (
ArtifactRef) – Aperturbation_clustersartifact fromcluster().- Return type:
- Returns:
Each perturbation’s cluster, membership strength, cells and place in the layout, the leaf order and the distances.
- Raises:
TypeError – If
clustersis not an ArtifactRef.ValueError – If it is not a
perturbation_clustersartifact, or its profiles were saved without their diagnostics, as earlier releases saved them.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
MemoryError – If the distances between the profiles do not fit the memory budget.
- load_edistance(edistance)#
Read a saved E-distance table.
- Parameters:
edistance (
ArtifactRef) – Aperturbation_edistanceartifact fromedistance().- Return type:
- Returns:
One row per target or guide, with the permutations and seed.
- Raises:
TypeError – If
edistanceis not an ArtifactRef.ValueError – If it is not a
perturbation_edistanceartifact.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
- load_efficiency(efficiency)#
Read a saved perturbation efficiency table.
- Parameters:
efficiency (
ArtifactRef) – Aperturbation_efficiencyartifact fromefficiency().- Return type:
- Returns:
One row per target or guide.
- Raises:
TypeError – If
efficiencyis not an ArtifactRef.ValueError – If it is not a
perturbation_efficiencyartifact, or a table saved without its diagnostics, as earlier releases saved them; the error names the call that measures it anew.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
- load_guide_calls(calls)#
Read saved guide calls as a table of cells and a table of calls.
- Parameters:
calls (
ArtifactRef) – Aguide_callsartifact, such as one fromimport_guide_calls().- Return type:
- Returns:
The calls, with one row per cell and one row per called guide of a cell, and the guide IDs of the assay.
- Raises:
TypeError – If
callsis not an ArtifactRef.ValueError – If it is not a
guide_callsartifact, or calls ofcall_guides()saved without their diagnostics, as earlier releases saved them; the error names the call that makes them anew.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
MemoryError – If its values do not fit the datastore memory budget.
- load_guide_thresholds(thresholds, *, guides=None)#
Read the fitted thresholds of guide calls, with each guide’s histogram.
- Parameters:
thresholds (
ArtifactRef) – Guide calls ofcall_guides()withmethod="poisson_gaussian"or"gaussian", or theirguide_thresholdsartifact. Read through the calls, the table also holds the smallest called count oncemin_umiapplies.guides (
Iterable[str] |None) – The IDs of the guides to read, such as a list, a NumPy array or theguidesindex of a loaded record; None reads every guide.
- Return type:
- Returns:
One row per sample and guide with its status, threshold and fitted parameters, and one row per sample, guide and UMI count with its cells.
- Raises:
TypeError – If
thresholdsis not an ArtifactRef, orguidesis text or not a collection of guide IDs.ValueError – If
thresholdsholds no fitted thresholds, or a guide is not a guide of the assay, orthresholdsis guide calls saved without their diagnostics, as earlier releases saved them.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
MemoryError – If the tables do not fit the memory budget.
- load_labels(labels)#
Read saved perturbation labels as tables of cells, targets and guides.
- Parameters:
labels (
ArtifactRef) – Aperturbation_labelsartifact fromlabels().- Return type:
- Returns:
One row per cell, one row per cell and gene its guides target, one row per guide with its target, and the controls and policy.
- Raises:
TypeError – If
labelsis not an ArtifactRef.ValueError – If it is not a
perturbation_labelsartifact.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
MemoryError – If its values do not fit the datastore memory budget.
- load_mixscape(classes)#
Read saved Mixscape classes.
- Parameters:
classes (
ArtifactRef) – Amixscape_classesartifact frommixscape().- Return type:
- Returns:
Each cell’s class, posterior and score, each target’s fit in each split, and its DE genes.
- Raises:
TypeError – If
classesis not an ArtifactRef.ValueError – If it is not a
mixscape_classesartifact.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
- load_profiles(profiles)#
Read saved perturbation profiles.
- Parameters:
profiles (
ArtifactRef) – Aperturbation_profilesartifact fromprofiles().- Return type:
- Returns:
Each perturbation’s profile with its cells and masked feature, the perturbations left out, and each sample’s control cells and control statistics of each feature.
- Raises:
TypeError – If
profilesis not an ArtifactRef.ValueError – If it is not a
perturbation_profilesartifact, or profiles saved without their diagnostics, as earlier releases saved them; the error names the call that computes them anew.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
MemoryError – If its profiles do not fit the memory budget.
- load_signature(signature, *, features=None)#
Read a saved perturbation signature.
- Parameters:
signature (
ArtifactRef) – Aperturbation_signatureartifact fromsignature().features (
Sequence[str] |None) – The IDs of the features to read, or None for every feature of the signature.
- Return type:
- Returns:
The signature of every cell, with each cell’s control flag, sample and neighbors.
- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
signatureis not aperturbation_signatureartifact, orfeaturesnames a feature it lacks.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
MemoryError – If the values read, a stored chunk of signatures and the IDs of the cells and their neighbors do not fit the memory budget.
- mixscape(signature, *, split_column=None, min_de_genes=5, min_cells=5, logfc_threshold=0.25, min_fraction=0.1, p_value_cutoff=0.05, scale=True, max_iterations=10, perturbation_type='KO', invalidate_cache=False)#
Call the cells of each target knocked out or escapers with Mixscape.
Mixscape (Papalexi et al. 2021) separates, among the cells that carry a target alone, those whose target was knocked out from the escapers that kept its function, as Seurat’s
RunMixscapedoes. For each target, within each split ofsplit_column:The DE genes compare the target’s cells with the control cells on log-normalized counts, at the signature’s
scale_factor, over every feature of the signature’s assay, as Seurat’sFindMarkers: a gene is tested when at leastmin_fractionof the cells of either group express it, rounded to 3 digits, and its log2 fold change of the mean normalized values with a pseudocount of 1 is at leastlogfc_thresholdin size, by a two-sided Wilcoxon rank-sum test with continuity correction; it is DE when its p-value times the number of features is belowp_value_cutoff. A group of fewer than 3 cells has no DE gene.With fewer than
min_de_genesDE genes, every cell of the target is an escaper, with the status"few_de_genes".Otherwise the signatures of the DE genes, from the signature, or computed from its neighbors for DE genes outside its features, are scaled over the target’s and control cells (
scale). Starting with every cell knocked out, each cell is projected onto the difference between the mean of the knocked-out cells and the mean of the control cells, a mixture of two normal distributions is fitted to the projections with the control component fixed at the control cells’ mean and standard deviation, and a cell is knocked out when its likelihood under the fitted component exceeds that under the control component. This repeats until the calls stop changing or formax_iterations. Fewer thanmin_cellsknocked-out cells make every cell an escaper, with the status"few_cells".
A cell’s class is
"<target> KO"(perturbation_typereplaces"KO") or"<target> NP","control"for a control cell, and its label otherwise, such as"Negative"or"Multiple", or"unlabeled"for a cell of the signature outside the labels.On a store merged from sources that measured different features, as its feature columns
measured_in_<source>record, the DE genes are drawn from the features that every source of the signature’s cells measured, and counted among them, with a warning that names the others, and the normalized values divide each cell’s counts by its total over those features, as the signature does. A signature that recorded other features, such as one computed before the record changed, is refused.- Parameters:
signature (
ArtifactRef) – Aperturbation_signatureartifact fromsignature().split_column (
str|None) – A cell metadata column whose splits are classified apart, or None for one split.min_de_genes (
int) – The fewest DE genes that let a target be classified.min_cells (
int) – The fewest knocked-out cells a target keeps.logfc_threshold (
float) – The smallest absolute log2 fold change a tested gene has.min_fraction (
float) – The smallest share of either group’s cells that express a tested gene.p_value_cutoff (
float) – The adjusted p-value below which a gene is DE.scale (
bool) – Scale each DE gene’s signatures before the projections.max_iterations (
int) – The most iterations of each target.perturbation_type (
str) – The word that names knocked-out cells.invalidate_cache (
bool) – Classify again instead of reusing saved classes.
- Return type:
- Returns:
A complete
mixscape_classesartifact with one class per cell of the signature. Read it withload_mixscape().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
signatureis not aperturbation_signatureartifact, a number is out of range,perturbation_typeis empty, holds a space or is the class of other cells, such as"NP",split_columnis not a cell metadata column or leaves a cell without a split, the signature recorded other features than those that every source of its cells measured, or no feature was measured by every source of its cells.PermissionError – If the store is read-only and the classes are not saved yet.
MemoryError – If one feature’s values over the classified and control cells, or one target’s and the control cells’ signatures in the target’s DE genes, do not fit the memory budget.
- profiles(labels, features, *, by='target', sample_column=None, min_cells=25, mask_targets=True, id_column='target_gene_id', invalidate_cache=False)#
Average each perturbation’s z-normalized expression into its profile.
Replogle et al. (2022) compare perturbations by their mean expression profiles, each feature measured against the control cells:
Each cell’s counts in
featuresare scaled so that its total, the sum of its stored counts over every feature of the assay, equals the median total of the control cells of the labels.Within each sample of
sample_column, such as a GEM group, each feature is z-normalized against the sample’s control cells,z = (x - mean) / sd, with the standard deviation’s n - 1 divisor, for every cell, control cells included.A perturbation’s profile is the mean z-score of its cells over all samples, computed in float64 and stored as float32.
This recipe reproduces the published profiles of Replogle et al.’s K562 essential screen from its cells to float32 rounding. A feature whose control cells in a sample hold one value has no spread there, and its z-scores in that sample are 0, CyteArc’s choice where Replogle et al.’s genome-wide profiles hold infinite values;
load_profilescounts such samples for each feature. A sample needs 2 control cells or more.A perturbation is a target of the labels that is not a control, or with
by="guide"a guide, each control guide included, as Replogle et al.’s profiles have a row for each guide pair, control pairs included; with targets, the control cells get no row, since their mean z-score is 0. A perturbation’s cells carry its target, or its guide, alone. With Mixscape classes aslabels, only the cells that Mixscape called knocked out count, among the cells of the classes, so that escapers do not dilute the profiles; a control guide keeps its cells. A perturbation with fewer thanmin_cellscells, 25 as in Replogle et al., gets no profile. Withmask_targets, each profile’s own target feature is set to 0, the control mean, so that the knockdown of the target itself does not make two perturbations alike; a target is matched to a feature asefficiency()matches it, and control guides mask nothing.The counts are read twice, the control cells and then the cells of the profiled perturbations, in bands of features that fit the memory budget, and the profiles do not depend on the bands or the threads.
On a store merged from sources that measured different features, as its feature columns
measured_in_<source>record, the features offeaturesthat some source of the profiled cells, the control cells and the cells of the profiled perturbations, did not measure are left out, through a feature selection of the others, with a warning that names them, and each cell’s total is its total over the features that every such source measured, as a store of those features alone holds it. The profiles then record those features asmeasured_features_fingerprint.The profiles save their diagnostics, which
ds.artifacts.inspect(profiles).diagnosticsreturns:leftOutPerturbations, the perturbations with fewer thanmin_cellscells, andleftOutPerturbationExamples, up to five of them with their cells, such as'GENE_C' (12). Such perturbations give aDiagnosticWarningeach time the profiles are computed or reused.- Parameters:
labels (
ArtifactRef) – Aperturbation_labelsartifact, or amixscape_classesartifact whose knocked-out cells alone count.features (
ArtifactRef) – Afeature_selectionartifact, such as highly variable genes, whose features the profiles hold; its assay is the expression assay.by (
str) –"target"for one profile per target gene, or"guide"for one per guide, control guides included.sample_column (
str|None) – A cell metadata column whose samples are z-normalized against their own control cells, or None for one sample.min_cells (
int) – The fewest cells of a profiled perturbation.mask_targets (
bool) – Set each profile’s own target feature to 0.id_column (
str|None) – The feature column of the guide assay that holds each guide’s target feature ID, or None to match targets by name only; it matters only withmask_targets.invalidate_cache (
bool) – Compute again instead of reusing saved profiles.
- Return type:
- Returns:
A complete
perturbation_profilesartifact scoped to the assay offeatures, with one profile per perturbation. Read it withload_profiles().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
labelsorfeaturesis not an artifact of its kinds,byis unknown,min_cellsis below 1,sample_columnis not a cell metadata column or leaves a control cell or a cell of a profiled perturbation without a sample, a sample has fewer than 2 control cells,id_columnis not a feature column of the guide assay, the labels have no control cell, no perturbation hasmin_cellscells, or every feature offeatureswas left out.PermissionError – If the store is read-only and the profiles are not saved yet.
MemoryError – If the profiles and one feature’s sums, beside the read of its counts, do not fit the memory budget.
- signature(labels, coordinates, *, features=None, dims=15, n_neighbors=20, sample_column=None, scale_factor=10000.0, invalidate_cache=False)#
Compute each cell’s perturbation signature against its nearest controls.
The first step of Mixscape (Papalexi et al. 2021) removes the variation that a cell shares with the control cells around it, such as its cell-cycle phase or its replicate. Every cell of the coordinates is matched with its
n_neighborsnearest control cells of the labels, by Euclidean distance over the firstdimsdimensions of the coordinates, found exactly; a control cell is its own nearest control, and of two equally near controls the first in store order is taken. The signature of a feature is the cell’s log-normalized value minus the log of its neighbors’ mean normalized value, log1p(y_i) - log1p(mean y_j), where y scales each cell’s counts toscale_factortotal counts, so log1p(y) is Seurat’s LogNormalize. A knockdown reads negative; Seurat’sCalcPerturbSigstores the negative, which leaves Mixscape’s classes unchanged.With
sample_column, each cell takes its neighbors from the control cells of its own sample, such as its replicate, as Seurat’ssplit.bydoes. Labeled cells without coordinates have no signature, and a log message counts them.On a store merged from sources that measured different features, as its feature columns
measured_in_<source>record, the features offeaturesthat some source of the cells of the coordinates did not measure are left out, through a feature selection of the others, with a warning that names them, and y scales each cell’s counts by its total over the features that every such source measured, as a store of those features alone holds it. The signature then records those features asmeasured_features_fingerprint.- Parameters:
labels (
ArtifactRef) – Aperturbation_labelsartifact, whose"control"cells are the neighbors.coordinates (
ArtifactRef) – A reduction, batch correction, imported coordinates or normalized values, whose cells get a signature.features (
ArtifactRef|None) – Afeature_selectionartifact of the expression assay, the signature’s columns. By default, the feature selection of the coordinates, such as the highly variable genes of a PCA.dims (
int) – The leading coordinate dimensions that find the neighbors.n_neighbors (
int) – The control cells averaged for each cell.sample_column (
str|None) – A cell metadata column whose samples keep their own control cells, or None for one sample.scale_factor (
float) – The counts each cell is scaled to before log1p.invalidate_cache (
bool) – Compute again instead of reusing a saved signature.
- Return type:
- Returns:
A complete
perturbation_signatureartifact scoped to the assay offeatures, with one row per cell of the coordinates. Read it withload_signature().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
labelsis not aperturbation_labelsartifact,coordinatesis not a coordinate artifact,featuresis not a feature selection or is missing for coordinates without one, a number is out of range,sample_columnis not a cell metadata column or leaves a cell without a sample, a sample has fewer thann_neighborscontrol cells with coordinates, or every feature offeatureswas left out.PermissionError – If the store is read-only and the signature is not saved yet.
MemoryError – If the neighbor search of one cell, or the control cells’ values and one block of counts beside the writer’s band, do not fit the memory budget.
ds.clones#
import_clones reads the clones that lineage tracing tools write, such as TREX’s clones.txt, CellTag-multi’s clone tables, Numbat’s clone posteriors or LARRY’s clone matrices, joins their cells to a cell selection by barcode, and saves a clones artifact that labels each cell with its clone. from_column saves the clones of a cell metadata column instead. load_clones reads the artifact as tables of cells and clones, and export_clones writes it as CoSpar’s clone table or a Matrix Market file. expansion saves each cell’s expansion category, by its clone’s size within its group of cells, and load_expansion reads it as tables of cells, categories and rank windows; diversity and rarefaction measure each group’s diversity indices and Hill numbers, rarefied and extrapolated, overlap and track compare groups by the clones they share and follow chosen clones across them, and coupling measures how strongly groups share clones against shuffled labels; these five save nothing. fate_bias saves, for each early cell, the share of its clone’s later cells in each fate, and tests each clone’s fates, and load_fate_bias reads it as tables of early cells, clones and fates. import_barcodes reads the expressed lineage barcodes that extraction tools write as reads, molecules or barcode counts, such as TREX’s molecule tables, pycashier’s and CellTag’s reads, QuiCAT’s and BARtab’s counts or Cell Ranger’s molecule_info.h5, and saves a lineage_barcodes artifact of each cell’s molecules and barcodes, which load_barcodes reads as tables. barcode_clones calls clones from them by the published rules of LARRY, TREX, CellTagR or CellTag-multi, or by rules chosen one by one, and saves a clones artifact. import_alleles reads the alleles that lineage recorder pipelines write, such as CARLIN’s and DARLIN’s allele files, Cassiopeia’s allele tables, PEtracer’s tables and character matrices and DNA Typewriter’s tape tables, and saves a lineage_alleles artifact of each cell’s sites and their states, which load_alleles reads as tables and export_characters writes as a character matrix for Cassiopeia or LAML. allele_clones calls clones from the rare alleles, by DARLIN’s frequency graph or CARLIN’s p_clonal test against a bank of allele frequencies, and saves a clones artifact. import_phylogeny reads the cell phylogenies that lineage recorders reconstruct, from Newick and TreeData files, joins their leaves to a cell selection and saves a cell_phylogeny artifact, load_phylogeny reads it as tables of nodes and trees, and phylogeny_clones cuts it into a clones artifact at a time or a depth. Clones API reference lists the formats and describes the join of barcodes to cells, files from several runs, cells in several clones, the summaries and their records.
- class cytearc.datastore.namespaces.ClonesAccessor(store)#
- allele_clones(alleles, *, method, frequencies=None, max_frequency=None, max_samples=None, max_alleles=None, fdr=0.05, within=None, invalidate_cache=False)#
Call clones from rare lineage recorder alleles.
Cells that share an edit descend from the cell in which it arose, unless it arose more than once: CRISPR arrays repeat their most likely edits in unrelated cells. So cells are linked through rare alleles only, and the connected components of the cells that share a rare allele, at any character, are the clones. An allele is one character’s edit, the text of a mark or of an unknown mark that names its allele, such as a DARLIN array’s
23_268del,55_248del; the unedited state, placeholders of unknown marks such as CARLIN’sX, and missing sites never link cells.method="graph"follows DARLIN (Li et al., Cell 2023): an allele is rare when its frequency is at mostmax_frequencyand it was found in at mostmax_samplesof its bank’s samples. DARLIN linked cells through alleles of frequency below 2e-5 found in one mouse, whichmax_frequency=float(np.nextafter(2e-5, 0))andmax_samples=1reproduce exactly.method="p_clonal"follows CARLIN (Bowling et al., Cell 2020): an allele of bank rate λ among the M cells of its group with an edit at its character arose more than once with probability p_clonal = (1 - e^(-λM) - λM e^(-λM)) / (1 - e^(-λM)), and is rare when that p-value survives the Benjamini-Hochberg procedure atfdrover the alleles of its group, every array’s in one family, and when it passesmax_samples. A clone whose cells hold more thanmax_allelesdistinct rare alleles leaves its cells without one, as DARLIN keeps clones of at most three: a cell holds at most one allele per array, so a clone of more is likely two that a homoplasic allele joined.frequenciesgives each character’s bank, a DataFrame of each allele’snormalized_count, its frequency among the bank’s edited observations, and optionally itssample_count, as DARLIN’s banks hold them;pd.read_csv("allele_bank_Gr_CA.csv.gz")reads one. A bank fits only alleles annotated by the pipeline that annotated it: CARLIN’s MATLAB notation and darlin-core’s place some events one base apart, so a bank in the other notation lists few of the alleles and calls most of them rare. The artifact’sbank_coverageattribute counts, for each character, its alleles and their observations, the pairs of a cell and an allele, and how many of each its bank lists. An allele missing from its bank counts as rare, with frequency and rate 0, as DARLIN counts it; CARLIN gives such alleles the mean rate of the alleles its bank model never observed, which a table of rates does not hold. p_clonal grows with M, so among tens of thousands of edited cells or more the listed alleles fail and the alleles missing from the bank are the ones that survive. Without a bank, an allele’s frequency is the share of the cells of its group with an edit at its character that hold it. Clonal expansion inflates these frequencies, so the alleles of large clones look common, and"p_clonal"needs a bank.Clones are numbered by size, so
clone_1is the largest, and ties follow their first cell. Theclonesartifact also holds each cell’sn_alleles, its distinct rare alleles, and its parameters the rules. Its diagnostics, whichds.artifacts.inspect(clones).diagnosticsreturns, count what each rule found, None for a rule that did not run: theallelestested, thoseallelesTooFrequent,allelesNotSignificantandallelesInTooManySamples, therareAllelesand thecellsWithRareAlleles, theclonesWithTooManyAllelesand theircellsInClonesWithTooManyAlleles, and, with banks, theallelesInBankand theobservationsandobservationsInBankthatbank_coverageadds up; as every source’s clones,cellsWithCloneandlargestCloneShare.- Parameters:
alleles (
ArtifactRef) – Alineage_allelesartifact, such as one fromimport_alleles().method (
str) –"graph"or"p_clonal".frequencies (
Mapping[str,DataFrame] |None) – Each character’s bank, keyed by its name: its integration, or{integration}-{site}for a named site, asexport_characters()names characters. Every character with an allele needs one. None takes each allele’s frequency from the cells.max_frequency (
float|None) – For"graph", the highest frequency of a rare allele, greater than 0 and at most 1, or None for no such filter.max_samples (
int|None) – The most samples of a bank in which a rare allele is found, such as 1 for alleles of at most one bank mouse, or None for no such filter; it needs banks with asample_count.max_alleles (
int|None) – The most distinct rare alleles of a clone, such as 3, or None for no such filter.fdr (
float) – For"p_clonal", the false discovery rate, greater than 0 and less than 1.within (
str|Sequence[str] |None) – Cell metadata columns whose labels keep clones apart, such as the mouse; alleles are tested within each group, and every cell with an edit needs a label.invalidate_cache (
bool) – Call again instead of reusing saved clones.
- Return type:
- Returns:
A complete datastore-scoped
clonesartifact aligned to the alleles’ cells. Read it withload_clones().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
allelesis not alineage_allelesartifact, the method is unknown, a rule is missing, out of range or does not apply to the method, a bank is malformed, names no character with an edit or is missing for one, or a within column is missing or has no label for a cell with an edit.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete.
PermissionError – If the store is read-only and the clones are not saved yet.
MemoryError – If the calling does not fit the memory budget.
- barcode_clones(barcodes, *, preset=None, min_reads=None, max_distance=None, metric=None, allowlist=None, min_umis=None, min_fraction=None, barcodes_per_cell=None, method=None, similarity=None, inclusive=None, prune=None, doublets=None, trex_rules=None, min_size=None, within=None, invalidate_cache=False)#
Call clones from imported lineage barcodes.
Cells that carry the same lineage barcodes descend from one labeled cell. The barcodes of each cell pass the rules of the method that made them, in this order: molecules with fewer than
min_readsreads are dropped; barcodes withinmax_distanceof each other bymetricmerge, within each group and library, into the most abundant of their connected component, ties going to the barcode that sorts last; barcodes outsideallowlistare dropped; a cell’s barcodes of fewer thanmin_umisUMIs, or belowmin_fractionof its top barcode’s UMIs, are dropped, in each library apart; cells with fewer or more barcodes thanbarcodes_per_cellallows get no clone. Thenmethod="sets"makes the cells of identical barcode sets a clone, andmethod="jaccard"links cells whose Jaccard index of barcode sets exceedssimilarity, or reaches it withinclusive;pruneremoves TREX’s bridges anddoubletsits doublets, and the connected components are the clones. Clones of fewer thanmin_sizecells leave their cells without one.presetsets every rule to a method’s published values:"larry"(LARRY),"trex"(TREX),"celltag"(CellTagR) or"celltag_multi"(CellTag-multi). An argument given replaces the preset’s value, and 0 turns a count filter off. Without a preset,methodis required,"jaccard"needssimilarityandinclusive, andmax_distanceneeds ametric. The clones API reference lists each preset’s rules, whichcytearc.clones.BARCODE_PRESETSholds.preset="trex"also applies TREX’s rules for its partial cloneIDs: molecules of low complexity are dropped, cloneIDs are compared where both hold a base and need 20 such bases, and a one-UMI barcode is dropped where another cell of its group holds it, as is a barcode whose only molecule has one read.trex_rulesleft None follows the preset, and True or False turns these rules on or off in any call, so a call with and without them shows what they remove.Counts are read in each library’s unit: UMIs, or reads in a library that counts no UMIs, such as scATAC-seq CellTags. A rule that needs a count that a library does not hold refuses rather than guess.
Clones are numbered by size, so
clone_1is the largest, and ties follow their first cell. Theclonesartifact also holds each cell’sn_barcodes, its barcodes after the pair filters, anddoublet, whether TREX’s rule removed it as a doublet, and its parameters the resolved rules. Its diagnostics, whichload_clones()andds.artifacts.inspect(clones).diagnosticsreturn, show when correction merges unrelated barcodes:distinctBarcodes, the distinct barcodes of each group and library that correction compares;expectedChanceMatches, the pairs of them expected withinmax_distanceby chance, None underlevenshteinbeyond 8 edits, whose count takes too long;mergedBarcodes, those that correction merged into another; then what each rule removed or found, None for a rule that did not run, which the clones API reference lists; and, as every source’s clones,cellsWithClone, the cells given a clone, andlargestCloneShare, the share of them that the largest clone holds. Barcodes whose files hold no row, or whose rows of selected cells hold no barcode, give clones of no cell, which the clone summaries andexport_clonesrefuse, naming that cause.- Parameters:
barcodes (
ArtifactRef) – Alineage_barcodesartifact, such as one fromimport_barcodes().preset (
str|None) –"larry","trex","celltag","celltag_multi"or None.min_reads (
int|None) – The fewest reads of a molecule.max_distance (
int|None) – The largest distance at which barcodes merge, 0 for no correction.metric (
str|None) –"hamming"or"levenshtein".allowlist (
Sequence[str] |bool|None) – The barcodes of the library, a sequence of text; the CellTag presets require one, and False calls them without.min_umis (
int|None) – The fewest UMIs, or reads, of a cell’s barcode.min_fraction (
float|None) – The share of the UMIs of a cell’s top barcode that its other barcodes must reach, from 0 to 1.barcodes_per_cell (
tuple[int,int|None] |None) – The fewest and the most barcodes of a called cell, the most None for no limit.method (
str|None) –"sets"or"jaccard".similarity (
float|tuple[float,float] |None) – The Jaccard index that links two cells, from 0 to 1; or two, within one library and across libraries.inclusive (
bool|None) – Whether an index equal to the similarity links.prune (
bool|None) – Remove the edges whose ends share no neighbor.doublets (
bool|None) – Remove the cells whose neighbors fall apart without them.trex_rules (
bool|None) – Apply TREX’s rules for partial cloneIDs: None withpreset="trex"alone, or True or False in any call.min_size (
int|None) – The fewest cells of a clone.within (
str|Sequence[str] |None) – Cell metadata columns whose labels keep clones apart, such as the mouse; every cell with a barcode needs a label.invalidate_cache (
bool) – Call again instead of reusing saved clones.
- Return type:
- Returns:
A complete datastore-scoped
clonesartifact aligned to the barcodes’ cells. Read it withload_clones().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
barcodesis not alineage_barcodesartifact, the preset is unknown, a required rule is missing, a value is out of range, TREX’s rules meet another metric than Hamming’s, an argument does not apply to the method, a rule needs counts that a library does not hold, or a within column is missing, is named twice or has no label for a cell with a barcode.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete.
PermissionError – If the store is read-only and the clones are not saved yet.
MemoryError – If the calling does not fit the memory budget.
- coupling(clones, *, group_by=None, groups=None, cell_selection=None, method='share_cosine', n_permutations=1000, random_seed=0)#
Measure how strongly groups of cells share clones, against shuffled labels.
Cell types whose cells often share a clone descend from common progenitors, so the clones that two groups share measure how closely their fates are coupled. The groups are the combinations of the labels of the
group_bycell metadata columns, such as the cell type, and of thegroupslabel artifact, among the cells ofcell_selection, such as the cells of one time point. Cells without a clone or a label are left out. Clonotypes are grouped within each receptor type, which joins the groups’ key columns asreceptor_type: only groups of one receptor type are coupled, the null shuffles labels within each receptor type, and clonotypes across receptor types, aswithin_receptor_type=Falsedefines them, are measured by each cell’s clonotype within its type. Nothing is saved.methodnames how a pair’s coupling is measured from each clone’s cells in each group, as CoSpar’sfate_couplingmeasures it:"share_cosine", CoSpar’s default, the cosine over the clones of each group’s share of each clone, after each group’s cells of a clone are divided by its cells with a clone and each clone’s shares by their sum, so every clone counts once;"abundance_cosine", the cosine of the clone sizes, whichoverlapalso reports;"normalized_covariance", the covariance over the clones of the two groups’ cells over the product of their mean cells per clone, negative when they share fewer clones than chance; and"jaccard", the clones of both groups over the clones of either.Each value is compared with a null: the group labels of the cells with a clone are shuffled
n_permutationstimes, which keeps each clone’s cells and each group’s cells, and the coupling measured again. The z-score is the value’s distance from the null mean in null standard deviations, which says whether a pair couples more than chance; when clones commit to few fates, most pairs fall below their null, so rank pairs by the coupling itself. Permutationkdraws from a random stream keyed byrandom_seedandk, so the result does not depend onnthreads. The groups are ordered by average linkage on the coupling, the most coupled together.- Parameters:
clones (
ArtifactRef) – A clone artifact, such asclonesorclonotypes.group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the groups.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the groups, or aNamedCellArtifactof one, whose name titles only the figures of the result.cell_selection (
ArtifactRef|None) – Only these cells, or None for every cell of the clones.method (
str) –"share_cosine","abundance_cosine","normalized_covariance"or"jaccard".n_permutations (
int) – The permutations of the null, 0 for none, or at least 2 to estimate its spread.random_seed (
int) – The seed of the permutations, a non-negative integer below 2**64.
- Return type:
- Returns:
The groups’ cells and clones, each pair’s coupling with its null and z-score, the groups’ order, and the groups’ labels in
group_keys.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
clonesis not a clone artifact,methodis unknown,n_permutationsis 1 or negative,random_seedis negative or 2**64 or more, the clones’ import gave no selected cell a clone, no cell has both a clone and a group, fewer than two groups hold a cell with a clone, no two groups share the labels that the clones keep apart, a column of the groups is missing or named twice, two key columns share a name, two groups get one name, or"normalized_covariance"meets fewer than two clones.KeyError – If the store holds no such
clonesartifact, or not the receptors of the clonotypes.RuntimeError – If the
clonesartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.MemoryError – If reading the clones, grouping the cells, or the coupling and one worker of its null do not fit the memory budget.
- diversity(clones, *, group_by=None, groups=None, cell_selection=None, size=None, coverage=None)#
Measure the diversity of the clones of groups of cells.
The groups are the combinations of the labels of the
group_bycell metadata columns, such as the sample, and of thegroupslabel artifact, such as a clustering. Cells without a clone or a label are left out. A clone’s size in a group is its cells there. Clonotypes are measured within each receptor type, which joins the groups’ key columns asreceptor_type.The indices are those of scRepertoire’s
clonalDiversity, immunarch’srepDiversityand vegan’sestimateR: Shannon entropy, Pielou’s evenness, the Simpson indices, the Gini coefficient, D50, Chao1 in its classic and bias-corrected forms, and ACE. Each depends on how many cells a group holds, so the Hill numbers of orders 0, 1 and 2, the effective numbers of clones, are also rarefied or extrapolated to a commonsizeand to a common samplecoverage, as iNEXT’sestimateDdoes (Chao et al. 2014): by default the smallest of the groups’ doubled sizes, and the lowest coverage of the groups at their doubled sizes. Compare groups by these standardized numbers. Nothing is saved.- Parameters:
clones (
ArtifactRef) – A clone artifact, such asclonesorclonotypes.group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the groups.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the groups, or aNamedCellArtifactof one, whose name titles only the figures of the result.cell_selection (
ArtifactRef|None) – Only these cells, or None for every cell of the clones.size (
int|None) – The common size in cells, or None for the default.coverage (
float|None) – The common coverage, between 0 and 1, or None for the default.
- Return type:
- Returns:
The groups’ indices and Hill numbers, observed, asymptotic and standardized, and the groups’ labels in
group_keys.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
clonesis not a clone artifact, the clones’ import gave no selected cell a clone, no cell has a clone and a group, a column of the groups is missing or named twice, orsizeis not positive.KeyError – If the store holds no such
clonesartifact, or not the receptors of the clonotypes.RuntimeError – If the
clonesartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.MemoryError – If reading the clones or grouping the cells does not fit the memory budget.
- expansion(clones, *, group_by=None, groups=None, cell_selection=None, breakpoints=None, frequency_breakpoints=None, invalidate_cache=False)#
Place each cell in an expansion category by its clone’s size in its group.
A clone that holds more than one cell has expanded: its founding cell divided. Its size is counted within groups of cells: the combinations of the labels of the
group_bycell metadata columns, such as the sample, and of thegroupslabel artifact, such as a clustering. Without a grouping, a clone’s size counts its cells in every sample, as scirpy’sclonal_expansiondoes withoutexpanded_in. Cells without a clone or a label are counted in no group. Clonotypes are counted within each receptor type, which joins the groups’ key columns asreceptor_type.breakpointssorts the cells by their clone’s cells in the group, as scirpy’sbreakpointsdo: the default(1, 2, 5, 20, 100)makes the categories"1 cell","2 cells","3 to 5 cells","6 to 20 cells","21 to 100 cells"and"more than 100 cells".frequency_breakpointssorts them instead by their clone’s frequency, its share of the group’s cells with a clone, in bins(lower, upper]that end at 1, as scRepertoire’sclonalHomeostasisdoes:(0.0001, 0.001, 0.01, 0.1, 1)makes its Rare, Small, Medium, Large and Hyperexpanded categories, named"0 to 0.0001"to"0.1 to 1". A frequency depends on the group’s number of cells, so compare groups of similar sizes, or bounds in cells.The artifact labels the cells of
cell_selection, or the clones’ cells without one; a selected cell that the clones do not hold has no clone. Its canonicalvalueshold each cell’s category, empty for a cell without a clone or a group, sods.select_cells(expansion, include=["more than 100 cells"])keeps the cells of the largest clones.group_clone_size,group_clone_frequencyandgroup_codesare its other per-cell arrays. Its diagnostics, whichds.artifacts.inspect(expansion)returns, count the cells that it leaves out:cellsWithoutClone,cellsWithoutGroup, the cells with a clone that no group holds, and thegroups.- Parameters:
clones (
ArtifactRef) – A clone artifact, such asclonesorclonotypes.group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the groups, such as the sample.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the groups, or aNamedCellArtifactof one, whose name titles only the figures of the result.cell_selection (
ArtifactRef|None) – The cells to measure, or None for every cell of the clones.breakpoints (
Sequence[int] |None) – Strictly increasing bounds in cells, or None.frequency_breakpoints (
Sequence[float] |None) – Strictly increasing frequency bounds, the last 1, or None. Pass at most one of the two bounds; without either,breakpointsare(1, 2, 5, 20, 100).invalidate_cache (
bool) – Measure again instead of reusing a saved result.
- Return type:
- Returns:
A complete datastore-scoped
clonal_expansionartifact. Read it withload_expansion()or plot it withds.plots.clonal_expansion.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
clonesis not a clone artifact, both bounds are given, the bounds are invalid, the clones’ import gave no selected cell a clone, no measured cell has both a clone and a group, a column of the groups is missing or named twice, or two groups get one name.KeyError – If the store holds no such
clonesartifact, or not the receptors of the clonotypes.RuntimeError – If the
clonesartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.PermissionError – If the store is read-only and the result is not saved yet.
MemoryError – If reading the clones, grouping the cells, or the measurement, about 300 bytes per cell, does not fit the memory budget.
- export_characters(alleles, path, *, format='treedata', unknown='state', cell_order='source')#
Write saved recorder alleles as a character matrix for tree builders.
A character is one site of one integration, named
{integration}-{site}, or after its integration when the site has no name, as a DARLIN array’s allele does. Its states are integers: 0 unedited, missing where a site is missing or not applicable, and its edits from 1: a mark written as a whole number without leading zeros, such as PEtracer’s marks1to8, is its own state, and the character’s other marks, by their text, then its unknown marks that name their allele, take the states after the largest such number. So each state names one allele of its character in every cell, a character matrix keeps its states through an import and an export, and a table names each state’s allele. An unknown mark that a placeholder writes, such as PEtracer’s!or CARLIN’sX, names no allele, so cells that hold it share no state: it is missing. Where a cell holds several allele rows of one integration, the row of most UMIs, then most reads, then most sites read is exported, as Cassiopeia keeps each integration’s most abundant allele, and thecellsWithSeveralAlleleRowsdiagnostic and a warning count those cells and integrations. Ordered slots export one character per slot, so their prefix rule is left to the tree builder’s model. Cells that read no character and characters that no cell reads are left out."treedata"writes a TreeData.zarrstore, which Cassiopeia 3.0’s solvers read:obsm['characters']with one int64 column per character,uns['missing_state']-1,uns['unmodified_state']0 anduns['character_states'], thecharacter,stateandalleleof each edited state."laml"writes LAML’s CSV, a headercell,<characters>and integer states with?for missing, and beside it<stem>_priors.csv, headerless rows of a character’s position from 0, a state and its probability, each state’s share of the exported cells with an edit at its character, and<stem>_states.csv, the table of each state’s allele. Each export reads back with its own token:import_alleles()reads the store asformat="treedata"and the CSV asformat="laml". Cell IDs are this store’s, and cells are written in the order of the file that the store imported, as theirsourceRowrecords it, or in store order withcell_order="stored".- Parameters:
alleles (
ArtifactRef) – Alineage_allelesartifact.path (
str|PathLike[str]) – For"treedata", the.zarrstore to create, which must not exist; for"laml", the CSV to write, replacing a file of that name, as the files beside it are.format (
str) –"treedata"or"laml".unknown (
str) –"state"gives each distinct unknown mark that names its allele, such as an insertion outside PEtracer’s lookup, a state of its own after the marks;"missing"writes every unknown mark as missing.cell_order (
Literal['source','stored']) –"source"or"stored".
- Return type:
- Returns:
The store or CSV written, its
rows, the cells written, and itsdiagnostics:cells,charactersandcellsWithSeveralAlleleRows.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
allelesis not alineage_allelesartifact,format,unknownorcell_orderis unknown, no cell reads a character, two integrations give one character name, a character’s states pass the int32 range, or, for LAML, a cell or character name holds a character that its files cannot hold.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete.
FileExistsError – For
"treedata", ifpathexists.MemoryError – If the export does not fit the memory budget.
- export_clones(clones, path, *, format='cospar', cell_order='source')#
Write saved clones as a file that lineage tracing tools read.
"cospar"writes CoSpar’s clone table, a CSV ofCell_IDandClone_IDwith one row per cell with a clone, which CoSpar reads andimport_clonesreads asformat="cospar"."matrix"writes a cells by clones Matrix Market file of the cells with a clone, holding a 1 where a cell belongs to a clone, withcells.tsvandclones.tsvbeside it that name its rows and columns, replacing files of those names;import_clonesreads the matrix with its lists asformat="matrix". Cell IDs are this store’s, and a path ending in.gzis gzip-compressed. Clone probabilities are not written. Cells are written in the order of the file that the store imported, as theirsourceRowrecords it, or in store order withcell_order="stored". Clones whose import gave no selected cell a clone, from files without rows or whose rows give none of the selected cells they name a clone, or becausemultiple="drop"left out every cell that the files gave one, and clones called from barcodes whose files hold no barcode of a selected cell, are refused before anything is written, while clones of a selection that the files’ rows do not reach write the header alone.- Parameters:
clones (
ArtifactRef) – A clone artifact, such asclonesorclonotypes.path (
str|PathLike[str]) – The file to write.format (
str) –"cospar"or"matrix".cell_order (
Literal['source','stored']) –"source"or"stored".
- Return type:
- Returns:
The file written, its
rows, the cells written, and itsdiagnostics:cells, the cells written.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
clonesis not aclonesorclonotypesartifact,formatorcell_orderis unknown, the clones’ import gave no selected cell a clone, the barcodes of barcode clones give no selected cell a barcode, a"cospar"table would hold a clone label that reads as no clone, such as"NA", or a"matrix"would list a label or cell ID that holds a line break.KeyError – If the store holds no such artifact, or not the receptors of the clonotypes.
RuntimeError – If the artifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.
MemoryError – If the export, about 200 bytes per cell beside the clones that it reads and the text of the cells’ IDs and of the clone labels, does not fit the memory budget.
- fate_bias(clones, *, group_by=None, groups=None, early, late, invalidate_cache=False)#
Follow each early cell’s clone to its late cells, and test each clone’s fates.
The late cells of an early cell’s clone, such as its clone-mates sampled days later, show which fates its progenitor took. The fates are the groups of the late cells: the combinations of the labels of the
group_bycell metadata columns, such as the cell type, and of thegroupslabel artifact. A late cell without a label has no fate. No cell may be both early and late.For each early cell the artifact holds the share of its clone’s late cells in each fate, the clonal fate map of CoSpar’s
fate_mapon a transition map of clones alone, its dominant fate, the fate that holds the most of them, and its clone’s late cells. An early cell whose clone has no late cell has no fractions and no dominant fate, and neither has one whose clone’s late cells tie between fates. For each clone with late cells it holds their count in each fate and a one-sided Fisher test per fate: the chance of at least that many of the clone’s late cells in the fate if they were drawn at random from all late cells with a fate, those without a clone included, as CoSpar’sclonal_fate_biastests a clone among the late cells, with the Benjamini and Hochberg adjustment over the clones within each fate. When the clones keep labels apart, such as receptor types, each fate holds one such label, which a late cell without a clone lacks, so it has no fate. The fates of clonotypes therefore name a receptor type each, such as"Neutrophil, TCR", and each clonotype is tested among the late cells of its receptor type that have a clonotype. Clonotypes thatwithin_receptor_type=Falsedefines across receptor types are measured, as every summary measures them, by each cell’s clonotype within its type, which they save, so each is tested as the clonotypes within types are, under a label such asclonotype_1 (TCR 2).The artifact’s canonical
valueshold each early cell’s dominant fate, empty for none, sods.select_cells(bias, include=["Neutrophil"])keeps the early cells whose clones went mostly to neutrophils.codes, each cell’s clone,fate_codes, its dominant fate’s position,n_late_cells, its clone’s late cells, andfractions, one column per fate, are its other per-cell arrays. Its diagnostics, whichds.artifacts.inspect(bias).diagnosticsreturns, count the cells that it leaves out:cellsWithoutClone, the late cells without a clone,cellsWithoutGroup, those with a clone but no fate, the fates ingroups,earlyCellsWithoutLateCells, the early cells with a clone whose clone has no late cell with a fate,earlyCellsWithTiedFates, those whose clone’s late cells tie between fates, andtestedClones, the clones tested.- Parameters:
clones (
ArtifactRef) – A clone artifact, such asclonesorclonotypes.group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the fates.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the fates, or aNamedCellArtifactof one, whose name titles only the figures of the result.early (
ArtifactRef) – The early cells, a cell selection.late (
ArtifactRef) – The late cells, a cell selection.invalidate_cache (
bool) – Measure again instead of reusing a saved result.
- Return type:
- Returns:
A complete datastore-scoped
clone_fate_biasartifact that labels the early cells. Read it withload_fate_bias()or plot it withds.plots.clone_fate_bias.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
clonesis not a clone artifact,earlyorlateis not a cell selection or selects no cell, a cell is both early and late, the clones’ import gave no selected cell a clone, the clones give no early cell or no late cell a clone, no late cell with a clone has a fate, fewer than two fates hold a late cell, a column of the fates is missing or named twice, two key columns share a name, or two fates get one name.KeyError – If the store holds no such
clonesartifact, or not the receptors of the clonotypes.RuntimeError – If the
clonesartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.PermissionError – If the store is read-only and the result is not saved yet.
MemoryError – If reading the clones, grouping the late cells, or the measurement does not fit the memory budget.
- from_column(column, *, cell_selection, invalidate_cache=False)#
Save the clones that a cell metadata column assigns.
A study’s metadata often holds each cell’s clone, such as a column imported with an AnnData file. The selected cells’ labels in
columnbecome aclonesartifact, asimport_clones()writes: a missing or blank label means no clone. Labels are text; integers read as their text, and floating-point whole numbers, which pandas writes for integer labels beside missing ones, as integers. The artifact records a stamp of the column’s stored chunks and of its missing values, read without decoding them, so editing the column gives new clones. The labels are read in blocks of as many cells as half of what the memory budget leaves.- Parameters:
column (
str) – A cell metadata column.cell_selection (
ArtifactRef) – The cells that the clones label.invalidate_cache (
bool) – Save again instead of reusing saved clones.
- Return type:
- Returns:
A complete datastore-scoped
clonesartifact.- Raises:
TypeError – If an argument has the wrong type, or a label is a floating-point number that is not whole.
ValueError – If
columnis not a cell metadata column, or the selection holds no cell.PermissionError – If the store is read-only and the clones are not saved yet.
MemoryError – If the labels do not fit the memory budget.
- import_alleles(paths, *, cell_selection, format=None, integrations=None, barcode_prefix=None, barcode_suffix=None, barcode_pattern=None, columns=None, invalidate_cache=False)#
Import the alleles of a lineage recorder for a set of cells.
Lineage recorders such as DARLIN, PEtracer and DNA Typewriter write heritable edits into target arrays, so cells that share an edit descend from the cell in which it arose. Their pipelines write each cell’s alleles, the edits that each copy of an array carries, as tables of their own. The import reads them, joins each row to a selected cell by its cell barcode and saves a
lineage_allelesartifact, whichload_alleles()reads back andexport_characters()writes for tree builders.An integration is one copy of a target array, named as its tool names it, such as a DARLIN array or a PEtracer
intID. Each site of a cell is unedited, a mark, an unknown mark, missing or not applicable, and each format writes these states with tokens of its own: Cassiopeia’sNoneis an uncut site, PEtracer’sNonean unedited one, a blank DNA Typewriter slot unedited after the last edit, and an insertion that holdsNmissing. A placeholder of an unknown mark, such as PEtracer’s!, names no allele. Text that pandas reads as missing is missing only in tables read throughcolumns. The clones API reference lists the formats and their tokens.Each file’s format is recognized from its contents unless
formatnames it. A file that holds one array, as a CARLIN pair does, has its array named byintegrations, never inferred; the arrays of one library, such as DARLIN’sCA,TAandRA, must share cells when they share a barcode prefix and suffix. Several alleles of one cell and integration are kept, as thedarlinCLI, Cassiopeia and PEtracer write them.Cell barcodes join cells as the other importers join them:
barcode_prefix, the barcode andbarcode_suffixname a cell’s ID,barcode_patternkeeps the part of each barcode that itsbarcodegroup matches, and barcodes that match no selected cell are counted in the join’s diagnostics, apart from those of cells outside the selection, and those that match no cell of the store are named in a warning, which a reused import gives again. Beside the join’s counts, the diagnostics thatds.artifacts.inspect(ref).diagnosticsreturns holdfileRows, the files’ rows,rowsPerFile, those of each file in the canonical order of the files,unmatchedRows, those of no selected cell,slotsBeyondLength, the slots beyond their integration’s length that hold an insertion, androwsWithoutIntegration, the rows that name none; each of the last two above 0 gives a warning too, and so does a file that holds no row, such as a table of a header alone, which the warning names. A file is identified by the SHA-256 of its bytes and of the files read beside it, so the order of the files does not matter.- Parameters:
paths (
str|PathLike[str] |Sequence[str|PathLike[str]]) – One allele file, or several, plain or gzip-compressed: a table, a CARLIN pair’s file or folder, a TreeData.h5tdfile or.zarrstore, or a parquet table.cell_selection (
ArtifactRef) – The cells that the alleles belong to.format (
str|None) – One of"carlin","darlin","cassiopeia","cassiopeia_parquet","petracer","petracer_characters","typewriter","typewriter_chains","treedata","laml"and"table", or None to recognize each file’s format.integrations (
str|Mapping[str,int] |Sequence[str|Mapping[str,int] |None] |None) – For a file that holds one array, its name, such as"CA"; for DNA Typewriter’s ordered slots, a mapping of each integration shorter than the recorder’s arrays to its number of slots, such as{"TTCACGTA": 2}, each named by a row or column of the import. One for every file, or a sequence with one per file.barcode_prefix (
str|Sequence[str|None] |None) – Text before each cell barcode in the cell IDs: one for every file, or one per file.barcode_suffix (
str|Sequence[str|None] |None) – Text after each cell barcode in the cell IDs, such as"-1": one for every file, or one per file.barcode_pattern (
str|Sequence[str|None] |None) – A regular expression whose named groupbarcodeis the part of each cell barcode that names the cell: one for every file, or one per file.columns (
Mapping[str,Any] |None) – Forformat="table", the columns to read by role:"cell","integration"(orintegrationsnames the one integration),"sites"(a column per site), or"allele"with"site"(one site per row) or"separator"(sites joined in one column, as many in each row as in the file’s first allele, or at most"slots"ordered slots),"umis","reads","kind"("indel","independent"or"ordered") and"slots", and the tokens"unedited","missing","not_applicable"and"unknown", the last placeholders that name no allele.invalidate_cache (
bool) – Import again instead of reusing saved alleles.
- Return type:
- Returns:
A complete datastore-scoped
lineage_allelesartifact.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If a file’s format is unknown or malformed, a site holds a token that its format does not read, a file that holds one array has no integration named, an option lists a value for another number of files, arrays of one library share no cell, or the selection holds no cell.
FileNotFoundError – If a file does not exist.
PermissionError – If the store is read-only and the alleles are not saved yet.
MemoryError – If the import does not fit the memory budget.
- import_barcodes(paths=None, *, cell_selection, from_assay=None, barcode_prefix=None, barcode_suffix=None, barcode_pattern=None, format=None, columns=None, library=None, invalidate_cache=False)#
Import the expressed lineage barcodes of a set of cells.
Lineage barcodes such as LARRY’s, CellTag’s and TREX’s are random sequences that cells and their descendants transcribe, so the barcodes that cells share mark their common ancestors. Extraction tools write each cell’s barcodes as reads, molecules (a cell, a UMI and a barcode, with the molecule’s reads or without) or pairs of a cell and a barcode with its UMIs or reads. The import reads any of them, joins each row to a selected cell by its cell barcode and saves the barcodes as a
lineage_barcodesartifact, whichload_barcodes()reads back.Each file’s format is recognized from its contents: TREX’s
molecules.txtandmolecules_corrected.txtof every release, pycashier’s per-read table with or without its header, CellTag-multi’s and the Biddy et al. workflow’s per-read tables, FateMap’sstepThreeStarcodeShavedReads.txt, QuiCAT’s per-sample tables and merged table, BARtab’scounts.tsvand cell barcode annotation, Cell Ranger’smolecule_info.h5, and AnnData files of cells by barcodes, such as QuiCAT’sbarcodes_output.h5ad.formatset to"reads","molecules"or"pairs"reads any other table by the columns thatcolumnsnames.from_assayimports the counts of an assay whose features are barcodes, such as a Cell Ranger feature barcode library, instead of files. The clones API reference lists the formats and their columns.Rows that are reads collapse into molecules whose reads are their rows, or, without UMIs, into pairs of a cell and a barcode. Rows that name one molecule or pair of a library merge, summing their reads. A pair counted 0 and a row without a barcode hold none, and are counted in the
emptyRowsdiagnostic.A cell’s ID is its file’s
barcode_prefix, the cell barcode andbarcode_suffix, matched exactly;barcode_patternkeeps the part of each cell barcode that itsbarcodegroup matches first. Cell barcodes that match no selected cell are counted in the join’s diagnostics, whichds.artifacts.inspect(ref).diagnosticsreturns, apart from those of cells outside the selection, besidefileRows, the files’ rows,rowsPerFile, those of each file in the canonical order of the files, andunmatchedRows, those of no selected cell, which count each item of a list field and each nonzero count of a merged table or a matrix. Barcodes of no cell of the store, such as droplets that cell calling rejected, are named in a warning, the files that hold no row, such as a table of a header alone, in another, and files whose rows name selected cells but give none of them a barcode in a third. That warning suggests othercolumnsfor files read by them, and when the files also name cells outside the selection, acell_selectionof those cells if the files list their barcodes. A reused import gives the warnings again. A file is identified by the SHA-256 of its bytes and by its library, the file’s name unlesslibrarynames it, so a file moved to another folder reuses the saved barcodes, as does a renamed one whose library is named, an edited one gives new ones, and the order of the files does not matter.The artifact’s canonical
n_barcodesholds each cell’s distinct barcodes, andn_umis,n_readsandn_recordsits UMIs, reads and records, -1 where its library counts no UMIs or reads. The records, one per molecule or pair, are stored in therecord_arrays, ordered by cell, library, barcode and UMI.- Parameters:
paths (
str|PathLike[str] |Sequence[str|PathLike[str]] |None) – One barcode file, or several, plain or gzip-compressed; or None withfrom_assay.cell_selection (
ArtifactRef) – The cells that the barcodes belong to.from_assay (
str|None) – An assay whose features are barcodes and whose counts are UMIs, read instead of files, or None.barcode_prefix (
str|Sequence[str|None] |None) – Text before each cell barcode in the cell IDs, such as"sample1__"in a merged store: one for every file, or one per file. None adds nothing.barcode_suffix (
str|Sequence[str|None] |None) – Text after each cell barcode in the cell IDs, such as"-1": one for every file, or one per file.barcode_pattern (
str|Sequence[str|None] |None) – A regular expression whose named groupbarcodeis the part of each cell barcode that names the cell, found asre.searchfinds it; a cell barcode it does not match names no cell. One for every file, or one per file.format (
str|None) – One of"trex","pycashier","celltag","fatemap","quicat","quicat_wide","bartab","bartab_annotation","molecule_info","h5ad","reads","molecules"and"pairs", or None to recognize each file’s format.columns (
Mapping[str,Any] |None) – Forformat="reads","molecules"or"pairs", the columns to read:"cell"and"barcode"(a column, or a list of columns whose values are joined by"__", such as the two halves of a CloneTracker XP barcode),"umi","umis","reads"and"library", and"separator", one of";",",",":"and"|", which splits the barcode and count fields of pairs into lists. Forformat="h5ad",{"reads": "X"}reads the counts as reads, and"library"names anobscolumn.library (
str|Sequence[str|None] |None) – The library of each file’s rows, such as"RNA"and"ATAC": one for every file, or one per file. None names a file’s library after its name before the first., and the assay after its name. Formolecule_info, the type of the library to read, such as"Custom".invalidate_cache (
bool) – Import again instead of reusing saved barcodes.
- Return type:
- Returns:
A complete datastore-scoped
lineage_barcodesartifact.- Raises:
TypeError – If an argument has the wrong type, or the assay’s counts are not integers.
ValueError – If a file’s format is unknown or malformed, a column is missing, an option lists a value for another number of files, a file is listed twice with the same prefix and suffix, a library holds molecules in one file and pairs in another, rows of a TREX molecule table repeat a cell and UMI, paths and
from_assayare both given or neither, or the selection holds no cell.FileNotFoundError – If a file does not exist.
PermissionError – If the store is read-only and the barcodes are not saved yet.
MemoryError – If the import does not fit the memory budget.
- import_clones(paths, *, cell_selection, barcode_prefix=None, barcode_suffix=None, barcode_pattern=None, format=None, columns=None, multiple='error', invalidate_cache=False)#
Import clones that a lineage tracing tool or a study assigned to cells.
A clone is the set of cells that descend from one ancestor cell. Tools that read lineage barcodes, CNV profiles or mitochondrial variants write which clone each cell belongs to, and the import joins each of those cells to a selected cell by barcode and saves the clones as a
clonesartifact, which every clone source writes. Each file’s format is recognized from its contents: CoSpar’s clone table, TREX’sclones.txtof every release, CellTag-multi’s and CellTagR’s clone tables, STICR’s cell metadata, Cassiopeia’s allele table, Numbat’sclone_post_{i}.tsv, a Matrix Market clone matrix with its cell list, such as LARRY’s on GEO, and AnnData files with CoSpar’sobsm['X_clone']or MiTo’sobs['MiTo_clone'].columnsreads any other table, or an AnnDataobscolumn, by the columns it names;formatnames a format that the contents leave open. The clones API reference lists the formats and their columns.A cell’s ID is its file’s
barcode_prefix, the barcode andbarcode_suffix, matched exactly;barcode_patternkeeps the part of each barcode that itsbarcodegroup matches first. Barcodes that match no selected cell are counted by the cell ID they name in the artifact’s diagnostics, whichds.artifacts.inspect(ref).diagnosticsreturns:fileBarcodes,unmatchedBarcodes, those that name no cell of the store,unselectedBarcodes, those of cells of the store outside the selection, and up to five examples of each, which show the barcode beside the cell ID it derives, thenfileRows, the rows of the files, a matrix’s cells, androwsPerFile, those of each file in the canonical order of the files. The clone writer addscellsWithCloneandlargestCloneShare. Barcodes of no cell are named in a warning, and so are the files that hold no row, such as a table of a header alone, and files whose rows name selected cells but give none of them a clone, as labels that mean no clone, such as MiTo’s"unassigned"or Cassiopeia’s lineage group 0, and a clone matrix without entries give; when the files also name cells outside the selection, the warning suggests acell_selectionof those cells if the files give them clones. The clone summaries andexport_clonesrefuse the clones of an import that gave no selected cell a clone so, or of whichmultiple="drop"left out every cell, naming the cause; a reused import gives the warnings again. A file is identified by the SHA-256 of its bytes, and of a matrix’s cell and clone lists, so a moved file reuses the saved clones, an edited one gives new clones, and the order of the files does not matter.Clone IDs are unique only within one tool’s run, so with several files each file’s labels start with its
barcode_prefix, or with its name without extensions and_; two files with the same namespace raiseValueError. A cell listed in two different clones raisesValueError, and withmultiple="drop"it is left without a clone and counted in thecellsInSeveralClonesdiagnostic. A selected cell that no file lists has no clone.The artifact’s canonical
valueshold each cell’s clone label, empty for a cell without one, which groupings treat as missing.codesnumbers the clones by size, largest first, then by label, -1 for none, andclone_sizeholds the cells of each cell’s clone, 0 for none. A Numbat file, or a probability column thatcolumnsnames, addsclone_probability, NaN where no probability is given.clone_idsandclone_sizeshold one row per clone.- Parameters:
paths (
str|PathLike[str] |Sequence[str|PathLike[str]]) – One clone file, or several, plain or gzip-compressed.cell_selection (
ArtifactRef) – The cells that the clones label.barcode_prefix (
str|Sequence[str|None] |None) – Text before each barcode in the cell IDs, such as"sample1__"in a merged store: one for every file, or one per file. None adds nothing.barcode_suffix (
str|Sequence[str|None] |None) – Text after each barcode in the cell IDs, such as"-1": one for every file, or one per file.barcode_pattern (
str|Sequence[str|None] |None) – A regular expression whose named groupbarcodeis the part of each barcode that names the cell, found asre.searchfinds it, such asr"_(?P<barcode>[ACGT]{16}-1)$"; a barcode it does not match names no cell. One for every file, or one per file.format (
str|None) – One of"cospar","trex","celltag_multi","celltagr","sticr","cassiopeia","numbat","table","matrix","cospar_h5ad","mito"and"h5ad", or None to recognize each file’s format.columns (
Mapping[str,str|Sequence[str]] |None) – The columns to read:"cell"(a column, or a list of columns whose values are joined by"__", such as["Library", "Cell barcode"]of LARRY’s metadata),"clone"and"probability". A table read by row names, such as a wide table with one clone column per labeling round, needs only"clone", and a clone matrix takes only"cell", the columns of its cell list.multiple (
str) –"error"or"drop", for a cell listed in two different clones.invalidate_cache (
bool) – Import again instead of reusing saved clones.
- Return type:
- Returns:
A complete datastore-scoped
clonesartifact. Read it withload_clones()or plot it withds.plots.clone_abundance.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If a file’s format is unknown or malformed, a column is missing, an option lists a value for another number of files, a file is listed twice with the same prefix and suffix, two files share a namespace, a cell is listed in two clones with
multiple="error", or the selection holds no cell.FileNotFoundError – If a file, or a clone matrix’s cell list, is missing.
PermissionError – If the store is read-only and the clones are not saved yet.
MemoryError – If the import does not fit the memory budget.
- import_phylogeny(paths, *, cell_selection, time_unit, format=None, barcode_prefix=None, barcode_suffix=None, barcode_pattern=None, invalidate_cache=False)#
Import cell phylogenies whose leaves are cells.
Lineage recorders such as PEtracer and DNA Typewriter, and tools such as Cassiopeia and LAML, reconstruct trees whose leaves are cells and whose internal nodes are their ancestors. The import reads Newick files, plain or gzip-compressed, with one tree or several, such as one tree per clone, and TreeData
.h5tdfiles and.zarrstores, joins each leaf to a selected cell by barcode, and saves the forest as acell_phylogenyartifact thatphylogeny_clones()cuts into clones. Newick is read without recursion, so trees of a million leaves on one line read like small ones, with bracket comments, quoted labels, polytomies, single-child nodes, zero and negative branch lengths and a length above the root. An unquoted number on an internal node is a support value, as treedata reads it, not a name.A node’s time runs from its tree’s root, plus any length above the root, in the unit that
time_unitdeclares, since no file states it. A TreeData node’stimeis preferred over the time its edge’slengthimplies, and a node below a branch without a length has no time.A leaf names the cell whose ID is its file’s
barcode_prefix, the leaf’s name andbarcode_suffix;barcode_patternkeeps the part of the name that itsbarcodegroup matches first. Leaves that name no selected cell are counted in the join’s diagnostics, apart from those of cells outside the selection, and those that name no cell of the store are named in a warning, which a reused import gives again. Beside the join’s counts, the diagnostics thatds.artifacts.inspect(ref).diagnosticsreturns holdcellsInNoTree, the selected cells that no leaf names,unnamedLeaves, the leaves without a name, andleafTimeSpread, the largest gap between a tree’s earliest and latest leaf intime_unit, None when a leaf has no time. Two leaves that name one cell raiseValueError.Each tree is named by its file’s
barcode_prefixand the file’s name without.gzand its extension, such asE7.5-R1-C1forE7.5-R1-C1.nwk.gz; a file of several trees adds_and each tree’s position from 1, or its TreeData key. The names, which must differ, start the labels of clones cut from several trees.- Parameters:
paths (
str|PathLike[str] |Sequence[str|PathLike[str]]) – One tree file, or several.cell_selection (
ArtifactRef) – The cells that the leaves name.time_unit (
str|None) – The unit of the trees’ times, such as"days", or None when their lengths are not times; then the trees are cut at depths only.format (
str|None) –"newick"or"treedata", or None to recognize each file: Zarr stores and HDF5 files hold TreeData.barcode_prefix (
str|Sequence[str|None] |None) – Text before each leaf’s name in the cell IDs: one for every file, or one per file.barcode_suffix (
str|Sequence[str|None] |None) – Text after each leaf’s name in the cell IDs.barcode_pattern (
str|Sequence[str|None] |None) – A regular expression whose named groupbarcodeis the part of each leaf’s name that names the cell; a name it does not match names no cell.invalidate_cache (
bool) – Import again instead of reusing saved trees.
- Return type:
- Returns:
A complete datastore-scoped
cell_phylogenyartifact.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If a file is not a well-formed tree file, a TreeData tree is not a tree, two trees share a name, two leaves name one cell, no leaf names a selected cell, or the selection holds no cell.
FileNotFoundError – If a file does not exist.
PermissionError – If the store is read-only and the trees are not saved yet.
MemoryError – If the import does not fit the memory budget.
- load_alleles(alleles)#
Read saved recorder alleles as tables of cells, records and files.
- Parameters:
alleles (
ArtifactRef) – Alineage_allelesartifact, such as one fromimport_alleles().- Return type:
- Returns:
The alleles, with one row per cell, one row per cell, integration, site and allele row, and one row per file.
- Raises:
TypeError – If
allelesis not an ArtifactRef.ValueError – If it is not a
lineage_allelesartifact.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete.
MemoryError – If the tables do not fit the memory budget.
- load_barcodes(barcodes)#
Read saved lineage barcodes as tables of cells, records and libraries.
- Parameters:
barcodes (
ArtifactRef) – Alineage_barcodesartifact, such as one fromimport_barcodes().- Return type:
- Returns:
The barcodes, with one row per cell, one row per molecule or pair, and one row per library.
- Raises:
TypeError – If
barcodesis not an ArtifactRef.ValueError – If it is not a
lineage_barcodesartifact.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete.
MemoryError – If the tables, about 120 bytes per record, 160 per cell and per distinct barcode and UMI, and 64 per cell, or the read of the cells’ IDs and values, which
artifacts.load_valueschecks, do not fit the memory budget.
- load_clones(clones)#
Read saved clones as a table of cells and a table of clones.
Clonotypes read as clones too, labeled
clonotype_1and so on, and their table of cells also holds each cell’sreceptor_type, whose labels every clone summary measures apart. Clonotypes defined across receptor types also hold each cell’swithin_type_clone, its clonotype within its receptor type, which every clone summary measures, labeled as the summaries label it, such asclonotype_1 (TCR 2).- Parameters:
clones (
ArtifactRef) – A clone artifact:clones, such as one fromimport_clones(), orclonotypes, fromclonotypes().- Return type:
- Returns:
The clones, with one row per cell and one row per clone, largest first.
- Raises:
TypeError – If
clonesis not an ArtifactRef.ValueError – If it is not a
clonesorclonotypesartifact.KeyError – If the store holds no such artifact, or not the receptors of the clonotypes.
RuntimeError – If the artifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.
MemoryError – If the tables, about 250 bytes per cell beside the clones that they read and the text of the cells’ IDs and of the clone labels, do not fit the memory budget.
- load_expansion(expansion, *, splits=(10, 100, 1000, 10000, 30000, 100000))#
Read saved clonal expansion as tables of cells, categories and ranks.
Besides each cell’s category and each group’s cells and clones per category, the loader ranks each group’s clones by their cells and counts the cells that the clones in each window of ranks hold, as scRepertoire’s
clonalProportiondoes: by default the 10 largest, 11 to 100, 101 to 1000, 1001 to 10000, 10001 to 30000, 30001 to 100000, and the rest.- Parameters:
expansion (
ArtifactRef) – Aclonal_expansionartifact, such as one fromexpansion().splits (
Sequence[int]) – The last rank of each window but the last, strictly increasing.
- Return type:
- Returns:
The clonal expansion, with one row per cell, one per group and category, and one per group and rank window, each naming its group, and the groups’ labels in
group_keys.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
expansionis not aclonal_expansionartifact, orsplitsare invalid.KeyError – If the store holds no such artifact, or not the clones that it measured or the receptors of clonotypes.
RuntimeError – If the artifact, the clones that it measured or the receptors of clonotypes are incomplete.
MemoryError – If the tables, about 500 bytes per cell and 2,000 per group besides the cells’ IDs as text and the clones and labels that they read, do not fit the memory budget.
- load_fate_bias(bias)#
Read saved fate bias as tables of early cells, clones and fates.
- Parameters:
bias (
ArtifactRef) – Aclone_fate_biasartifact, such as one fromfate_bias().- Return type:
- Returns:
The fate bias, with one row per early cell, its shares of the fates in a table of their own, one row per clone with late cells and fate of its stratum, one per fate, and the fates’ labels in
group_keys.- Raises:
TypeError – If
biasis not an ArtifactRef.ValueError – If it is not a
clone_fate_biasartifact.KeyError – If the store holds no such artifact, or not the clones that it measured or the receptors of clonotypes.
RuntimeError – If the artifact, the clones that it measured or the receptors of clonotypes are incomplete.
MemoryError – If the tables, about 200 bytes per early cell, 24 per fraction and 160 per row of clone and fate, beside the early cells’ IDs as text and the clone labels that they read, do not fit the memory budget.
- load_phylogeny(phylogeny)#
Read saved phylogenies as a table of nodes and a table of trees.
- Parameters:
phylogeny (
ArtifactRef) – Acell_phylogenyartifact, fromimport_phylogeny().- Return type:
- Returns:
The trees in the natural order of their names, with one row per node, each tree in preorder, and one row per tree.
- Raises:
TypeError – If
phylogenyis not an ArtifactRef.ValueError – If it is not a
cell_phylogenyartifact.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as an import that stopped before it finished leaves it.
MemoryError – If the tables do not fit the memory budget.
- overlap(clones, *, group_by=None, groups=None, cell_selection=None)#
Compare groups of cells by the clones they share.
The groups are the combinations of the labels of the
group_bycell metadata columns, such as the sample or the tissue, and of thegroupslabel artifact, such as a clustering, among the cells ofcell_selection. Cells without a clone or a label are left out. Clonotypes are grouped within each receptor type, which joins the groups’ key columns asreceptor_type, and only groups of one receptor type are compared. Nothing is saved.Each pair of groups gets presence indices, which count clones, and abundance indices, which weigh them by their cells, as scRepertoire’s
clonalOverlapand immunarch’srepOverlapreport them:shared(the clones of both),jaccard,sorensen,overlap(shared over the smaller group’s clones),cosine(Ochiai’s, of presence),morisita_hornandabundance_cosine, and the share of each group’s cells whose clone the other holds. Presence indices grow with the cells of both groups, since a larger sample finds more of the rare clones; the Morisita-Horn index depends little on them and is near 1 when the same expanded clones dominate both groups.- Parameters:
clones (
ArtifactRef) – A clone artifact, such asclonesorclonotypes.group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the groups.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the groups, or aNamedCellArtifactof one, whose name titles only the figures of the result.cell_selection (
ArtifactRef|None) – Only these cells, or None for every cell of the clones.
- Return type:
- Returns:
The groups’ cells and clones, the indices of every pair, and the groups’ labels in
group_keys.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
clonesis not a clone artifact, the clones’ import gave no selected cell a clone, no cell has both a clone and a group, fewer than two groups hold a cell with a clone, no two groups share the labels that the clones keep apart, a column of the groups is missing or named twice, two key columns share a name, or two groups get one name.KeyError – If the store holds no such
clonesartifact, or not the receptors of the clonotypes.RuntimeError – If the
clonesartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.MemoryError – If reading the clones, grouping the cells, or the pairs of groups do not fit the memory budget.
- phylogeny_clones(phylogeny, *, time=None, depth=None, invalidate_cache=False)#
Cut cell phylogenies into clones at a time or at a depth.
Cutting a tree at
timemakes a clone of each clade whose root is the first node at or past that time on the way down from the tree’s root: the cells that descend from one lineage alive at that time, counted in the trees’time_unitfrom each root plus any length above it. Cutting atdepthcounts branchings below each root instead, after merging each node that has one child with that child, so a root with one child, as PEtracer’s trees have, starts at depth 0 like its child. Each child of a polytomy that the cut passes is a clone of its own. Cutting atdepth=0, or at a time at or before every root’s time, such astime=0when no negative length lies above a root, makes each tree one clone.A cell whose leaf ends before the cut, earlier than
timeor fewer thandepthbranchings below its root, is in no clone; the artifact’s diagnostics count such cells incellsBeforeCut, and a warning names how many, again when the cut is reused. Leaves of a tree that is not ultrametric end at different times, and the phylogeny’sleafTimeSpreaddiagnostic holds the largest gap between a tree’s earliest and latest leaf. Selected cells in no tree have no clone either.A clone is named by its root’s name when every node of its tree has a name of its own, as PEtracer’s and Cassiopeia’s trees do, and otherwise by
nodeand its root’s position in the tree, from 0 at the tree’s root, as the phylogeny’snodestable numbers them. With several trees, each label starts with its tree’s name and/, so the clones of one tree per clone stay apart. The artifact is aclonesartifact like any other: codes number the clones by size, largest first, then by label.- Parameters:
phylogeny (
ArtifactRef) – Acell_phylogenyartifact.time (
float|None) – The time of the cut from each tree’s root, in the trees’time_unit.depth (
int|None) – The branchings below each tree’s root.invalidate_cache (
bool) – Cut again instead of reusing saved clones.
- Return type:
- Returns:
A complete datastore-scoped
clonesartifact of the phylogeny’s cells.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
phylogenyis not acell_phylogenyartifact, both or neither oftimeanddepthare given,timeis not finite,depthis negative, the trees were imported without atime_unitandtimeis given, or a node has no time.KeyError – If the store holds no such
phylogenyartifact.RuntimeError – If the
phylogenyartifact is incomplete.PermissionError – If the store is read-only and the clones are not saved yet.
MemoryError – If the cut does not fit the memory budget.
- rarefaction(clones, *, group_by=None, groups=None, cell_selection=None, orders=(0, 1, 2), sizes=None, endpoint=None, knots=40)#
Rarefy and extrapolate the Hill numbers of groups of cells.
Each group’s Hill numbers of
orders0, 1 and 2 are computed for samples of more and fewer cells than it holds, with the sample coverage of each size, as iNEXT’siNEXTdoes (Chao et al. 2014, 2023). Below a group’s size the curve is the expected value of a random subsample; above it, an extrapolation that is reliable up to about twice the group’s size for order 0. The groups are those ofdiversity(). Nothing is saved.By default each group’s curve has iNEXT’s
knotssizes: about half evenly from 1 to its size and half from there toendpoint, by default twice its size.sizesgives every group the same sizes instead.- Parameters:
clones (
ArtifactRef) – A clone artifact, such asclonesorclonotypes.group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the groups.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the groups, or aNamedCellArtifactof one, whose name titles only the figures of the result.cell_selection (
ArtifactRef|None) – Only these cells, or None for every cell of the clones.orders (
Sequence[int]) – Orders of the Hill numbers, from 0, 1 and 2.sizes (
Sequence[int] |None) – Sizes in cells for every group, or None for each group’s default sizes.endpoint (
int|None) – The largest default size, or None for twice each group’s size.knots (
int) – The number of default sizes.
- Return type:
- Returns:
The curves, one row per group, order and size, and the groups’ labels in
group_keys.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
clonesis not a clone artifact, an order, size, endpoint or knots is invalid, the clones’ import gave no selected cell a clone, or no cell has a clone and a group.KeyError – If the store holds no such
clonesartifact, or not the receptors of the clonotypes.RuntimeError – If the
clonesartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.MemoryError – If reading the clones, grouping the cells, or the curves do not fit the memory budget.
- track(clones, *, group_by=None, groups=None, cell_selection=None, top_n=10, labels=None)#
Follow chosen clones across groups of cells.
By default the clones are the
top_nwith the most cells in each group, together, as scRepertoire’sclonalComparechooses them, with ties going to the larger clone overall;labelsnames them instead, such as["clone_3"]. Each chosen clone gets its cells and share of cells in every group, zeros included, so a clone that expands between time points or spreads between cell types shows it. The groups are those ofoverlap(), and a clonotype is followed through the groups of its own receptor type. Clonotypes thatwithin_receptor_type=Falsedefines across receptor types are followed, as every summary measures them, by each cell’s clonotype within its type, labeled such asclonotype_1 (TCR 2); a clonotype’s own label inlabelsfollows each of its clonotypes within types. Nothing is saved.- Parameters:
clones (
ArtifactRef) – A clone artifact, such asclonesorclonotypes.group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the groups.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the groups, or aNamedCellArtifactof one, whose name titles only the figures of the result.cell_selection (
ArtifactRef|None) – Only these cells, or None for every cell of the clones.top_n (
int) – The clones with the most cells to take from each group.labels (
Sequence[str] |None) – Clone labels to follow instead, as a sequence or a one-dimensional array, or None.
- Return type:
- Returns:
One row per chosen clone and group in its
table, the chosen clones’ labels, and the groups’ labels ingroup_keys.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
clonesis not a clone artifact,top_nis not positive,labelsis empty or a label names no clone, the clones’ import gave no selected cell a clone, no cell has both a clone and a group, a column of the groups is missing or named twice, two key columns share a name, or two groups get one name.KeyError – If the store holds no such
clonesartifact, or not the receptors of the clonotypes.RuntimeError – If the
clonesartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.MemoryError – If reading the clones, grouping the cells, or the table of the chosen clones’ groups does not fit the memory budget.
ds.repertoire#
import_receptors reads the T cell and B cell receptor contigs of a set of cells from Cell Ranger’s contig annotations or AIRR Rearrangement files, joins them to the cells by barcode, and saves them as an immune_receptors artifact, which ranks each cell’s chains and labels the cell with its receptor type, subtype and chain pairing. clonotypes groups the cells into clonotypes by identical chains, or into clonotype clusters by chains within a Hamming or Levenshtein distance, and saves a clonotypes artifact that labels each cell with its clonotype, which the clone summaries of ds.clones read as clones. gene_usage and spectratype count the genes and junction lengths of groups’ chains, without saving anything. export_airr writes the contigs, with each cell’s clonotype, as an AIRR Rearrangement file. Repertoire API reference describes the receptor model, the clonotype options, and the records that load_receptors, load_clonotypes, gene_usage and spectratype return.
- class cytearc.datastore.namespaces.RepertoireAccessor(store)#
- clonotypes(receptors, *, sequence='nt', receptor_arms='all', dual_ir='any', same_v_gene=False, same_j_gene=False, within=None, within_receptor_type=True, metric='identity', max_distance=None, invalidate_cache=False)#
Group the cells of imported receptors into clonotypes.
Two cells share a clonotype when the junctions of their chains are identical, as scirpy’s
define_clonotypesdecides, and clonotypes are the connected groups that these links form.sequencecompares the junctions’ nucleotides ("nt") or residues ("aa");receptor_armsthe arms that must agree:"all"(both arms when both cells have both, else the one arm that each has),"any","VJ"or"VDJ";dual_irthe chains of an arm:"any"(one chain of each cell),"all"(every chain, so both cells need the same number) or"primary_only".same_v_geneandsame_j_genealso require matched chains to share their gene calls.Cells of different receptor types, such as T cells and B cells, never share a clonotype unless
within_receptor_typeis False, and cells with different labels in thewithincell metadata columns, such as the donor, never do. A cell without a receptor, or without a compared sequence among the chains that take part, has no clonotype. Defined across receptor types, the artifact also saves each cell’s clonotype within its type, aswithin_receptor_type=Truedefines it, incodes_within_type, which every clone summary measures, so the summaries of clonotypes across types equal those of clonotypes within types, under labels such asclonotype_1 (TCR 2), and the representative of each, aswithin_receptor_type=Truechooses it, inrepresentatives_within_type, whose junction names it in figures, such asCASSB (TCR 2).metriclinks chains whose junctions are similar instead, as scirpy’sdefine_clonotype_clustersdoes:"hamming"(at mostmax_distancesubstitutions between junctions of one length),"normalized_hamming"(substitutions as a percentage of the length, rounded half up, at mostmax_distance) or"levenshtein"(at mostmax_distancesubstitutions, insertions and deletions), under the same rules for arms, dual chains, genes and groups. The resulting clonotype clusters group T cells that likely share their epitope, or B cells of one clone despite somatic mutations.max_distancehas no default for these metrics, since it decides the clusters, and amax_distanceof 0 links identical junctions alone, as scirpy’s cutoff of 0 does.Clonotypes are numbered by size, so
clonotype_1is the largest; ties follow the receptor type in sorted order, then thewithinlabels in natural order, then the sorted chains, so the numbers do not depend on the order of the cells. The artifact’s canonicalvalueshold each cell’s clonotype label, empty for a cell without one, which groupings treat as missing;clone_sizeholds the cells of each cell’s clonotype. The clone summaries ofds.clones, such asdiversity(), read the artifact as they read clones, and measure the cells of each receptor type apart. Its diagnostics, whichds.artifacts.inspect(clonotypes).diagnosticsreturns, are those of every source’s clones:cellsWithClone, the cells given a clonotype, andlargestCloneShare, the share of them that the largest holds.- Parameters:
receptors (
ArtifactRef) – Animmune_receptorsartifact.sequence (
str) –"nt"or"aa".receptor_arms (
str) –"all","any","VJ"or"VDJ".dual_ir (
str) –"any","all"or"primary_only".same_v_gene (
bool) – Require matched chains to share their V gene call.same_j_gene (
bool) – Require matched chains to share their J gene call.within (
str|Sequence[str] |None) – Cell metadata columns whose labels keep clonotypes apart, such as the donor; every cell with a receptor needs a label.within_receptor_type (
bool) – Keep the clonotypes of each receptor type apart.metric (
str) –"identity","hamming","normalized_hamming"or"levenshtein".max_distance (
int|None) – The largest distance of linked chains for the distance metrics: substitutions, percent, or edits; None with"identity".invalidate_cache (
bool) – Define again instead of reusing saved clonotypes.
- Return type:
- Returns:
A complete datastore-scoped
clonotypesartifact aligned to the receptors’ cells. Read it withload_clonotypes().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
receptorsis not animmune_receptorsartifact, an option is unknown, a distance metric has nomax_distance, the receptors’ import read no contig, the receptors store no junction of the compared kind, or awithincolumn is not a cell metadata column or has no label for a cell with a receptor.KeyError – If the store holds no such receptors.
RuntimeError – If the receptors are incomplete.
PermissionError – If the store is read-only and the clonotypes are not saved yet.
MemoryError – If reading the receptor types, grouping the cells by their
withinlabels, or the definition, 1,000 bytes per cell and 12 per contig and with a distance metric the 512 MiB of the search, does not fit the memory budget, across receptor types beside the clonotypes across types while each cell’s clonotype within its type is defined; or, with a distance metric, the junctions that the cells’ chains hold, decoded for the search, or the pairs of chains withinmax_distanceand the links between the chains or arms that match, 32 bytes each, do not fit what is left.
- export_airr(source, path, *, fields=None, chains_only=False, cell_order='source', temp_dir=None)#
Write imported contigs as an AIRR Rearrangement file.
The AIRR Community’s Rearrangement TSV is what Immcantation (Change-O, SHazaM, dowser), dandelion and scirpy read, so exported contigs carry a CyteArc analysis to their clonal lineage, somatic hypermutation or other analyses. Each row is one contig: its
cell_id, the cell’s ID in this store, the AIRR fields that the receptors store, and with aclonotypesartifact assource,clone_id, the cell’s clonotype label, empty for a cell without one, replacing any importedclone_id. The schema’s required fields come first, empty when the receptors do not store them; logical fields are writtenTandF, and other values as they are, unquoted, as the AIRR file format asks. The format forbids tabs and newlines in values, so a value that holds a tab, a newline or a carriage return is refused before the file is opened; it advises against@,#,"and', so the export warns with the number of values that hold them and their fields, and apart, in every field, with the values that start with a double quote, which readers that take quotes read as an opening quote. Asequence_idthat repeats, such as<barcode>_contig_1of the TCR and the BCR files of one cell, gets_2,_3and so on from its second occurrence, in the order of the file’s rows, since the schema requires unique identifiers. A path ending in.gzis gzip-compressed at level 6.Cells are written in the order of the file that the store imported, as their
sourceRowrecords it, or in store order withcell_order="stored"; each cell’s contigs keep their stored order, the order of the contig files. In the file’s order, the contigs are read and rendered in store order, the fastest, and each row is sent to its place in the file through temporary files on local disk, intemp_dir, which hold the rows uncompressed, about the size of the file without gzip, each file deleted once its rows are written;cell_order="stored"needs no temporary files.The contigs are read and written in blocks of about 32 MiB, at most a sixteenth of the memory budget, as many contigs as fit when each field holds its longest value. Beside one block, the export holds the cells’ IDs and clonotypes, the distinct values of the text fields and the repeated IDs’ new names, and until it has named the repeated IDs, a hash of each contig’s ID. In the imported file’s order, it also holds the place of each row in the file, the block that a thread sends to the temporary files while the next one renders, at most a block of rows waiting for them, and two pieces of the files’ rows, each sized to read in about a block, as they are read back. Every stored array is read a chunk at a time, and what each step reads and holds is checked against the memory budget before the step runs, all before the file is written.
- Parameters:
source (
ArtifactRef) – Animmune_receptorsorclonotypesartifact.path (
str|PathLike[str]) – The file to write.fields (
Sequence[str] |None) – The stored fields to write, or None for every stored field;sequence_idandcell_id, and with clonotypesclone_id, are always written.chains_only (
bool) – Write only the contigs that count as chains.cell_order (
Literal['source','stored']) –"source"writes the cells in the order of the imported file,"stored"in store order.temp_dir (
str|PathLike[str] |None) – Directory of the temporary files of an export in source order. None uses the system’s temporary directory.
- Return type:
- Returns:
The file written, its
rows, the contigs written, and itsdiagnostics:contigs,renamedContigIds, the repeated contig IDs written with a suffix,leadingQuoteValuesanddiscouragedValues, the values that start with a double quote and those that hold a character that the format advises against, andleadingQuoteFieldsanddiscouragedFields, their fields. Each of the three counts of values and IDs above 0 gives a warning.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
sourceis not animmune_receptorsorclonotypesartifact, the receptors’ import read no contig, a field is not stored,cell_orderis unknown, or a value to be written holds a tab, a newline or a carriage return.KeyError – If the store holds no such
sourceartifact, or not the receptors of the clonotypes.RuntimeError – If the
sourceartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.MemoryError – If a step of the export would hold more than the memory budget.
OSError – If the temporary directory lacks the disk that the rows take there.
- gene_usage(source, *, genes='v_call', level='gene', slots=('VJ_1', 'VDJ_1'), count='cells', group_by=None, groups=None, cell_selection=None)#
Count the genes of the chains of groups of cells.
Each cell counts by its chains in
slots, by default its primary chain of each arm,VJ_1andVDJ_1, as scirpy reads a slot’s gene calls; each chain counts within its locus, so TRA and TRB genes get their own shares.genesnames one gene field, such as"v_call", or several, such as("v_call", "j_call")for the V-J pairs of each chain.levelnames calls as called, with their allele ("allele"), as genes ("gene", the default) or as families ("family"), and a call naming several genes keeps its first. A chain without a call is not counted.sourceis animmune_receptorsartifact, whose cells with a chain count, or aclonotypesartifact, whose cells with a clonotype count;count="clonotypes"then counts each clonotype once per group and gene instead of each cell, which keeps expanded clones from dominating the shares, and clonotypes defined across receptor types by each cell’s clonotype within its type, as every clone summary measures them. The groups are the combinations of the labels ofgroup_bycolumns and of agroupslabel artifact, among the cells ofcell_selection; without either, every cell is one group. Nothing is saved.- Parameters:
source (
ArtifactRef) – Animmune_receptorsorclonotypesartifact.genes (
str|Sequence[str]) – One gene field or several, fromv_call,d_call,j_callandc_call.level (
str) –"allele","gene"or"family".slots (
str|Sequence[str]) – The chain slots to count.count (
str) –"cells"or"clonotypes".group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the groups.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the groups, or aNamedCellArtifactof one, whose name titles only the figures of the result.cell_selection (
ArtifactRef|None) – Only these cells, or None for every cell.
- Return type:
- Returns:
One row per group, locus and gene, or gene combination, and the groups’ labels in
group_keys.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
sourceis not animmune_receptorsorclonotypesartifact, an option is unknown, the receptors’ import read no contig, a gene field is not stored,count="clonotypes"is asked of receptors, a column of the groups is missing or named twice, two key columns share a name, or two groups get one name.KeyError – If the store holds no such
sourceartifact, or not the receptors of the clonotypes.RuntimeError – If the
sourceartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.MemoryError – If reading the chain slots, grouping the cells, holding the chains and counting them, or decoding the gene calls does not fit the memory budget.
- import_receptors(paths, *, cell_selection, barcode_prefix=None, barcode_suffix=None, barcode_pattern=None, format=None, productive_only=True, invalidate_cache=False)#
Import the immune receptor contigs of a set of cells.
A V(D)J library, such as 10x Genomics Chromium Single Cell Immune Profiling, assembles each cell’s T or B cell receptor transcripts into contigs. The import reads Cell Ranger’s contig annotations,
filtered_contig_annotations.csvorall_contig_annotations.csv, or AIRR Rearrangement files with acell_idfield, such as Cell Ranger’sairr_rearrangement.tsv; each file’s format is read from its header unlessformatnames it. It joins each contig to a selected cell by barcode, keeps every contig of the selected cells, and saves them as animmune_receptorsartifact. Pass the TCR and BCR files of one library together, so a cell with both kinds of chain is found.Each cell’s chains are ranked as scirpy ranks them, as the repertoire API reference describes: a contig counts as a chain when it has a locus of a receptor chain and a junction amino-acid sequence, is productive unless
productive_onlyis False, and is not flagged by Cell Ranger as outside a cell or of low confidence. The first two chains of each arm fill the cell’sVJ_1,VJ_2,VDJ_1andVDJ_2slots, and the chains give the cell’s receptor type, subtype and chain pairing. A selected cell without a chain is"no IR".A contig’s cell ID is its file’s
barcode_prefix, its barcode andbarcode_suffix, matched exactly;barcode_patternkeeps the part of each barcode that itsbarcodegroup matches first. A merged store prefixes each sample’s barcodes with its name and two underscores, so pass each sample’s files with that sample’s prefix. The artifact’s diagnostics, whichds.artifacts.inspect(ref).diagnosticsreturns, hold the join’s counts of the files’ barcodes, those that match no cell of the store and those of cells outside the selection, with examples of each, thenfileContigs, the files’ contigs,contigsPerFile, those of each file in the canonical order of the files,unmatchedContigs, those that match no selected cell, andcellsWithChain, the selected cells with a chain. Barcodes that match no cell of the store are named in a warning, and the files that hold no contig in another; the calls that read contigs refuse receptors whose import read none. A reused import gives both warnings again. A file is identified by the SHA-256 of its bytes, so a moved file reuses the saved receptors and an edited file gives new ones, and the order of the files does not matter.The artifact’s canonical
valueshold each cell’s receptor type, and its other per-cell arrays arereceptor_subtype,chain_pairing,multichain,n_vjandn_vdj(its chains of each arm) andn_contigs.select_cellsreads them, sods.select_cells(receptors, include=["TCR"])keeps the T cells with a receptor.- Parameters:
paths (
str|PathLike[str] |Sequence[str|PathLike[str]]) – One contig file, or several, plain or gzip-compressed.cell_selection (
ArtifactRef) – The cells that the contigs belong to.barcode_prefix (
str|Sequence[str|None] |None) – Text before each barcode in the cell IDs, such as"sample1__"in a merged store: one for every file, or one per file. None adds nothing.barcode_suffix (
str|Sequence[str|None] |None) – Text after each barcode in the cell IDs, such as"-1": one for every file, or one per file.barcode_pattern (
str|Sequence[str|None] |None) – A regular expression whose named groupbarcodeis the part of each barcode that names the cell, found asre.searchfinds it, such asr"^(?P<barcode>[ACGT]{16})"; a barcode it does not match names no cell. One for every file, or one per file.format (
str|None) –"cellranger"or"airr"for every file, or None to read each file’s format from its header.productive_only (
bool) – Count only productive contigs as chains.invalidate_cache (
bool) – Import again instead of reusing saved receptors.
- Return type:
- Returns:
A complete datastore-scoped
immune_receptorsartifact. Read it withload_receptors()or plot it withds.plots.receptor_qc.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If a file is neither format or not the named one, is malformed, repeats a contig ID, or is listed twice with the same prefix and suffix, an option lists a value for another number of files, a pattern has no
barcodegroup, or the selection holds no cell.FileNotFoundError – If a file does not exist.
PermissionError – If the store is read-only and the receptors are not saved yet.
MemoryError – If the import would not fit the memory budget: at its peak it holds about three times the bytes of its encoded contigs, 400 bytes per selected cell and each cell’s ID as text, and reading the IDs decodes a stored chunk of them.
- load_clonotypes(clonotypes)#
Read saved clonotypes as a table of cells and a table of clonotypes.
- Parameters:
clonotypes (
ArtifactRef) – Aclonotypesartifact, such as one fromclonotypes().- Return type:
- Returns:
The clonotypes, with one row per cell and one row per clonotype, largest first, with the chains of each clonotype’s representative cell and the name of its
withingroup, and eachwithingroup’s labels ingroup_keys.- Raises:
TypeError – If
clonotypesis not an ArtifactRef.ValueError – If it is not a
clonotypesartifact.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete.
MemoryError – If the tables, 300 bytes per cell and 700 per clonotype beside the cells’ IDs, the representatives’ chains and the
withinlabels that they read as text, do not fit the memory budget.
- load_receptors(receptors, *, fields=None)#
Read saved immune receptors as a table of cells and a table of contigs.
- Parameters:
receptors (
ArtifactRef) – Animmune_receptorsartifact, such as one fromimport_receptors().fields (
Sequence[str] |None) – The contig fields to load, by AIRR name, or None for every stored field. The table of contigs holds them, and the table of cells holds those ofSLOT_FIELDSfor each slot;fields=[]loads the labels and chain counts of each cell alone.
- Return type:
- Returns:
The receptors, with one row per cell and one row per contig.
- Raises:
TypeError – If
receptorsis not an ArtifactRef orfieldsis not a sequence of names.ValueError – If it is not an
immune_receptorsartifact, or a field is not stored.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as a call that stopped before it finished leaves it.
MemoryError – If the tables do not fit the datastore memory budget.
- spectratype(source, *, sequence='aa', slots=('VJ_1', 'VDJ_1'), count='cells', group_by=None, groups=None, cell_selection=None)#
Count the junction lengths of the chains of groups of cells.
The spectratype of a repertoire is the distribution of its junction lengths, in residues (
sequence="aa") or nucleotides ("nt"), as scirpy’sspectratypecounts them; a narrow peak points to an expanded clone, and a repertoire of naive cells has a smooth, roughly Gaussian one. Junctions include their conserved cysteine and phenylalanine or tryptophan, as Cell Ranger’s CDR3 does. Cells, slots, counts and groups are those ofgene_usage(). Nothing is saved.- Parameters:
source (
ArtifactRef) – Animmune_receptorsorclonotypesartifact.sequence (
str) –"aa"or"nt".slots (
str|Sequence[str]) – The chain slots to count.count (
str) –"cells"or"clonotypes".group_by (
str|Sequence[str] |None) – Cell metadata columns whose labels define the groups.groups (
ArtifactRef|NamedCellArtifact|None) – A cell-label artifact whose labels define the groups, or aNamedCellArtifactof one, whose name titles only the figures of the result.cell_selection (
ArtifactRef|None) – Only these cells, or None for every cell.
- Return type:
- Returns:
One row per group, locus and length, and the groups’ labels in
group_keys.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
sourceis not animmune_receptorsorclonotypesartifact, an option is unknown, the receptors’ import read no contig, the junctions are not stored,count="clonotypes"is asked of receptors, a column of the groups is missing or named twice, two key columns share a name, or two groups get one name.KeyError – If the store holds no such
sourceartifact, or not the receptors of the clonotypes.RuntimeError – If the
sourceartifact or the receptors of the clonotypes are incomplete, as an import that stopped before it finished leaves them.MemoryError – If reading the chain slots, grouping the cells, holding the chains and counting them, or measuring the junctions does not fit the memory budget.
ds.variants#
import_counts reads the per-cell allele counts of mitochondrial and targeted variants that mgatk, maegatk, cellsnp-lite, MQuad, VarTrix, MiTo, giftwrap and the GoT tools write, joins their cells to a cell selection by barcode, and saves a variant_counts artifact of the sites, their alleles and each cell’s depth, counts and calls. load_counts reads the artifact as tables of sites, alleles, cells and stored entries. informative scores every variant across cells with mgatk’s statistics and selects the informative ones by Signac’s or MAESTER’s thresholds, saved as a variant_selection artifact that load_informative reads, and frequency_clones calls the clones that the informative variants mark from their allele frequencies, as Signac’s FindClonotypes does. genotypes calls each cell’s genotype at targeted sites by GoT’s rules, GIFT’s model or the tools’ own calls, saved as a variant_genotypes artifact that load_genotypes reads, and genotype_clones calls the clones that the combinations of mutations define, by the likelihood of a model of allelic dropout or by exact agreement. Variants API reference lists the formats and describes count units, depth, the statistics, the presets and masks, the calls and methods of genotyping, and the VariantCounts, VariantSelection and VariantGenotypes records.
- class cytearc.datastore.namespaces.VariantsAccessor(store)#
- frequency_clones(informative, *, n_neighbors=10, resolution=1.0, within=None, invalidate_cache=False)#
Call clones from the allele frequencies of informative variants.
Cells that descend from one ancestor share its mitochondrial variants, at similar frequencies. As Signac’s
FindClonotypesdoes, each cell’s neighborhood holds itself and then_neighbors - 1cells most similar to it by the cosine similarity of the square roots of their allele frequencies of the informative variants; two cells that share a neighbor are joined with the Jaccard index of their neighborhoods, dropping joins below 1/15, as Seurat’sFindNeighborsbuilds its shared-neighbor graph; and the Leiden algorithm partitions the graph atresolutionwhere Signac uses Seurat’sFindClusters.Every cell is compared with every other cell, so the time grows with the square of the cells;
withincompares the cells of each group apart. Cells that tie, such as cells that show one informative variant each, take the same few neighbors and join every other such cell, so the graph also grows with the square of their number, and a graph that does not fit the memory budget raisesMemoryError.A cell’s frequency is undefined where it was not covered, so the similarity of two cells counts only the variants that both cover, where Signac counts an uncovered variant as frequency 0. Cells with no coverage at any informative variant, cells that show none of them and cells similar to no other cell carry no evidence of a clone and get none; the artifact’s diagnostics, which
ds.artifacts.inspect(clones).diagnosticsreturns, count them incellsWithoutCoverage,cellsWithoutAlternativeandcellsWithoutNeighbors, beside the informativevariants, thecellsScoredand theedgesof the shared-neighbor graph, and, as every source’s clones,cellsWithCloneandlargestCloneShare. The clones cover the cells of the counts thatinformativescored, and its statistics cover the cells that the clones are called from.The similarity counts a frequency whatever the reads behind it, so one stray read of a clone’s variant can put a cell in that clone. The cells of a clone of fewer cells than
n_neighborstake as neighbors the cells of other clones that they resemble, so the clone can join the most similar one, and a smallern_neighborsseparates smaller clones; cells that resemble no other clone’s stay apart. The call warns when awithingroup, or withoutwithinall the scored cells, holds fewer cells thann_neighbors.Clones are numbered by size over every
withingroup, soclone_1is the largest, and ties follow their first cell.- Parameters:
informative (
ArtifactRef) – Avariant_selectionartifact frominformative(), whose counts the frequencies are read from.n_neighbors (
int) – The cells of a full neighborhood, the cell itself included as Seurat counts it, at least 2.resolution (
float) – The Leiden resolution; larger values give more, smaller clones.within (
str|Sequence[str] |None) – Cell metadata columns whose labels keep clones apart, such as the donor or the mouse: clones never join cells of two groups. Every cell that the statistics covered needs a label.invalidate_cache (
bool) – Call clones again instead of reusing them.
- Return type:
- Returns:
A complete datastore-scoped
clonesartifact over the counts’ cells, which every clone summary reads. Read it withload_clones().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
informativeis not avariant_selectionartifact or selects no informative variant,n_neighborsis below 2, the resolution is not finite and positive, or a within column is missing, is named twice or has no label for a cell that the statistics covered.KeyError – If the store holds no such
informativeartifact, or not the counts that it scored.RuntimeError – If the
informativeartifact or its counts are incomplete.PermissionError – If the store is read-only and the clones are not saved yet.
MemoryError – If grouping the cells by
within, the frequencies, similarities or graph, or the clone labels as the store saves them do not fit the memory budget.
- genotype_clones(genotypes, *, sites=None, within=None, method='likelihood', dropout_probability=None, error_probability=None, min_size=None, min_posterior=None, invalidate_cache=False)#
Call clones from the combinations of mutations that cells carry, tolerating allelic dropout.
Cells that descend from one mutated ancestor share its mutations. Each cell’s calls at the chosen sites are mutant (heterozygous, homozygous alternative or alternative present), wild type, or unknown where the cell was
missingorfiltered. Single-cell DNA amplification loses one allele of a cell at some sites, allelic dropout, which turns a heterozygous mutant call into a wild-type one, so two cells of one clone can disagree.method="likelihood", the default, fits SCClone’s mixture model (Yu, Du and Song, Frontiers in Genetics 2022, doi:10.3389/fgene.2022.823941): each clone is a set of mutations, a cell of a clone reads wild type at one of its mutations with the site’s dropout probability and mutant at another site with the site’s error probability, and an unknown call adds nothing. Each site’s two probabilities are estimated from the cells by EM, shrunk toward the probabilities pooled over every site by priors worth 20 and 200 calls, a site’s error probability stays at most five times the pooled one, and the pooled one at most 0.1, so that a mutation that every cell carries cannot pass for errors;dropout_probabilityorerror_probabilityholds one probability at every site instead. A greedy search chooses the number of clones by Schwarz’s criterion, in which a clone costs its weight and the sites at which it differs from its neighbor on a minimum spanning tree of the clones rooted at the wild type. The genotype without mutations is always a component: its cells, like cells without a mutant call, take no clone. Each cell takes its most probable clone, its posterior saved asclone_probability; a cell with a mutant call whose most probable component has a posterior belowmin_posterioris ambiguous and takes none, and a clone of fewer thanmin_sizecells leaves its cells without one. Every cell with a call at the chosen sites takes part in the fit. A subclone that differs from its parent at one site cannot be told from that site’s dropout by calls alone: both explanations fit the calls equally, so such a subclone may join its parent.method="exact"links two cells when they agree at every site that both were called at, a Jaccard index of 1 over the sites both know. Cells whose calls agree with two cells that disagree at a site they were not called at cannot be placed and join neither: they are left out as ambiguous, however many there are. The linked groups are the clones, and a cell without a mutant call gets no clone. One dropout splits a cell from its clone under this rule.Clones are numbered by size as
clone_1and on.withinnames cell metadata columns, such as the donor: clones never join cells of two groups, and the likelihood fits each group apart, with its own rates. The artifact’s diagnostics, whichds.artifacts.inspect(clones).diagnosticsreturns, count thesitescompared, themutantCells, theambiguousCellsand, for the likelihood, thecellsInSmallClones; record the pooleddropoutProbabilityanderrorProbabilitythat the fit used, weighed over the groups by the calls that estimate them; and count thecappedSearches, the groups whose search stopped splitting at 500 clones, the most that a fit holds, and thecellsInCappedSearchesthat those searches fitted, beside every source’scellsWithCloneandlargestCloneShare; the rule that does not run records None. Clones that a capped search’s score would split further may hold several of the cells’ clones, so aDiagnosticWarningsays so each time the clones are computed or reused. The likelihood also saves each site’s label and each group’s dropout and error probability at each site.- Parameters:
genotypes (
ArtifactRef) – Avariant_genotypesartifact fromgenotypes().sites (
Sequence[str|int] |ndarray|Index|None) – The genotyped sites whose calls define the clones, by label or by position on counts of one contig, asload_genotypes()takes them, or None for every genotyped site.within (
str|Sequence[str] |None) – Cell metadata columns to call clones within, or None; every cell with a call, for"likelihood", or with a mutant call, for"exact", needs a label.method (
str) –"likelihood"or"exact".dropout_probability (
float|None) – For"likelihood", the chance that a cell carrying a site’s mutation reads wild type there, held at every site, from 0 up to 1; None to estimate each site’s.error_probability (
float|None) – For"likelihood", the chance that a cell without a site’s mutation reads mutant there, held at every site, from 0 up to 1; None to estimate each site’s.min_size (
int|None) – For"likelihood", the fewest cells of a clone, None for 2.min_posterior (
float|None) – For"likelihood", the posterior that a cell’s most probable component must reach, else the cell is ambiguous, from 0 to 1; None for 0.6.invalidate_cache (
bool) – Call the clones again instead of reusing them.
- Return type:
- Returns:
A complete datastore-scoped
clonesartifact over the genotypes’ cells, which every clone summary reads. Itsambiguousarray marks the cells left out as ambiguous and, for the likelihood, itsclone_probabilityarray holds each cell’s posterior of its clone. Read it withload_clones().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
genotypesis not avariant_genotypesartifact,sitesnames a site it did not genotype or a position of counts of several contigs,methodis unknown, a rule is given to"exact"or is out of range,withinnames a column twice or no cell metadata column, or a cell that needs a label has none in it.KeyError – If the store holds no such artifact, or not its counts when
sitesnames a position.RuntimeError – If the artifact is incomplete, or its counts when
sitesnames a position.PermissionError – If the store is read-only and the clones are not saved yet.
MemoryError – If reading the calls, fitting or linking the cells, or saving the clone labels does not fit the memory budget.
- genotypes(counts, *, method, sites=None, alleles=None, min_umis=None, min_mutant_umis=None, min_fraction=None, min_posterior=None, swap_probabilities=None, min_quality=None, min_depth=None, invalidate_cache=False)#
Call each cell’s genotype at targeted sites, in one vocabulary of calls.
A call says what a cell carries at a site:
wild_type,heterozygous,homozygous_alternative,alternative_present(the alternative, without a claim of how many copies carry it),missing(no evidence) orfiltered(evidence that the rule did not call). Three methods call them:"source"adopts the calls that the tool wrote into the imported files, such as GoT’sGenotype, GoT-Multi’sgenotype_mergedorgenotype_finaland Gotcha’sgenotype_pred, keeping each call’s own label. Where the files wrote several call columns for a site, each cell takes its call from the first that holds one for it: GoT-Multi’s refined call, then its merged call, then a single call column, and its channels’ calls last. A label of no call where the cell holds evidence at the site or at its channels, such asUnprofiledbeside ambiguous UMIs, isfiltered, and a cell with evidence but no call isfilteredtoo. Tapestri and DAb-seq call each variant of a position apart, so each alternative of a position is genotyped as a site of its own, labeled likechr1:115256513:G/T.min_qualityandmin_depthfilter the adopted calls, as Tapestri’s pipeline filters genotypes by their quality and depth: a call whose quality, such as Tapestri’sGQ, is belowmin_qualityor missing, or whose cell’s depth at the site, or at the deepest of its channels, is belowmin_depth, isfiltered. Only Tapestri’s and DAb-seq’s calls carry a quality, so counts of other formats refusemin_quality, and a genotyped site at which no cell holds depth, as in a GoT table of calls alone, refusesmin_depth."threshold"calls each cell from its UMIs of the site’s wild type and alternative by the rules given, since GoT studies apply different ones:min_mutant_umis=1calls a cellalternative_presentwith one mutant UMI andwild_typewith none, as for patients’ cells, andmin_fractioncalls a cell mutant or wild type when that allele’s share of its UMIs reaches it. Nam et al. (2019) called cell lines whose allele held more than 90% of their UMIs, whichmin_fraction=float(np.nextafter(0.9, 1))reproduces exactly;min_fraction=0.9also calls a cell whose allele holds exactly 90%, such as 9 of 10 UMIs.min_umisUMIs of the two, 1 by default, are needed for any call."gift"applies GIFT’s model to giftwrap’s counts: each UMI’s gapfill goes to the probe’s wild type or mutant by its edit distance to them, each UMI may come from template switching with the probability thatswap_probabilitiesgives for its reads, and the UMIs of a cell give the posterior of the wild type, the heterozygote and the homozygous mutant under a uniform prior. The most probable genotype is called when its posterior reachesmin_posteriorand the cell holds at leastmin_umisUMIs, 1 by default, whose swap probability lies below 0.1. By default the posterior must exceed 0.6, as GIFT calls cells, which the artifact records as the next number above 0.6, 0.6000000000000001. Withoutswap_probabilitiesevery UMI counts, as GIFT treats cell lines once their UMIs of few reads are dropped.
"threshold"and"gift"compare each site’s wild type, the allele of role"reference", with its one alternative;allelesnames them for a site whose files do not, such as a GIFT probe whose manifest lacks its gapfills, as{"JAK2 c.1849G>T": ("CAC", "AAC")}. Withoutsites, every site that the method can call is genotyped: those with calls for"source", those with one wild type and one alternative otherwise.The artifact’s diagnostics, which
ds.artifacts.inspect(ref).diagnosticsreturns, count the calls of each kind,wildTypeCalls,heterozygousCalls,homozygousAlternativeCalls,alternativePresentCalls,missingCallsandfilteredCalls, andalternativesNotShown, the sites whose alternative thatallelesnames no cell shows, None for"source", which compares no alleles; such sites give a warning, which reused genotypes give again.- Parameters:
counts (
ArtifactRef) – Avariant_countsartifact fromimport_counts().method (
str) –"source","threshold"or"gift".sites (
Sequence[str|int] |ndarray|Index|None) – Site labels to genotype, such as["CALR"]or["chrM:310"], or positions of counts of one contig, such as[310], as a list, a NumPy array or a pandas index; None for every site the method can call.alleles (
Mapping[str,Sequence[str]] |None) – Each site’s wild-type and alternative allele, by label.min_umis (
int|None) – The fewest UMIs that a call needs, for"threshold"and"gift".min_mutant_umis (
int|None) – The fewest mutant UMIs of a mutant call, for"threshold".min_fraction (
float|None) – The share, above 0.5 and at most 1, that the called allele’s UMIs must reach, for"threshold".min_posterior (
float|None) – The posterior, from 0 to 1, that a"gift"call must reach; None for GIFT’s rule, a posterior above 0.6.swap_probabilities (
Mapping[int,float] |None) – For"gift", the probability that a UMI of each number of reads came from template switching, from 1 read up; a UMI takes the value of the most reads given that it reaches, and its reads are its entry’s reads per UMI.min_quality (
float|None) – For"source", the quality that an adopted call needs, such as Tapestri’sGQ, or None to adopt calls whatever their quality.min_depth (
int|None) – For"source", the depth at the site that an adopted call needs, or None to adopt calls whatever their depth. Every genotyped site needs depth in some cell.invalidate_cache (
bool) – Call the genotypes again instead of reusing them.
- Return type:
- Returns:
A complete datastore-scoped, cell-aligned
variant_genotypesartifact over the counts’ cells. Its canonicaln_mutant_sitescounts each cell’s mutant sites. Read it withload_genotypes().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
countsis not avariant_countsartifact, the method is unknown, a rule is given to a method that does not use it or is out of range,min_qualityis given for counts whose calls carry no quality ormin_depthfor a site at which no cell holds depth, a named site is unknown or cannot be called by the method,allelesnames an unknown site, a source’s call label is unknown, or no site can be genotyped.KeyError – If the store holds no such
countsartifact.RuntimeError – If the
countsartifact is incomplete.PermissionError – If the store is read-only and the genotypes are not saved yet.
MemoryError – If the counts’ rows, the calls or the cells’ arrays do not fit the memory budget.
- import_counts(paths, *, cell_selection, barcode_prefix=None, barcode_suffix=None, barcode_pattern=None, format=None, count_unit=None, swap_strands=False, include_variants=None, invalidate_cache=False)#
Import per-cell allele counts of mitochondrial or targeted variants.
Mitochondrial lineage tracing (mtscATAC-seq, MAESTER) and targeted genotyping (GoT, GIFT, Tapestri) count, for each cell, the reads or UMIs of each allele at variant sites: the positions of the mitochondrial genome or of a targeted panel, or targets and probes without coordinates. The import reads those counts, joins each cell to a selected cell by barcode and saves a
variant_countsartifact: the sites and their alleles, and for each cell its depth at each site, its count of each allele and the calls the source made itself. Depth 0 means the cell was not covered at the site, so an allele frequency there is undefined rather than 0.Each path is a folder or a file of one format, recognized from its contents: an mgatk folder (
<name>.A.txt.gzto.T.txt.gz, the<contig>_refAllele.txtreference and the depth table), a maegatk folder, a cellsnp-lite or MQuad folder, a VarTrix folder of its coverage matrices with the VCF and barcodes, MiTo’s allele frequency matrix, giftwrap’scounts.N.h5or a folder of its per-UMI table, the GoT tables of IronThrone, GoT-Multi, Gotcha and GEO, a Tapestri Pipeline.h5file of DNA variants and a DAb-seq.hdf5file of genotypes. The variants API reference lists the files and columns of each format. Six-column mgatk files look like maegatk’s, which counts strands the other way round, so they needformat.A Tapestri file imports the variants that pass the pipeline’s default filters, and a DAb-seq file every variant, with those that
include_variantsnames. Each position is a site, whose alleles are its reference and the alternatives of its variants; Tapestri gives each variant’s alternative reads asAF × DP / 100, its depthDPand its genotypeNGTas a call with the genotype qualityGQ, and DAb-seq itsAD,RD,DPandGTwithGQ. Variants with an emptyALT, or alleles that are not bases, are skipped, counted in theskippedEmptyAlternativesandskippedOtherAllelesdiagnostics, each variant once however many files of its panel skip it, with up to fiveskippedVariantExamples, and named in a warning, which a reused import gives again; other formats choose no variants, so those counts are None. A Tapestri file’s cells are named<sample>__<barcode>, asTapestriToZarrnames them.A cell’s ID is its file’s
barcode_prefix, the barcode andbarcode_suffix, matched exactly;barcode_patternkeeps the part of each barcode that itsbarcodegroup matches first. Barcodes that match no selected cell are counted by the cell ID they name in the artifact’s diagnostics, whichds.artifacts.inspect(ref).diagnosticsreturns:fileBarcodes,unmatchedBarcodes, those that name no cell of the store,unselectedBarcodes, those of cells of the store outside the selection, and up to five examples of each, which show the barcode beside the cell ID it derives. Barcodes of no cell are named in a warning, which a reused import gives again. A source is identified by the SHA-256 of each file it reads, so moved files reuse the saved counts and the order of the paths does not matter. The diagnostics also holdlistedCells, the selected cells that the files list,sortedRuns, the sorted runs of rows that the import wrote to disk because the rows did not fit the memory budget at once, andrepeatedCalls, the calls that a source repeats for a cell’s allele, which are kept once.Several paths must share a format, such as one mgatk folder per library with each library’s prefix. Sites that they share are one site, so their counts must lie on the same reference: a contig with another length or sequence raises
ValueError, as do one sequence under two contig names and a cell that two files count at the same site. The paths must also count in one unit, define depth alike and give their counts the same fields, such as base qualities; a table of calls alone, such as GoT-Multi’s refined table, gives no counts.The canonical
mean_depthholds each cell’s depth summed over the sites and divided by their number, NaN for a selected cell that no file names;n_covered_sitescounts its sites with depth above 0 andlistedmarks the cells a file names.ds.select_cells(counts, low=10)keeps cells with a mean depth above 10.Rows that outgrow the memory budget are sorted in runs on local disk, in the system’s temporary folder (
TMPDIRon Linux and macOS), and removed when the import ends.- Parameters:
paths (
str|PathLike[str] |Sequence[str|PathLike[str]]) – One file or folder, or several of one format.cell_selection (
ArtifactRef) – The cells that the counts belong to.barcode_prefix (
str|Sequence[str|None] |None) – Text before each barcode in the cell IDs, such as"sample1__"in a merged store: one for every path, or one per path. None adds nothing.barcode_suffix (
str|Sequence[str|None] |None) – Text after each barcode in the cell IDs, such as"-1": one for every path, or one per path.barcode_pattern (
str|Sequence[str|None] |None) – A regular expression whose named groupbarcodeis the part of each barcode that names the cell, such asr"^(?P<barcode>[ACGT]{16})"to trim a multiplexed Flex barcode; a barcode it does not match names no cell. One for every path, or one per path.format (
str|None) – One of"mgatk","maegatk","cellsnp_lite","mquad","vartrix","mito","giftwrap","ironthrone","got","got_multi","gotcha","tapestri"and"dab_seq", or None to recognize each path’s format.count_unit (
str|None) –"reads","umis"or"molecules": what cellsnp-lite, MQuad and VarTrix counted, which their files do not state, since it depends on how they were run, and what a MiTo matrix counted when itsunsdoes not say. Other formats count in a unit of their own, which a given value must match.swap_strands (
bool) – Swap the forward and reverse counts of mgatk files written bycallorbcallof mgatk 0.4.0 to 0.5.8, which counted reverse-aligned reads as forward.include_variants (
Sequence[str] |None) – Variants of Tapestri or DAb-seq files to import beside those that pass, named as the file names them, such as"chr1:115256513:G/T", or positions, such as"chr1:115256513"for every variant there; None for the passing variants alone. The source record counts the variants added, so names that add the same variants reuse the import.invalidate_cache (
bool) – Import again instead of reusing saved counts.
- Return type:
- Returns:
A complete datastore-scoped
variant_countsartifact. Read it withload_counts()or plot it withds.plots.variant_depth.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If a format is unknown or its files are malformed, the paths hold several formats, a count unit is missing or differs from the format’s, the files lie on different references, count in different units, define depth differently or give their counts different fields, a cell is counted twice at a site, an option lists a value for another number of paths,
include_variantsis given for another format or names a variant that a file lacks or cannot be read, a file has no variant to import, or the selection holds no cell.FileNotFoundError – If a path or a file it needs is missing.
PermissionError – If the store is read-only and the counts are not saved yet.
MemoryError – If the import does not fit the memory budget.
- informative(counts, *, cell_selection=None, preset=None, min_cells=None, min_strand_correlation=None, min_vmr=None, min_depth=None, min_quality=None, mask=None, invalidate_cache=False)#
Score every variant across cells and select the informative ones.
A variant is an alternative allele at a site, such as
310T>C; the variants scored are those that some chosen cell shows. Each variant gets mgatk’s per-variant statistics, computed over the chosen cells in bands of cells, with an allele frequency only where a cell is covered: the pooledmeanfrequency, thevarianceof the covered cells’ frequencies and their ratiovmr, the cells with 2 or more reads of the allele on each strand (n_cells_conf_detected), the Pearson correlation of the forward and reverse counts over the cells that show the allele (strand_correlation), the cells whose frequency reaches 5, 10, 20 and 95%, the highest frequency, themean_coverageat the site and MAESTER’s mean base quality of the allele (mean_quality).A variant is informative when it passes every threshold that is set and no mask lists it.
preset="atac"sets Signac’s thresholds for mtscATAC-seq: at least 5 confidently detected cells, a strand correlation of at least 0.65 and a VMR above 0.01.preset="rna"sets MAESTER’s for RNA libraries, whose strands follow the transcript: a mean depth above 20 and a mean base quality above 30, with a VMR above 0.01. A threshold given by name replaces the preset’s. Every statistic must reach its threshold, somin_vmr=0.01keeps a VMR of exactly 0.01; a preset’s rule that a statistic exceed its value holds the next floating-point number above it, ascytearc.variants.INFORMATIVE_PRESETSshows, so the presets keep exactly the variants of the published rules. A statistic that is undefined, such as the strand correlation of a variant that one cell shows, fails.Signac computes the same statistics but sets the frequency of an uncovered cell to 0 and, by default, replaces the frequency of a cell with depth below 10 by the pooled mean before taking the variance; here an uncovered cell has no frequency, as in mgatk, so variances and VMRs differ where coverage is sparse.
The artifact’s diagnostics, which
ds.artifacts.inspect(ref).diagnosticsreturns, count thecellswhose evidence was scored, thevariantsscored, theinformativeVariantsand themaskedVariants.- Parameters:
counts (
ArtifactRef) – Avariant_countsartifact, such as one fromimport_counts().cell_selection (
ArtifactRef|None) – A cell selection within the counts’ cells whose evidence the statistics use, such asds.select_cells(counts, low=10)for the cells whose mean depth exceeds 10, as mgatk scores them; None uses every cell that the counts’ files name. Cells that no file names are left out either way.preset (
str|None) –"atac","rna"or None.min_cells (
int|None) – The fewest cells with 2 or more reads of the allele on each strand.min_strand_correlation (
float|None) – The lowest strand correlation.min_vmr (
float|None) – The lowest VMR.min_depth (
float|None) – The lowest mean depth at the site.min_quality (
float|None) – The lowest mean base quality.mask (
str|Sequence[str] |None) – Names of lists of variants that artifacts mimic, which are never informative:"numt", the 25 false positives of two common NUMTs (Laricchia et al. 2022);"rna_editing", the RNA-DNA differences at 295, 2617 and 13710 (Bar-Yaacov et al. 2013); and"artifact_prone", every variant at 301, 302, 310, 316, 3107 and 16182 (Laricchia et al. 2022). Masks list rCRS positions, so they need a 16,569-base contig.invalidate_cache (
bool) – Score again instead of reusing saved statistics.
- Return type:
- Returns:
A complete datastore-scoped
variant_selectionartifact. Read it withload_informative(), plot it withds.plots.variant_statisticsor call clones from it withfrequency_clones().- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
countsis not avariant_countsartifact, the preset, a threshold or a mask is unknown or invalid, no threshold is set, a threshold tests a statistic that the counts cannot give (strand tests without strand counts, quality without base qualities), a mask meets a contig that is not rCRS-sized, or no chosen cell is named by the counts’ files.KeyError – If the store holds no such
countsartifact.RuntimeError – If the
countsartifact is incomplete, as an import that stopped before it finished leaves it.PermissionError – If the store is read-only and the statistics are not saved yet.
MemoryError – If the statistics do not fit the memory budget.
- load_counts(counts, *, sites=None, cell_selection=None)#
Read saved variant counts as tables of sites, alleles, cells and rows.
The long tables hold one row per stored entry: a cell’s depth at a site where it was covered, its count of an allele it showed, and the calls its source made. A cell and site without a depth row was not covered, so a frequency there is undefined; one with depth but without a count row of an allele showed none of it.
sitesandcell_selectionkeep the tables to some sites and cells;cell_selection=[]reads only the sites and alleles, with each site’s depth summed over all cells.The budget counts each row read, at about 120 bytes, the two stored chunks that a read’s first and last rows decompress whole, the cells’ IDs as text, whose read decodes a stored chunk of them, and 40 bytes for each cell of the counts, whose offsets and per-cell arrays are read whole; cells named by ID are found among the IDs of every cell of the counts.
- Parameters:
counts (
ArtifactRef) – Avariant_countsartifact, such as one fromimport_counts().sites (
Sequence[str|int] |ndarray|Index|None) – Site labels as thesitestable names them, such as"chrM:310"or"IDH2_Mut1", or positions of an artifact of one contig, such as310, as a list, a NumPy array or a pandas index; None for all sites.cell_selection (
ArtifactRef|Sequence[str] |ndarray|Index|None) – A cell selection within the counts’ cells, or cell IDs as a list, a NumPy array or a pandas index; None for all cells.
- Return type:
- Returns:
A
VariantCountsrecord.- Raises:
TypeError – If an argument has the wrong type.
ValueError – If
countsis not avariant_countsartifact, or a site or cell is not in it.KeyError – If the store holds no such artifact.
RuntimeError – If the artifact is incomplete, as an import that stopped before it finished leaves it.
MemoryError – If the tables do not fit the memory budget; pass fewer sites or cells.
- load_genotypes(genotypes, *, sites=None)#
Read saved genotype calls as tables of sites, cells and calls.
A cell that the calls table does not list at a site holds no evidence there, the call
missing.- Parameters:
genotypes (
ArtifactRef) – Avariant_genotypesartifact fromgenotypes().sites (
Sequence[str|int] |ndarray|Index|None) – The genotyped sites to read the calls of, by label as thesitestable names them, such as"CALR"or"chr1:115256513:G/T", or by position on counts of one contig, such as310, which takes every genotyped site there; None for every genotyped site.
- Return type:
- Returns:
A
VariantGenotypesrecord.- Raises:
TypeError – If
genotypesis not an ArtifactRef orsitesnot a sequence of labels or positions.ValueError – If
genotypesis not avariant_genotypesartifact,sitesnames a site it did not genotype, or a position is given for counts of several contigs.KeyError – If the store holds no such artifact, or not its counts when
sitesnames a position.RuntimeError – If the artifact is incomplete, or its counts when
sitesnames a position.MemoryError – If the tables do not fit the memory budget.
- load_informative(informative)#
Read saved per-variant statistics and the informative variants.
- Parameters:
informative (
ArtifactRef) – Avariant_selectionartifact, such as one frominformative().- Return type:
- Returns:
A
VariantSelectionrecord whosevariantstable holds one row per scored variant, with mgatk’svariant_statscolumns and theinformativeflag.- Raises:
TypeError – If
informativeis not an ArtifactRef.ValueError – If it is not a
variant_selectionartifact.KeyError – If the store holds no such artifact, or not the counts that it scored.
RuntimeError – If the artifact or the counts that it scored are incomplete.
ds.imputation#
- class cytearc.datastore.namespaces.ImputationAccessor(store)#
- compute_imputed(feature_name, diffusion, *, from_assay=None)#
Impute feature values by diffusing along the KNN graph (MAGIC-style).
A string that exactly matches a live cell metadata column (case-sensitive) diffuses that column’s values. Any other string names assay features case-insensitively, and a
FeatureReflooks a feature up by name, ID, or index, as plots andcompare.testdo. A name that several features share raisesValueErrornaming their IDs: impute one of them withFeatureRef(value=feature_id, by="id"), or their mean withFeatureRef(value=name, reduction="mean"). A metadata column whose linked missing mask flags a cell in the operator’s cell selection raisesValueError, because diffusion would spread its stored placeholder to neighboring cells.- Parameters:
feature_name (
str|FeatureRef|Sequence[str|FeatureRef] |ndarray|Series) – One feature name, cell metadata column, orFeatureRef, or a sequence, one-dimensional array, or Series of them in the desired output order.diffusion (
ArtifactRef) – Explicit diffusion-operator artifact returned byimputation.diffusion.from_assay (
str|None) – Assay whose features are imputed. A native graph’s operator uses the graph’s own assay, which a given value must match. An integrated graph’s operator requires it unless every name is a cell metadata column. AFeatureRefthat names an assay must name this one.
- Return type:
ndarray- Returns:
A vector for one feature, or a cells-by-features array for several features.
- Raises:
KeyError – If no feature of the assay has a requested name, ID, or index.
ValueError – If a name or ID matches several features without the
reductionof aFeatureRef, or aFeatureRefnames another assay.UnmeasuredCellsError – If the assay did not measure a cell of the operator.
ValueError – If the source of a merge of a cell of the operator did not measure a requested feature, as the assay’s
measured_in_<source>feature columns record.
- diffusion(graph, *, t=2, invalidate_cache=False)#
Compute and persist a sparse MAGIC diffusion operator.
The returned artifact is aligned to the graph’s exact stored cell selection. Repeating the same graph and diffusion power reuses the complete artifact unless
invalidate_cacheis true.- Raises:
MemoryError – A diffusion step, or loading the finished operator, would exceed the datastore memory budget. The check runs before anything is persisted.
- Return type:
- load_diffusion(diffusion)#
Load a validated diffusion-operator artifact as a COO matrix.
- Return type:
coo_matrix
ds.trajectory#
- class cytearc.datastore.namespaces.TrajectoryAccessor(store)#
- aggregation(pseudotime, *, features, min_exp=0.001, window_size=200, chunk_size=50, smoothen=True, z_scale=True, n_neighbors=11, n_clusters=10, batch_size=None, ann_params=None, nan_cluster_value=-1, invalidate_cache=False, **norm_params)#
Cluster features by pseudotime and store one immutable artifact.
Features with similar binned profiles are grouped into
n_clustersmodules: each retained feature’sn_neighborsnearest features, found exactly by distances summed over the bins in order, form a graph whose Paris hierarchy is cut into the modules. Of two equally near features the earlier ranks first, so the same profiles give the same modules on every platform. The modules are numbered from 1 by the median bin of their features’ peaks.Features that some source of a merged store’s cells did not measure are left out, with a warning, as the DataStore API reference’s contracts for stores merged from sources of different features say.
- Parameters:
pseudotime (
ArtifactRef) – Explicit pseudotime artifact defining cells and ordering.features (
ArtifactRef) – Explicit assay-scoped feature-selection artifact.min_exp (
float) – Minimum mean normalized expression required for clustering.window_size (
int) – Rolling window size used to smooth feature values.chunk_size (
int) – Number of pseudotime bins to create.smoothen (
bool) – Whether to smooth expression along pseudotime.z_scale (
bool) – Whether to standardize each retained feature.n_neighbors (
int) – Number of neighbors in the feature graph.n_clusters (
int) – Number of feature modules to create.batch_size (
int|None) – Number of features processed per batch. When None, selected features are grouped into chunk-aligned blocks that fit the operation memory budget.ann_params (
dict|None) – The distance between profiles, as{"space": "l2"}, the squared Euclidean distance and the default;"ip", one minus the inner product; or"cosine", one minus the cosine similarity. The settings of an approximate search, such asef, have no effect and are left out with aFutureWarning.nan_cluster_value (
int) – Value assigned to features excluded from clustering.**norm_params (
Any) – Extra keyword arguments forwarded to normalized expression.
- Return type:
- Returns:
Reference to the immutable pseudotime-aggregation artifact.
- Raises:
UnmeasuredCellsError – If the assay did not measure a valid pseudotime cell.
- branch_cells(membership, lineages, *, window=0.2, invalidate_cache=False)#
Select the cells around the point where two lineages part.
The selection holds the
windowshare of the cells that follow either lineage, rounded up, whose pseudotime lies closest to the two lineages’ branch point. Pass it ascellstodrivers(), withlineagesnaming the two to keep its table to the pair: the table holds, for each of the two fates, each gene’s correlation with that fate’s probability among the selected cells, by which to rank the genes that rise with each fate and compare the two lists.- Parameters:
membership (
ArtifactRef) – Explicitlineage_membershipartifact.lineages (
list[Any]) – The sink labels of the two lineages, in either order.window (
float) – Share of the cells that follow either lineage to select, above 0 and at most 1.invalidate_cache (
bool) – Create a fresh selection instead of reusing a match.
- Return type:
- Returns:
A complete datastore-scoped
cell_selectionartifact of some of the membership’s cells.- Raises:
MemoryBudgetError – If loading the graph of the membership’s fate map, or checking the saved membership, needs more than
mem_budget; the graph is checked before it is read.ValueError – If
lineagesdoes not name two lineages of the membership, or the two have no branch point: they never share a cell, never part, or their shared cells do not come before the cells that follow only one of them.
- curves(fate, *, lineages=None, coordinates=None, n_points=100, df=10.0, batch_size=None, invalidate_cache=False)#
Fit one fate-weighted curve per lineage and place every cell on them.
A lineage’s curve is the fate-weighted mean of the cells’ coordinates as a smooth function of their weighted pseudotime rank along the lineage: the share of its fate weight carried by cells earlier in pseudotime. Cells near a lineage’s sink weigh most in its curve, and cells of a shared trunk shape every curve, so the curves share the trunk and part where the fate probabilities part. Each coordinate is a penalized cubic spline of the rank with
dfeffective degrees of freedom (Eilers and Marx 1996), fitted to fine rank bins in one pass over the coordinates. These are principal curves (Hastie and Stuetzle 1989) whose projection index stays at the pseudotime rank; their reprojection iterations are not run, because they fold curves into loops inside compact start and end clusters.Every scored cell is then projected orthogonally onto every curve. Its
progressis the rank of the nearest curve point, from zero at the start to one at the sink, and itsdistancethe Euclidean distance to it. Draw the curves withlineage_curves()and place other cells withproject().- Parameters:
fate (
ArtifactRef) – Explicit fate-map artifact. Its pseudotime, or the score that directs it, orders the cells and its probabilities weight them.lineages (
list[Any] |None) – Sink labels to fit, in order.Nonefits every sink.coordinates (
ArtifactRef|None) – Coordinates of the fate map’s cells, or of its graph’s cells, to fit the curves in.Noneuses the coordinates its graph was built on; an integrated graph has none, so it needs this argument. Only the fate map’s cells are read.n_points (
int) – Points on each curve.df (
float) – Effective degrees of freedom of each coordinate’s spline, from just above 2, a straight line, to below 32. Larger values follow sharper bends and noise.batch_size (
int|None) – Rows per coordinate block.Nonesizes blocks to the memory budget.invalidate_cache (
bool) – Fit new curves even when matching ones exist.
- Return type:
- Returns:
Reference to an artifact with
points,curve_pseudotime, and each cell’sprogress,distance, andvalidentry.
- curves_in_layout(curves, layout, *, lineages=None, df=None)#
Draw lineage curves in a two-dimensional layout, such as a UMAP, as a table.
The curves were fitted in their own coordinates, often many reduced dimensions. To draw one in a layout, the layout coordinates of the scored cells are averaged with the lineage’s fate weights in fine bins of the cells’ progress along the curve and smoothed with the spline that the curves were fitted with, as Slingshot’s
embedCurvesdoes.plots.lineage_curvesdraws these points over the layout. The call needs no plotting dependencies and saves nothing, so a viewer of its own can draw the curves.- Parameters:
curves (
ArtifactRef) – Explicitlineage_curvesartifact.layout (
ArtifactRef) – A two-dimensional embedding that holds every cell of the curves, such as a UMAP of their graph, whichever operation made its cell selection. It may hold more cells, such as every cell of the graph when the curves follow some of them; only the curves’ cells are read.lineages (
Sequence[Any] |None) – Sink labels of the lineages to draw, in order, or None for every lineage of the curves.df (
float|None) – Effective degrees of freedom of the smoothing, greater than 2 and less than the size of the curves’ spline basis, 32 by default, or None for the curves’ own.
- Returns:
lineage, the lineage’s sink label;point, the point’s number along the curve, from 0 at its start; andxandy, its layout coordinates. Each curve has as many points as the fitted curves, evenly spaced in progress from the start to the sink.- Return type:
DataFrame- Raises:
TypeError – If
curvesorlayoutis not an ArtifactRef, ordfis not a real number.ValueError – If
curvesis not a completelineage_curvesartifact,dfis out of range,layoutis not an embedding of two finite columns or lacks a cell of the curves, orlineagesnames a lineage that the curves do not hold, repeats one or names none.
- drivers(fate, *, features, lineages=None, cells=None, include_sinks=False, min_cells=10, confidence_level=0.95, gene_batch_size=None, invalidate_cache=False, **norm_params)#
Store each feature’s correlation with every lineage’s fate probability.
As CellRank’s lineage drivers (Lange et al. 2022), a feature’s Pearson correlation with a lineage’s fate probability ranks genes whose expression rises with the commitment to that lineage. P-values and confidence intervals use Fisher’s z-transform, and p-values are adjusted by Benjamini-Hochberg within each lineage over its tested features.
Cells of the sinks are left out by default: their probabilities are fixed at zero or one by the model, so including them mostly recovers the markers that defined the sinks. Each correlation concerns one lineage’s probability on its own, whatever
lineagesnames. To study where two lineages part, pass the cells thatbranch_cells()selects ascellsand the two lineages aslineages: the table then holds, for each of the two fates, each gene’s correlation with that fate’s probability among those cells, by which to rank the genes that rise with each fate and compare the two.Features that some source of a merged store’s cells did not measure are left out, with a warning, as the DataStore API reference’s contracts for stores merged from sources of different features say.
- Parameters:
fate (
ArtifactRef) – Explicit fate-map artifact.features (
ArtifactRef) – Explicit assay-scoped feature-selection artifact.lineages (
list[Any] |None) – Sink labels to analyze, in order.Noneanalyses every sink.cells (
ArtifactRef|None) – Cell-selection artifact within the fate map’s cells to correlate.Noneuses every scored cell.include_sinks (
bool) – Also correlate the cells of the sinks.min_cells (
int) – Fewest expressing cells for a feature to be tested.confidence_level (
float) – Coverage of the confidence intervals.gene_batch_size (
int|None) – Number of features loaded per batch.Nonesizes batches to the memory budget.invalidate_cache (
bool) – Compute a new result even when one matches.**norm_params (
Any) – Extra keyword arguments forwarded to normalized expression.
- Return type:
- Returns:
Reference to the immutable
lineage_driversartifact.- Raises:
UnmeasuredCellsError – If the assay did not measure a correlated cell.
- fate(pseudotime=None, sink_labels=None, *, sinks=None, graph=None, direction=None, beta=10.0, solver_tol=1e-06, max_iterations=1000, invalidate_cache=False)#
Compute fate probabilities of a walk that a pseudotime or a score directs.
Each cell’s probability of each fate is the probability that a random walk on the graph from the cell is absorbed first by that fate’s sink cells. The walk is directed: an edge to a cell of lower pseudotime keeps
2 / (1 + exp(beta * d))of its weight, wheredis the drop in pseudotime rescaled to [0, 1].A pseudotime directs the walk on the graph that it scored, its graph or the subgraph of the cells that it was given as
cells, and the map covers the cells that it scored.directiontakes any per-cell score in its place, higher meaning later, such as a pseudotime that another tool computed or thecell_potencyartifact ofpotency(), which names no source, with thegraphto walk on; the walk is biased by the score exactly as by a pseudotime. A direction score scores the cells where it holds a finite value. Those cells must make up whole connected components of the graph, as a pseudotime’s do, and the map covers those of them in components that hold a sink. Other components stay out of the map, with a warning when the score covers them. A walk stays in its component, so a cell’s probability is 0 for each sink without a cell in the cell’s component. A score given as an array is saved as a snapshot of the graph’s cells, which the fate map records as its direction. The lineage analyses of a map that a score directs, such ascurves()andlineage_markers(), order its cells by the score in place of a pseudotime.- Parameters:
pseudotime (
ArtifactRef|None) – Explicit pseudotime artifact, which directs the walk on the graph that it scored. Leave it out withdirection.sink_labels (
ArtifactRef|None) – Explicit cell-label artifact of the pseudotime’s cells or of its graph’s cells, or withdirectionof the cells ofgraph.sinks (
list[Any] |None) – Ordered sink labels. Every matching selected cell becomes a fate boundary.graph (
ArtifactRef|None) – Explicit connectivity-map or integrated-graph artifact to walk on, required withdirectionand only with it.direction (
ArtifactRef|Series|None) – Per-cell score that directs the walk in place of a pseudotime, higher meaning later: a cell-aligned artifact of real values over the graph’s cells, other than a pseudotime, or a pandas Series indexed by cell ID, aligned to the graph’s cells by ID; values of other cells are left out. A missing or non-finite value leaves a cell unscored.beta (
float) – Strength of the penalty applied to backward graph edges.solver_tol (
float) – Absolute tolerance on the Bellman residual of each solved sink column. A solve stops once its largest residual over all cells is at mostsolver_tol, or half of its share of the validation limit when that is smaller, independent of sink size. Results are rejected when any residual exceeds10 * solver_tol * (len(sinks) - 1), bounded below by float32 precision and above by1e-3.max_iterations (
int) – Maximum number of preconditioned GMRES inner iterations per sink. GMRES restart is fixed at 20.
- Return type:
- Returns:
Reference to an artifact containing
probabilitiesandvalid.- Raises:
SourceSinkLabelsError – If no selected cell, or no cell that the pseudotime or the direction scores, holds a sink label.
TypeError – If
directionis neither an artifact reference nor a pandas Series indexed by cell ID, such as an array, whose values would land on cells by position.ValueError – If neither or both of
pseudotimeanddirectionare given,graphcomes withoutdirection, the direction scores some cells of a graph component and leaves others unscored, or a Series lacks a cell of the graph or repeats a cell ID.
- lineage_aggregation(fate, *, features, lineages=None, n_bins=50, smoothing=2.0, min_exp=0.001, z_scale=True, n_neighbors=11, n_clusters=10, batch_size=None, ann_params=None, nan_cluster_value=-1, invalidate_cache=False, **norm_params)#
Store fate-weighted feature profiles along each lineage, with modules.
Along the fate map’s pseudotime, or the score that directs it, each lineage’s fate weight is cut into
n_binsbins of equal weight, a cell whose weight straddles a cut being shared in proportion. A feature’s profile is its weighted mean in every bin, smoothed across neighboring bins by a Gaussian ofsmoothingbins, so every lineage runs from the shared start to its sink. Withz_scale, each feature is scaled by one mean and standard deviation over all lineages, which keeps its lineages comparable. Features with similar profiles across all lineages are grouped inton_clustersmodules, asaggregation()groups them along one pseudotime.Features that some source of a merged store’s cells did not measure are left out, with a warning, as the DataStore API reference’s contracts for stores merged from sources of different features say.
- Parameters:
fate (
ArtifactRef) – Explicit fate-map artifact.features (
ArtifactRef) – Explicit assay-scoped feature-selection artifact.lineages (
list[Any] |None) – Sink labels to profile, in order.Noneprofiles every sink.n_bins (
int) – Bins per lineage. Each lineage needs a total fate weight of at least one cell per bin.smoothing (
float) – Standard deviation, in bins, of the Gaussian that smooths each profile; 0 leaves the bin means as they are. A lineage with little fate weight holds few cells per bin, so its profiles need this smoothing most.min_exp (
float) – Minimum mean normalized expression required for clustering.z_scale (
bool) – Whether to standardize each retained feature.n_neighbors (
int) – Number of neighbors in the feature graph.n_clusters (
int) – Number of feature modules to create.batch_size (
int|None) – Number of features processed per batch.Nonesizes batches to the memory budget.ann_params (
dict|None) – The distance between profiles, as{"space": "l2"}, the squared Euclidean distance and the default;"ip", one minus the inner product; or"cosine", one minus the cosine similarity. The settings of an approximate search, such asef, have no effect and are left out with aFutureWarning.nan_cluster_value (
int) – Value assigned to features excluded from clustering.invalidate_cache (
bool) – Compute a new result even when one matches.**norm_params (
Any) – Extra keyword arguments forwarded to normalized expression.
- Return type:
- Returns:
Reference to the immutable
lineage_aggregationartifact.- Raises:
UnmeasuredCellsError – If the assay did not measure a scored cell.
- lineage_markers(fate, *, features, lineages=None, min_cells=10.0, gene_batch_size=None, invalidate_cache=False, **norm_params)#
Store each lineage’s fate-weighted feature associations with pseudotime.
markers()correlates features with one pseudotime over every scored cell, so a gene that rises on one branch is diluted by the others. Here each lineage weighs every scored cell by its fate probability, and a feature’s weighted Pearson correlation with pseudotime is computed per lineage. P-values come from a Student t test on Kish’s effective number of cells,(sum w)^2 / sum w^2, and are adjusted by Benjamini-Hochberg within each lineage over its tested features. They treat cells as independent and are not inference across biological replicates.Features that some source of a merged store’s cells did not measure are left out, with a warning, as the DataStore API reference’s contracts for stores merged from sources of different features say.
- Parameters:
fate (
ArtifactRef) – Explicit fate-map artifact. Its pseudotime, or the score that directs it, and its probabilities define the cells, their order, and their weights.features (
ArtifactRef) – Explicit assay-scoped feature-selection artifact.lineages (
list[Any] |None) – Sink labels to analyze, in order.Noneanalyses every sink.min_cells (
float) – Smallest fate weight, in cells, that a feature’s expressing cells must carry in a lineage for it to be tested.gene_batch_size (
int|None) – Number of features loaded per batch.Nonesizes batches to the memory budget.invalidate_cache (
bool) – Compute a new result even when one matches.**norm_params (
Any) – Extra keyword arguments forwarded to normalized expression.
- Return type:
- Returns:
Reference to the immutable
lineage_markersartifact.- Raises:
UnmeasuredCellsError – If the assay did not measure a scored cell.
- lineage_membership(curves, *, band=0.5, distance_score=5.0, n_bins=10, invalidate_cache=False)#
Call which lineages each cell follows, and find where each pair of lineages parts.
Fate probabilities sum to one over the sinks, so a cell on no trajectory still splits its probability among them, and a cell that has not committed looks like a member of its most likely lineage. Progenitors also split their probability unevenly, so the rule measures each lineage’s probability against that lineage’s own trunk probability in the cell’s graph component: the mean probability for the lineage of the earliest tenth, by the pseudotime or the score that directs the fate map, of the component’s scored cells outside the fate map’s sinks. A fate map that a pseudotime directs covers one component; one that a score directs can cover several, each with its own trunk. A scored cell follows each lineage whose sink cells share its component and whose probability is still at least
bandtimes its trunk probability there, and only when the cell lies on the trajectory: within some lineage’s distance limit at the cell’s progress on that lineage’s curve. A progenitor therefore follows every lineage that starts in its trunk, whatever share of the trunk’s probability the lineage receives, and as a cell commits it leaves the lineages whose probability falls rather than joining the one whose probability rises. Precisely, each probability is divided by the lineage’s trunk probability, and a cell follows a lineage whose divided probability is positive and at leastbandtimes the smaller of one and its largest divided probability over the curves’ lineages. When the curves follow every sink of the fate map, a component’s trunk probabilities of the lineages whose sink cells it holds sum to one, and that largest is at least one. When they follow some of the sinks, a cell that moves toward a sink they leave out can have every divided probability below one, and it then follows each lineage whose divided probability is at leastbandtimes its largest. In each ofn_binsequal bins of progress, the lineage’s cells weigh by their fate probability for it, and their spread is their weighted median distance plusdistance_scoretimes their weighted median absolute deviation scaled by 1.4826, which estimates the standard deviation of a normal spread. A bin’s limit is the median spread of three neighboring bins, so a state off the trajectory that projects onto one stretch of a curve, such as a dead end off it, cannot widen the limit there. A cell that follows several lineages is shared by them, and a cell that lies on no curve follows none, whatever its probabilities.Two lineages part where their shared cells give way to cells that follow only one of them. Their branch point is the pseudotime that splits the pair’s shared cells, before it, from its parted cells, after it, with the fewest cells on the wrong side. A pair has no branch point, NaN, when it never shares a cell, never parts, or its shared cells do not come before its parted cells, so that the best split lies before the first cell or after the last.
branch_cells()selects the cells around a branch point. Pass them ascellstodrivers(), withlineages=[first, second]to keep its table to the pair: the table holds, for each of the two fates, each gene’s correlation with that fate’s probability among those cells, by which to rank the genes whose expression rises with each fate and compare the two lists.- Parameters:
curves (
ArtifactRef) – Explicitlineage_curvesartifact.band (
float) – Share of a lineage’s trunk probability, above 0 and at most 1, that a cell’s probability for the lineage must keep for the cell to follow it. Larger values let a cell leave a lineage sooner and call fewer cells shared.distance_score (
float) – Robust standard deviations beyond the median distance of a lineage’s cells at which a cell lies off that lineage’s curve. Smaller values call more cells none; cells where a curve cuts the corner of a sharp bend lie farther from it than its other cells, so values below 4 can call some of them none.n_bins (
int) – Equal bins of progress along each curve, each with its own distance limit.invalidate_cache (
bool) – Compute a new membership even when one matches.
- Return type:
- Returns:
Reference to a
lineage_membershipartifact, whose labelsselect_cellsreads.- Raises:
MemoryBudgetError – If loading the graph of the curves’ fate map, or calling the membership, needs more than
mem_budget; the graph is checked before it is read.ValueError – If a lineage’s sink label reads
"shared"or"none",band,distance_scoreorn_binsis out of range, or the earliest cells outside the sinks in the graph components of a lineage’s sink cells give that lineage no probability, as when its sink cells fill a component of their own.
- lineage_tree(graph, labels, *, cells=None, coordinates=None, root=None, ends=None, batch_size=None, invalidate_cache=False)#
Join clusters by a minimum spanning tree and propose lineages.
This is the lineage step of Slingshot (Street et al. 2018). The distance between two clusters is
(m_i - m_j)^T (S_i + S_j)^{-1} (m_i - m_j)for their mean coordinatesmand covariancesS, using the diagonal whereS_i + S_jis singular. A minimum spanning tree joins the clusters, and the paths fromrootto the other leaves propose lineages.endsmakes clusters leaves: the tree first spans the others, then each end joins its nearest cluster.A tree must join every cluster, so similar terminal clusters can be chained through one another and the result depends on clustering resolution. Treat leaves as candidate sinks to check with markers before passing them to
fate().- Parameters:
graph (
ArtifactRef) – Explicit graph artifact; its cells are the tree’s cells, unlesscellsnames some of them.labels (
ArtifactRef) – Explicit cell-label artifact of the graph’s cells, or ofcells, such ascluster_labels. Every cell of the tree needs a label.cells (
ArtifactRef|None) – Cell-selection artifact of some of the graph’s cells to build the tree over, such as the cells of some clusters, or None for every cell of the graph. It becomes the tree’s cell selection, and only these cells’ labels and coordinates are read.coordinates (
ArtifactRef|None) – Coordinates of the graph’s cells, or ofcells.Noneuses the coordinates the graph was built on; an integrated graph has none, so it needs this argument.root (
Any) – Cluster label that starts the lineages, orNonefor an unrooted tree without lineages.ends (
list[Any] |None) – Cluster labels to hold as leaves.batch_size (
int|None) – Rows per coordinate block.Nonesizes blocks to the memory budget.invalidate_cache (
bool) – Build a new tree even when a matching one exists.
- Return type:
- Returns:
Reference to a
lineage_treeartifact.- Raises:
ValueError – If
cellsholds cells outside the graph’s.
- load_aggregation(ref)#
Load a lazy pseudotime aggregation from an explicit artifact.
- Return type:
- load_curves(ref)#
Load lineage curves and cell positions from an explicit artifact.
- Return type:
- load_drivers(ref)#
Load a lineage-driver table from an explicit artifact.
- Return type:
- load_fate(ref)#
Load fate probabilities from an explicit completed artifact.
- Return type:
- load_lineage_aggregation(ref)#
Load fate-weighted lineage profiles from an explicit artifact.
- Return type:
- load_lineage_markers(ref)#
Load a lineage-marker table from an explicit artifact.
- Return type:
- load_lineage_membership(ref)#
Load which lineages each cell follows, and the branch points, from an explicit artifact.
- Return type:
- load_lineage_tree(ref)#
Load a cluster tree and its proposed lineages from an explicit artifact.
- Return type:
- load_markers(ref)#
Load a pseudotime-marker table from an explicit artifact.
- Return type:
- load_pseudotime(ref)#
Load pseudotime values from an explicit completed artifact.
The result also gives each cell’s connected component of the graph, numbered by decreasing size, and the components’ cell counts, which the loader computes from the stored graph without storing them. For a pseudotime of some of the graph’s cells, these are the components of the subgraph that those cells induce.
- Return type:
- load_states(states)#
Load the states of a walk from an explicit completed artifact.
- Parameters:
states (
ArtifactRef) – Atrajectory_statesartifact fromstates().- Return type:
- Returns:
Each cell’s state and memberships, the walk between the states, and the table of each state’s role and scores.
- Raises:
TypeError – If
statesis not an ArtifactRef.ValueError – If it is not a complete
trajectory_statesartifact ofstates(), or its record or arrays do not match the contract.
- markers(pseudotime, *, features, min_cells=10, gene_batch_size=None, invalidate_cache=False, **norm_params)#
Store feature correlations with an explicit pseudotime artifact.
Features that some source of a merged store’s cells did not measure are left out, with a warning, as the DataStore API reference’s contracts for stores merged from sources of different features say.
- Parameters:
pseudotime (
ArtifactRef) – Explicit pseudotime artifact defining cells and ordering.features (
ArtifactRef) – Explicit assay-scoped feature-selection artifact.min_cells (
int) – Minimum number of expressing cells required for a feature.gene_batch_size (
int|None) – Number of features loaded per batch. When None, selected features are grouped into chunk-aligned blocks that fit the operation memory budget.**norm_params (
Any) – Extra keyword arguments forwarded to normalized expression.
- Return type:
- Returns:
Reference to the immutable pseudotime-marker artifact.
- Raises:
UnmeasuredCellsError – If the assay did not measure a valid pseudotime cell.
- plan()#
Report what the trajectory calls made in a block would reuse and compute, without running them.
Use the plan as a context manager around the calls of a trajectory, written as they would run:
with ds.trajectory.plan() as plan: pseudotime = ds.trajectory.pseudotime( graph, source_sink=clusters, sources=[1], sinks=[2] ) fate = ds.trajectory.fate(pseudotime, clusters, sinks=[2, 3]) plan.computed
Inside the block,
pseudotime,fate,states,curves,lineage_tree,lineage_membership,branch_cells,markers,aggregation,lineage_markers,driversandlineage_aggregationlook for their results as they do when they run, and the plan records each of them. A call whose result the store holds, complete and current, returns the result’s ref. A call that would compute returns its plan, aTrajectoryCallPlanthat says why, in place of the ref. A later call that takes that plan is reported computed with the reason"upstream", since its result depends on one that does not exist yet, and it does not run, so its arguments are not checked until it runs. Pass a reused call’s result on as its ref, not its plan. After the block, the calls run as they always do.The planned calls save nothing. Each does the work that it does before it looks for its result: it reads its inputs’ records and small arrays, the metadata it checks, and the graph that it walks, so a plan costs about one graph load for each call but
lineage_tree, and reads no count matrix. A call whose inputs exist raises the errors that it raises before it writes, such as a refused memory budget. A plan describes the store as it is: a call made twice is planned computed twice, though the chain would compute it once, and a snapshot that two calls save of the same values is named for both, though only the first would save it.The plan covers the calls made in the thread that opened it; a call sent to another thread, such as a thread pool’s, runs as it always does. Any other call in the block reuses a saved result as it always does, and one that would compute raises
RuntimeErrorwhen the block ends; pipeline runs and resumes refuse to start inside it. A call that changes the store without saving a result, such asds.cells.insert, still writes.- Return type:
- Returns:
The plan, whose calls fill as the block runs.
- Raises:
RuntimeError – If the block opens while another plan is open, makes a planned call on another DataStore, or makes a call that the plan does not cover and that would compute.
- pseudotime(graph, *, cells=None, method='untruncated', n_singular_vals=None, source_sink=None, sources=None, sinks=None, ss_vec=None, min_max_norm_ptime=True, random_seed=None, component_policy='largest', solver_tol=None, max_iterations=None, invalidate_cache=False)#
Calculate pseudotime and return an immutable cell artifact.
This is a reimplementation of the population balance analysis approach from Weinreb et al. 2018, whose potential applies the pseudoinverse of the graph’s random-walk Laplacian to the source-sink vector. The graph’s stored cell selection, or
cells, defines the output axis. Disconnected cells excluded bycomponent_policyremain represented with NaN values and a falsevalidentry.cellsscores some of the graph’s cells without building a graph of their own: the pseudotime scores the subgraph that they induce, the graph’s edges among them, and finds that subgraph’s connected components, which can be more than the graph’s, since cells at the edge of the selection lose their edges to the cells left out. The subgraph keeps the neighbors that the graph’s cells chose, so it orders the cells by the variation that the whole graph follows; a graph built on the chosen cells’ own reduction follows the variation within them.The default
method="untruncated"solves for that potential over all of the Laplacian’s modes, with MINRES on the symmetric graph Laplacian (cytearc.trajectory.pba_potential).method="truncated"keeps then_singular_vals - 1smallest nonzero singular modes, which SciPy’ssvdsfinds with ARPACK’s Lanczos solve (cytearc.trajectory.truncated_pba_potential); releases before 1.4.0 computed only this potential, so it reproduces their pseudotimes. Either solve advances a progress bar with its products of the Laplacian and logs their count at INFO level every 30 seconds.- Parameters:
graph (
ArtifactRef) – Explicit connectivity-map or integrated-graph artifact.cells (
ArtifactRef|None) – Cell-selection artifact of some of the graph’s cells to score, or None for every cell of the graph. It becomes the pseudotime’s cell selection, whichfate,curvesand the feature calls follow; the graph’s own selection gives the pseudotime that None gives.method (
Literal['untruncated','truncated']) – The potential,"untruncated"over all modes or"truncated"over the smallest singular modes. It is recorded.n_singular_vals (
int|None) – Number of smallest singular modes requested, including the null mode, formethod="truncated"only, which takes 30 when it is None.source_sink (
ArtifactRef|None) – Explicit label artifact of the graph’s cells, or ofcells. Required withsourcesorsinksand omitted whenss_vecis supplied.sources (
list[Any] |None) – A list of group/cluster ids fromsource_sinkto be treated as sources. Sources are usually progenitor/precursor or other actively dividing cell states.sinks (
list[Any] |None) – A list of group/cluster ids fromsource_sinkto be treated as sinks. Sinks are usually more differentiated (or terminally differentiated) cell states.ss_vec (
Series|None) – Custom source-sink value for each scored cell, of the graph or ofcells, as a pandas Series indexed by cell ID; values of other cells are left out. It must sum to zero, with negative values for sources and positive values for sinks. This is mutually exclusive with label-based arguments.min_max_norm_ptime (
bool) – Whether to perform min-max normalization on the final pseudotime values so that values are in 0 to 1 range. (Default: True)random_seed (
int|None) – The seed of the start vector ofsvds, formethod="truncated"only, which takes 4444 when it is None.component_policy (
Literal['largest','sources','error']) – How to handle a disconnected selected graph.'largest'scores the largest connected component and marks other selected cells as unscored.'sources'scores the component that holds the most source cells, the cells with a source label or a negativess_vecvalue, so a smaller component can be scored.'error'raises instead. Every source and sink label must have cells in the scored component.solver_tol (
float|None) – Tolerance of the solve. None, the default, solves to machine precision. Formethod="untruncated"it is MINRES’srtol: the solve stops once its residual falls belowsolver_toltimes the estimated norms of the symmetric Laplacian and of its solution, and the potential’s error grows smoothly with it. Formethod="truncated"it is the relative tolerance of the singular values, passed tosvdsastol; a looser tolerance can end the search before it finds the smallest singular values, so the potential can lose modes, and a result without the null mode is refused. A set tolerance is recorded.max_iterations (
int|None) – Bound of the solve: MINRES iterations, one product with the Laplacian each, or formethod="truncated"the implicit restarts ofsvds, passed asmaxiter. None, the default, is SciPy’s five iterations or ten restarts per cell; the restarts can run for hours on graphs of several hundred thousand cells. A set bound is recorded, so it gives another artifact than the default.
- Return type:
- Returns:
Reference to an artifact containing
pseudotimeandvalid.- Raises:
PseudotimeConvergenceError – If the solve reaches
max_iterationsbefore it converges.SourceSinkLabelsError – If no selected cell, or no cell of the scored component, holds a source or sink label.
TypeError – If
ss_vecis not a pandas Series indexed by cell ID, such as an array, whose values would land on cells by position.ValueError – If
methodis neither"untruncated"nor"truncated",n_singular_valsorrandom_seedis set withmethod="untruncated",cellsholds cells outside the graph’s, orss_veclacks a scored cell or repeats a cell ID.
- states(graph, direction, *, n_states, labels=None, cells_per_state=30, beta=10.0, max_iterations=None, invalidate_cache=False)#
Find the initial and terminal states of the walk that a per-cell score directs on a graph.
The walk is the one that
fate()takes with the samegraph,directionandbeta: it follows the graph’s edges, and an edge to a cell of lower score keeps2 / (1 + exp(beta * d))of its weight. The search splits it inton_statesmetastable states, groups of cells that the walk enters and rarely leaves, by generalized robust Perron cluster analysis (Reuter et al. (2018), Journal of Chemical Theory and Computation 14:3579-3594, doi:10.1021/acs.jctc.8b00079; Reuter, Fackeldey and Weber (2019), Journal of Chemical Physics 150:174103, doi:10.1063/1.5064530), as CellRank does (Lange et al. (2022), Nature Methods 19:159-170, doi:10.1038/s41592-021-01346-6). Each cell gets a membership in each state, a cell’s memberships summing to one, and the states get the walk between them.The states are ordered by their mean direction score. The first is the initial state. Each other state is terminal when a long walk spends a larger share of its time in it than the state’s share of the cells, an enrichment above one, and intermediate otherwise. CellRank instead calls a state terminal when one step of the walk stays in it with probability at least 0.96; on the pancreas walk of the fate mapping tutorial every state stays with probability 0.97 or more, so that rule calls every state terminal. The table keeps each state’s
stabilityfor comparison. A late intermediate state in which the walk slows, such as the Pre-endocrine cells before the endocrine fates, can also hold more than its share, so check terminal calls with markers. The roles need the walk to have a direction: atbeta=0a long walk spends its time in proportion to the cells’ degrees, so enrichment measures how densely a state’s cells are joined rather than where the process ends.The
cells_per_statemost likely cells of each state carry its name in the artifact’s canonical array, missing for other cells, so the artifact givesfate()itssink_labels, and any state can be a sink:found = ds.trajectory.load_states(states) fate = ds.trajectory.fate( sink_labels=states, graph=graph, direction=score, sinks=found.terminal, )
The search covers the largest connected component of the graph’s scored cells; cells of other components belong to no state, with a warning. Choose
n_statesa few above the number of populations that you expect along the process, and trust the terminal states that persist whenn_stateschanges by one or two. A warning also names a last state whose eigenvalue ties the next one’s, as those of identical parts of a walk tie, since the last state is then one mix of their directions among many.The memberships are the crispest, those whose states overlap least, that Nelder-Mead finds in at most
200 * (n_states - 1)**2trials, as CellRank runs it. A search of many states can stop at that limit before the crispness converges. Its states then depend on where the optimization stopped, and a small change to the graph can give other terminal states, so the search warns. The artifact’s diagnostics, whichds.artifacts.inspect(states).diagnosticsreturns, record thecrispnessand thecrispnessOptimization,"converged"or"stopped_at_limit".- Parameters:
graph (
ArtifactRef) – Explicit connectivity-map or integrated-graph artifact to walk on.direction (
ArtifactRef|Series) – Per-cell score that directs the walk, higher meaning later, asfate()takes it: a cell-aligned artifact of real values over the graph’s cells other than a pseudotime, such as thecell_potencyartifact ofpotency(), or a pandas Series indexed by cell ID, which is saved as the snapshot thatfatesaves of it. A missing or non-finite value leaves a cell unscored, and the scored cells must make up whole connected components of the graph.n_states (
int) – Number of states, initial, intermediate and terminal together; at least 2.labels (
ArtifactRef|None) – Cell labels of the graph’s cells, such as clusters. Each state takes the name of the label that most of its cells hold, with_1,_2for repeats. Without labels, states are named1ton_statesin the walk’s order.cells_per_state (
int) – How many of each state’s most likely cells its name marks.beta (
float) – Strength of the penalty on edges to cells of lower score, as infate().max_iterations (
int|None) – Bound on the restarts of the eigen-solve. None takes SciPy’s bound of ten per cell.invalidate_cache (
bool) – Compute a new search even when one matches.
- Return type:
- Returns:
Reference to a
trajectory_statesartifact, whichload_states()loads andfate()takes assink_labels.- Raises:
TypeError – If an argument has the wrong type, such as a
directionthat is neither an artifact reference nor a pandas Series indexed by cell ID.ValueError – If an argument is out of range,
directionis a pseudotime or holds labels,labelsholds values or other cells, the searched cells are too few, orn_stateswould split a pair of complex conjugate eigenvalues.RuntimeError – If the eigen-solve does not converge within
max_iterationsor finds no invariant subspace.MemoryBudgetError – If the search does not fit the memory budget; the graph is checked before it is read.
PermissionError – If the search must be computed and the store is not opened with
zarr_mode='r+'.
pseudotime orders cells by the potential of population balance analysis, which Weinreb et al. (2018) define as half the pseudoinverse of the graph’s random-walk Laplacian applied to the source-sink vector. The default, method="untruncated", solves for that potential over all of the Laplacian’s modes by MINRES on the symmetric Laplacian, to machine precision: on synthetic graphs of one million cells it took 28 to 29 s and 724 to 777 iterations in containers of 4 CPUs, also when an eighth of the cells was joined to the rest by 64 edges. method="truncated" keeps the n_singular_vals - 1 smallest nonzero singular modes, 29 by default, which SciPy’s svds finds with ARPACK; it is the potential of releases before 1.4.0 and reproduces their pseudotimes. When the graph’s slow modes outnumber the modes it keeps, as on graphs of many weakly joined clusters, the truncated potential departs from the full one, to a correlation of 0.971 on a synthetic graph of 20,000 cells in 150 clusters, and its solve can run for hours on graphs of several hundred thousand cells. Both potentials drop the component of the source-sink vector along the degree vector, as the pseudoinverse does, since the range of the Laplacian is orthogonal to that vector.
max_iterations bounds the solve and solver_tol sets its tolerance, and each enters the artifact’s record only when set. For the untruncated potential they are MINRES’s iterations, five per cell by default, and its rtol, which stops the solve once the residual falls below solver_tol times the estimated norms of the Laplacian and of the potential; the potential moves smoothly with it, by about 1% of its range at solver_tol=1e-8 on the graphs of one million cells. For the truncated potential they are the restarts of svds, ten per cell by default, and the relative tolerance of its singular values; a looser tolerance can make it miss singular modes, so leave solver_tol unset there unless a measurement shows the potential unchanged. The solve advances a progress bar and logs its count of operator products at INFO level every 30 seconds, and a solve that reaches max_iterations raises PseudotimeConvergenceError with its counts.
The untruncated default is revision 2 of run_pseudotime_scoring (Operation revisions). Pseudotimes saved by earlier releases record no method, so a default call computes them anew, the fate maps and lineage results built on them follow through their inputs, and ds.artifacts.lineage marks them stale. A pseudotime that records method="truncated" stays current and is reused.
A pseudotime scores one connected component of its graph: the largest by default, or with component_policy="sources" the one that holds the most source cells, the cells with a source label or a negative ss_vec value. load_pseudotime returns each cell’s component, numbered by decreasing size, and the component_sizes, computed from the stored graph. A source or sink label that no selected cell holds, or no cell of the scored component, raises SourceSinkLabelsError from pseudotime and from fate, naming the labels in missing_sources and missing_sinks.
pseudotime and lineage_tree take cells, a cell selection of some of the graph’s cells, such as the cells of some clusters from select_cells, and score those cells without a graph of their own. The pseudotime scores the subgraph that the cells induce, the graph’s edges among them with their weights, and numbers that subgraph’s connected components, which can outnumber the graph’s: cells at the edge of the selection lose their edges to the cells left out. cells becomes the result’s cell selection, which fate, curves, markers, aggregation and the lineage calls follow. The graph’s own selection gives the result that a call without cells gives, and a selection with cells outside the graph raises ValueError. Labels may hold the graph’s cells or cells, and the coordinates of curves and lineage_tree the graph’s cells or the result’s; only the result’s cells are read. The subgraph keeps the neighbors that the whole graph chose, so it orders the cells by the variation that the whole graph follows, while a graph built on the selected cells’ own principal components follows the variation within them; the trajectory checks score one lineage on its subgraph and compare it with the whole graph’s pseudotime.
fate computes each cell’s probability of reaching each sink group in a random walk on the graph, whose edges toward a cell of lower pseudotime keep 2 / (1 + exp(beta * d)) of their weight, d being the drop in pseudotime rescaled to [0, 1]. Any per-cell score that orders the cells, higher meaning later, can direct the walk in place of a pseudotime: fate(sink_labels=labels, graph=graph, direction=score, sinks=[...]) takes direction as a cell-aligned artifact of real values over the graph’s cells or as a pandas Series indexed by cell ID, aligned to the graph’s cells by ID and saved as a snapshot; values of other cells are left out, and an array raises TypeError, because its values would land on cells by position. pseudotime(graph, ss_vec=...) takes its source-sink values the same way, keyed by the IDs of the cells it scores. The other per-cell inputs of computations and plots follow the same rule: an initialization DataFrame of embeddings.umap, tsne and localmap, the query_batches DataFrame of mapping.run, the target_groups of mapping.compute_scores, plots.mapping_score and plots.mapping_evidence, the known_labels of plots.mapping_confusion and plots.mapping_calibration, the labels of LabelTransferResult.label_vote_shares, and the point_sizes of plots.embedding. The walk is biased by the score as by a pseudotime, so a score equal to a pseudotime gives that pseudotime’s fate map, and a score rescaled linearly, such as from [0, 1] to [0, 100], gives the same probabilities. A cell whose score is missing or not finite is unscored. The scored cells must make up whole connected components of the graph, as a pseudotime’s do: a component with some cells scored and others not is refused. The map covers the scored components that hold a sink, a sink without a scored cell raises SourceSinkLabelsError, and a scored component without a sink stays out of the map with a warning. A walk stays in its component, so a cell’s probability is 0 for each sink without a cell in the cell’s component. The map records the score as its direction input in place of pseudotime, so maps directed by a pseudotime keep their identities, and load_fate returns it as FateMappingResult.direction. The lineage methods below order the cells of such a map by its score, which then takes the pseudotime’s place in their results, such as curve_pseudotime, bin_pseudotime and the branch points of lineage_membership.
states(graph, direction, n_states=...) finds the initial and terminal states of the walk that fate takes with the same graph, direction and beta. It splits the walk into n_states metastable states, groups of cells that the walk enters and rarely leaves, by generalized robust Perron cluster analysis, as CellRank does: each cell gets a membership in each state, and the states get the walk between them. The states are ordered by their mean direction score. The first is the initial state, and each other state in which a long walk spends a larger share of its time than the state’s share of the cells is terminal; a late intermediate state where the walk slows can also qualify, so check terminal calls with markers. The cells_per_state most likely cells of each state, 30 by default, carry its name in the artifact’s labels, missing for other cells, so fate(sink_labels=states, graph=graph, direction=direction, sinks=found.terminal) maps fates to the terminal states, and any state can be a sink. load_states returns a TrajectoryStatesResult, whose table gives each state’s label, role, cells, share of the cells, share of the walk’s time, their ratio, stability and mean direction. The roles need the walk to have a direction: at beta=0 a long walk spends its time in proportion to the cells’ degrees. The search covers the largest connected component of the scored cells and warns about the cells it leaves out. It also warns when it finds no terminal state apart from the initial one, when the last state’s eigenvalue ties the next one’s, as those of identical parts of a walk do, and when the optimization of the memberships stops at its limit of 200 * (n_states - 1)**2 trials before their crispness converges, which the artifact’s crispnessOptimization diagnostic records; a small change to the graph can then give other terminal states. Choose n_states a few above the number of populations that you expect along the process, and trust the terminal states that persist when it changes by one or two. Methods and limitations gives the algorithm, why the role rule departs from CellRank’s, and the comparison with CellRank.
- exception cytearc.trajectory.PseudotimeConvergenceError(*, method, n_cells, operator_products, max_iterations, solver_tol, relative_residual=None, n_modes=None, converged_modes=None, restarts=None)#
The solve of a pseudotime’s potential stopped at its bound.
methodnames the solve:"untruncated"for MINRES on the symmetric graph Laplacian,"truncated"for the Lanczos solve of the smallest singular values. The fields of the other solve are None.- method#
The potential that the solve computed,
"untruncated"or"truncated".
- n_cells#
The cells of the scored component, one row of the graph Laplacian each.
- operator_products#
The products of the graph Laplacian, or of its transpose, with a vector that the solve computed.
- max_iterations#
The bound that stopped the solve, on MINRES iterations or on the implicit restarts of the singular value solve: the caller’s, or SciPy’s default of five iterations or ten restarts per cell.
- solver_tol#
The tolerance of the solve, or None for machine precision.
- relative_residual#
For
"untruncated", the residual of the symmetric system relative to its right-hand side when the solve stopped.
- n_modes#
For
"truncated", the singular modes that the solve sought, the null mode included.
- converged_modes#
For
"truncated", the modes that had converged when the solve stopped.
- restarts#
For
"truncated", the implicit restarts that the Lanczos solve ran, which reachedmax_iterations.
- exception cytearc.trajectory.SourceSinkLabelsError(message, *, missing_sources, missing_sinks, missing_from, component_sizes=None)#
Source or sink labels that a pseudotime or a fate map needs are missing.
- missing_sources#
The source labels that no checked cell holds, in the order given.
- missing_sinks#
The sink labels that no checked cell holds, in the order given.
- missing_from#
"labels"when no selected cell holds them, or"scored component"when no scored cell holds them: no cell of the graph component that the pseudotime scores, or of the components that the direction score of a fate map scores.
- component_sizes#
The cell counts of the graph’s connected components, largest first, when
missing_fromis"scored component", and None otherwise.
The lineage methods resolve one fate map into its lineages: each scored cell weighs in each lineage by its fate probability. lineage_markers and lineage_aggregation follow features along each lineage, drivers correlates features with fate probabilities, and curves fits one curve per lineage through the graph’s coordinates. lineage_tree is a diagnostic that proposes candidate sinks from a cluster tree; check them before passing them to fate, or find terminal states from the walk itself with states. See Resolve gene dynamics by lineage and Draw lineage curves and check the trajectory.
Each trajectory call reads only the saved results that its arguments name, so a call made in a process of its own, from the refs of the calls before it, saves what the same call saves in a chain in one process, with the same provenance, and returns that result where the store already holds it (Several processes on one store).
curves_in_layout(curves, layout) returns the curves drawn in a two-dimensional layout, such as a UMAP, as a table of each curve’s points, lineage, point, x and y, which plots.lineage_curves draws. It averages the layout coordinates of the scored cells with each lineage’s fate weights along the curve and smooths them with the curves’ spline, needs no plotting dependencies and saves nothing, so a viewer of its own can draw the curves. The layout may come from any cell selection that holds the curves’ cells, such as a UMAP of the whole graph for curves of some of its cells.
lineage_tree saves its tree, so a store opened with zarr_mode="r" refuses to build a tree that it does not hold. cytearc.trajectory.build_cluster_tree() builds the same tree from the cells’ coordinates and labels without a store, as a ClusterTree, with the clusters in the order that the saved tree gives them, so a caller can show a tree before saving it or from a read-only store.
- cytearc.trajectory.build_cluster_tree(coordinates, labels, *, root=None, ends=None)#
Build the cluster tree that
ds.trajectory.lineage_treesaves, without a store.Use it to see the tree before saving it, or on a store opened read-only, where
lineage_treecannot save one. The clusters are the distinct labels in their natural order, and the tree is built aslineage_treebuilds it: the distance between two clusters is(m_i - m_j)^T (S_i + S_j)^{-1} (m_i - m_j)for their mean coordinatesmand covariancesS, using the diagonal whereS_i + S_jis singular, a minimum spanning tree joins the clusters, and the paths fromrootto the other leaves propose lineages (Street et al. 2018).endsmakes clusters leaves: the tree first spans the others, then each end joins its nearest cluster. Given the coordinates and labels of a saved tree’s cells, the tree equals the one thatload_lineage_treereturns.- Parameters:
coordinates (
Any) – Coordinates of the cells, cells by dimensions, such as the PCA that a graph was built on.labels (
Any) – One cluster label per cell, such as the values of a clustering. Every cell needs a label.root (
Any) – Cluster label that starts the lineages, or None for an unrooted tree without lineages.ends (
list[Any] |None) – Cluster labels to hold as leaves.
- Return type:
- Returns:
The tree, as a
ClusterTree.- Raises:
TypeError – If
coordinatesare not numbers,endsis not a list, or the root or an end is not a scalar label.ValueError – If
coordinatesare not finite cells by dimensions,labelsdoes not hold one label for each of their rows, a label is missing, the labels hold values that would form one cluster but print differently, such as1,1.0andTrue, or values that print alike but would form separate clusters, such as1and"1", fewer than two clusters remain, the root or an end is not a cluster label or repeats, the root is also an end, every cluster is an end, or the tree can join two clusters only across an infinite distance.
Fate probabilities sum to one over the sinks, so a cell on no trajectory still splits its probability among them, and a cell that has not committed looks like a member of its most likely lineage. lineage_membership(curves) calls, for each cell of the curves, the lineage it follows, "shared" when it follows several or "none", and saves the rule with its thresholds. Progenitors split their probability unevenly among the fates, 0.45 Beta against 0.04 Delta on the pancreas cells of the lineage tutorials, so each lineage is measured against its trunk probability in each graph component that holds its sink cells: its mean probability over the earliest tenth, by the pseudotime or the score that directs the fate map, of the component’s scored cells outside the fate map’s sinks. A fate map that a pseudotime directs covers one component, and one that a score directs can cover several, each with its own trunk. A scored cell follows each lineage whose sink cells share its component and whose probability is still at least band times its trunk probability there, 0.5 by default, and only when the cell lies on the trajectory: within some lineage’s distance limit at its progress along that lineage’s curve. A progenitor therefore follows every lineage that starts in its trunk, whatever share each lineage receives and however many cells its branch and sink hold, as long as the earliest tenth lies before the branches part, and as a cell commits it leaves the lineages whose probability falls rather than joining the one whose probability rises. Precisely, a cell follows a lineage when its probability divided by the trunk probability is positive and at least band times the smaller of one and its largest such ratio. With curves of every sink, a component’s trunk probabilities of the lineages whose sink cells it holds sum to one, so that largest ratio is at least one; with curves of some of the sinks, a cell that moves toward a sink they leave out can have every ratio below one, and it then follows each lineage whose ratio is at least band times its largest. A lineage that its trunk cells give no probability, as when its sink cells fill a graph component of their own, is refused. In each of n_bins bins of progress, the lineage’s cells weigh by their fate probability for it, and their spread is their weighted median distance plus distance_score, 5 by default, times their weighted median absolute deviation scaled by 1.4826. A bin’s limit is the median spread of three neighboring bins, so a state that projects onto one stretch of a curve, such as a dead end off it, cannot widen the limit there. load_lineage_membership returns a LineageMembershipResult with each cell’s label and lineages, the limits, the trunk probabilities by component and lineage, and for each pair of lineages its branch point: the pseudotime that best splits the cells the two share, before it, from the cells that follow one of them, after it, with the progress there on each curve. A pair has no branch point, NaN, when it never shares a cell, never parts, or its shared cells do not come before its parted cells. select_cells reads the labels, and branch_cells(membership, lineages) selects the cells that follow either of two lineages nearest their branch point, a window share of them. drivers(fate, cells=..., lineages=[first, second]) holds, for each of the two fates, each gene’s correlation with that fate’s probability among those cells, by which to rank the genes that rise with each fate and compare the two lineages.
Plan a trajectory#
ds.trajectory.plan() tells which calls of a trajectory the store already holds and which would compute, before any of them runs, for example before a trajectory is split over jobs. Wrap the calls, written as they would run, in its block:
with ds.trajectory.plan() as plan:
pseudotime = ds.trajectory.pseudotime(graph, source_sink=clusters, sources=[1], sinks=[2])
fate = ds.trajectory.fate(pseudotime, clusters, sinks=[2, 3, 4])
curves = ds.trajectory.curves(fate)
plan.computed # the calls that would compute, in the order made
plan["fate"].reason # "upstream" when the pseudotime would compute
plan.to_dict() # the plan as JSON values
Inside the block, pseudotime, fate, states, curves, lineage_tree, lineage_membership, branch_cells, markers, aggregation, lineage_markers, drivers and lineage_aggregation look for their results as they do when they run, and the plan records each call. A call whose result the store holds, complete and current, returns the result’s ref, so the calls after it plan from the stored result. A call that would compute returns its plan, a TrajectoryCallPlan, in place of the ref: its status is "computed", and its reason takes the values of a pipeline plan’s (Plan a call) or "invalidate_cache", when the call asks to compute again. A later call that takes that plan as an input does not run, so its arguments are not checked until it does: its identity depends on a result that does not exist yet, so it is reported computed with the reason "upstream", and its upstream holds the positions of the calls that it waits on. Pass a reused call’s result on as its ref, not as its plan. After the block, the calls run as they always do.
The planned calls save nothing, and a plan works on a read-only store. Each call does the work that it does before it looks for its result: it reads its inputs’ records and small arrays, the metadata it checks, and the graph that it walks, so a plan costs about one graph load for each call but lineage_tree, and reads no count matrix. A call whose inputs exist raises the errors that it raises before it writes, such as a refused memory budget. A plan describes the store as it is: a call made twice is planned computed twice, though the chain would compute it once, and a snapshot that two calls save of the same values is named for both, though only the first would save it.
A plan covers the calls made in the thread that opened it; a call sent to another thread, such as one of a thread pool, runs as it always does. Any other call in the block reuses a saved result as it always does, and one that would compute raises RuntimeError when the block ends, while pipeline runs and resumes refuse to start inside it. A call that changes the store without saving a result, such as ds.cells.insert, still writes.
- class cytearc.datastore.trajectory_plan.TrajectoryPlan(store)#
What the trajectory calls made in a plan’s block would reuse and compute.
ds.trajectory.plan()returns the plan, a context manager. Its calls fill as the block runs and are final once it ends.- property calls: tuple[TrajectoryCallPlan, ...]#
Every planned call, in the order made.
- property computed: tuple[str, ...]#
The calls that would compute, in the order made.
- property reused: tuple[str, ...]#
The calls whose results the store holds, in the order made.
- to_dict()#
Return the plan as JSON-compatible values.
- Return type:
dict[str,Any]
- class cytearc.datastore.trajectory_plan.TrajectoryCallPlan(call, ordinal, status, reason=None, detail=None, operation=None, ref=None, existing=None, changed_parameters=(), changed_inputs=(), upstream=())#
What one call of a planned trajectory would do.
Inside the plan’s block, a call that would compute returns this plan in place of the ref that it would return, and later planned calls take it as an input.
- call#
The trajectory method, such as
"fate".
- ordinal#
The call’s position in the plan, from 0.
- status#
"reused"when the store holds the call’s result, complete and current;"computed"when the call would compute it.
- reason#
Why a computed call computes:
"absent", the store holds no artifact of the operation;"changed", the closest one was computed with other parameters or inputs;"superseded", an operation revision supersedes the stored one;"incomplete", the stored one was interrupted;"missing_diagnostics", the stored one lacks the diagnostics that its operation saves;"invalid", the stored one fails its payload checks;"invalidate_cache", the call asks to compute it again;"upstream", the call takes the result of a call before it that would compute. None for a reused call.
- detail#
The reason in one sentence, or None.
- operation#
The operation whose artifact the call would compute first, such as the snapshot of a direction given as a pandas Series, or None.
- ref#
The result that a reused call returns, or None.
- existing#
The stored artifact that the reason concerns: the one that a revision supersedes, that was interrupted, that lacks diagnostics, or that fails its checks, or the closest one of the operation. None otherwise.
- changed_parameters#
For
"changed", the operation’s parameters in which the closest artifact differs.
- changed_inputs#
For
"changed", the inputs in which it differs.
- upstream#
For
"upstream", the positions of the calls whose results the call takes, in order.
- to_dict()#
Return the call’s plan as JSON-compatible values.
- Return type:
dict[str,Any]
ds.mapping#
- class cytearc.datastore.namespaces.MappingAccessor(store)#
ds.compare#
- class cytearc.datastore.namespaces.CompareAccessor(store)#
- compute_bulk(groups, *, from_assay=None, cell_selection=None, secondary_groups=None, aggr_type='mean', count_detected=False, feature_label='index', remove_empty_features=True, remove_empty_columns=True, pseudo_reps=1, null_vals=None, secondary_null_vals=None, random_seed=4466)#
Merge data from cells to create a bulk profile.
With
aggr_type='mean', cells are normalized with the assay’s normalization fitted once over every selected cell, then averaged within each group. RNA library-size normalization is per cell; ATAC document frequency and ADT CLR geometric means are therefore shared by all groups rather than learned separately for each group.On a store merged from sources that measured different features, as its feature columns
measured_in_<source>record, the features that some source of the cells that it reads did not measure are left out of the profiles,remove_empty_featuresor not, with a warning that names them, since their zero counts in that source’s cells are not measurements.Cells whose group or sub-group label is missing join no group, like cells whose value is in
null_vals. Missing labels areNaN,None, blank text, and values flagged by a linked missing mask.Each bulk column is one group, one group and sub-group combination, or one pseudo-replicate of either, and is labeled by them: by its group label alone, or by a MultiIndex of the levels
group,subgroup, andreplicate(numbered from 1) that the call uses, so labels that hold_keep their columns apart. A column without cells, such as a combination that no cell has or a pseudo-replicate of a group with fewer cells thanpseudo_reps, is left out, so that no empty column passes for a measured profile of zeros. Withremove_empty_columns=Falsesuch columns are kept and hold NaN.- Parameters:
groups (
ArtifactRef|str) – Explicit clustering artifact or user-owned metadata column used to group cells.from_assay (
str|None) – Name of assay to be used. If None andgroupsis an artifact, the artifact’s assay is used; otherwise the default assay is used.cell_selection (
ArtifactRef|None) – Explicit selection. Artifact grouping derives its selection from lineage, and this argument may only narrow it. For metadata-column grouping, None uses the liveIcolumn as the selection.secondary_groups (
ArtifactRef|str|None) – Optional clustering artifact or user-owned metadata column used to sub-group cells.aggr_type (
Literal['mean','sum']) – Type of aggregation to be used. Can be either ‘mean’ or ‘sum’. (Default value: ‘mean’)count_detected (
bool) – Also count, for each feature, the cells of each bulk column whose raw count is above zero. (Default value: False)feature_label (
Literal['index','id','name']) – The feature metadata that labels the rows: the feature’s position ('index', the default), its'id', or its'name'.pseudo_reps (
int) – Within each group, randomly split cells into this many pseudo-replicates, an integer of at least 1. Values greater than 1 produce descriptive resamples of the same cells, not independent biological replicates. (Default value: 1)remove_empty_features (
bool) – Remove features that are not expressed in any cell. (Default value: True)remove_empty_columns (
bool) – Leave out bulk columns without cells (default). With False they are kept and hold NaN.null_vals (
list[Any] |None) – Primary group values to skip.secondary_null_vals (
list[Any] |None) – Secondary group values to skip. These values will be skipped.random_seed (
int) – Seed used when assigning cells to pseudo-replicates, from 0 to 2**32 - 1.
- Return type:
- Returns:
The bulk profiles as
BulkProfiles: the features-by-columnsprofiles, thecolumnstable of each bulk column’sn_cells, and, withcount_detected, the int64detectedcounts, from whichdetected_fractionderives the share of each column’s cells.- Raises:
TypeError – If
pseudo_repsorrandom_seedis not an integer.ValueError – If
aggr_type,feature_label,pseudo_reps, orrandom_seedis not one of the values above, which is checked before anything is read, or if no feature was measured by every source of the cells that it reads.UnmeasuredCellsError – If the assay did not measure a cell that is read.
- load_tests(artifact)#
Return one exact immutable statistical-test result.
- Return type:
- test(keys, grouping, *, cell_selection=None, groups=None, comparisons=None, test='auto', posthoc=None, adjustment='fdr_bh', alternative='two-sided', sample_by=None, study_design=None, pair_by=None, sample_stat='mean', expression_cutoff=0.0, subset_by=None, from_assay=None, normalization=None, skip_save=False, invalidate_cache=False)#
Run statistical tests on values grouped by an explicit source.
This mirrors the inputs of
distributionso results can be compared directly against violin or box plots.keysmay be cell-metadata columns or feature names. The chosen test follows the single-cell conventions for zero-inflated, non-normal values:"mann_whitney": two independent groups, two-sided. When the two groups can be formed in at most 100,000 ways, as in typical sample-level designs, p-values come from the exact permutation null with ties handled exactly. Larger designs use the tie- and continuity-corrected normal approximation of the marker search.result.p_value_methodrecords"exact"or"asymptotic"."kruskal_wallis": three or more groups, with optionalposthoc="dunn"for pairwise significance."wilcoxon": paired samples on aggregated (pseudobulk) data. Requiressample_byandpair_by."welch"(alias"t_test"): cell-level Welch’s t-test on raw normalized values for exactly two groups, honoringalternative. Descriptive only; no sample aggregation."one_way_anova": cell-level one-way ANOVA omnibus test on raw normalized values. Descriptive only; no post-hoc yet.
With
test="auto"the test is chosen from the design: paired data uses Wilcoxon, two groups use Mann-Whitney, and three or more use Kruskal-Wallis. Auto never picks a parametric method.groupsrestricts the group set and fixes its order (which sets the contrast direction);comparisonsrestricts pairwise rows to the listed group pairs. Withposthoc="dunn"both the omnibus Kruskal-Wallis and the pairwise Dunn’s results are preserved. When multiple keys are tested,adjustmentcorrects p-values across keys in one pooled pass (default"fdr_bh"); post-hoc p-values are corrected separately.A
study_designwithsubject_by(orpair_by) pairs samples only for the Wilcoxon test: explicitly, or withtest="auto"when two conditions remain. Repeated measures across three or more conditions, subjects nested within conditions, and independent tests raise an error. For nested subjects, pass the subject column assample_byinstead.Without
sample_by, the tests treat each cell as an independent observation, and a warning says so on every call, whether it computes the result or reuses a saved one.Results are persisted as immutable artifacts unless
skip_saveisTrue. Writing requireszarr_mode='r+'; a matching saved result is still reused from a read-only store. Passresult.artifacttocompare.load_testsfor exact retrieval.- Parameters:
keys (
str|CellField|FeatureRef|Sequence[str|CellField|FeatureRef]) – Feature names or cell-metadata columns to test.grouping (
ArtifactRef|CellField) – Exact categorical artifact or explicit cell metadata field.cell_selection (
ArtifactRef|None) – Optional frozen selection for a metadata field, or a subset of an artifact grouping’s stored selection.groups (
Sequence[Any] |None) – Keep and order only these grouping categories.comparisons (
Sequence[tuple[Any,Any]] |None) – Restrict pairwise comparisons to these group pairs.test (
Literal['auto','mann_whitney','kruskal_wallis','wilcoxon','welch','t_test','one_way_anova']) – Statistical test, or"auto"to pick from the design.posthoc (
Optional[Literal['dunn']]) – Pairwise test to run after Kruskal-Wallis ("dunn").adjustment (
Literal['fdr_bh','bonferroni','holm','none']) – Multiple-testing correction across keys and rows.alternative (
Literal['two-sided','less','greater']) – Direction of the alternative hypothesis. Only the Welch t-test honors it; other tests remain two-sided.sample_by (
str|None) – Cell metadata column identifying biological samples.study_design (
StudyDesign|None) – Study design supplyingsample_byand, for the Wilcoxon test only, the pairing column.pair_by (
str|None) – Cell metadata column identifying subjects or donors for paired tests.sample_stat (
Literal['mean','median','fraction']) – Aggregation across cells within a sample.expression_cutoff (
float) – Detection cutoff forsample_stat="fraction".subset_by (
str|None) – Boolean metadata column keeping onlyTruecells.from_assay (
str|None) – Assay to read feature values from.normalization (
NormalizationSpec|None) – How feature values are read.skip_save (
bool) – Return results without writing to Zarr.invalidate_cache (
bool) – Recompute even when a matching artifact exists.
- Return type:
- Returns:
- Raises:
PermissionError – If a result must be written to a store that is not opened with
zarr_mode='r+'. The check runs before any value is computed.UnmeasuredCellsError – If a feature’s assay did not measure a tested cell.
ValueError – If the source of a merge of a tested cell did not measure a tested feature, as the assay’s
measured_in_<source>feature columns record.
Updating existing calls#
Replace the method name using this table. Arguments, defaults, return values, and saved artifacts stay the same, with two later changes. The default Leiden backend of clusters.leiden is now "cytearc" instead of "igraph", so pass backend="igraph" to keep reusing clusterings made with the earlier default (see ds.clusters above). compare.compute_bulk returns a BulkProfiles record instead of a frame or a tuple of frames, count_detected=True replaces return_fraction=True, and return_n_cells is removed because the record always holds each column’s cells; the rows after ds.make_bulk(...) show how to read the record, which the selected analysis contracts below describe. The previous names are no longer methods on DataStore. Saved provenance retains its operation names, such as run_umap.
Previous call |
Current call |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Store-bound plotting#
DataStore.plots binds the datastore argument for canonical store-first functions in cytearc.plotting.
Array and DataFrame diagnostics such as elbow, qc, graph_qc, and highly_variable_features remain standalone.
- class cytearc.datastore.plot_accessor.DataStorePlotAccessor(store)#
Datastore-bound facade for store-first plotting functions.
- allele_frequencies(variants, *, clones=None, max_cells=2000, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot each cell’s allele frequency of each informative variant.
- Return type:
- association_calibration(tests, *, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot whether the association tests keep their error rate, and find effects.
- Return type:
- association_volcano(tests, *, targets=None, label_top=10, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot how much and how significantly each perturbation changes each gene.
- Return type:
- barcode_calls(barcodes, *, max_barcodes_per_cell=10, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the barcodes per cell, UMIs per barcode and reads per molecule of lineage barcodes.
- Return type:
- clonal_diversity(diversity, *, indices=('n_clones', 'shannon', 'inverse_simpson'), groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot diversity indices of groups of cells, one panel of bars per index.
- Return type:
- clonal_expansion(expansion, *, group_by=None, groups=None, count='cells', normalize=True, splits=(10, 100, 1000, 10000, 30000, 100000), target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the clonal expansion and clonal space of groups of cells.
- Return type:
- clonal_rarefaction(rarefaction, *, base='size', groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the rarefaction and extrapolation curves of groups of cells.
- Return type:
- clone_abundance(clones, *, group_by=None, groups=None, max_clones=20, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot how many clones have each size, and the largest clones.
- Return type:
- clone_coupling(coupling, *, value='coupling', color_scale=None, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the fate coupling of every pair of groups as a heatmap with its dendrogram.
- Return type:
- clone_fate_bias(bias, *, max_clones=40, normalize=False, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the fates of the clones of early cells, each clone’s late cells by fate.
- Return type:
- clone_overlap(overlap, *, index='morisita_horn', color_scale=None, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot an overlap index between every pair of groups as a heatmap.
- Return type:
- clone_tracking(tracking, *, order=None, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the share of cells of chosen clones across groups of cells.
- Return type:
- cluster_connectivity(*, group_by=None, layout_key=None, groups=None, layout=None, graph, cell_key='I', position='median', positions=None, categorical_scale=None, size_scale=None, minimum_edge_weight=0.02, max_edges_per_node=None, show_cells=False, cell_size=None, cell_alpha=0.3, cell_color=None, node_edgecolor=None, node_linewidth=0.8, edge_color=None, edge_alpha=0.45, edge_width_range=(0.4, 5.0), labels=True, target=None, figsize=None, theme='notebook', show=True)#
Summarize cell graph connectivity between embedding clusters.
- Return type:
- cluster_tree(*, graph, clusters, from_assay=None, fill_by_value=None, force_ints_as_cats=True, width=1, lvr_factor=0.5, vert_gap=0.2, min_node_size=10, node_size_multiplier=10000.0, node_power=1.2, root_size=100, non_leaf_size=10, show_labels=True, fontsize=10, root_color='#C0C0C0', non_leaf_color='k', cmap=None, color_key=None, edgecolors='k', edgewidth=1, alpha=0.7, figsize=(5, 5), ax=None, theme='notebook', show=True)#
Plot a stored hierarchical clustering tree.
- Return type:
- composition(*, category_by=None, categories=None, cell_key='I', sample_by=None, grouping=None, subject_by=None, pair_by=None, condition_by=None, study_design=None, kind='stacked', show_summary=True, uncertainty=None, categorical_scale=None, bar_width=0.82, bar_gap=0.12, segment_edgecolor=None, segment_linewidth=0.5, show_percent_labels=False, label_min_fraction=0.08, percent_format='{:.0%}', target=None, figsize=None, max_figure_width=7.5, theme='notebook', show_legend=True, show=True)#
Plot category composition for the selected cells.
- Return type:
- distribution(keys, *, grouping=None, cell_selection=None, groups=None, split_by=None, sample_by=None, study_design=None, sample_stat='mean', expression_cutoff=0.0, subset_by=None, from_assay=None, normalization=None, categorical_scale=None, split_scale=None, kind='violin', bins=40, max_points=10000, max_density_points=20000, point_size=0.8, point_alpha=0.28, seed=0, color='steelblue', color_by='group', color_scale=None, orientation='vertical', row_standardize=False, share_y=None, violin_inner='quartile', violin_linewidth=0.8, violin_alpha=0.9, italicize_features=False, target=None, figsize=None, max_figure_width=7.5, title=None, theme='notebook', show_legend=True, stats_results=None, stats_keys=None, stats_bracket_height=None, stats_show_p=True, show=True)#
Plot distributions of cell metadata or feature values.
stats_resultsoverlays significance brackets fromcompare.testresults onto the drawn violins or boxes; seecytearc.plotting.distribution()for the full behavior.max_pointsdefaults to10000; explicitNonedisables the point overlay for stacked violins and otherwise uses10000. Each violin’s density uses at mostmax_density_pointsvalues.- Return type:
- dotplot(*, features, group_by=None, groups=None, cell_key='I', from_assay=None, sample_by=None, study_design=None, normalization=None, expression_cutoff=0.0, standardize='none', color_scale=None, size_scale=None, categorical_scale=None, group_order=None, feature_order=None, swap_axes=False, marker_edgecolor=None, marker_linewidth=0.3, label_wrap=None, italicize_features=False, target=None, figsize=None, max_figure_width=7.5, theme='notebook', show_legend=True, show=True)#
Summarize feature expression as a dot plot.
- Return type:
- edistance(edistance, *, max_rows=40, alpha=0.05, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot how far each perturbation moves its cells from the control cells.
- Return type:
- efficiency(efficiency, *, max_rows=40, alpha=0.05, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot how strongly each perturbation changes the expression of its target gene.
- Return type:
- embedding(*, layout_key=None, layout=None, run=None, color_by=None, facet_by=None, facet_order=None, cell_key='I', from_assay=None, normalization=None, point_size=None, point_sizes=None, point_size_range=(1.0, 28.0), point_edgecolor=None, point_edgewidth=None, point_alpha=1.0, sort_values=None, color_scale=None, categorical_scale=None, default_color='steelblue', missing_color=None, clip_fraction=0.0, subset_by=None, groups=None, n_columns=None, target=None, figsize=None, theme='notebook', legend_loc='auto', max_on_data_labels=40, show_legend=True, show_titles=True, frame='minimal', density_overlay=None, highlight=None, seed=0, rasterize_threshold=50000, show=True)#
Plot cells in a stored two-dimensional embedding.
- Return type:
- embedding_raster(*, layout_key=None, layout=None, run=None, color_by=None, cell_key='I', pixels=400, block_rows=None, color_scale=None, missing_color=None, subset_by=None, target=None, figsize=None, theme='notebook', seed=0, show=True)#
Rasterize continuous cell metadata over a stored embedding.
- Return type:
- gene_pairing(usage, *, max_genes=20, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot how the V and J genes of each locus pair, one panel per locus.
- Return type:
- gene_usage(usage, *, max_genes=30, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the gene usage of groups of cells, one panel per locus.
- Return type:
- genotypes(genotypes, *, sites=None, group_by=None, groups=None, layout=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the cells’ genotype calls by group and on an embedding.
- Return type:
- guide_calls(calls, *, max_guides_per_cell=5, bins=20, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot how many guides each cell carries and how many cells carry each guide.
- Return type:
- guide_thresholds(thresholds, *, guides=None, samples=None, max_panels=12, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the UMI thresholds that guide calling fitted to each guide in each sample.
- Return type:
- lineage_curves(*, curves, layout, lineages=None, df=None, lineage_cmap=None, line_width=2.5, point_size=None, point_alpha=0.6, cell_color='#d0d0d0', target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Draw fate-weighted lineage curves over a two-dimensional layout.
- Return type:
- lineage_heatmap(*, aggregation, lineages=None, show_features=None, figsize=None, vmin=None, vmax=None, heatmap_cmap='coolwarm', pseudotime_cmap='viridis', clusterbar_cmap=None, tick_fontsize=10, axis_fontsize=12, feature_label_fontsize=10, theme='notebook', show_legend=True, show=True)#
Plot fate-weighted feature profiles side by side for each lineage.
- Return type:
- lineage_tree(*, tree, layout, show_cells=True, cell_color='#d0d0d0', point_size=None, point_alpha=0.5, node_size=80.0, node_color='#56B4E9', root_color='#0072B2', leaf_color='#D55E00', edge_color='#555555', labels=True, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Draw a cluster tree over a two-dimensional layout.
- Return type:
- lineage_trends(*, aggregation, features, lineages=None, axis='progress', lineage_cmap=None, line_width=2.0, n_columns=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot selected features’ profiles along each lineage.
- Return type:
- mapping_calibration(transfer, *, known_labels, metric='voteFraction', direction='auto', thresholds=None, n_thresholds=50, chosen_threshold=None, target=None, figsize=None, theme='notebook', show=True)#
Plot held-out label accuracy against retained coverage per threshold.
- Return type:
- mapping_confusion(transfer, *, known_labels, normalize='true', known_order=None, predicted_order=None, abstention_label='Abstained', color_scale=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot known query labels against the labels of one saved transfer.
- Return type:
- mapping_evidence(transfer, *, target_groups=None, metrics=('voteFraction', 'topTwoMargin', 'voteEntropy', 'referenceDistancePercentile'), kind='histogram', bins=30, categorical_scale=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the saved evidence of one label transfer for query groups.
- Return type:
- mapping_score(result, *, reference, target_groups=None, layout=None, kind='embedding', reference_labels=None, size_by_score=False, log_transform=True, multiplier=1000, weighted=True, fixed_weight=0.1, bins=40, point_size=None, color_scale=None, categorical_scale=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot reference-cell mapping scores for one or more query groups.
- Return type:
- marker_heatmap(*, marker, topn=5, log_transform=None, vmin=-1, vmax=2, figsize=None, fontsize=10, width_factor=0.03, height_factor=0.02, cmap='magma_r', color_scale=None, row_order=None, column_order=None, cluster_rows=True, cluster_columns=True, cluster_method='ward', cluster_metric='euclidean', row_annotations=None, column_annotations=None, annotation_scales=None, target=None, theme='notebook', show_legend=True, show=True, **heatmap_kwargs)#
Plot the stored marker table as a heatmap.
- Return type:
- matrixplot(*, features, group_by=None, groups=None, cell_key='I', from_assay=None, sample_by=None, study_design=None, normalization=None, expression_cutoff=0.0, value='mean', standardize='none', color_scale=None, feature_order=None, group_order=None, cluster_features=False, cluster_groups=False, cluster_method='average', cluster_metric='euclidean', row_annotations=None, column_annotations=None, annotation_scales=None, categorical_scale=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Summarize feature expression as a matrix plot.
- Return type:
- mixscape(classes, *, panel='classes', targets=None, max_targets=40, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the share of each target’s cells that Mixscape calls knocked out, or their scores.
- Return type:
- modality_weights(*, graph, layout, point_size=None, point_alpha=1.0, cmap='viridis', n_columns=None, target=None, figsize=None, theme='notebook', frame='minimal', rasterize_threshold=50000, show=True)#
Plot each assay’s WNN contribution over an explicit embedding.
- Return type:
- perturbation_clusters(clusters, *, panel='heatmap', perturbations=None, cluster_ids=None, label=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot clusters of perturbations as a heatmap of their profiles or as a map.
- Return type:
- phylogeny(clones, *, tree=None, max_leaves=100, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the cell phylogeny that clones were cut from, its clades collapsed to at most
max_leaveswedges.- Return type:
- pseudotime_heatmap(*, aggregation, show_features=None, feature_order=None, feature_cluster_order=None, figsize=(5, 10), vmin=-2.0, vmax=2.0, heatmap_cmap=None, pseudotime_cmap=None, clusterbar_cmap=None, color_scale=None, feature_cluster_scale=None, pseudotime_scale=None, tick_fontsize=10, axis_fontsize=12, feature_label_fontsize=12, target=None, theme='notebook', show_legend=True, show=True)#
Plot feature profiles ordered by stored pseudotime.
- Return type:
- receptor_qc(receptors, *, group_by=None, groups=None, normalize=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the receptor types, chain pairings and chains per cell of imported receptors.
- Return type:
- recorder_states(alleles, *, max_sites=40, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the fraction of cells that each recorder site reads as each state.
- Return type:
- run_recipe(recipe, *, artifacts=None, targets=None, output_dir=None, show=False, continue_on_error=False)#
Run a declarative plotting recipe against this datastore.
- Return type:
- spectratype(spectratype, *, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the junction lengths of groups of cells, one panel per locus.
- Return type:
- variant_depth(counts, *, group_by=None, groups=None, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot the depth of variant counts at each site and in each cell.
- Return type:
- variant_statistics(variants, *, target=None, figsize=None, theme='notebook', show_legend=True, show=True)#
Plot each variant’s VMR against its strand correlation.
- Return type:
Selected analysis contracts#
Feature producers return immutable ArtifactRef values. Use
features.resolve(assay, ref) for strict read-only validation.
features.universe(from_assay=...) creates or reuses the canonical immutable all-feature
selection for granular workflows. It does not write a live feature metadata column.
snapshot_cell_selection(cell_key) captures the explicit immutable cell input for granular graph
construction. features.normalize(cell_selection, features) requires both exact refs. It saves the
values of the assay’s normed with its configured normMethod. A log_transform or
renormalize_subset left as None is True for the RNA library-size normalizers that apply it, and
False for every other normalizer, whose scale CyteArc cannot know; a flag that the normalizer cannot
apply raises ValueError when True (Assays and metadata API reference).
Direct marker, WAGGR, AUCell, and pseudotime feature analyses likewise require exact refs.
Graph-derived methods require a graph ref and project feature selections through its named lineage edges.
They do not accept a separate feature selection.
Normalize a selection such as the highly variable genes rather than the whole feature universe.
The normalized artifact is a dense float32 matrix of every selected cell and feature, so the
27,998 genes of 3,696 cells take 414 MB before compression, and reduction.pca of more than 4096
features uses its randomized solver, which reads the normalized values once per pass.
cells = ds.snapshot_cell_selection("I")
features = ds.features.hvgs(cells, top_n=2000, show_plot=False)
normalized = ds.features.normalize(cells, features)
diffusion = ds.imputation.diffusion(graph_ref, t=2)
imputed = ds.imputation.compute_imputed("CD4", diffusion)
membership = ds.clusters.membership_strength(cluster_ref, graph_ref)
doublets = ds.qc.doublets(cluster_ref, graph_ref)
imputation.compute_imputed starts with the features and aligns its returned array to the cell selection in the explicit diffusion-operator lineage. It accepts one name or FeatureRef, or a sequence, one-dimensional array, or Series of them. A string that exactly matches a live cell metadata column, including case, diffuses that column; it takes precedence over an assay feature of the same name. Other strings match assay feature names case-insensitively, and a FeatureRef finds a feature by name, ID, or index, as plots and compare.test find features. A name that several features share raises ValueError naming their IDs: FeatureRef(value=feature_id, by="id") imputes one of them, and FeatureRef(value=name, reduction="mean") their mean. A feature that the assay does not hold raises KeyError. Metadata columns need no assay, so from_assay is required only for features from an integrated graph’s operator; a native graph’s operator uses its own assay. A metadata column with a missing value in the operator’s cell selection raises ValueError, because diffusion would spread its stored placeholder to neighboring cells. imputation.diffusion raises MemoryError before persisting an operator that could not be formed or loaded again within the datastore memory budget. imputation.load_diffusion(ref) exposes the validated sparse operator for direct matrix work. Membership strength and doublet detection consume exact cluster and graph refs and return artifacts.
compare.compute_bulk(groups, ...) accepts a categorical cell artifact or a user-owned metadata column name.
Artifact inputs derive their cell selection from lineage; cell_selection= can restrict that
selection explicitly. A metadata column without cell_selection= snapshots the live I column.
secondary_groups= provides an optional nested grouping without writing artifact labels to a cell
column. Mean profiles fit the assay normalization once over every selected cell, so ATAC document
frequency and ADT CLR geometric means are shared by all groups. Each mean averages the group’s rows
of the assay’s normed values, so a cell without counts adds zeros and still counts toward its
group’s size. A mean or floating-point sum that is not finite, such as one from a custom
normalization that returns NaN, raises ValueError naming the group and the feature index. RNA
means also raise ValueError when a selected cell’s <assay>_nCounts total is negative or not
finite. Cells whose group or sub-group label is recorded as missing join no group, as values in
null_vals do.
The call returns a BulkProfiles record: profiles, the features-by-columns profiles; columns, one row per bulk column with its n_cells as int64, so a downstream count model can weight or drop small pseudobulk samples; and, with count_detected=True, detected, the int64 number of each column’s cells whose raw count of each feature is above zero, which detected_fraction divides by n_cells. A bulk column is labeled by its group label, or by a pandas MultiIndex of the levels group, subgroup and replicate (numbered from 1) when the call passes secondary_groups= or pseudo_reps above 1, and profiles, detected and columns share these labels. Labels are never joined into text, so the groups a_b with sub-group c and a with sub-group b_c make two columns, and numeric labels stay numbers. A bulk column without cells, such as a group and sub-group combination that no cell has or a pseudo-replicate of a group with fewer cells than pseudo_reps, is left out rather than returned as a profile of zeros; remove_empty_columns=False keeps such columns, with NaN profiles, no detecting cells, and n_cells 0. pseudo_reps must be an integer of at least 1 and feature_label one of "index", "id", or "name"; other values raise before anything is read.
add_grouped_assay(groups, assay_label=...) similarly accepts a
pseudotime-aggregation ref or an explicit feature metadata column when constructing a new assay.
An aggregation ref groups only the features it clustered, and missing metadata values never form a
group. The source normalization is fitted on the cells that the source assay measured, and other
cells get zero means.
add_grouped_assay and add_melded_assay make the new assay visible only after its counts are
complete. A write that fails with an error removes the partial assay. A pending assay stays when
the write is interrupted, as by KeyboardInterrupt, when the process is killed, or when the final
write that publishes the assay fails, because that write is never undone. Opening ignores a pending
assay, repacking refuses it, and it blocks its name in every workspace; after confirming that no
process is writing it, remove it with discard_interrupted_assay(assay_label).
The new assay has a row for every cell and measures the cells that its source assay measured. When
the source records them in its membership column <source>_I, the new assay’s <assay_label>_I is
a copy, written with the assay and removed with a failed or discarded one; a source without the
column gives an assay without one, which measures every cell (Assay membership). A cell
column that already has the name <assay_label>_I makes both methods raise ValueError before
they compute anything.
cytearc.datastore.namespaces.QcAccessor.auto_filter() defaults to method="mad"
over the pooled selection. Supplying sample_column estimates MAD bounds separately per sample.
n_mads controls the bounds; groups with fewer than min_cells_per_sample=20 active cells
are retained with a warning, including small pooled selections. Pass method="gaussian"
explicitly to use the former pooled Gaussian policy and configure its min_p and max_p
quantiles. Changing these probabilities with either MAD path raises an error.
cytearc.datastore.namespaces.QcAccessor.doublets() scores and calls doublets the way Scrublet does, within each sample of sample_column, the column of each cell’s capture: doublets are simulated from pairs of the sample’s own cells and every cell is scored against its sample’s cells and simulated doublets only, so no doublet pairs cells of two captures. The simulated doublets of an RNA assay are projected onto the graph’s PCA, and those of an ATAC assay are weighted by TF-IDF and projected onto its LSI. Each sample gets its own automatic threshold on its simulated doublets’ scores, or the given threshold. The doublet_score artifact holds the score in values, the fraction of simulated doublets among a cell’s neighbors in raw_scores, and the calls in predicted_doublets; its samples attribute lists each sample’s threshold, calls, and estimated doublet rate (Doublet detection):
doublets = ds.qc.doublets(cluster_ref, graph_ref, sample_column="sample")
singlets = ds.select_cells(doublets, value="predicted_doublets", include=[False])
ds.artifacts.load(doublets).attrs["samples"] # thresholds and calls per sample
qc.filter and qc.auto_filter apply the same rules as pipeline filtering. A cell whose
metric is recorded as missing in a nullable column or artifact never passes a filter and does not
inform automatic bounds. MAD filtering rejects missing sample labels among active cells. Automatic
bounds reject non-finite metric values, such as the undefined percentages of zero-count cells, and
every filter raises when no cell remains.
cytearc.datastore.datastore.DataStore.select_cells() thresholds the numeric values of an
exact cell-aligned artifact, or retains categorical values with include=[...], and composes the
result with its stored source selection. It reads the kind’s canonical array
(Read per-cell values), such as values of a quality metric, phase of a cell-cycle
artifact, labels of a Paris cut, or pseudotime of a pseudotime artifact, or the other per-cell
array that value= names, such as predicted_doublets of a doublet score, and refuses a kind
that is not cell-aligned. The selection records the name of an array other than the canonical one.
An explicit
cell_selection= may narrow, but never widen, that source selection. Cells whose value the
artifact records as missing are never selected, and a selection that retains no cell raises.
Doublet detection, markers.search, clusters.membership_strength, and clusters.relabel_by_overlap reject label
artifacts with missing labels before reusing or writing a result. For markers.search, select
the labeled cells with select_cells(labels, include=[...]) and freeze their labels with
snapshot_cluster_labels(labels, cell_selection=...). For clusters.relabel_by_overlap, freeze both label
artifacts over one selection of the cells labeled in both. Doublet detection and
clusters.membership_strength need a label for every cell of the graph. Build the graph over labeled
cells only when some of its cells have no label, then freeze the labels over the cell selection
that the graph was built from, such as run["analysis_cell_selection"] of a pipeline run.
cytearc.datastore.datastore.DataStore.snapshot_cluster_labels() freezes one label for each cell of an explicit cell_selection into a datastore-scoped cluster_labels artifact. Label consumers accept it like a clustering, among them markers.search, compare.compute_bulk, select_cells, compare.test, clusters.relabel_by_overlap, and clusters.compute_concordance. The labels come from a cell metadata column, such as an annotation or a condition, or from a cell-label artifact, such as a clustering, a Paris cut, or imported clusters. An artifact is read for a subset of its own cell selection, so its labels can be narrowed to the labeled cells or to some of its clusters. Floating-point labels that are whole numbers within the int64 range, such as the float64 ids that pandas writes for integer ids with missing values, are stored as int64, and other floating-point labels raise TypeError. Every selected cell needs a label: a missing label, including a row that a linked missing mask flags, or a blank label raises ValueError. Text is stored at the width of the selected labels, and integer and boolean labels keep their dtype. The identity holds the source column name or source artifact, the cell selection, and a fingerprint of the stored labels, so the same labels reuse one artifact, also from a read-only store, and changed labels create a new one while earlier snapshots keep their values. A new snapshot keeps the categories that its source records when it is made, as the levels, ordered and display attributes of its array: the categories of a categorical column or of a column imported from a categorical, in their order, unused ones included, whether they are ordered, and the colors and labels that an H5AD import keeps, or those that a label artifact records, such as an imported clustering. Plots and exports of the snapshot draw and write its categories as those of its source. Whole-number float categories are stored as int64, as the labels are, and other float categories are left out; a source of more than 10,000 categories keeps none, as an H5AD import keeps none for such a column. The categories are no part of the identity, so a reused snapshot keeps the categories that it was made with, and one that an earlier release made holds none and draws as before. On a mounted store the artifact is written to the target.
For example, rank the genes that separate disease from normal cells within one annotated cell type of a mounted store:
ds = cytearc.mount_datastore(source_path, at=target_path, default_assay="RNA")
cell_type = pd.Series(ds.cells.fetch_all("cell_type"), index=ds.cells.fetch_all("ids"))
ds.cells.insert("is_t_cell", cell_type == "T cell", overwrite=True)
t_cells = ds.snapshot_cell_selection("is_t_cell")
disease = ds.snapshot_cluster_labels("disease", cell_selection=t_cells)
screen = ds.markers.search(disease, features=ds.features.universe(from_assay="RNA"))
ds.markers.load(screen, group_id="COVID-19")
This screen is descriptive: it treats every cell as an independent observation, although cells of
one donor are not. To test a condition, aggregate cells to donors, for example with
compare.test(genes, CellField("disease"), cell_selection=t_cells, sample_by="donor_id"),
as in Compare biological conditions across donors.
Nullable metadata columns keep a stored placeholder in each row that their linked missing mask
flags. cells.fetch and cells.fetch_all return stored values, placeholders included.
cells.to_pandas_dataframe, cells.head, get_cell_vals, plots, and exports show those rows as
missing: numeric columns become float64 with NaN, and other columns hold a missing value.
sift and multi_sift never select them. imputation.compute_imputed and cytearc.metrics.silhouette_scoring
reject a live column with a missing value among the cells they use.
cytearc.metadata.MetaData.insert() writes such a column. Values given only for the rows that
key selects ("I" by default) leave the other rows missing, holding empty text, NaN, 0,
False, or NaT; values for every row keep every row.
The cell table takes per-cell values only as a pandas Series keyed by cell ID: its index must hold exactly the ids of those rows, in any order, and each value lands on the cell with its ID, so annotations from a table in another order, such as an AnnData’s obs, land on the right cells. A store’s cells need not be in the order of values computed elsewhere, as a merge reorders them, so the cell table refuses values that would land on cells by position: arrays, lists, tuples, a bare pd.Categorical or other pandas array, and a Series with a RangeIndex raise TypeError. A Series whose labels are not exactly those ids, such as repeated labels or the row positions of a frame read with key, raises ValueError. Key values computed in store order by the ids of their rows:
ids = ds.cells.fetch_all("ids")
log_counts = np.log1p(ds.cells.fetch_all("RNA_nCounts")) # one value per cell, in store order
ds.cells.insert("log_counts", pd.Series(log_counts, index=ids))
ds.cells.insert("cell_type", adata.obs["cell_type"]) # keyed by adata.obs_names
# scores holds one value per cell of I, in store order; the other cells are left missing.
ds.cells.insert("score", pd.Series(scores, index=ds.cells.fetch("ids", key="I")), key="I")
update_key takes its values the same way. Feature tables keep positional values, because feature order does not change: ds.RNA.feats.insert also assigns arrays, lists, and a Series with a RangeIndex by position, and values.to_numpy() assigns a Series by position there.
to_pandas_dataframe raises KeyError for a column that the table does not hold, and grep returns the stored names that match, so names that differ only in case stay distinct. None, NaN, pd.NA, and NaT among object, categorical, nullable, or string values are missing too, and those values are typed as imports type them: bool, int64, float64, complex128, or else text; object integers outside the int64 range raise ValueError, and so does a value that is a list, tuple, set, dict, array or other collection, naming the column and the first row that holds one, since a column holds one value per row; a zero-dimensional array counts as the value it holds, and NumPy’s masked constant is missing. To store lists, tuples or one-dimensional arrays as text, pass text that keeps every element and the missing rows, such as values.map(lambda v: ",".join(map(str, v)), na_action="ignore"), which the refusal of such values suggests. An explicit fill_value is stored as a real value without a mask and must fit the values: text for text, which widens the column, a bool for a Boolean column, an integer within range for integers, a real number that is not a bool for floating-point values, and a datetime without a time zone or a timedelta that the unit of datetime or timedelta values holds exactly; anything else raises ValueError before the store changes. I, ids, and names never hold a missing value. A boolean column with masked rows selects the same cells as one filled with False, so selections snapshotted from it keep their identity, while metadata snapshots and filters over it record its mask. Replacing a column reads the previous column, its attributes, and its mask first; if writing the new column fails or is interrupted, the previous one is written back before the error propagates. When that also fails, a note on the error names the column.
Pandas categorical values, a Series of categorical dtype or, in a feature table, a pd.Categorical, are stored as a categorical column: each row’s code, -1 for a missing row, in the smallest signed integer type that holds it, beside the categories, every category in its order with whether they are ordered (Categorical columns). The categories are typed together, as other values are, so categories that read alike once stored, such as 1 and "1", raise ValueError, and an explicit fill_value must be one of them. I, ids and names store the labels of categorical values. Every read returns the labels of either layout: fetch, fetch_all, to_pandas_dataframe, artifacts.load_values of a CellField, groupings and plots read a categorical column as they read a text column of the same labels, and the fingerprints that results record of those labels are the same, apart from the stamp of stored chunks that clones.from_column records. Plots draw the categories of an ordered categorical column in their stored order, and sort those of an unordered one naturally, as they sort a text column (Plotting API reference). to_anndata and to_h5ad export a categorical column as an AnnData categorical of its codes and categories, every category in its stored order with whether they are ordered (Import and export API reference). cytearc.metadata.MetaData.fetch_categorical() returns a column’s labels for the rows that key selects, or for every row with key=None, as a pandas Categorical: the codes and categories of a categorical column as stored, unused categories included, and for another column its distinct values as unordered categories, numbers ascending and text in the natural order of plots.
labels = pd.Categorical(labels, categories=["T cell", "B cell", "NK cell"])
ds.cells.insert("cell_type", pd.Series(labels, index=ds.cells.fetch_all("ids")))
cell_type = ds.cells.fetch_categorical("cell_type", key=None)
cell_type.codes, cell_type.categories
The cell table reserves the membership column <assay>_I of every assay of the store, which only
imports, merges, and derived assays write (Assay membership). insert, with or without
overwrite, update_key, and reset_key raise ValueError for that name whether or not the
column exists, and drop raises for a column that carries the membership role, because a store
without it counts every cell as measured. A plain column of that name without the role can be
dropped.
A cell that an assay did not measure holds zero counts of the assay, which are no measurement, so
an operation that reads the assay’s values refuses it. Normalization, integration.modalities, HVG and
detected-feature selection, WAGGR, AUCell, marker search, compare.compute_bulk, the feature keys of
compare.test, prevalent peaks, cell-cycle scoring, feature percentages, HTO
demultiplexing, doublet detection, pseudotime markers and aggregation, the feature names of
imputation.compute_imputed, mapping.run of the query assay, and to_anndata(matrix="normed")
without a run check their cells against the membership column after their own argument and
assay-type checks and before they reuse or write anything, on a read-only store too, and raise
UnmeasuredCellsError, a ValueError that names the
operation, the assay, the column, and how many of the selected cells the assay did not measure.
The pipeline recipes pipeline.rna, pipeline.atac, and pipeline.adt check their cells the
same way before they write anything; as recipes write, they first need a store opened with
zarr_mode="r+".
compare.compute_bulk checks the cells whose counts it reads: the cells of its bulk columns, or every selected
cell for a mean that fits the assay’s normalization over them, as ATAC and ADT means do; for a
metadata grouping without cell_selection, it finds them from the live I column before it
snapshots I. Quality control reads the assay of each metric that it filters on:
qc.auto_filter, qc.filter on such a column, and the filtering stage of a pipeline recipe
refuse unmeasured cells too. A cell
column is a metric of the assay whose preparation wrote it, <assay>_nCounts,
<assay>_nFeatures, or a percentage column that the assay records in its percentFeatures
attribute, such as RNA_percentMito; a quality_metric artifact of an assay is a metric of that
assay; other columns read no assay. Operations that read only other results or metadata (such as
PCA, graphs, clustering, and snapshot_cluster_labels) and derived assays do not check. Exports
that declare membership, to_h5ad and to_anndata without layers, keep unmeasured cells; to_mtx
and a to_anndata layer of another assay cannot declare it and refuse them.
select_measured_cells() keeps the measured cells of
a selection: pass its result as cell_selection, which compare.compute_bulk, compare.test,
and the QC filters also take directly, build graphs over it, or freeze labels over it with
snapshot_cluster_labels(labels, cell_selection=...). A pipeline recipe takes that selection as
its cells, or a boolean column. Normalized export takes a cell_key column instead. Either
column must be True only for the cells of I that the assay measured, such as
ds.cells.insert("RNA_measured", pd.Series(ds.cells.fetch_all("I") & ds.cells.fetch_all("RNA_I"), index=ds.cells.fetch_all("ids"))); the
membership column alone also holds cells that a filter removed from I. select_measured_cells
returns the input selection itself when the assay measured every selected cell, so fully measured
stores keep their identities. Plots and get_cell_vals show the feature values of unmeasured cells
as missing, NaN, instead of zero, and normalize only the measured cells, so that a normalizer
fitted over the cells it reads, such as ATAC TF-IDF, gives a measured cell the value of a read of
the measured cells alone. Opening saved results does not rerun membership checks; a pipeline
recipe whose cells include unmeasured cells raises before it creates a run record.
A store merged from sources that measured different features records which features each source measured in the feature columns measured_in_<source> (Import and export API reference), and each cell’s source in a cell column of sources, dataset unless the merge’s source_column names another. A feature that a cell’s source did not measure holds zero counts in that cell, which are no measurement, and the readers of the record treat them as follows:
plots and
get_cell_valsshow such a feature as missing in that cell and normalize each feature over the cells whose source measured it;markers.search,features.hvgs,features.prevalent_peaks,features.detected,scores.waggr,scores.aucell,scores.cell_cycle,scores.chromvar,scores.potency,qc.feature_percentage,regulons.grn,trajectory.markers,trajectory.aggregation,trajectory.lineage_markers,trajectory.lineage_aggregation,trajectory.drivers,add_grouped_assay,add_melded_assay,compare.compute_bulk,perturbation.signature,perturbation.mixscape,perturbation.associationsandperturbation.profilesleave out the features that some source of their cells did not measure, with one warning that names how many each source lacks, and raiseValueErrorwhen none remains;scores.potencyleaves them out of its network,add_grouped_assayout of each group, and a group that keeps none out of the new assay,add_melded_assayleaves out the peaks that some source did not call,perturbation.mixscapeleaves them out of its search for DE genes, andperturbation.associationsout of its trans pairs and calibration pairs, and the targets’ genes out of its positive controls with a warning of their own;perturbation.efficiencygives a target whose gene some source of its compared cells did not measure the status"no_feature", as a store of the other genes does, with aDiagnosticWarningthat names the gene and those sources;the percentage columns that preparation writes, such as
<assay>_percentMitoand<assay>_percentRibo, leave out the genes that some source of the assay’s cells did not measure, with the same warning; a column none of whose genes every source measured is unavailable, with a warning that names what each source lacks, and cell filtering, which would otherwise filter on it, warns that it leaves it out, so filter each source’s cells onqc.feature_percentageinstead;HVGs, prevalent peaks, cell-cycle, WAGGR and potency scores, melded assays, the TF-IDF normalization of an ATAC assay and the perturbation efficiency, signatures, Mixscape classes and profiles, which compare cells across sources, divide each cell’s counts by its total over the features that every source of the cells measured, as a store of those features alone does, and record those features, Mixscape’s classes through their signature;
perturbation.associationstakes each cell’s UMIs and detected genes, the depth covariates of its regressions, over the same features; feature percentages, the prepared percentage columns and the library-size normalization of an RNA assay keep each cell’s own total, as its source’s own store gives it. For sources whose gene sets differ a lot, such as a targeted panel and a whole transcriptome, a merge withfeatures="intersection"keeps only the shared genes, so every analysis takes totals over them;mapping.runprojects each query cell on the reference features that its own source measured; the others are missing for that cell and take the fill ofmissing_feature_policy, so each source’s cells map as its own store maps them, and a source that measured none of them is refused, as its own store is;compare.test,imputation.compute_imputed,features.normalize,to_anndata(matrix="normed")andperturbation.associations, for the pairs and positive controls of a table, raiseValueErrorfor such a feature, naming the features and the sources that lack them; select the cells of the sources that measured them, or only the features that every source of the cells measured.
- exception cytearc.metadata.membership.UnmeasuredCellsError(operation, assay, column, unmeasured, selected, remedy=None, cell_key=None)#
An operation would read an assay over cells that the assay did not measure.
- operation#
The refusing operation.
- assay#
The assay that the operation reads.
- column#
The assay’s membership column,
<assay>_I.
- unmeasured#
How many of the selected cells the assay did not measure.
- selected#
How many cells the operation would read.
- remedy#
The input that the message tells the caller to narrow.
- cell_key#
The boolean cell column whose cells the operation reads, or None.
Saved cytearc.datastore.namespaces.MarkersAccessor.search() calls return the exact immutable marker-table reference.
Pass that reference as markers.load(marker=ref) to select the exact feature-specific result.
Marker tables report group_id as a string and list groups in the same order as plot
categories: decimal labels first in numeric order, so "2" precedes "10", then other labels in
natural order, so "1_2" precedes "1_10" and "2_T" precedes "B cell".
markers.export_csv uses the same column order. An unknown group_id raises an error.
Any label names a group, "T/NK", "." and labels beyond ASCII included, and markers.load(group_id="T/NK") selects that group; only a blank label raises ValueError, since CyteArc’s groupings count it as missing. A table whose labels cannot all name a Zarr group stores its groups by code beside the labels (Marker tables).
Fresh marker results include score, expression fractions, fold change, AUC, two-sided Mann-Whitney p-values, and Benjamini-Hochberg values adjusted within each one-versus-rest group over tested features.
These are cell-level marker statistics, not replicate-aware differential expression.
Statistics are stored at full float64 precision. neg_log10_p_value holds -log10 of the
p-value; for the normal approximation it is computed in log space, so it stays finite and keeps
its order where p_value underflows to 0, near a z statistic of 38. A group whose cells can be
split from the other cells in at most 100,000 ways, such as a group of two cells among at most 447,
gets exact p-values from the permutation null of its rank sum, ties included, as compare.test
does; other groups keep the tie- and continuity-corrected normal approximation. A group of fewer
than two cells cannot be compared with the rest: markers.search skips it with a warning that
names it, records it in the table’s skipped_groups metadata, keeps its cells in the rest of every
other group, and markers.load gives it no rows. A clustering without any group of at least two
cells and at least two other cells raises ValueError naming the groups.
Each row of markers.load names its feature by feature_name and by feature_id, the ID that the marker table froze, and gives the feature’s index in the assay as feature_index. The rows of two features that share a name, such as the two MATR3 genes of the 10x Genomics human reference, ENSG00000280987 and ENSG00000015479, stay apart by their IDs. markers.export_csv writes names only.
A marker table of operation revision 1, written before release 1.3.0, records neither
neg_log10_p_value nor p_value_policy. markers.load, markers.export_csv, and
marker_heatmap still read it, from read-only stores too, under an explicit policy: its
statistics keep the five-decimal rounding they were stored with, except for the p-values, which
come from the tie- and continuity-corrected normal approximation for every group, the p-value
policy that the readers report as asymptotic_tie_and_continuity_corrected. Its
neg_log10_p_value is derived as -log10(p_value), and is inf where p_value underflowed to
0. The filters and sort_by apply as to any table. markers.search never reuses such a table: on
a writable store it recomputes it at revision 2, and on a read-only store it raises
PermissionError. A table without p_value_policy that does not have exactly the revision 1
columns, or that records skipped_groups, raises ValueError.
markers.load and markers.export_csv keep a row that passes every filter that is not None:
min_frac_exp=0.2, min_auc=0.6, and max_p_adj=0.05 by default, on frac_exp, auc, and
p_value_adjusted. min_score defaults to None. score is a group’s share of the mean dense
ranks summed over all groups, so a gene that is uniform across groups scores 1/n_groups, and a
gene with distinct values in the n cells of one group and zero elsewhere scores
(n + 3) / (n + 1 + 2 * n_groups). A fixed score threshold therefore hides perfect markers of
small groups and of fine partitions:
LILRA4 in the plasmacytoid dendritic cells of a 60-group partition of 1,000 PBMCs has an AUC of 1.0
and a score of 0.125. Pass None for every filter to read every tested feature, negative markers
included. sort_by orders the rows of each group: "score" (the default), "auc", or
"fold_change" descending, or "p_value" ascending. Ties fall to the p-value, with
neg_log10_p_value ordering p-values that underflow to 0, except that ties in "p_value" fall to
the AUC so that positive markers come first; then to the feature name and index.
fold_change is the group’s mean divided by mean_rest, the means of the values that the
search ranks. It is inf for a feature that no other cell expresses, so such features sort above
every finite ratio, and NaN when both means are 0 or either is negative, as signed counts can
give. Every other statistic is finite, except the derived neg_log10_p_value of a revision 1
table. The ranked values are the assay’s normalized values, such
as library-size normalized RNA counts, log-scale with log_transform=True, CLR values of ADT
counts, which are log-scale too, or TF-IDF values of ATAC counts. No pseudocount is added, and
fold changes compare only within one assay and normalization. Marker tables record this policy in
their fold_change_policy metadata. markers.load, markers.export_csv, and marker_heatmap
raise ValueError for tables missing that policy; recompute them with markers.search.
Marker search reads raw counts of any storage dtype. Library-size markers require finite
non-negative counts and cell totals: a negative or non-finite normalized value of a tested feature,
or total of a selected cell (its <assay>_nCounts value, or with renormalize_subset=True its sum
over the tested features), raises ValueError before anything is written.
Every marker, pseudotime-marker, and pseudotime-aggregation search ranks or correlates the values
of the assay’s normed with its configured normMethod. Their log_transform and
renormalize_subset default to False; log_transform=True takes log1p of the normalizer’s own
output, and a flag that the normalizer cannot apply, such as log_transform=True with ADT CLR or
ATAC TF-IDF, raises ValueError (Assays and metadata API reference). The artifact records the resolved flags.
cytearc.datastore.namespaces.TrajectoryAccessor.markers() leaves untested features with r_value 0.0 and NaN for p_value and p_value_adjusted, and adjusts p-values over tested features only.
cytearc.datastore.namespaces.CompareAccessor.test() computes Mann-Whitney
p-values from the exact permutation null, ties included, when the two groups can be formed in at
most 100,000 ways, as in typical sample-level designs. Larger designs keep the marker-search normal
approximation. StatisticalTestResult.p_value_method records "exact" or "asymptotic", and a
saved Mann-Whitney result without that record must be recomputed. A StudyDesign pairing column
applies only to the paired Wilcoxon test; for subjects nested within conditions, pass the subject
column as sample_by. Writing a result requires zarr_mode='r+' and is checked before any value
is computed, while a matching saved result is still reused from a read-only store.
cytearc.datastore.namespaces.ScoresAccessor.waggr() and
cytearc.datastore.namespaces.ScoresAccessor.aucell() match network targets to active feature
names without case sensitivity. A target that matches several active features, such as a gene
symbol shared by two feature ids, is ambiguous. The default ambiguous_targets="drop" removes its
edges before tmin pruning, logs a warning, and records the target in the artifact’s
dropped_ambiguous_targets attribute; ambiguous_targets="error" raises instead. Both producers
require zarr_mode='r+' and an intact prepared dataset identity.
cytearc.datastore.namespaces.TrajectoryAccessor.aggregation() aggregates and clusters
features before it starts an artifact. It raises ValueError, and leaves no incomplete artifact,
when too few features pass min_exp or when n_clusters is greater than one but smaller than the
number of disconnected components of the feature neighbor graph. Modules tied at the cut height are merged so that exactly
n_clusters modules are returned.
cytearc.datastore.namespaces.TrajectoryAccessor.fate() treats solver_tol as an absolute
bound on the largest Bellman residual of each solved sink column, so large sink groups do not
loosen the solve.
modalities() is the public SNN/WNN graph integration entry point.
WNN requires two or more cell-aligned assays and stores one per-cell weight for each assay.
SNN also requires two or more explicit connectivity-map refs.
ds.pipeline.multimodal(runs) runs this integration over completed modality runs of the same
cells and records a durable run (Analysis pipeline API reference).
The recommended workflow is in Read RNA and protein together with CITE-seq; method comparison and diagnostics are in Compare multimodal integration methods.
Analysis results#
- class cytearc.FateMappingResult(ref, graph, pseudotime, sink_labels_artifact, cell_selection, sink_labels, values, valid, direction=None)#
Fate probabilities loaded from an immutable artifact.
The walk of a fate map is directed by a pseudotime, which
pseudotimenames, or by a per-cell score, whichdirectionnames; the other is None.
- class cytearc.PseudotimeScoreResult(ref, graph, cell_selection, values, valid, component, component_sizes)#
Pseudotime values loaded from an immutable artifact.
componentgives each cell’s connected component of the graph, numbered by decreasing size, andcomponent_sizesthe components’ cell counts, largest first; each component holds a cell. Thevalidcells form the scored component.
- class cytearc.PseudotimeMarkerResult(ref, table, assay, cell_selection, feature_selection, pseudotime)#
Pseudotime correlation table loaded from an immutable artifact.
- class cytearc.PseudotimeAggregationResult(ref, data, feature_indices, feature_clusters, assay, cell_selection, feature_selection, pseudotime)#
Lazy pseudotime aggregation loaded from an immutable artifact.
- property feature_ids: ndarray#
Frozen feature IDs aligned to the aggregation rows.
- property feature_names: ndarray#
Frozen feature names aligned to the aggregation rows.
- class cytearc.trajectory.PotencyResult(ref, cell_selection, graph, measure, smoothing, species, network, genes_matched, genes_used, edges_used, matched_by, differentiation, potency, signaling_entropy, ccat)#
Potency scores loaded from an immutable artifact.
Each array holds one value per cell of
cell_selection, in its order.potencyis the rank in [0, 1] of themeasure, smoothed overgraphwhen a graph smoothed it, anddifferentiationis one minuspotency, so it rises along the process and directsds.trajectory.fateas it stands.signaling_entropyandccathold both raw measures, unsmoothed, whichever of them ranks the cells.networknames the network’s source, version, file name and SHA-256 digest;genes_matchedcounts the network genes that the assay’s features matched, bymatched_by("ensembl_id"or"symbol"), andgenes_usedandedges_usedthe largest connected part of them, over which the scores were computed.
- class cytearc.trajectory.LineageMarkerResult(ref, table, assay, lineages, effective_cells, cell_selection, feature_selection, fate)#
Fate-weighted associations of features with pseudotime, per lineage.
tableholds one row per tested or untested selected feature and lineage.effective_cellsgives each lineage’s Kish effective number of cells, which its p-values use.
- class cytearc.trajectory.LineageDriverResult(ref, table, assay, lineages, n_cells, cell_selection, driver_cells, feature_selection, fate)#
Correlations of features with each lineage’s fate probability.
tableadds the Fisher-z confidence interval of each correlation,ci_lowandci_high.n_cellscounts the cells that were correlated, anddriver_cellsis the selection they were drawn from.
- class cytearc.trajectory.LineageAggregationResult(ref, data, feature_indices, feature_clusters, feature_names, feature_ids, lineages, bin_pseudotime, lineage_weight, assay, cell_selection, feature_selection, fate)#
Fate-weighted feature profiles along each lineage, with feature modules.
dataholds the retained features by lineages by bins. Each lineage’s bins split its fate weight into equal parts along pseudotime;bin_pseudotimeis the weighted mean pseudotime of each bin andlineage_weighteach lineage’s total weight.
- class cytearc.trajectory.LineageCurvesResult(ref, fate, coordinates, cell_selection, lineages, points, curve_pseudotime, progress, distance, weights, valid)#
Fate-weighted curves through reduced coordinates, one per lineage.
pointsholds lineages by points by dimensions in the space ofcoordinates, andcurve_pseudotimethe fitted pseudotime of each point.progressanddistanceplace every scored cell on every curve, cells by lineages, andweightsholds the fate probability with which each cell weighed in each curve’s fit; unscored cells hold NaN and a falsevalid.- property curve_progress: ndarray#
The rank of each curve point, from zero to one.
- project(coordinates, *, nthreads=1)#
Place rows of coordinates on every curve.
coordinatesmust lie in the space the curves were fitted in, with one column per dimension ofpoints, such as rows of the same reduction for cells that were not scored. Rows are projected in parallel overnthreadsthreads.- Raises:
ValueError – If the coordinates are not finite or have the wrong number of dimensions.
- Return type:
- class cytearc.trajectory.CurveProjection(lineages, progress, pseudotime, distance)#
Positions of cells on lineage curves.
Each array is cells by lineages.
progressis the rank of the nearest curve point, from zero at the start to one at the sink;pseudotimethe curve’s fitted pseudotime there; anddistancethe Euclidean distance to it.
- class cytearc.trajectory.LineageTreeResult(ref, labels, coordinates, cell_selection, clusters, sizes, means, edges, root, ends, leaves, lineages)#
A minimum spanning tree over clusters and the lineages it proposes.
edgeslists the tree’s edges by cluster label with their Slingshot distance.leavesare clusters joined to one other cluster; with a root,lineagesare the paths from it to the other leaves. Leaves are candidates for sinks, not discovered fates: a tree must join every cluster, so similar terminal clusters can be chained.- property candidate_sinks: tuple[Any, ...]#
Leaves other than the root, the clusters to check as sinks.
- class cytearc.trajectory.ClusterTree(clusters, sizes, means, edges, root, ends, leaves, lineages)#
A minimum spanning tree over clusters and the lineages it proposes, built without a store.
build_cluster_tree()returns it, with the fields of theLineageTreeResultthatds.trajectory.lineage_treesaves, less the artifacts that a saved tree records.clustersholds the cluster labels in their natural order,sizesthe cells of each cluster andmeansits mean coordinates.edgeslists the tree’s edges by cluster label with their Slingshot distance.leavesare clusters joined to one other cluster; with a root,lineagesare the paths from it to the other leaves. Leaves are candidates for sinks, not discovered fates: a tree must join every cluster, so similar terminal clusters can be chained.- property candidate_sinks: tuple[Any, ...]#
Leaves other than the root, the clusters to check as sinks.
- class cytearc.trajectory.LineageMembershipResult(ref, curves, cell_selection, lineages, labels, members, valid, distance_limits, branch_points, trunk_probabilities)#
Which lineages each cell follows, and where each pair of lineages parts.
labelsnames, for each cell ofcell_selection, what it follows: the text of one lineage’s sink label,"shared"for several lineages, or"none".membersholds the lineages that each cell follows, cells by lineages, and unscored cells follow none with a falsevalid.distance_limitsholds, lineages by bins of progress, the farthest distance from each curve that lies on it.branch_pointsholds one row per pair of lineages in their order:firstandsecond, thepseudotimeat which they part, thefirst_progressandsecond_progressthere on their curves, and theshared_cellsandparted_cellsthat place the split. A pair that never shares a cell, never parts, or whose shared cells do not come before its parted cells has no branch point and holds NaN.trunk_probabilitiesholds, for each graph component that holds sink cells of the lineages, indexed by itscomponentnumber, each lineage’s trunk probability there: its mean probability over the earliest tenth of the component’s cells outside the sinks. It is NaN where the component holds none of the lineage’s sink cells, or no cell outside the sinks.
- class cytearc.trajectory.TrajectoryStatesResult(ref, graph, direction, cell_selection, labels_artifact, names, labels, memberships, valid, coarse_transitions, table, eigenvalues, crispness)#
The initial, intermediate and terminal states of a walk, loaded from an artifact.
nameslists the states in the order of the walk, earliest mean direction first.labelsgives, for each cell ofcell_selection, the state whose most likely cells it is among, missing elsewhere, andmembershipseach cell’s membership in each state, cells by states, in float32 as stored, NaN outside thevalidcells that the search covered.coarse_transitionsis the walk between the states, each row summing to one.tableholds one row per state: thelabelthat most of its cells hold, which its name repeats with a suffix where states share one, None without labels; itsrole, thecellsthat its name marks, itscell_share, the mean of its memberships, itswalk_share, its share of a long walk’s time, their ratioenrichment, itsstability, the probability that one step of the walk stays in it, and its meandirectionscore rescaled to [0, 1]. The first state is the initial one, and each other state whose enrichment exceeds one is terminal.eigenvaluesholds the walk’sn_states + 1leading eigenvalues, largest real part first, andcrispnesshow little the states overlap, from 0 to 1.- property initial: str#
The name of the initial state, the one that the direction places earliest.
- property terminal: list[str]#
The names of the terminal states, in the order of the walk, to pass to
fateassinks.
- class cytearc.EnrichmentResult(data, source_names, source_sizes, cell_index, artifact, storage_path, assay, cell_selection, feature_selection, method, deviations=None)#
A persisted gene-set or peak-set enrichment result.
- data#
Lazy score matrix with cells as rows and sources as columns. chromVAR stores z-scores here, with NaN where a cell has too few expected fragments in a set.
- source_names#
Source names aligned to the score columns.
- source_sizes#
Matched target counts aligned to
source_names.
- cell_index#
Assay cell indices aligned to the score rows.
- artifact#
Immutable enrichment artifact backing the result.
- storage_path#
Zarr path that owns the result.
- assay#
Name of the assay used for scoring: an RNA assay for WAGGR and AUCell, an ATAC assay for chromVAR.
- cell_selection#
Immutable cell selection used for scoring.
- feature_selection#
Feature-selection artifact used for scoring.
- method#
Enrichment method:
"waggr","aucell", or"chromvar".
- deviations#
chromVAR’s bias-corrected deviations, aligned to
data; None for other methods.
- to_pandas()#
Read the scores as a cells-by-sources DataFrame.
The columns are the source names, and the index holds the assay cell indices in the order of the score rows.
- Return type:
DataFrame
- class cytearc.regulons.GrnResult(adjacencies, regulators, artifact, assay, cell_selection, feature_selection, method, random_seed)#
A persisted transcription-factor to target importance network.
- adjacencies#
One row per link with
TF,target,importance, andcorrelationcolumns, sorted by decreasing importance.correlationis the Pearson correlation of the factor and the target over the scored cells, which pySCENIC uses to separate activating from repressing links.
- regulators#
Names of the factors offered to every target model.
- artifact#
Immutable
grn_adjacenciesartifact backing the result.
- assay#
Name of the RNA assay whose counts were modeled.
- cell_selection#
Cells whose counts were modeled.
- feature_selection#
Genes that were modeled as targets and regulators.
- method#
Inference method,
"grnboost2".
- random_seed#
Random state of every target’s regressor.
- class cytearc.features.statistical.StatisticalTestResult(method, posthoc, adjustment_method, grouping, group_field, sample_by=None, pair_by=None, sample_stat='mean', expression_cutoff=0.0, alternative='two-sided', equal_var=None, n_groups=0, n_cells=0, tested_features=(), summary_scope='cell', artifact=None, cell_selection=None, cell_selection_fingerprint=None, group_fingerprint=None, group_order=(), normalization=<factory>, normalization_method=None, size_factor=None, source_assays=(), source_dataset_fingerprint=None, value_fingerprints=(), sample_fingerprint=None, pair_fingerprint=None, tables=<factory>, posthoc_tables=<factory>, p_value_method=None)#
Statistical tests for one grouping across multiple value keys.
p_value_methodis"exact"or"asymptotic"for Mann-Whitney, chosen by design size as the module docstring describes, andNonefor other tests.
- class cytearc.features.aggregation.BulkProfiles(profiles, columns, detected)#
The bulk profiles of groups of cells, as
compare.compute_bulkreturns them.Each bulk column holds the cells of one group, of one group and sub-group, or of one pseudo-replicate of either, and is labeled by them: by its group label alone, or by a MultiIndex of the levels
group,subgroup, andreplicate(numbered from 1) that the call uses. The columns ofprofilesanddetectedand the rows ofcolumnscarry the same labels, in the same order. Rows ofprofilesanddetectedare features, labeled asfeature_labelasks.- profiles#
Each bulk column’s mean or summed feature profile. A column without cells, kept with
remove_empty_columns=False, holds NaN.
- columns#
One row per bulk column, with
n_cells, its number of cells, as int64.
- detected#
The number of each bulk column’s cells whose count of each feature is above zero, as int64, or None unless the call passed
count_detected=True.
- property detected_fraction: DataFrame#
The share of each column’s cells that detect each feature.
It divides
detectedbyn_cells, so a column without cells holds NaN.- Raises:
ValueError – If the cells that detect each feature were not counted.
- class cytearc.clustering.ParisClusteringResult(labels, mode, n_clusters, diagnostics=(), min_cluster_size=None, hierarchy_artifact_id=None, ref=None)#
Labels and diagnostics returned by a Paris cut.
refis set when the cut was written to a store and staysNonefor cuts produced directly from a hierarchy.
- class cytearc.clustering.ParisClusterDiagnostic(label, selected_node, parent_event, component, size, resolution_lower, resolution_upper, persistence, forced, blocking_child_count, folded_cell_count, decision_margin)#
Structural diagnostic for one selected Paris cluster.
- class cytearc.clustering.connectivity.ClusterConnectivity(nodes, edges)#
The graph weight between each pair of clusters.
- nodes#
One row per cluster, in the order of its categories:
category, the cluster’s label;nCells, its number of cells; andincidentWeight, the summed weighted degree of its cells, edges within the cluster included.
- edges#
One row per pair of clusters that the graph joins:
sourceandtarget, the clusters’ labels, the source first in the order ofnodes;rawWeight, the summed weight of the edges between their cells, each undirected edge once; andnormalizedWeight,rawWeightdivided bysqrt(incidentWeight[source] * incidentWeight[target]), or 0 when either incident weight is 0. Rows sort by source, then target, in the order ofnodes.
- class cytearc.quality_control.cell_calling.EmptyDropsResult(barcodes, total, log_probability, p_value, fdr, limited, ambient, lower, retain, knee, inflection, alpha, n_iter, random_seed, n_ambient)#
EmptyDrops statistics of every barcode.
Arrays hold one value per barcode, in input order. Barcodes at or below
lowerare not tested: their statistics are NaN andlimitedis False. Barcodes at or aboveretainare cells with p-value 0.- barcodes#
Barcode identifiers, or None when the input had none.
- total#
Total count of each barcode.
- log_probability#
Log-probability of the barcode’s counts under the ambient Dirichlet-multinomial model.
- p_value#
Monte Carlo p-value against the ambient model.
- fdr#
Benjamini-Hochberg adjusted p-value over the tested barcodes.
- limited#
True where no simulated count vector was as improbable as the barcode, so the p-value is the smallest that
n_iteriterations give and more iterations could lower it.
- ambient#
Good-Turing proportion of each feature in the ambient pool; features without counts in any barcode have 0.
- lower#
Bound of the ambient pool.
- retain#
Barcodes with at least this total were retained.
- knee#
Total at the knee of the barcode-rank curve, or NaN.
- inflection#
Total at the inflection of the barcode-rank curve, or NaN.
- alpha#
Estimated or given Dirichlet-multinomial precision, or None when the ambient pool fits a multinomial best.
- n_iter#
Monte Carlo iterations.
- random_seed#
Seed of the simulations.
- n_ambient#
Barcodes with a total from 1 to
lower.
- is_cell(fdr=0.001)#
Return True for each barcode whose adjusted p-value is at most
fdr.- Raises:
TypeError – If
fdris not a real number.ValueError – If
fdris not greater than 0 and at most 1.
- Return type:
ndarray
- to_pandas()#
Return the tested barcodes with their statistics, one row each.
- Return type:
DataFrame
- class cytearc.quality_control.cell_calling.BarcodeRanks(rank, total, fitted, knee, inflection, lower)#
The barcode-rank curve with its knee and inflection points.
Barcodes are ranked by decreasing total count; tied totals share their average rank. The curve is a cubic smoothing spline of
log10(total)againstlog10(rank)over the distinct totals abovelower. The inflection point is the total where the fitted curve falls most steeply, and the knee is the total, at or above the inflection, where its signed curvaturef'' / (1 + f'^2)^1.5is lowest: the bend from the cell plateau into the drop towards empty droplets (Lun et al. 2019).- rank#
Average rank of each distinct total, in increasing order.
- total#
The distinct totals, in decreasing order.
- fitted#
Fitted total at each rank above
lower, and NaN at the rest.
- knee#
Total of the barcodes at the knee, or NaN when fewer than five distinct totals exceed
lower.
- inflection#
Total of the barcodes at the inflection point, or NaN.
- lower#
Totals at or below this bound were left out of the fit.
- to_pandas()#
Return the curve as a table with
rank,total, andfitted.- Return type:
DataFrame
Inheritance appendix#
These implementation classes are not intended for analysts to construct directly.
- class cytearc.datastore.base_datastore.BaseDataStore(zarr_loc, assay_types, default_assay, min_features_per_cell, mito_pattern, ribo_pattern, zarr_mode, workspace, resources, storage_profile, storage_options=None, storageIo=None, source_storage_options=None)
This is the base datastore class that deals with loading of assays from Zarr files and generating basic cell statistics like nCounts and nFeatures. Superclass of the other DataStores.
- Parameters:
zarr_loc (
str|Store) – Path to Zarr file created using one of writer functions of CyteArcassay_types (
dict[str,str] |None) – A dictionary with keys as assay names present in the Zarr file and values as either one of: ‘RNA’, ‘ATAC’, ‘ADT’, ‘HTO’, ‘CRISPR’, ‘ANTIGEN’, ‘CUSTOM’, ‘GeneActivity’, ‘GeneScores’, ‘URNA’ or ‘Assay’. A read-only open cannot change an assay’s type.default_assay (
str|None) – Name of assay that should be considered as default. It is mandatory to provide this value when DataStore loads a Zarr file for the first timemin_features_per_cell (
int|None) – The first writable open of a store removes fromIevery cell whose default-assay feature count is not greater than this value, 10 when None, unless that would remove at least half of the active cells, and records the value it applied in the cell table. Later opens never filterI.mito_pattern (
str|None) – Feature-name pattern for the{assay}_percentMitocolumn of each RNA assay. The first writable open replaces any existing column with values computed from this pattern, or^MT-when None. Later opens keep the stored values when None and reject a pattern that differs from the recorded one.ribo_pattern (
str|None) – The same for{assay}_percentRibo, using^RPS|^RPL|^MRPS|^MRPLwhen None.zarr_mode (
Literal['r','r+','a','w','w-']) – For read-write mode user+or for read-only user. (Default value:r+)workspace (
str|None) – Workspace name within the Zarr store (None for legacy single-workspace layout).resources (
ResourceBudget) – Resolved memory and worker budget for this datastore.storage_profile (
Literal['fast_local','cloud']) – Zarr encoding profile used for new arrays written through this datastore.storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.storageIo (
Any|None) – Optional explicit read, compute, and write widths for storage work. Unset values stay under automatic planning.
- cells
MetaData object with cells and info about each cell (e. g. RNA_nCounts ids).
- nthreads
Number of threads to use for this datastore instance.
- z
The Zarr file (directory) used for this datastore instance.
- class cytearc.datastore.graph_datastore.GraphDataStore(zarr_loc, assay_types, default_assay, min_features_per_cell, mito_pattern, ribo_pattern, zarr_mode, workspace, resources, storage_profile, storage_options=None, storageIo=None, source_storage_options=None)
This class extends BaseDataStore by providing methods required to generate a cell-cell neighborhood graph.
It also contains all the methods that use the KNN graphs as primary input like UMAP/tSNE embedding calculation, clustering and trajectory analysis.
- cells
List of cell barcodes.
- nthreads
Number of threads to use for this datastore instance.
- z
The Zarr file (directory) used for this datastore instance.
- class cytearc.datastore.mapping_datastore.MappingDatastore(zarr_loc, assay_types, default_assay, min_features_per_cell, mito_pattern, ribo_pattern, zarr_mode, workspace, resources, storage_profile, storage_options=None, storageIo=None, source_storage_options=None)
This class extends GraphDataStore by providing methods for mapping/ projection of cells from one DataStore onto another. It also contains the methods required for label transfer and mapping score generation.