Analysis pipeline API reference#
DataStore.pipeline runs CyteArc’s modality recipes and records each run in the datastore. A call
that fails its checks writes nothing
(Validation before a run starts), and plan reports what a call
would reuse and compute without running it (Plan a call). rna, atac, and adt each
analyze one assay, multimodal integrates completed runs of the same cells, and perturbation
analyzes a pooled CRISPR screen from its RNA and guide assays. Each recipe
returns a durable, read-only PipelineRun whose outputs are exact immutable
ArtifactRef values.
A datastore-bound handle for one durable pipeline invocation. |
|
A narrow, immutable view over one completed pipeline-run axis. |
|
A handled pipeline failure with a durable run identifier. |
|
A pipeline run that stopped because its CancellationToken was cancelled. |
|
Ask a running pipeline to stop at its next safe checkpoint. |
|
Send the events of every pipeline run started in this context to |
|
Store-bound entry point for CyteArc's durable modality recipes. |
|
Analyze an RNA assay and return the durable run. |
|
Analyze an ATAC assay of peak counts and return the durable run. |
|
Analyze an ADT (antibody) assay and return the durable run. |
|
|
Integrate completed modality runs of the same cells into one graph. |
|
Analyze a pooled CRISPR screen and return the durable run. |
Report what a recipe call would reuse and compute, without running it. |
|
Run a run's recipe again with the settings it recorded, changing some of them. |
|
Run the rest of a paused run under the same run ID, on any machine that opens the store. |
|
|
End a paused run that will not resume, recorded as interrupted. |
|
Describe the stage keywords of a recipe, their settings, and the defaults it uses. |
Open one durable run by ID or immutable label. |
|
|
List recent runs, newest first, optionally filtered by status. |
|
Mark an exact stopped finalizer interrupted so its label can be retried. |
One step of a pipeline run, as listeners receive it. |
|
Progress of the bounded work a stage is doing. |
|
What a recipe call would reuse and compute, stage by stage. |
|
What one stage of a planned call would do. |
|
What a stage took when the latest earlier run of its recipe computed it. |
|
The stage keywords of one recipe, in the order of its method's signature. |
|
One stage keyword of a recipe. |
|
One setting that a stage keyword's mapping takes. |
Recipes#
Recipe |
Analyzes |
Graph coordinates |
Feature field |
Off by default |
|---|---|---|---|---|
|
an RNA assay |
PCA of the highly variable genes |
|
cell calling, hashing, Harmony, Paris, membership strength, LocalMAP, t-SNE |
|
an ATAC assay of peak counts |
LSI of the most prevalent peaks |
|
Harmony, Paris, membership strength, LocalMAP, t-SNE, doublets |
|
an ADT assay of antibody counts |
PCA of the antibody panel |
|
filtering, Harmony, Paris, membership strength, LocalMAP, t-SNE |
|
two or more completed runs of the same cells |
none; it integrates the runs’ graphs |
none |
Paris, membership strength, t-SNE |
|
the RNA assay and the guide assay of a pooled CRISPR screen |
none; E-distances and signatures read the PCA of the highly variable genes, or its Harmony correction |
|
Harmony, Mixscape, association tests, clusters |
rna, atac, adt, and perturbation take assay=None by default: the default assay when it has
the recipe’s modality, else the store’s only assay of that modality. A store with several such assays needs
assay=. An assay of another modality raises TypeError, such as
The rna recipe analyzes RNA assays; assay 'ADT' is of type 'ADT'.
Recipes write, so they need a store opened with zarr_mode="r+"; a read-only store raises
PermissionError before the recipe checks its settings. Opening, listing, and reporting runs work
on a read-only store.
RNA#
rna = ds.pipeline.rna(label="rna")
rna["clusters"]
rna.cells.to_pandas_dataframe(["umap_1", "umap_2", "clusters"])
ds.plots.embedding(run=rna, layout="umap", color_by="clusters")
ds.markers.load(marker=rna["markers"], group_id=1)
The rna recipe runs these stages in order:
input_snapshot, cell_calling, hashing, filtering, cell_cycle, highly_variable_features, normalization, pca, harmony, ann_index, neighbors, connectivity, embedding_initialization, umap, localmap, leiden, paris, cluster_selection, membership_strength, tsne, doublets, markers.
By default it filters cells on their QC metrics with MAD bounds, scores the cell cycle, selects
1,000 highly variable genes, normalizes them, keeps 21 PCA dimensions, builds a graph of 11
neighbors, embeds it with UMAP, clusters it with Leiden at resolutions 0.5, 0.75, 1.0, and 1.25,
saves the candidate with the best silhouette as run["clusters"], scores doublets, and ranks
markers. These numbers are the defaults of the stages’ methods: features.hvgs top_n,
reduction.pca dims, and graph.neighbors k.
ATAC#
atac = ds.pipeline.atac(label="atac")
atac["lsi"]
atac.features.fetch("prevalent_peaks")
The atac recipe runs input_snapshot, filtering, prevalent_peaks, normalization, lsi, harmony, ann_index, neighbors, connectivity, embedding_initialization, umap, localmap, leiden, paris, cluster_selection, membership_strength, tsne, doublets, and markers.
By default it filters cells on <assay>_nCounts and <assay>_nFeatures with MAD bounds, keeps the 10,000 most prevalent peaks (features.prevalent_peaks top_n), normalizes them with the assay’s normalizer, TF-IDF for an ATAC assay (Normalization method), and reduces them to 11 LSI dimensions without the first component (reduction.lsi dims and skip_first). It then builds, embeds, and clusters a graph and ranks markers as the RNA recipe does. With Harmony, the run corrects its LSI coordinates.
prevalent_peaks top_n defaults to 10,000 or one fewer than the assay’s number of peaks,
whichever is smaller, and a given top_n must be below the assay’s number of peaks; the run records
the resolved top_n. The LSI needs dims prevalent peaks, one more when skip_first leaves out
the first component, so lsi dims with that component must not exceed top_n, and skip_first
must be a boolean.
doublets=True scores doublets after the run clusters, with the keywords of qc.doublets, as the RNA recipe does (Doublets and Harmony). The simulated doublets are weighted by TF-IDF and projected onto the run’s LSI (Doublet detection), so the run must normalize with "tf_idf", the ATAC default, and each sample is scored by Euclidean distances in the LSI, whatever ann_index ann_metric the graph uses. Doublet scoring is off by default, so a run recorded before the ATAC recipe scored doublets replays as it ran.
ADT#
# Analyze the antibodies of the RNA run's cells.
adt = ds.pipeline.adt(cells=rna, label="adt")
adt.features.fetch("panel")
The adt recipe runs input_snapshot, filtering, panel, normalization, pca, harmony, ann_index, neighbors, connectivity, embedding_initialization, umap, localmap, leiden, paris, cluster_selection, membership_strength, tsne, and markers.
The assay must be of type ADT; an HTO assay is read by the RNA recipe’s hashing stage instead. The panel leaves out the antibodies whose names match cytearc.datastore.pipeline_accessor.DEFAULT_PANEL_EXCLUDE, the regular expression (?i)isotype|control|ctrl, so isotype controls stay out of the reduction. panel={"exclude": ...} sets another pattern, and panel={"exclude": None} keeps every antibody that every source of the run’s cells measured. On a store merged from sources of different antibody panels, the panel follows the run’s own cells: it leaves out the antibodies that some source among the run’s cells did not measure, as the merged feature table records them (Import and export API reference), since their zero counts in that source’s cells are not measurements, so a run of the cells of one source keeps that source’s whole panel. A warning names the antibodies that it leaves out, and the run records them as the panel’s unmeasured. The run’s markers then rank the antibodies that every source of its cells measured, which the run saves as measured_antibodies, in place of every antibody of the assay, so a run of the merged store ranks what a run of a merge of the shared antibodies alone ranks. The panel must keep at least two antibodies, and the run records the excluded names. The antibodies are normalized with the assay’s normalizer, CLR for an ADT assay (Normalization method), and PCA keeps one dimension fewer than the panel holds, at most 21, unless pca sets dims, which must be at least 1 and below the panel’s number of antibodies. The recipe filters cells only when filtering asks for it, because an ADT run usually takes the QC-passing cells of an RNA run.
Multimodal#
wnn = ds.pipeline.multimodal([rna, adt], label="wnn")
wnn["integrated_graph"]
wnn.cells.fetch("weight_ADT")
ds.markers.load(marker=wnn["markers_ADT"], group_id=1)
The multimodal recipe runs input_snapshot, integration, embedding_initialization, umap, leiden, paris, cluster_selection, which is always skipped, membership_strength, tsne, and markers.
It integrates the runs’ graphs with weighted nearest neighbors (method="wnn", the default), which weighs each run’s neighbors, or with shared nearest neighbors (method="snn"), which shares each run’s connectivity-map edges (Integration and metrics API reference). It then embeds and clusters the integrated graph and ranks each run’s assay’s features for the joint clusters as one markers_<assay> output per run, with the normalizer that the run recorded (Normalization method). integration takes the keywords of integration.modalities: chunk_size and, for WNN only, l2_normalize.
runs is a sequence of two or more completed runs of different assays that analyze the same
cells: their analysis_cell_selection outputs must be the same ref, which a run gets by taking an
earlier run as its cells. WNN weighs each modality by the coordinates that built its neighbors,
so each run’s graph must be built on PCA, LSI, or Harmony coordinates; an RNA run with
pca={"dims": 0} can be integrated with SNN only. SNN shares edges between graphs of one
neighbor count, so with method="snn" the runs must have been built with the same neighbors
k. The joint embedding starts from the first run’s coordinates, so the first run needs a
neighbors output when UMAP or t-SNE runs. The joint run’s assay and feature_universe are the
first run’s, and its feature view covers that assay’s features with I, ids, and names only,
without the first run’s feature field.
The integrated graph has no shared coordinates in which to compare Leiden candidates by
silhouette. leiden partitions therefore default to [1.0], the only candidate is the saved
clustering, and several partitions need a selected resolution.
LocalMAP draws its mid-near pairs in the coordinates that built its graph, which an integrated graph of several assays does not have, so localmap must stay False: a call that turns it on raises ValueError before anything is written. Turn LocalMAP on in a modality run instead.
Compose runs of the same cells#
A CITE-seq analysis runs the RNA recipe, analyzes the antibodies of the same cells, and integrates the two runs:
rna = ds.pipeline.rna(label="rna")
adt = ds.pipeline.adt(cells=rna, label="adt")
wnn = ds.pipeline.multimodal([rna, adt], label="wnn")
adt takes the RNA run’s analysis cells as they are, so both runs share one cell selection. The
ADT assay must have measured each of those cells. Each run is a separate durable record with its
own label, and the multimodal run records its sources as config["sources"]. A TEA-seq analysis
adds atac = ds.pipeline.atac(cells=rna, label="atac") and integrates [rna, atac, adt].
Perturbation#
screen = ds.pipeline.perturbation(labels={"controls": ["Non-Targeting"]}, label="screen")
ds.perturbation.load_efficiency(screen["efficiency"]).table
ds.perturbation.load_edistance(screen["edistance"]).table
print(screen.report(format="markdown"))
The perturbation recipe analyzes a pooled CRISPR screen (Perturbation API reference): an RNA assay and a guide assay, declared CRISPR, that measured the same cells. It runs these stages in order:
input_snapshot, filtering, guide_calling, perturbation_labels, efficiency, highly_variable_features, normalization, pca, harmony, edistance, signature, mixscape, associations, profiles, perturbation_clusters.
By default it filters cells on their RNA QC metrics as the rna recipe does, calls the guides of the analysis cells with perturbation.call_guides and its default method="poisson_gaussian", labels each cell by the genes that its guides target, and measures each target’s efficiency on its own gene. It then selects 1,000 highly variable genes, normalizes them, keeps 21 PCA dimensions, and measures each target’s E-distance from the control cells in the PCA, with 1,000 permutations. Harmony, Mixscape, the association tests, and the clusters are off. The guides are called and the cells labeled before the PCA, so a labeling that fails stops the run early.
labels is required and must name controls, the targets of the control guides, which perturbation.labels needs: CyteArc never guesses which guides are controls. guide_assay defaults to the store’s only assay declared CRISPR. guide_calling takes the keywords of perturbation.call_guides, or path with barcode_prefix, barcode_suffix and barcode_pattern, with which the stage imports Cell Ranger’s protospacer_calls_per_cell.csv through perturbation.import_guide_calls instead. Fitted calls output their fits as guide_thresholds beside the guide_calls. Efficiency matches each target to a gene by the guide assay’s target_gene_id column, which 10x imports fill, so a guide assay without it needs efficiency={"id_column": None}, which matches targets by name; the run refuses the default otherwise.
Cell Ranger writes a call file for each sample, and the import matches each of its barcodes to the cell whose ID is barcode_prefix, the barcode or the part of it that barcode_pattern keeps, and barcode_suffix. A cell that no barcode can reach would be labeled "Negative" and left out of every later stage, so a run that imports a call file refuses such cells before it writes anything: with barcode_prefix, cells of cells whose IDs do not start with it, with barcode_suffix, cells whose IDs do not end with it, and without a prefix, cells of cells from several samples of a merged store, which names each cell <sample>__<barcode>. A sample’s name may end with _: the cells of pool_ have IDs such as pool___AAAC-1, which pool__ also starts, so their prefix is pool___, and a prefix that ends with __ refuses cells whose IDs go on from it with _. Without a prefix, the samples of cells are those of the store’s cell column of sources, which a merge writes when its sources measured different features; without that column, cells whose IDs go on with _ after their first __ are refused. The run also reads the file before it writes anything, as the import reads it, and refuses a file that the import would refuse or whose barcodes name no cell of cells (Validation before a run starts). In a merged store, restrict cells to the cells of one sample and pass its prefix, such as barcode_prefix="lane1__", or call the guides from their counts. The stage summary’s unmatchedBarcodes counts the file’s barcodes that match no cell of the store, which the import warns about, and unselectedBarcodes the barcodes of cells outside the analysis cells, such as the cells that QC filtering removed, which the import logs without a warning.
signature configures the signature that mixscape=True computes first, and profiles the profiles that clusters=True clusters; their settings without that stage raise ValueError. The signature holds the highly variable genes, and its dims must not exceed the PCA’s, so its default of 15 needs pca dims of at least 15. E-distances and the signature read the Harmony coordinates when the run has Harmony, and the PCA otherwise. The association tests test every target against every highly variable gene (pairs="trans"), so associations takes neither pairs nor features, and its positive_controls is "targets" or None; call ds.perturbation.associations for a table of pairs. For a screen with several guides per cell, associations={"moi": "high"} runs the high-MOI tests, which compare each target’s cells with all other cells and need guide UMIs in every cell. The efficiency, E-distances, Mixscape with its signature, and the clusters with their profiles compare each perturbation with the cells that carry control guides only, which such a screen hardly holds, so a run with moi="high" refuses them before it writes anything: pass efficiency=False and edistance=False, and leave mixscape and clusters off. In a run with Mixscape, the profiles average each target’s knocked-out cells by default, from the mixscape output, so that escapers do not dilute them. A target with fewer than min_cells knocked-out cells gets no profile, so a screen whose targets Mixscape leaves with few knocked-out cells can keep them with profiles={"cells": "labeled"}, which averages every cell of each label, as a run without Mixscape does. "knocked_out" without Mixscape raises ValueError before the run writes anything. The run records which output the profiles read as config["profileLabels"].
Each perturbation stage calls a ds.perturbation method with the run’s refs and settings, so the method called with the same refs and settings returns the run’s artifact, and a run reuses the artifacts of such calls. A reused artifact repeats its method’s warnings, so the stage records them as the stage that computed it did. The stages from filtering to harmony are those of the rna recipe. A run with the cells and the filtering, hvg, normalization, pca, and harmony settings of an rna run reuses that run’s analysis cells, highly variable genes, normalized values, PCA, and Harmony coordinates, and so does a run given the RNA run as cells, which keeps its analysis cells, with the same hvg, normalization, pca, and harmony settings:
rna = ds.pipeline.rna(label="rna", hvg={"top_n": 2000}, pca={"dims": 30})
# Reuse the RNA run's cells, genes, and PCA, and run every stage.
screen = ds.pipeline.perturbation(
cells=rna,
labels={"controls": ["Non-Targeting"]},
hvg={"top_n": 2000},
pca={"dims": 30},
signature={"dims": 30, "sample_column": "lane"},
mixscape=True,
associations={"sample_column": "lane"},
clusters=True,
label="screen_all_stages",
)
The run’s assay is the RNA assay. Its cell view holds each cell’s guide_call, the call of the run’s guide_calls: the ID of its one called guide, "Negative" without a guide, or "Multiple" with several. It holds perturbation_label, the label of the run’s perturbation_labels, and is_control, which is True for a cell with control guides only, labeled "control". A cell with several guides of one gene, or with a gene’s guides beside control guides, is called "Multiple" but labeled by the gene; Label cells by perturbation lists every case. With Mixscape, the view also holds mixscape_class and mixscape_posterior. The guide calls and labels belong to the guide assay, and the view reads them by the run’s cells (Frozen fields). ds.perturbation.load_guide_calls(screen["guide_calls"]) and ds.perturbation.load_labels(screen["perturbation_labels"]) read their other columns, such as each cell’s guides and genes:
screen.cells.to_pandas_dataframe(["ids", "guide_call", "perturbation_label"])
adata = ds.to_anndata(run=screen) # obs holds the three fields as categories
Stage keywords#
Each stage keyword configures one stage:
An optional stage,
cell_calling,hashing,filtering,cell_cycle,umap,localmap,tsne,leiden,paris,doublets,efficiency,edistance,mixscape,associations, orclusters, takesFalseto skip it,Trueto run it with its defaults, or a mapping of settings, which also runs it.Noneis not a switch:umap=NoneraisesTypeError.filtering=Noneis the default of thefilteringkeyword, described in Filtering.A stage that always runs,
hvg,normalization,pca,prevalent_peaks,lsi,panel,ann_index,neighbors,connectivity,embedding_initialization,integration, orguide_calling, takes None for its defaults or a mapping of settings. A bool raisesTypeError, such aspca must be a mapping because the stage always runs.harmonyis None, the default, orFalse, which leave Harmony off, or a mapping that namesbatch_columns.harmony=TrueraisesValueError(harmony needs a mapping with batch_columns), and any other value, such as a list of columns, raisesTypeError.membership_strengthandmarkersare plain bools.labels, the settings of aperturbationrun’s labels, is a required mapping that namescontrols.signatureandprofilesconfigure the stages that aperturbationrun’smixscapeandclustersrun: None, the default, or a mapping of settings, which raisesValueErrorwhile its stage is off. A bool raisesTypeError.
A setting means exactly what the same keyword means on the stage’s method, and an omitted setting takes that method’s default, with four exceptions that fit the recipe to its data: an adt run’s pca dims defaults to one fewer than the panel’s antibodies, at most 21 (ADT); an atac run’s prevalent_peaks top_n to 10,000 or one fewer than the assay’s peaks (ATAC); an rna or perturbation run’s pca feat_scaling to False when the run normalizes with Pearson residuals, and to True otherwise (Normalization method); and with Harmony, an rna or atac run’s doublets sample_column to the Harmony batch columns (Doublets and Harmony). The pipeline supplies the artifacts that each stage consumes, so a mapping holds settings only. A few keys configure the recipe instead: Leiden partitions and selected, Harmony batch_columns, cell-calling sample_column, hashing assay, panel exclude, normalization method, which names the run’s normalizer (Normalization method), guide-calling path, barcode_prefix, barcode_suffix and barcode_pattern, which import Cell Ranger’s calls in place of calling guides, and profiles cells, which chooses the cells that the profiles average (Perturbation). An unknown key raises ValueError that lists the allowed keys, such as Unknown pca settings ['dim']; allowed: ['batch_size', 'dims', 'feat_scaling']. ds.pipeline.describe(recipe) gives every stage’s settings with these defaults and rules in code (Describe a recipe).
run = ds.pipeline.rna(
label="tuned",
filtering={"method": "manual", "attrs": ["RNA_nCounts"], "lows": [500], "highs": [20000]},
hvg={"flavor": "seurat_v3", "top_n": 2000},
pca={"dims": 30},
neighbors={"k": 15},
umap={"n_epochs": 400, "min_dist": 1.0, "spread": 2.0, "parallel": True},
leiden={"partitions": [0.6, 0.8, 1.0, 1.2, 1.4], "selected": 1.0},
membership_strength=True,
tsne={"max_iter": 800, "early_iter": 200, "alpha": 10, "box_h": 0.7},
species="homo_sapiens",
)
Keyword |
Recipes |
Method |
Settings |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
the rules of |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
the antibody panel |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
all but |
|
|
|
all but |
|
|
|
|
|
|
|
all but |
|
|
|
all but |
|
|
|
all but |
|
|
|
all but |
none; a bool |
|
|
|
|
|
|
all but |
none; a bool |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The other keywords configure the run itself:
label: an immutable name for the completed run, unique in the store (Open, list, and report runs).cells: the cells the run analyzes (Cells);multimodaltakes the cells of its runs.snapshot_columns: cell columns frozen into the run’s cell view. They must exist and must not use a reserved field name (Frozen fields). The run records how plots draw each column: its stored display, or for a column stored as ordered its categories in their stored order with the default colors, so run plots draw the column as plots of the live column do, and run exports write it in that order with those colors.species: a species key recorded with the run, one ofhomo_sapiens,mus_musculus,rattus_norvegicus,danio_rerio,drosophila_melanogaster, orcaenorhabditis_elegans.multimodalandperturbationtake none.guide_assay: the guide assay of aperturbationrun (Perturbation).callback: a callable that receives eachPipelineEventof the run (Events and listeners).cancel: aCancellationTokenthat stops the run (Cancellation).
Settings are JSON values: numbers, strings, bools, None, lists, and mappings with string keys. Infinity and NaN are never settings. Some settings spell a derived default as None: hvg min_cells, the cube root of the number of selected cells rounded up and at least 20, or 5% of a smaller selection’s cells and at least 5, for the default flavor; hvg max_cells, which for the default flavor excludes genes detected in more than 99.5% of the selected cells; batch_size of every stage that takes it; cell_cycle ctrl_size and log_transform; paris min_cluster_size; normalization method, the assay’s normMethod; and normalization log_transform and renormalize_subset, whose defaults follow the run’s normalizer (Assays and metadata API reference). The run records the settings it was given under config["stages"], with the normalization method it resolved, and each artifact records the values its method resolved.
Normalization method#
Every stage of a run that reads normalized values, such as gene selection, normalization, cell cycle scores and markers, applies one normalizer: the one that the normalization method names, or the assay’s normMethod when the call names none. The run records the normalizer, so run.settings(), ds.pipeline.rerun and ds.pipeline.plan(run) normalize as the run did in any session, including a new session whose RNA assay normalizes by library size. method names a built-in normalizer by its function’s name without norm_, and norm_dummy as "passthrough":
|
Normalizer |
Assays |
|---|---|---|
|
|
RNA |
|
|
RNA |
|
|
RNA |
|
|
every assay |
|
|
ATAC |
|
|
every assay |
run = ds.pipeline.rna(label="residuals", normalization={"method": "pearson_residuals"})
run.settings()["normalization"] # {'method': 'pearson_residuals'}
The run makes its normalizer the assay’s normMethod while its stages run, and so does a plan of the call, since the identities of the stages’ artifacts depend on it; the session’s normMethod comes back however the run ends, completed, failed, or cancelled. A call without method records the assay’s normMethod by its name. A name that is not in the table, or a normalizer that the assay’s class cannot apply, such as "lib_size" for an ATAC assay, raises ValueError before anything is written.
A custom normalizer, and a PearsonResidualNormalizer with options other than the defaults, has no name: a run applies it as the assay’s normMethod and records the identity that provenance records for it (Assays and metadata API reference), such as {"identity": "cytearc.assay.pearson_residuals:theta=50.0:clip=sqrt-n"}, which run.settings() returns as its method. A rerun or a plan of such a run raises ValueError before it computes anything unless the assay’s normMethod has that identity, and the message names it. normalization={"method": None} reruns with the assay’s normMethod instead.
Pearson residuals are already standardized, so the PCA of a run of residuals scales no feature: pca feat_scaling defaults to False for such a run, as reduction.pca(residuals, feat_scaling=False) does, and to True for every other normalizer, and a value that the call gives wins. The run’s cell cycle scores average residuals and its markers rank them. Doublet scoring normalizes its simulated doublets as the run normalized its cells, with what the normalizer fitted over them, and projects them onto the PCA, scaled or not, so a run of any built-in normalizer scores doublets; a custom normalizer passes doublets=False. A multimodal run ranks each assay’s markers with the normalizer that the run of that assay recorded.
Validation before a run starts#
A recipe checks its call against the store before it creates a run record, and a call that fails a check raises an error such as TypeError, ValueError, or KeyError without writing anything. Unknown keywords or settings, settings without a JSON value, a bool for a stage that always runs, an assay of another modality, missing columns, cells that select no cell, cells that an assay did not measure, reserved snapshot fields, invalid stage combinations, settings that a stage’s method refuses, and an already completed label fail this way. Among the errors:
doublets and markers require at least one Leiden candidate(rnawithleiden=False;atacnames the stages that the call turns on, such asmarkers require at least one Leiden candidate, andadtraises that message), andmembership_strength requires at least one Leiden candidate;pca={'dims': 0} builds the graph on normalized values, which Harmony cannot correct; ...andpca={'dims': 0} builds the graph on normalized values, but doublet scoring needs a PCA graph; ...;The run normalizes assay 'RNA' with ..., but doublet scoring normalizes its simulated doublets as the run's cells were, which it can do for the built-in normalizers ... alone; ...(rnawith doublet scoring on, when the run normalizes with a custom normalizer): passnormalization={"method": ...}with a built-in normalizer, ordoublets=False;The run normalizes assay 'ATAC' with ..., but doublet scoring weights its simulated doublets by TF-IDF and needs tf_idf; ...(atacwith doublet scoring on, when the run normalizes with another normalizer): passnormalization={"method": "tf_idf"}ordoublets=False;normalization['method'] must be one of [...], or the identity of a custom normalizer that a run recorded; ...,Assay 'ATAC' opens as ATACassay, but lib_size needs an RNAassay; ..., andnormalization['method'] is the custom normalizer ..., which a run applies only as the assay's normMethod, ...(Normalization method);PCA settings need dims above 0; dims=0 skips PCA, for otherpcasettings besidedims=0;leiden selected must be one of the partitions;snapshot_columns collide with reserved run fields: [...];TypeError("callback must be callable")and acancelthat is not aCancellationToken;run_until='clustering' is not a stage of the rna recipe; ...andrun_until='harmony' names a stage that this run's settings skip; ..., which list the stages that the run runs (Pause and resume a run);The rna recipe needs counts: its doublet scoring reads counts. ..., for an assay of normalized values, naming every stage of the run that needs counts and the argument that turns it off, as normalized values describes.
Before the run starts, the recipe also checks the settings of every stage with the checks of the stage’s method, so a value that the method refuses raises the method’s error, with the stage’s name before the method’s message, such as pca: batch_size must be at least 1, since several stages take a batch_size or a seed. An omitted setting is checked as the method’s default. Among them, doublets={'expected_doublet_rate': 1.5}, ann_index={'ann_m': 1}, pca={'feat_scaling': 0}, umap={'min_dist': -1}, leiden={'backend': 'louvain'}, and paris={'n_clusters': 0} raise ValueError or TypeError. A normalization flag must apply to the run’s normalizer, as the stage that reads it requires: normalization={'log_transform': True} of a run of Pearson residuals or of an atac run, and cell_cycle={'log_transform': True} of a run of Pearson residuals, raise ValueError. The recipe also checks:
hvg: the checks offeatures.hvgs.min_cellsmust be None or an integer of at least 0,top_nandn_binsintegers of at least 1,lowess_fraca finite number from 0 to 1 for eitherbin_strategy,keep_boundsa bool,bin_strategy"adaptive"or"fixed",blacklistNone, False or text that is a regular expression,flavor"cytearc","seurat_v3", or"pearson_residuals",spangreater than 0 and at most 1,thetapositive, andclipNone or at least 0; the options of one flavor keep their defaults under another, andbatchmust name a cell metadata column that gives every cell ofcellsa batch: a missing value, NaN in a float column, or empty or whitespace text raisesValueError, as batch-aware HVG selection refuses such a cell. An omitted setting is checked as itsfeatures.hvgsdefault.pcadims: an integer of at least 0 forrnaand at least 1 foradt, below the number of features that PCA reads, because PCA needsdims + 1of them: for anrnarun, the smaller of thehvgtop_nand the assay’s features, since HVG selection keeps at most both, and for anadtrun, the panel’s antibodies. When fewer genes pass the HVG filters, the PCA stage refuses the dimensions and names the features selected.prevalent_peakstop_nand thelsidimsandskip_first, as ATAC describes.ann_indexann_metric:"l2"or"cosine", the metrics that the ANN index and the mapping reference of doublet scoring take; another value raisesValueError.tsne: the checks ofembeddings.tsne, because the stage runs after most others.tsne_dims,max_iter, andalphamust be integers of at least 1,early_iteran integer of at least 0,lambda_scaleandbox_hfinite positive numbers, andsymmetric_graphandgraph_upper_onlybools.localmap: the checks ofembeddings.localmap.localmap_dims,n_mid_near, andn_furthermust be integers of at least 1,iterationsthree integers of at least 1, one per phase,learning_rateandmax_distancefinite positive numbers, andrandom_seedan integer of at least 0. Amultimodalrun refuseslocalmap(Multimodal).The graph flags: the
umapsymmetric_graphandgraph_upper_onlysettings must beFalse, and aleidenortsnegraph_upper_onlyset toTrueneedssymmetric_graph=True.harmonyharmony_params: the checks ofreduction.harmony. Its keys are the keyword options offit_harmony()other thannthreads, and an unknown key, a key of an earlier release such asnclust(nown_clusters), or an invalid value raisesValueErrororTypeError; Integration and metrics API reference lists the keys.harmonybatch_columns: each column must label every cell ofcells. A missing value, or NaN in a float column, raisesValueError, while empty text is a label, as Harmony takes it.cell_calling: the checks ofqc.call_cellsforlower,retain,n_iter,alpha,fdr, andrandom_seed. Withsample_column, every cell ofcellsneeds a capture label: a missing value, or NaN in a float column, raisesValueError. The stage checks its frozen labels again.hashing:positive_quantile, greater than 0 and less than 1, and the HTO assay.filtering: its method, columns, and options (Filtering).panelexclude: a valid regular expression that keeps at least two antibodies.The runs of
multimodal(Multimodal). Withmethod="snn", runs built with differentneighborskraiseValueErrorthat namesneighbors={'k': ...}andmethod='wnn'.The guide assay of
perturbation: the store’s only assay declaredCRISPR, or the one thatguide_assaynames, which must be declaredCRISPRand store unsigned counts. A store with no CRISPR assay, or several, raisesValueErrorthat lists them.labels:controls, which a mapping without them, orlabels=None, lacks (ValueError,labels needs controls, the targets of the control guides, ...), and the checks ofperturbation.labelsagainst the guide assay’s targets: a control that no guide has, a target that is not a control and is a reserved label or, withpolicy="combinations", holds"+",targetsthat name a guide that the assay lacks, and atarget_columnthat the guide assay lacks. A called guide without a target shows only in the calls, so theperturbation_labelsstage refuses it, and the run fails.guide_calling: the checks ofperturbation.call_guidesformethod,min_umi,fraction_threshold, andsample_column, or apaththat is a file (FileNotFoundErrorotherwise) with abarcode_prefixand abarcode_suffixof text or None (TypeErrorotherwise) and abarcode_patternthat is None or a regular expression with a named groupbarcode. Apathbeside a calling setting, or an import setting withoutpath, raisesValueError, and so do cells ofcellsthat the call file cannot reach: withbarcode_prefix, cells whose IDs do not start with it or go on with_from a prefix that ends with__, withbarcode_suffix, cells whose IDs do not end with it, and without a prefix, cells from several samples of a merged store or whose IDs do not tell their sample. The recipe then reads the guide assay’s IDs and the file as the import does, each step charged to the memory budget before it allocates (MemoryBudgetErrorotherwise, naming the step and the budget that passes it), and raisesValueErrorfor a file that the import would refuse, such as a malformed file, one without a call column, one that calls a guide the guide assay lacks, or one with two barcodes that name one cell ofcells, which the run refuses even where filtering would leave that cell out, and for a file none of whose barcodes, joined to the prefix and suffix as the import joins them, is the ID of a cell ofcells, which would label every cell"Negative".The settings of
efficiency,edistance,signature,mixscape,associations,profiles, andclusters: the checks of their methods, anid_columnthat the guide assay lacks where the stage reads it (efficiency,associationswithpositive_controls="targets", andprofileswithmask_targets), sample, split, and covariate columns that the store lacks (ValueError, as the methods raise), covariates that do not hold numbers, andclustersperturbationsthat name fewer than 3 distinct perturbations, fewer thanmin_samples, or a perturbation that can have no profile: by target, the profiles hold the targets that are not controls, and withprofiles={"by": "guide"}, every guide with a target.The
sample_columnofguide_calling,signature,associations, orprofiles, and a Mixscapesplit_column, must label every cell ofcells: a missing value, NaN in a float column, or empty or whitespace text raisesValueError. Each covariate ofassociationsmust hold a finite value for every cell ofcells, and at least two distinct values over them, since the tests refuse a constant covariate: a missing, NaN, or infinite value, or a single value, raisesValueError. The methods need labels and covariate values only on the cells that they read, such as the control cells and the cells of the tested targets, but which cells those are depends on the data, so the run asks for them on every cell ofcells. Withassociations, every cell ofcellsneeds counts in the RNA assay, since the tests adjust for the log of each tested cell’s UMIs. Withassociations={"moi": "high"}, every cell ofcellsneeds guide UMIs too, since the tests adjust for their log and test every labeled cell, and an enabledefficiency,edistance,mixscapeorclustersstage raisesValueError(Perturbation).pcadimsof aperturbationrun: at least 1 and below the smaller of thehvgtop_nand the RNA assay’s features, and at leastsignaturedimswhen the run calls Mixscape.signaturesettings withoutmixscape,profilessettings withoutclusters, aprofilescellsother than"knocked_out"or"labeled","knocked_out"withoutmixscape, andpairs,features, or a table ofpositive_controlsinassociationsraiseValueError.
A stage’s method checks the limits that depend on the data when the stage runs, such as the memory that the ANN index or cluster selection needs, a Paris n_clusters above the number of cells, a sample with fewer control cells than the signature’s n_neighbors, or clusters of fewer than 3 profiles. Such a limit fails its stage after the earlier stages have run: the run is recorded as failed and raises PipelineExecutionError.
A handled stage failure raises PipelineExecutionError after the stage and the run are recorded as failed. Use its run_id to inspect the persisted failure, and its stage to identify the failing stage, "pause" when pausing the run failed, or "finalize" when completing the run record failed. The original exception is retained as __cause__.
from cytearc import PipelineExecutionError
try:
run = ds.pipeline.rna(label="baseline")
except PipelineExecutionError as error:
failed_run = ds.pipeline.open(run_id=error.run_id)
report = failed_run.report(format="dict")
Plan a call#
A run reuses every stage whose artifacts the store already holds, but which stages those are shows only as each stage starts. ds.pipeline.plan tells beforehand. It takes the recipe’s name and the arguments of the recipe’s method, checks the call as the recipe does, and reports for each stage whether the run would reuse its artifacts or compute them, and why. It writes nothing, reads no count matrix, and works on a read-only store, so it can precede a long run, show what a changed setting recomputes, or confirm that a new run after a failure reuses what the failed one finished.
plan = ds.pipeline.plan("rna", label="tuned", hvg={"top_n": 2000}, pca={"dims": 30})
for stage in plan.stages:
print(stage.stage, stage.status, stage.reason, stage.detail)
plan.computed # the stages that would compute, in run order
plan["pca"].estimate # what PCA took when an earlier rna run computed it
plan("multimodal", [rna_run, adt_run], ...) takes the runs as the method does. plan.config holds the settings that the run would record, plan["pca"] the plan of one stage, and plan.to_dict() the whole plan as JSON values. Each PipelineStagePlan has a status:
|
Meaning |
|---|---|
|
Every artifact that the stage plans exists, complete and current. |
|
The stage would compute an artifact, for the |
|
The call turns the stage off. |
|
Why the stage computes |
|---|---|
|
The store holds no artifact of the operation. |
|
The store holds artifacts of the operation, and the closest, the one that differs in the fewest parameters and inputs, is |
|
An operation revision supersedes |
|
|
|
|
|
|
|
The stage reads what the stages in |
An artifact’s identity includes the identities of its inputs. A stage that reads what an earlier stage would compute therefore cannot know its own identity, since its inputs do not exist yet, and its artifact will be new whatever the store holds. The plan reports such a stage computed with the reason upstream and names, in upstream, the earlier stages whose outputs it reads; those may wait on others in turn. A stage that reads nothing that would change stays reused: after a change to the umap settings, the Leiden candidates, cluster selection, doublet scoring, and markers read the graph, not UMAP, so the plan, like the run, reuses them.
A computed stage’s estimate, a PipelineStageEstimate, holds what the stage took in the latest earlier run of the same recipe and assay that computed it, with that run’s ID: its wall and CPU time, sampled RSS peaks, OS thread peak, network bytes, the process’s peak RSS when the stage raised it, and the resources that its process had, such as workers and memoryLimitBytes (Stage resources). A run that reused every artifact of the stage does not count, and with no such run estimate is None. A value that the earlier run did not record, as runs of releases before these measurements record no CPU time, is None. It is a past measurement, not a model: that run’s cells and settings can differ, and its resources describe the machine it ran on.
A plan raises the errors that the call raises before it writes, such as a ValueError for an already completed label or for a setting that the stage’s method refuses (Validation before a run starts), and a TypeError for run_until, callback, or cancel, which belong to a run. A stage’s method checks the limits that depend on the data only when the stage runs: when every stage before it would be reused, the plan reaches that check and raises the stage’s error, as the run would. The plan goes through each stage until the stage would compute an artifact, so a reused stage warns from its saved diagnostics as it does in a run.
No recipe runs trajectory calls, so they have a plan of their own: ds.trajectory.plan() plans the calls made in its block, as written (Plan a trajectory).
Rerun a run with changed settings#
ds.pipeline.rerun runs a run’s recipe again with the settings that the run recorded, so a call passes only what it changes. run.settings() returns those settings as the keywords of the recipe’s method, every keyword but label, run_until, callback, and cancel, and ds.pipeline.plan takes a run in place of a recipe’s name to report what the rerun would compute.
base = ds.pipeline.open(label="baseline")
base.settings()["leiden"] # {'partitions': [0.5, 0.75, 1.0, 1.25], 'selected': None}
ds.pipeline.plan(base, leiden={"partitions": [2.0]}).computed
fine = ds.pipeline.rerun(base, label="fine", leiden={"partitions": [2.0]})
A mapping changes a stage’s settings key by key: leiden={"partitions": [2.0]} keeps the run’s other Leiden settings, among them its selected resolution, which must be one of the new partitions or None. A mapping inside a stage’s settings, such as Harmony’s harmony_params, is replaced whole. False turns an optional stage off, True runs it with its defaults, None takes the keyword’s default, and every other value replaces the run’s. A rerun with new cells therefore keeps the run’s filtering, and filtering=None filters the new cells as a call that omits filtering would. Stages whose settings and inputs are unchanged reuse the run’s artifacts, and the new run takes its own label.
The settings are those that the call gave, with the defaults that the recipe fits to its data resolved, such as an atac run’s prevalent_peaks top_n: a rerun that changes the cells or the panel keeps them, and the recipe refuses a value that no longer fits. They hold the run’s normalizer as its normalization method, so a rerun normalizes as the run did whatever the session’s normMethod is, and refuses a custom normalizer that the assay’s normMethod is not (Normalization method). A cells column is passed by its name, so a rerun reads the column as it is now, and settings that the run did not set take this release’s defaults (Runs saved by other releases). A run records its settings when it starts, so a failed or interrupted run reruns too, with the setting that failed changed. A run recorded before its recipe gained a keyword or a stage setting, such as an rna run recorded before localmap, reruns with that setting’s default, which matches what the earlier release did, so the plan reuses the run’s stages and a call can turn the new stage on; a run recorded before the normalization method reruns with the normalizer that its normalized values record and the PCA feature scaling that it applied (Runs saved by other releases). run.settings() raises ValueError for a run whose recipe this release lacks, such as one that pipeline.run() saved, and for a run that records a keyword its recipe no longer takes.
Pause and resume a run#
A long run can stop after a chosen stage and continue later under the same run ID, in this process or another, on any machine that opens the store. Pass run_until, the name of a stage that the call runs, to a recipe or to rerun: the run pauses once that stage has completed and returns with status paused. ds.pipeline.resume runs the rest:
paused = ds.pipeline.rna(label="baseline", run_until="pca")
paused.status # 'paused'
ds.pipeline.plan(paused).computed # the stages that a resume would compute
# Later, in any process that opens the store, such as one on a larger machine:
run = ds.pipeline.resume(paused.run_id)
run.status, run.label # ('completed', 'baseline')
resume takes the paused run or its run ID. It rebuilds the recipe from the settings that the run recorded, as rerun does, and restores what the finished stages left from their saved artifacts, computing and writing nothing for them. It then runs the next stages and completes the run, or pauses it again after the stage that its own run_until names; it takes callback and cancel as a recipe does. A run paused after each stage in turn and resumed to the end holds the same artifacts, provenance, and stage records as a single call, apart from timings and resources. ds.pipeline.plan(paused) previews a resume: the finished stages are reused, and the plan reports which of the others would compute, as for any call (Plan a call).
A resume reads the store, so the process that resumes plans its work with the nthreads and memory budget of the store that it opened, and each stage record holds the resources of the process that ran it (Stage resources). Two things come from the resuming session instead:
A run of a custom normalizer resumes only where the assay’s
normMethodis that normalizer, since a run applies a custom normalizer only as the assay’snormMethod(Normalization method). In a fresh session, set it before the resume, asds.RNA.normMethod = my_normalizer; otherwiseresumeraisesValueError.A
perturbationrun that imports its guide calls reads the call file again at the recordedpath, andresumeraisesFileNotFoundErrorwhen the file is not there.
run_until must name a stage that the call runs: a name outside the recipe, or a stage that the call’s settings skip, raises ValueError before anything is written, listing the stages that the run runs, or for a resume, the stages that the run has left to run. When only skipped stages follow the stage, the run completes instead of pausing. plan takes no run_until.
A paused run has no outputs and no label yet: run[key] and the frozen views raise RuntimeError, as for a running run, and list_runs(status="paused") lists the runs that wait to resume. Its record holds segments, one for the process that started the run and one for each process that resumed it, with the times at which the process started and stopped, the stages that it ran, why it stopped (paused, or the status that the run ended with), and its signal protection. The Markdown report shows them as a table.
resume refuses, writing nothing, a run that is not paused, a run that another CyteArc release recorded, a run whose recorded settings no longer resolve to the stages and settings that it recorded, and a run whose finished stages would not reuse the artifacts that their stage records name, as after a cell column that a stage read changed or an artifact was copied incompletely with the store. Each error names the next step, usually ds.pipeline.rerun(run), which starts a new run that reuses the finished stages that still match; a running run is left to the process that runs it.
A paused run keeps its requested label without reserving it. The label is checked when the run pauses and when it resumes, and claimed when the run completes, as for any run. A run whose label another run has committed meanwhile fails when it would pause, with PipelineExecutionError for the step pause, and resume refuses it and suggests ds.pipeline.rerun(run, label=...); a run that only holds the label’s claim while it finalizes does not stop the pause, since it may still fail and leave the label.
A resume claims its pause with an atomic write before it records the resume, so of two processes that resume one paused run at once, one runs it and the other raises RuntimeError, which says that another process resumed or ended the run. A storage backend without atomic conditional creation therefore refuses run_until, resume and end_paused before anything is written. A process that dies between claiming the pause and recording the resume, a window of one metadata write, leaves the run paused with its pause claimed, so that no process can resume it; ds.pipeline.rerun(run) recovers the analysis under a new run ID, reusing every finished stage, and end_paused with release_claim=True ends the run (End a paused run).
A cancellation, signal, or failure after a resume ends the run interrupted or failed, as for any run, and its last segment records why. A process that dies leaves the run running, as for any run. The finished stages keep their artifacts either way, so rerun reuses them under a new run ID.
End a paused run#
A paused run waits for a resume until a process resumes it. ds.pipeline.end_paused ends one that never will, because the analysis was dropped or its resume cannot go on:
ds.pipeline.end_paused(paused, reason="analysis dropped")
# Every paused run of the store: list_runs returns at most limit runs, and a
# run that another process resumed or ended since the listing raises.
for run in ds.pipeline.list_runs(status="paused", limit=10_000):
try:
ds.pipeline.end_paused(run, reason="analysis dropped")
except (ValueError, RuntimeError):
continue
The run ends interrupted, with an interruption of kind ended_pause whose message is reason (default "ended while paused"), and its last segment closes with reason interrupted and otherwise as the pause left it, with the time of the pause and the stages that it ran. list_runs(status="paused") and the paused count of DataStore.summary() no longer include it. The run keeps its stage records and artifacts, and it never held its requested label, so ds.pipeline.rerun(run, label=...) reuses every finished stage under a new run ID and can take that label. end_paused takes the paused run or its run ID, and refuses a run that is not paused with ValueError, writing nothing.
The end claims the pause with the same atomic write as a resume, so of a resume and an end of one paused run, only one goes ahead, and the other raises without writing: RuntimeError, which says that another process resumed or ended the run, or, for a resume that the end overtook while it replayed the finished stages, ValueError, which says that the run is no longer paused. Two states need release_claim=True: a pause that a resume or an end claimed without recording itself, as a process that died between its two writes leaves it, and a pause whose write was cut off, paused with complete false, whose process may still be writing it. Pass it once you have confirmed that the other process stopped: CyteArc cannot tell a stopped process from a live one, and does not guess from elapsed time. If that process is alive after all, the write that lands last wins: the end can be lost, as a resume’s record replaces it and the run goes on, or the resume’s next stage fails, as the ended record refuses it.
Describe a recipe#
An application that offers a recipe’s settings, with the defaults of the installed release, reads them from ds.pipeline.describe. It takes a recipe’s name and returns a RecipeDescription of the recipe’s stage keywords, in the order of its signature. The description needs no store, so PipelineAccessor.describe("rna") gives the same one, and it is built from the code that resolves the recipe, so a setting added to a stage appears in it with its method’s type and default.
from cytearc.datastore.pipeline_accessor import PipelineAccessor
rna = PipelineAccessor.describe("rna")
rna["leiden"].methods # ("clusters.leiden",)
rna["leiden"]["partitions"].default # (0.5, 0.75, 1.0, 1.25)
rna["filtering"].rule # when the stage runs if filtering is omitted
rna["hvg"]["top_n"].annotation # "int"
PipelineAccessor.describe("atac")["prevalent_peaks"]["top_n"].rule
# "the smaller of 10000 and one fewer than the assay's peaks"
rna.to_dict() # the description as JSON values
A StageDescription gives in runs whether the stage runs when its keyword is omitted, or None with the rule that decides, such as "when mixscape runs" for the signature of a perturbation run. methods names the public methods that the stage passes its settings to: filtering filters with qc.auto_filter, or with qc.filter for method="manual". settings describes each setting that the keyword’s mapping takes, the keys that configure the recipe first and then each method’s keywords in the order of its signature.
A SettingDescription gives the setting’s annotation, as the method’s signature declares it or as the recipe takes it, such as a cell column for hvg batch, and the method whose keyword it is, or None for a key that configures the recipe, such as the Leiden partitions. Its default is what the recipe uses when a call omits the setting: the method’s default, or the recipe’s own, as for the Leiden partitions of each recipe. A default that the recipe fits to its data or to the rest of the call has no value: default is None, and rule states how the recipe sets it. required marks a setting that a mapping must give, such as Harmony’s batch_columns. In to_dict(), a default that is not a finite number, such as hvg min_var, is the text "-inf" or "inf".
A plan (Plan a call) applies these rules to a store: its config holds the settings that the run would record, where a fitted default takes its value, such as plan.config["stages"]["prevalent_peaks"]["top_n"] of an atac call.
Migrate from pipeline.run#
DataStore.pipeline.run() and its params mapping are removed. This is a breaking change within
the 1.x releases, and no alias remains: ds.pipeline.run raises AttributeError. The rna recipe
replaces it, with one keyword per stage:
Removed |
Replacement |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
unchanged |
Paris on by default |
|
|
|
the |
|
The stages of the rna recipe record the same provenance as those of pipeline.run(), so a call
with the same settings reuses the artifacts of an earlier pipeline.run() call. Pass paris=True
to reuse its Paris clustering too. A run with Harmony or snapshot_columns is the exception: the
recipe freezes those columns apart from the QC columns that filtering reads
(Run snapshots), so its filtered cells and its Harmony fit, and the artifacts
computed from them, get new identities. The first such call computes them again and later calls
reuse them; nothing is migrated, and the earlier artifacts stay in the store. Callbacks receive
more events than before: run events, stage_progress, and stage_skipped, and PipelineEvent has
more fields (Events and listeners). Runs that pipeline.run() saved still
open and report (Runs saved by other releases).
Cells#
cells names the cells that a single-assay run analyzes:
a boolean cell column,
"I"by default, which the run snapshots into an immutable selection;a datastore cell-selection artifact, such as the result of
ds.select_measured_cells("ADT")ords.select_cells(...); ora completed
PipelineRun, whoseanalysis_cell_selectionthe run reuses as the same ref.
The run’s input_cell_selection output is the snapshot of the column, or the given selection
itself. A run that is not completed, or a run of another datastore, raises ValueError.
The recipe checks every assay that it reads over these cells, the analyzed assay and, with
hashing, the HTO assay, and the assay of each QC metric that it filters on. A cell that one of them
did not measure raises UnmeasuredCellsError with the
operation pipeline.rna, pipeline.atac, pipeline.adt, or pipeline.perturbation, whose guide
assay is checked too, and a message that says how to pass
measured cells as cells; when the cells are an earlier run’s, it says to run that earlier run on
cells that the assay measured too, so that the runs analyze the same cells. The run never narrows
cells on its own.
Quality control stages#
The rna recipe calls cells, demultiplexes hashtags, and filters, in that order. Each stage reads
the cells that the one before it kept, and the cells that remain are the run’s
analysis_cell_selection.
Cell calling#
cell_calling=True calls cells in a raw droplet matrix with EmptyDrops
(call_cells()). It tests the barcodes of cells,
so open a raw droplet store with min_features_per_cell=-1, which keeps every barcode, the ambient
pool included, in I. The run gains the cell_calling statistics and the called_cell_selection.
cell_calling={"sample_column": "capture"} calls each capture apart, with its own ambient profile
and knee, and analyzes the union of the called cells; that run’s called_cell_selection records
each capture’s calls as its inputs, and the run has no cell_calling output. Every cell of cells
needs a capture label. The input snapshot freezes the capture column apart, as its
capture_snapshot, so each capture’s calls stay the same when the filtering or snapshot settings
change. When the calling of one capture fails, the stage’s error names that capture, such as
Cell calling failed for capture 'a' of 'capture': ....
Hashing#
hashing=True demultiplexes hashtags with
hto_demultiplexing(). It reads the store’s only
assay of type HTO, or the one that hashing={"assay": ...} names. The run keeps the cells of
exactly one hashtag, those not called Negative or Doublet, as its hashed_cell_selection, and
gains the hashing labels. With MAD filtering and no sample_column, the filter computes its bounds
within each hashtag, and the run records "sampleSource": "hashing" in its filtering settings. A
hashing stage that calls no cell a singlet fails.
When pools of cells used different hashtags, hashing={"sample_column": ...} names the cell column of each cell’s pool, and each pool is demultiplexed on its own, as a run of its cells would. One fit over every pool is refused, because each hashtag’s background then lies in a pool that did not use it. hashing={"hashtags": [...]} demultiplexes only the named hashtags, in every pool, and a mapping from each pool’s label to its hashtags names them pool by pool. The run checks the column and the hashtags before it starts and records each list in the assay’s order; the stage checks the mapping’s labels against the pools of its cells.
Filtering#
filtering=None, the default, filters the cells of an rna or atac run whose cells names a
column, and keeps a given selection’s or run’s cells as they are, which are taken as already
filtered. An rna run that calls cells or demultiplexes hashtags filters the cells that those
stages keep whatever its cells, because called cells and hashtag singlets are not filtered yet.
The adt recipe filters only when filtering is True or a mapping. True filters with the
defaults, False keeps the input cells, and a mapping configures the filter.
Filtering reads the QC values frozen in the run’s cell snapshot. Without attrs, it reads the QC
columns that the assay’s preparation wrote: <assay>_nCounts, <assay>_nFeatures,
<assay>_percentMito, and <assay>_percentRibo for RNA, <assay>_nCounts and
<assay>_nFeatures for ATAC, and <assay>_nCounts alone for ADT, because nearly every cell detects
nearly every antibody of a small panel. If filtering is requested and none of those columns exists,
validation raises instead of silently analyzing the unfiltered cells. Pass filtering=False only
when that choice is deliberate.
The filter applies the rules of qc.auto_filter. The default and method="auto" both resolve to
method="mad". MAD filtering accepts attrs, n_mads, min_cells_per_sample, and optionally
sample_column; without a sample column it uses pooled bounds. Groups with fewer than 20 active
cells are retained with a warning by default, including small pooled selections. Pass
method="gaussian" for the Gaussian policy, with attrs, min_p, and max_p; Gaussian filtering
does not accept a sample column. method="manual" requires lows and highs, one bound for each
of the attrs, which default to the assay’s QC columns as for the other methods, with an optional
bool keep_bounds. Probability, MAD, and manual-bound values must be finite numbers when present;
bools and numeric strings are rejected rather than coerced.
run = ds.pipeline.rna(
filtering={
"method": "manual",
"attrs": ["RNA_nCounts", "RNA_nFeatures"],
"lows": [1000, 500],
"highs": [15000, 4000],
},
)
The run records the filter’s resolved parameters as config["stages"]["filtering"], such as
{"enabled": True, "method": "mad", "attrs": [...], "minP": 0.01, "maxP": 0.99, "sampleColumn": None, "nMads": 3.0, "minCellsPerSample": 20}, or {"enabled": False} when the
run does not filter.
Stage contracts#
Embeddings#
umap=False skips UMAP, and the embedding initialization unless LocalMAP or t-SNE, which use it, runs; a skipped stage’s artifact does not appear in the completed run. UMAP forms the fuzzy union of the graph itself, so umap symmetric_graph and graph_upper_only must stay False. neighbors ann_ef sets the search depth of the neighbor query, by default max(200, 2 * k) with the default index; the neighbors artifact records a depth other than its index’s own as its ann_ef.
LocalMAP lays out the run’s connectivity map from the same initialization, right after UMAP; its coordinates appear as localmap_1, localmap_2, and so on. The stage runs on the datastore’s threads, which do not change the layout, so localmap={"nthreads": ...} is rejected as an unknown setting.
t-SNE embeds the run’s graph from the same initialization, after the clustering stages; its
coordinates appear as tsne_1, tsne_2, and so on. A new t-SNE embedding needs the optional
sgtsnepi package of the tsne extra; without it the tsne stage fails, after the earlier stages
have completed, and the run raises a PipelineExecutionError whose __cause__ is the
ImportError that names the extra. A run whose t-SNE embedding the store already holds reuses it
without the package, so a run that enables t-SNE without sgtsnepi is not refused: the run logs a
warning that names the extra before it creates a run record, and then runs.
tsne={"parallel": ...} is rejected as an unknown setting.
Leiden and Paris#
The leiden stage clusters the graph at each resolution of partitions, by default 0.5, 0.75, 1.0, and 1.25, or 1.0 for a multimodal run. leiden=True and leiden={} use the defaults. Partitions must be a non-empty sequence without duplicate resolutions, and the run orders them by resolution. run["leiden"] holds the candidates, a tuple of refs in that order, and the stage record times them together. Each candidate records its resolution among its parameters, so ds.artifacts.find("clusters", graph=run["connectivity_map"], method="leiden", resolution=1.0) finds one, with graph=run["integrated_graph"] for a multimodal run, in runs of this release and of earlier ones alike. selected names one of the partitions as the saved clustering, run["clusters"], in place of the silhouette choice, and the cluster-selection stage is skipped; the other partitions still run beside it.
run = ds.pipeline.rna(label="rna")
run["leiden"] # (ArtifactRef(...), ArtifactRef(...), ArtifactRef(...), ArtifactRef(...))
fine = ds.artifacts.find(
"clusters", graph=run["connectivity_map"], method="leiden", resolution=1.25
)
ds.plots.embedding(run=run, color_by=[run["clusters"], fine])
backend defaults to "cytearc", CyteArc’s own multi-threaded Leiden implementation, which runs on
the datastore’s worker budget and gives the same labels for any thread count. "igraph" and
"leidenalg" need those GPL-licensed packages, which CyteArc does not install. Without them, a
Leiden stage that must compute a new partition with either backend fails, after the earlier stages
have completed, and the run raises a PipelineExecutionError whose __cause__ is the
ImportError naming the missing package; a partition that the store already holds is reused
without the packages.
Doublets, markers, and membership strength require at least one Leiden candidate. Paris can still
run as a diagnostic output when those stages are off: ds.pipeline.rna(leiden=False, paris=True, doublets=False, markers=False) has run["paris"] and no run["clusters"]. Membership strength
is computed on the saved clustering and appears as membership_strength: the fraction of each
cell’s graph neighbors that carry the cell’s own cluster label.
Graphs without PCA#
pca={"dims": 0} skips the pca stage of an rna run. The graph is then built on the normalized
values of the selected features, one coordinate per feature: the ANN index, the neighbors, the
embedding initialization, and cluster selection use run["normalized"] as their coordinates, and
the run records no pca output. Harmony corrects reduced coordinates and doublet scoring needs a
PCA graph, so dims=0 with harmony, or with doublet scoring on, which it is by default, raises
ValueError before a run record is created; pass doublets=False.
With dims=0 the graph has one coordinate per highly variable gene, so the memory and time of the
ANN index, the neighbor queries, the embedding initialization, and cluster selection scale with
hvg top_n instead of the PCA dimensions. The hnswlib index holds about
4 * top_n + 8 * ann_m + 130 bytes per cell on x86-64 Linux, about 4.3 GB for 1,000,000 cells
with 1,000 genes and 8.3 GB with 2,000 at the default ann_m=24, and the ann_index and
neighbors stages fail before they create or load it when it does not fit the memory budget: the
run raises a PipelineExecutionError whose __cause__ is the MemoryError. By default the
embedding initialization reads the coordinates in their stored row bands, and fits k-means in memory
over every cell’s coordinates, 4 bytes per gene per cell, when one band holds every cell; set
embedding_initialization={"batch_size": ...} below the cell count to select the streamed fit,
which holds a sample of the cells and one block of coordinates at a time.
Doublets and Harmony#
harmony={"batch_columns": [...]} corrects the run’s reduced coordinates, PCA or LSI, and the main graph then uses the Harmony coordinates. Doublets form only within one capture, so when an rna or atac run with Harmony scores doublets, it simulates and scores them within each batch, the cells that share every Harmony batch label, on the uncorrected PCA or LSI coordinates that Harmony started from; no other graph is built. doublets={"sample_column": ...} names the column of each cell’s capture instead, and cannot be None with Harmony. Without Harmony, doublets are scored within each sample of that column, or across every cell when it is omitted. The input snapshot stage freezes the sample labels as its doublet_sample_snapshot output and the Harmony batch labels as its harmony_snapshot output, apart from the cell snapshot that filtering reads (Run snapshots), and the run configuration records the doublet sample columns as doubletSampleColumns.
The doublets stage simulates doublets from any two cells of a sample by default. With
doublets={"heterotypic_fraction": ...} above 0, it forces that share of the simulated doublets to
pair parents from two different clusters, so it needs a saved clustering with two or more
clusters. The silhouette choice never saves a partition with one cluster, but leiden selected
can. The stage then fails with a PipelineExecutionError that names the settings to change: select
a partition with two or more clusters, set doublets={"heterotypic_fraction": 0} to simulate
doublets from any two sampled cells, or pass doublets=False. A run with doublets has the frozen
cell fields doublet_score and predicted_doublet, the call of each cell
(Doublet detection).
Automatic cluster selection#
The cluster_selection stage of the rna, atac, and adt recipes scores the Leiden candidates
in the coordinates that built the graph: PCA, LSI, or Harmony coordinates, or with
pca={"dims": 0} the normalized values. A multimodal run has no automatic selection: its integrated
graph has no shared coordinates, so its only or selected Leiden candidate is run["clusters"],
and its cluster_selection stage is always skipped. Paris remains run["paris"] for diagnosis and
comparison; it is never the automatic run["clusters"] winner.
Selection uses one deterministic shared sample of at most 10,000 selected cells with seed 4466.
The sample reserves up to two seeded cells per cluster across every Leiden candidate, then fills
remaining capacity without replacement. The sampled cells’ coordinates are read in blocks under the
datastore memory budget, and pairwise distances are computed in chunks of a third of the budget
that remains after the sampled coordinates in float64 and a small allowance for each sampled cell,
at most 1 GiB. Before it reads a coordinate, the stage fails when the sampled coordinates, in their
stored dtype and as float64, with one block of the read or with the distance chunks, exceed the
budget: the run raises a PipelineExecutionError whose __cause__ is the MemoryError. Reading
a sample spread over a large normalized matrix, as with pca={"dims": 0}, decodes most of its
stored chunks.
This silhouette comparison is a reproducible provisional baseline. It is not biological validation or ground truth. Keep alternative Leiden refs and Paris when the study question needs other evidence.
The resulting cluster_selection artifact records each candidate’s key, its resolution as text such as "1.0", with its ref and silhouette score, the sample definition (sampleStrategy="sharedClusterQuota" and minClusterQuota=2), invalid-candidate reasons, deterministic tie order, and the selected key. Runs of earlier releases keyed their candidates by output name, such as "leiden_1.0", so a new run on their store computes the decision once again while it reuses their Leiden candidates.
run["clusters"] is the selected Leiden candidate’s exact ref. It is not a copied artifact or
metadata column. If no Leiden candidate can be scored, the stage fails. A single valid Leiden
candidate still receives a decision artifact.
Persisted cluster selection is intentionally pipeline-only. The recipes own the candidate set,
deterministic sampling policy, and run-ledger decision. Granular callers can evaluate their own
partitions with public APIs such as evaluate_cluster_separability in cytearc.metrics. There is
no public “best clustering” function and no separate DataStore persistence method that could
imply the pipeline policy outside a run.
Durable outputs and frozen views#
A completed run exposes its outputs in a fixed order; an output that the run did not produce is
absent. A default rna run has:
input_cell_selection, analysis_cell_selection, feature_universe, cell_cycle,
highly_variable_features, normalized, pca, ann_index, neighbors, connectivity_map,
embedding_initialization, umap, cluster_selection, clusters, doublets, markers, leiden
Optional stages add their outputs in place: cell_calling, called_cell_selection, hashing, and hashed_cell_selection after input_cell_selection; harmony after pca; localmap after umap; paris after localmap; membership_strength and tsne after clusters; and an atac run’s doublets before markers. A run with leiden selected has no cluster_selection output. leiden, the one output that holds several refs, comes after the others. Runs of earlier releases have one output per Leiden candidate in its place, such as leiden_1.0 after umap, and no leiden output.
A default atac run has:
input_cell_selection, analysis_cell_selection, feature_universe, prevalent_peaks, normalized, lsi,
ann_index, neighbors, connectivity_map, embedding_initialization, umap, cluster_selection, clusters,
markers, leiden
A default adt run has the same outputs with panel in place of prevalent_peaks and pca in
place of lsi, and measured_antibodies after panel when the sources of its cells measured
different antibodies. A default WNN multimodal run of an RNA run and an ADT run has:
input_cell_selection, analysis_cell_selection, feature_universe, integrated_graph,
embedding_initialization, umap, clusters, markers_RNA, markers_ADT, leiden
Its input_cell_selection and analysis_cell_selection are both the selection that its runs share, and its feature_universe is the first run’s. A default perturbation run has:
input_cell_selection, analysis_cell_selection, feature_universe, guide_thresholds, guide_calls,
perturbation_labels, efficiency, highly_variable_features, normalized, pca, edistance
Its optional stages add harmony after pca, and signature, mixscape, associations, profiles, and perturbation_clusters, in that order, after edistance. Calls that fit no thresholds, with method="fixed" or "top_guide" or imported from Cell Ranger, have no guide_thresholds.
run.recipe names the recipe, "rna", "atac", "adt", "multimodal", or "perturbation", and run.assay the analyzed assay, the RNA assay of a perturbation run, or the first run’s assay for a multimodal run. Normal mapping operations such as run["pca"], list(run), and run.items() are available only on a successfully completed run. Each output is one ArtifactRef, except run["leiden"], a tuple of refs, which len(run) counts once.
Run snapshots#
The input_snapshot stage freezes the metadata that later stages and the run’s fields read, so a
later change to a live column never changes the run’s results or fields. Its snapshots are
outputs of the stage, which its stage record lists, not run outputs: run["cell_snapshot"] raises
KeyError. Besides the cell and feature snapshots, each other group of cell columns has a snapshot
of its own, which the stage writes only when the run reads that group:
Stage output |
Holds |
Read by |
|---|---|---|
|
the cell IDs and |
the |
|
the feature IDs and |
the stages that name features, such as |
|
the capture column of per-capture cell calling, |
the |
|
the Harmony |
the |
|
the columns whose labels split doublet scoring, |
the |
|
the run’s |
the run’s cell fields of those columns |
A column that one stage reads therefore never changes the identity of what another stage computes:
runs that differ only in their Harmony batch columns or their snapshot_columns filter to the same
analysis_cell_selection artifact and share every artifact that does not depend on that
difference, and per-capture cell calls stay the same when the filtering or snapshot settings
change. A multimodal run’s cell_snapshot holds the cell IDs and names only, beside a
column_snapshot when the run names snapshot_columns, and its input stage stores a
feature_snapshot_<assay> and a feature_universe_<assay> for each source run’s assay.
Frozen fields#
run.cells and run.features are narrow read-only views over captured selections, metadata
snapshots, and result artifacts:
view.columns
view.fetch(column) # rows selected by the run's stored I
view.fetch_all(column) # values aligned to the complete stored axis
view.to_pandas_dataframe(columns) # selected rows
view.head(n=5)
Field |
View |
Present when |
|---|---|---|
|
cells and features |
always |
the |
cells |
named |
|
cells |
an |
|
cells |
UMAP runs |
|
cells |
LocalMAP runs |
|
cells |
t-SNE runs |
|
cells |
Paris runs |
|
cells |
a Leiden candidate is saved; the other candidates have no field, and |
|
cells |
|
|
cells |
an |
|
cells |
a WNN |
|
cells |
a |
|
cells |
a |
|
features |
an |
Cell I is the analysis selection. Feature I is backed by the immutable
run["feature_universe"] selection created during the input stage, not the live feature I
column; a multimodal run’s feature view covers its first run’s assay with I, ids, and names
only. The views retain captured names and requested metadata even if live values or live I later
change. They fail closed if ordered cell or feature identities change. There is no live overlay or
mutation surface.
Every assay of a store shares its cells, so a cell field can read an artifact of any assay, such as the guide calls of a perturbation run, which belong to the guide assay. The cell view checks that each artifact was computed on the run’s cells, as its recorded cell selection shows, and refuses one computed on other cells. Each assay has its own features, so a feature field reads only artifacts of the run’s assay. A run opens both views before it completes, so a field that a view refuses fails the run at "finalize", and the run does not take its label.
snapshot_columns cannot use the name of a field that the run produces or could produce: I, ids, names, s_score, g2m_score, cell_cycle_phase, the run’s umap_<n>, localmap_<n>, and tsne_<n> fields, leiden_<resolution> for each Leiden candidate, the field that runs of earlier releases gave it, paris, clusters, membership_strength, doublet_score, predicted_doublet, and the recipe’s feature field, or for a multimodal run its weight_<assay> fields. A perturbation run also reserves guide_call, perturbation_label, and is_control, and mixscape_class and mixscape_posterior, which a run without Mixscape does not produce.
Pipeline execution writes immutable artifacts and run records only. It never inserts result
columns or rewrites live I. Plotting, marker loading, and export stay on DataStore:
ds.plots.embedding(run=run, layout="umap", color_by="clusters")
markers = ds.markers.load(marker=run["markers"], group_id=1)
adata = ds.to_anndata(run=run)
# adata.obsm["X_umap"] holds frozen UMAP; cluster labels stay in adata.obs
A run export writes an RNA or ADT run’s PCA as obsm["X_pca"] and an ATAC run’s LSI as
obsm["X_lsi"], with their Harmony corrections as obsm["X_pca_harmony"] and
obsm["X_lsi_harmony"]. matrix="normed" exports the run’s normalized values over its feature
field’s features. A multimodal run exports the raw counts of its first run’s assay and has no
normalized output (Import and export API reference).
The marker table of a run saved before CyteArc 1.0.0 cannot be read, because its fold_change
column held sentinels: markers.load raises and names
ds.markers.search(run["clusters"], features=run["feature_universe"]), which recomputes the
table for the run’s clusters.
Run configuration#
run.report()["run"]["config"] records how the run was called. For rna, atac, and adt, it holds cells ({"column": ...}, {"selection": ref}, or {"run": {"runId", "label"}, "selection": ref}), snapshotColumns, species, doubletSampleColumns (rna, and atac runs recorded since the ATAC recipe scores doublets), stages, and shutdown, the signal protection of the run. stages maps each stage keyword to the settings that the call gave it, False for an optional stage that the call turned off, and a bool for membership_strength and markers. The recipe resolves a few of them: normalization records its method, pca its dims, prevalent_peaks its top_n, leiden its partitions and selected resolution, panel its exclude pattern and the excluded names, and the unmeasured antibodies when it leaves any out, hashing its assay, and filtering the filter’s parameters. A multimodal run records method, sources (each run’s runId, label, recipe, and assay), cells ({"selection": ref}), snapshotColumns, stages, and shutdown.
A perturbation run records cells, snapshotColumns, guideAssay, the guide assay, profileLabels, the output whose cells the profiles average ("mixscape" for knocked-out cells, the default in a run with Mixscape, "perturbation_labels" for every labeled cell, and None without clusters), stages, and shutdown. Its stages record False for signature without Mixscape and for profiles without clusters, and a guide_calling path as the text of the path.
Open, list, and report runs#
A label is optional. A run that completes takes its label as an immutable name, unique in the store:
run = ds.pipeline.open(label="baseline")
same_run = ds.pipeline.open(run_id=run.run_id)
recent = ds.pipeline.list_runs(limit=20)
failed = ds.pipeline.list_runs(status="failed")
unfinished = ds.pipeline.list_runs(status=["running", "interrupted"])
open requires exactly one of run_id or label. Only a successfully completed run acquires its requested label. Paused, failed, and interrupted attempts do not reserve it. list_runs returns newest first and includes every status, running, paused, completed, failed, and interrupted, unless status names one or a sequence of them. Concurrent finalizers use an atomic label claim, so at most one completed run can acquire a name. A storage backend without atomic conditional creation rejects label= before a run record or computation starts; unlabeled runs are unaffected. An unclean incomplete finalizer blocks reuse of its requested label and fails closed.
After confirming that the owner process has stopped, explicitly abandon that exact claim before retrying the label:
interrupted = ds.pipeline.abandon_label_claim(
label="baseline",
run_id=stopped_run_id,
reason="worker terminated after finalization began",
)
replacement = ds.pipeline.rna(label="baseline")
The recovery call succeeds only for the exact current owner while complete=False, including a
torn terminal payload, and records an abandoned_label_claim interruption. It refuses every
complete=True owner and has no timeout or automatic stale-process heuristic.
Several runs can run at once on one store, each in a process of its own, as Several processes on one store describes. Each writes its own run record, and a stage that two runs share and neither has saved yet is computed by both.
Every status exposes identity, status, recipe, and run.report(format="dict" | "markdown"). Only a completed run exposes mapping outputs and frozen views. Reports include what each stage used and what its process had (Stage resources), artifact plans with created or reused dispositions, stage summaries and warnings (Diagnostics), failures, interruption details, and signal-guard availability.
A hard process death can leave complete=False; this is reported as an unclean incomplete run. Such a run has no repair or same-ID retry, since only a paused run resumes (Pause and resume a run), and a new invocation reuses only its complete artifacts.
Stage resources#
Each stage record’s metrics holds what the stage used beside what its process had, so every run carries a resource trace of its stages: which stage stays on one core, which reads the most over the network, and which needs the most memory. cpuSeconds over wallSeconds gives the cores that a stage used on average, and resources["workers"] the worker count it was given, the store’s nthreads. A stage that stays near one core although given eight runs serially, as UMAP’s layout does by default. The trace holds up to 64 samples of each stage, about 3 s apart over a 17-minute stage, with the CPU seconds and network bytes counted since the stage started and the largest RSS and thread count between samples. resources also records the CPUs and memory that the process could use as the stage started, so stages that different machines ran stay comparable. Pipeline records and snapshots describes each field.
The measurements cover the whole process, so work on other threads of the process during a stage counts toward that stage. RSS peaks are sampled lower bounds, and a call that holds the GIL, such as SciPy’s wrapped BLAS and LAPACK routines, pauses sampling until it returns. rssHighWaterEndBytes, the kernel’s mark of the process’s peak RSS, keeps such a peak when the stage raised it above rssHighWaterStartBytes. networkRxBytes and networkTxBytes count the process’s network namespace, which on a container worker is the container and on a laptop is usually the whole machine.
RSS, thread counts, and network bytes come from the Linux /proc filesystem. On platforms without it, such as macOS and Windows, RSS is not sampled, so sampleCount is 0, and the other two are null, each with its reason in unavailable. CPU time and its trace are recorded on every platform, and the process’s peak RSS wherever Python offers getrusage, which Windows does not.
Runs saved by other releases#
A run completed under any 1.x release reopens under every later 1.x release. open by label or
run ID, list_runs, run[key], run.report(), and the frozen run.cells and run.features
views work as long as the artifacts the run references exist and satisfy their payload contracts.
Runs that pipeline.run() saved open unchanged. Their run.recipe is "basic_rna_analysis", and
their configuration keeps the shape that their release recorded, such as cellKey, hvgCount,
pcaDims, and params. Reopening never checks a configuration against the current recipes, so
such a run reopens and reports although no current recipe accepts its configuration. To run it
again, translate its configuration into ds.pipeline.rna keywords with the
migration table; a new run never modifies the earlier one. Their
stage records have no summaries or warnings, which their reports show as None and an empty list.
Stage records of releases before the stage resources hold metrics without cpuSeconds, threadsPeak, rssHighWaterStartBytes, rssHighWaterEndBytes, networkRxBytes, networkTxBytes, resources, trace, and unavailable. Their reports show each as None, and the plan’s estimates take None for them.
Running a configuration again recomputes a stage whose operation gained a revision that applies to
it, or whose recorded provenance a later release changed. Lineage reports of the earlier run’s
outputs mark those that a revision supersedes stale. A changed default changes the recorded
provenance too. The default Leiden backend changed from "igraph" to "cytearc", so a run that
does not set leiden={"backend": ...} computes new Leiden partitions where an earlier release
stored igraph partitions, and the stages that use them, such as cluster selection, doublet scoring,
and marker search, compute new results too. The earlier partitions are not superseded or marked
stale: set leiden={"backend": "igraph"} to reuse them, which needs no igraph installation while
the store holds them.
Runs saved by releases before the normalization method, such as every run of 1.4.0, do not record their normalizer, and their recipes applied the assay’s normMethod of the session that ran them. run.settings() of such a run gives it the method of the normalizer that its saved normalized values record in their provenance: a built-in normalizer’s name, or a custom normalizer’s identity, which a rerun and a plan then need as the assay’s normMethod (Normalization method). A rerun or a plan of the run in any session therefore normalizes as the run did. A run that saved no normalized values, such as one interrupted before its normalization stage, gets no method, so a rerun takes the assay’s normMethod; run.settings() raises ValueError for a run whose saved normalized values are missing or record no normalizer. Such a run also scaled its PCA’s features unless its call set feat_scaling, the default then, where a run of Pearson residuals now does not, and a custom normalizer may be one. run.settings() of a run of Pearson residuals or of a custom normalizer that set no feat_scaling therefore gives its pca the feat_scaling of True that it applied, so a rerun reuses its PCA and the stages after it. The scaling comes after a rerun’s changes, so pca={"dims": 0} reruns without PCA, and a feat_scaling that the rerun gives wins.
A run whose records a newer CyteArc saved with fields this release does not know fails closed:
opening it by run ID, or reading its stage records with report(), raises a ValueError that
names those fields. Upgrade CyteArc to read it. Within 1.x, releases only add record fields, so runs
from earlier releases never meet this error. The pipeline recipes added the stage fields summary
and warnings: a 1.x release from before the recipes opens the runs that they save, but its
report() raises on those fields. A 2.0 release may change run records and lists each change in
its compatibility inventory.
Releases from before the stage resources open the runs that this release saves, but their report() raises on the new metric fields, and their plan skips those stage records with a warning.
Runs of releases before the one leiden stage hold one leiden_<resolution> stage, output, and cell field for each Leiden candidate, and they keep them: run["leiden_1.0"] and run.cells.fetch("leiden_1.0") read such a run, and it plots and exports with those names, while it has no run["leiden"]. To read a candidate the same way in runs of every release, find it by its graph and resolution with ds.artifacts.find("clusters", graph=run["connectivity_map"], method="leiden", resolution=1.0). A new run with the same settings reuses their Leiden candidates. The runs that this release saves hold the record field outputLists, which earlier releases do not know: they skip those runs when they list runs and raise when they open one.
A run that paused holds the record field segments and may hold the status paused, which releases before pause and resume do not know: they skip such a run when they list runs and raise when they open it. A run that never paused holds no segments, so its record is unchanged. A paused run resumes only with the release that recorded it.
A cell field can read an artifact of another assay than the run’s, as the guide fields of a perturbation run do (Frozen fields). Such a field is an ordinary entry of the record’s fields, so run records keep their shape, with no new record field, schema version, or migration, and every saved run reads as before. CyteArc 1.3.0 and earlier releases read cell fields of the run’s assay only: they refuse the cell view of a run with such a field, with an ArtifactResolutionError whose code is pipeline_field_axis_mismatch, while its outputs and feature view open. They do not know the artifact kinds of a perturbation run’s guide calls and labels, such as guide_calls, so they open no perturbation run. A run keeps the fields that it recorded and gains none later: a perturbation run saved without the guide fields gets them only from a new run of the recipe with the same settings, under another label or none, which reuses every artifact of the earlier run.
Run and stage records are otherwise strict: a missing or unknown field, or a malformed value,
fails closed. list_runs and open-by-label skip records they cannot read so healthy runs remain
accessible, and log a warning that names each skipped run ID and why it could not be read. Opening
that run by its exact ID raises its error.
Diagnostics#
A completed stage records a small summary when its outputs have diagnostics. The summary is
computed from the artifacts that the stage produced, so a reused artifact reports the same numbers
as a computed one, and it is computed within the stage, so its time, memory, and warnings belong to
that stage. A summary reads attributes and bounded blocks of small arrays, never a matrix. A stage
with one summarized output records that output’s summary; a stage with several records one summary
for each output key. Metadata snapshots and ANN indexes have no diagnostics, so input_snapshot
reports only its input cells and feature universe, and ann_index records None. A summary that
cannot be computed is logged as a warning and left out. For example:
Stage |
Summary |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The perturbation summaries count adjusted p-values of at most 0.05 and targets with fewer than 25 cells, fixed thresholds; the loaders of Perturbation API reference read every row for others.
Each stage record also keeps the warnings that CyteArc logged or issued while the stage ran, oldest first: at most 50, each cut to 512 characters. The stage’s own worker threads report into it; warnings that unrelated work logs on other threads or asyncio tasks at the same time are not collected. Only a completed stage holds a summary; a failed or interrupted stage keeps its warnings.
run.report() returns three entries:
run: the run record, withrunId,recipe,requestedLabel,label,assay,startedAtNs,finishedAtNs,status,complete,cytearcVersion,config,stageOrder,outputs,fields,error,interruption, andoutputLists, the outputs that hold several refs, such asleiden;stages: each stage record written so far, skipped stages included, withstage,ordinal,status, its times,outputsandoutputLists, each listed artifact with whether the stage reused it,plans,metrics(Stage resources),error,interruption,summary, andwarnings;summary:createdArtifacts,reusedArtifacts,uncleanIncomplete,signalProtection, andwarnings, a list of{"stage", "message"}entries for every stage’s warnings in stage order.
run.report(format="markdown") shows each stage’s wall and CPU seconds, sampled peak RSS, received bytes, and warning count in its stage table, and adds a ## Diagnostics section with each stage’s summary as JSON and its warnings. A stage record of an earlier release leaves the CPU seconds and received bytes empty.
Events and listeners#
A recipe’s callback, and every listener registered with cytearc.pipeline_listener(),
receives a PipelineEvent for each step of a run.
Events report a run; they cannot change it. To stop a run, use a
cancellation token.
import cytearc
events = []
with cytearc.pipeline_listener(events.append):
rna = ds.pipeline.rna(label="rna")
adt = ds.pipeline.adt(cells=rna, label="adt")
[(event.recipe, event.kind, event.stage) for event in events]
Every event carries kind, run_id, recipe, label (the requested label, or None), stage,
ordinal (the stage’s position in run.report()["run"]["stageOrder"]), stages (how many stages
the run has, skipped stages included), and time_ns. The other fields depend on the kind:
Kind |
Emitted |
Other fields |
|---|---|---|
|
after the run record is created |
|
|
after a paused run is recorded running again, in place of |
|
|
after a stage’s record is written, before the stage runs |
|
|
while a stage runs, as a CyteArc progress bar advances |
|
|
after the stage’s outputs are recorded |
|
|
after a stage that the run does not compute is recorded as skipped: one that the call turned off, or one that the recipe skips, such as |
|
|
after the stage and the run are recorded as failed |
|
|
after the stage and the run are recorded as interrupted |
|
|
after the run is recorded paused, once the stage that |
|
|
after the run record is complete |
|
|
after the run is recorded as failed |
|
|
after the run is recorded as interrupted |
|
outputs holds the (key, ref) pairs that a completed stage produced, one pair for each ref of an output that holds several, such as leiden, and reused the keys whose artifacts were reused rather than computed; an output of several refs counts as reused when every one of them was. metrics and summary are the values that the stage
record holds. error is the exception: the stage’s own for stage_failed, the
PipelineExecutionError for run_failed, and the interruption for stage_interrupted and
run_interrupted.
A run emits run_started first, and a process that resumes a paused run emits run_resumed instead and then the events of the stages that it runs. Each stage then emits stage_skipped alone, or stage_started, any number of stage_progress events, and one of stage_completed, stage_failed, or stage_interrupted, before the next stage emits anything. The process then ends with one run event: run_completed after the last stage, run_paused after the stage that run_until names, run_failed, or run_interrupted. run_started, run_resumed, run_paused, and run_completed name no stage.
run_failedalways names a stage. It followsstage_failedand names that stage. A failure to write a stage’s first record emits it without a stage event, a failure to pause the run names the steppause, and a failure to complete the run record names the stepfinalize; neither step has an ordinal. An error while a skipped stage is recorded emitsstage_failedwithoutstage_started.run_interruptednames a stage only when the interruption cut that stage’s work short: it then followsstage_interrupted. An interruption between two stages or while a skipped stage is recorded emitsrun_interruptedalone, with no stage. So does one that a stage notices just after its work finished: that stage is recorded as completed and emitsstage_completedfirst.
Events are delivered synchronously, on the thread that runs the recipe, after the durable state
that they describe is written. The run’s own callback is called first, then the listeners in the
order they were registered. A slow callback delays the run, so hand events to a queue for slow work
such as updating a remote UI. Callbacks run in a copy of the context in which the recipe was called,
taken before the run installs its shutdown and cancellation handling, and outside every stage. What
a callback does, such as logging a warning, drawing a progress bar, or computing an artifact, never
enters a stage’s record or events, and a pending cancellation or signal never interrupts the
CyteArc work that a callback does. An exception from a callback or listener, BaseException
included, is logged and never changes the run.
pipeline_listener(listener) is a context manager. Its registration is context-local: it covers
the runs started in the with block on that thread or asyncio task, and registrations nest. A run
reads its listeners when it starts, so a listener registered later does not receive its events. A
run started on another thread receives a listener only when that thread runs in a copy of the
registering context, as asyncio.to_thread and contextvars.copy_context().run provide.
event.to_dict() returns the event as JSON-compatible values for a UI or a log, with camelCase
keys: kind, runId, recipe, label, stage, ordinal, stages, timeNs, progress,
metrics, summary, outputs as {"key", "artifact", "reused"} entries, warnings, and error
as {"type", "message"} with the message cut to 512 characters. PipelineEvent and
PipelineProgress are frozen dataclasses, and an event pickles when its error does.
Progress events#
While a stage runs, the CyteArc progress bars that advance on the run’s thread report to the run’s
callbacks and listeners as stage_progress events. Their progress is a
PipelineProgress: the bar’s description, or
None, the units completed, and the total units, or None when the bar has no total. A stage
emits at most one progress event every 0.25 seconds for each progress bar, so bars that share a
description are throttled apart, and it always emits a bar’s first update and the update that
reaches the bar’s total; later updates past the total are throttled like the others. Progress
events are emitted while bars are hidden with configure_output(progress=False) too, and only when
the run has a callback or listener. A stage that streams the matrix in blocks, such as HVG
statistics or marker ranking, advances its bar on the run’s thread as each block’s result is used.
Work that draws no CyteArc bar emits none: UMAP’s training bar belongs to umap-learn and is not
forwarded.
Cancellation#
A CancellationToken stops a run from any thread, such as a UI’s stop button:
import threading
import cytearc
token = cytearc.CancellationToken()
outcome = {}
def analyze() -> None:
try:
outcome["run"] = ds.pipeline.rna(label="rna", cancel=token)
except cytearc.PipelineCancelled as error:
outcome["cancelled"] = error
worker = threading.Thread(target=analyze)
worker.start()
token.cancel("stopped from the UI")
worker.join()
The run stops at its next safe checkpoint. CyteArc checks between stages and between the bounded
blocks of streamed work, so a step that holds no checkpoint finishes before the run stops. The run
records the stage that was running, if any, as completed when its work had finished and otherwise
as interrupted, and records the run as interrupted, with interruption kind cancelled and the
reason as its message. It emits run_interrupted after that stage’s event, and raises
PipelineCancelled, a RuntimeError whose run_id, stage, and reason
name the run, the stage whose work the cancellation cut short, and the reason. Like
run_interrupted, it names no stage, stage None, when the run stopped between stages or just
after a stage’s work finished. Completed stages keep their artifacts, so a new run with the same
settings reuses them.
A cancellation that arrives once the run record is complete comes too late to stop the run, and the call returns the completed run, or the paused run when the run had paused. One that races with a stage failure leaves the run failed and raises PipelineExecutionError.
A token stays cancelled. A run given a cancelled token raises PipelineCancelled with run_id and
stage None before it writes anything; its call is still validated first. cancel() returns True
only for the token’s first cancellation, and reason keeps the first reason. One token may stop
several runs at once. A signal that stops a run never cancels the token, and a cancellation never
runs a prior signal handler. PipelineCancelled pickles, so it can cross a process boundary.
A signal that arrives after a cancellation does not escalate, because it is the run’s first signal.
The run still stops at its next checkpoint and is recorded as interrupted with the kind of the
first request, cancelled. Once that is written, the signal takes its usual effect: its prior
handler runs, or the signal is raised again. With the default handlers, the call therefore raises
KeyboardInterrupt after SIGINT, and SIGTERM or SIGHUP terminates the process, instead of
the call raising PipelineCancelled.
Graceful interruption and signals#
On the main interpreter thread, a run temporarily installs cooperative handlers for available
SIGTERM, SIGINT, and SIGHUP, while respecting signals already set to ignore and handlers
installed outside Python. The first signal requests shutdown at a safe checkpoint. The run records
the stage that was running, if any, as completed when its work had finished and otherwise as
interrupted, and records the run as interrupted, with interruption kind signal. It emits
run_interrupted after that stage’s event, naming the stage only when the signal cut its work
short, restores prior handlers, and propagates the original signal behavior. A second catchable
termination signal escalates immediately. A signal that arrives after a cancellation was requested
is the first signal, so it does not escalate (Cancellation). A run on another
thread records that signal protection was unavailable, in
run.report()["summary"]["signalProtection"]; stop it with a cancellation token.
KeyboardInterrupt, an escaped asyncio.CancelledError, and the concurrent.futures.CancelledError that Zarr’s synchronous API raises for a cancelled read or write use the same durable interruption boundary, with interruption kinds keyboard_interrupt and asyncio_cancelled, the latter for both cancellation classes. Other stage exceptions produce a failed run instead. Run and stage records hold at most 512 characters of an error or interruption message. A longer message keeps its first 509 characters followed by ...; the raised exception keeps its full message. If a termination signal races with an ordinary failure or the final successful handoff, the run preserves that durable outcome and still propagates the pending signal after cleanup.
SIGKILL, SIGSTOP, out-of-memory termination, power loss, and expired shutdown grace periods
cannot perform cleanup. Their durable contract is an incomplete artifact or run, followed by a new
invocation that reuses only complete artifacts.
Follow a run from another process#
A run writes its run and stage records as it goes, so another process can follow it without a callback. Open the store read-only and report its running runs:
import cytearc
monitor = cytearc.DataStore("analysis.zarr", zarr_mode="r")
for running in monitor.pipeline.list_runs(status="running"):
report = running.report()
current = report["stages"][-1]["stage"] if report["stages"] else None
print(report["run"]["requestedLabel"], current, len(report["run"]["stageOrder"]))
report() reads the stage records again on every call, but a PipelineRun keeps the run record that it opened, so open the run again with monitor.pipeline.open(run_id=...) to see its status change. A running run has no label until it completes; its requestedLabel names the label that it will claim. A stage record shows running while its stage runs and its terminal status, metrics, summary, and warnings once it ends; stages that have not started have no record yet. A process that died without cleanup leaves its run running, and the record has no heartbeat, so confirm that the process has stopped before treating such a run as abandoned. A paused run is paused, and list_runs(status="paused") lists the runs that wait for a resume.
Public types#
- class cytearc.datastore.pipeline_accessor.PipelineAccessor(store)#
Store-bound entry point for CyteArc’s durable modality recipes.
Each recipe checks its call against the store before it writes anything: its keywords and settings, the columns and cells it names, its stage combinations, and the setting values that can be checked without reading data. A call that fails these checks raises and writes nothing. The recipe then runs its stages in order and returns a durable
PipelineRun. A few values, such as a Leidenbackend, are checked only by their stage’s method when the stage runs, and such a failure records a failed run.A stage keyword takes the keywords of the stage’s method, which mean exactly what they mean there, and an omitted setting takes that method’s default, except for a few defaults that a recipe fits to its data, such as an ADT run’s PCA
dims.- abandon_label_claim(*, label, run_id, reason)#
Mark an exact stopped finalizer interrupted so its label can be retried.
The caller must first confirm that the process executing
run_idhas stopped. CyteArc does not infer abandonment from elapsed time because a slow live finalizer must never lose its label claim.- Return type:
- adt(*, assay=None, label=None, cells='I', filtering=None, panel=None, normalization=None, pca=None, harmony=None, ann_index=None, neighbors=None, connectivity=None, embedding_initialization=None, umap=True, localmap=False, tsne=False, leiden=True, paris=False, membership_strength=False, markers=True, snapshot_columns=(), species=None, run_until=None, callback=None, cancel=None)#
Analyze an ADT (antibody) assay and return the durable run.
The recipe leaves isotype controls out of the panel, normalizes the antibodies with CLR, reduces them with PCA, optionally corrects batches with Harmony, and then builds, embeds, and clusters a graph as the RNA recipe does:
input_snapshot,filtering,panel,normalization,pca,harmony,ann_index,neighbors,connectivity,embedding_initialization,umap,localmap,leiden,paris,cluster_selection,membership_strength,tsne,markers.Analyze ADT with the cells of an RNA run,
cells=rna_run, to integrate the two withmultimodal().- Parameters:
assay (
str|None) – The ADT assay, of typeADT. Defaults to the default assay when it is one, else the store’s only ADT assay.filtering (
bool|Mapping[str,object] |None) – QC filtering, as forrna(). The run filters only whenfilteringis True or a mapping; None, the default, keeps the cells as they are, since an ADT run usually takes the QC-passing cells of an RNA run. Withoutattrs, the filter reads the assay’s<assay>_nCountscolumn only.panel (
Mapping[str,object] |None) –exclude, a regular expression of the antibody names to leave out (defaultDEFAULT_PANEL_EXCLUDE, which matches “isotype”, “control”, and “ctrl” in any case), or None to keep every antibody that every source of the run’s cells measured. On a store merged from different panels, the panel leaves out the antibodies that not every source of the run’s cells measured, which the run records asunmeasured, and the markers rank only those that every such source measured, so a run of one source’s cells keeps that source’s panel. The panel must keep at least two antibodies, and the run records the excluded names.normalization (
Mapping[str,object] |None) –methodand the keywords offeatures.normalize, as forrna().methoddefaults to the assay’snormMethod,"clr"for an ADT assay.pca (
Mapping[str,object] |None) – The keywords ofreduction.pca.dimsdefaults to one fewer than the panel’s antibodies, at most the PCA default, and must be below the panel’s number of antibodies.
- Return type:
The other arguments mean what they mean for
rna(). The run records the panel as itspanelfeature field.
- atac(*, assay=None, label=None, cells='I', filtering=None, prevalent_peaks=None, normalization=None, lsi=None, harmony=None, ann_index=None, neighbors=None, connectivity=None, embedding_initialization=None, umap=True, localmap=False, tsne=False, leiden=True, paris=False, membership_strength=False, doublets=False, markers=True, snapshot_columns=(), species=None, run_until=None, callback=None, cancel=None)#
Analyze an ATAC assay of peak counts and return the durable run.
The recipe filters cells on their counts and accessible peaks, selects the most prevalent peaks, normalizes them with TF-IDF, reduces them with LSI, optionally corrects batches with Harmony, and then builds, embeds, and clusters a graph as the RNA recipe does, and optionally scores doublets:
input_snapshot,filtering,prevalent_peaks,normalization,lsi,harmony,ann_index,neighbors,connectivity,embedding_initialization,umap,localmap,leiden,paris,cluster_selection,membership_strength,tsne,doublets,markers.- Parameters:
assay (
str|None) – The ATAC assay. Defaults to the default assay when it is an ATAC assay, else the store’s only ATAC assay.prevalent_peaks (
Mapping[str,object] |None) – The keywords offeatures.prevalent_peaks, such astop_n, which defaults to 10,000 or one fewer than the assay’s peaks, whichever is smaller, and must be below the assay’s number of peaks. The run records the resolvedtop_n.normalization (
Mapping[str,object] |None) –methodand the keywords offeatures.normalize, as forrna().methoddefaults to the assay’snormMethod,"tf_idf"for an ATAC assay.lsi (
Mapping[str,object] |None) – The keywords ofreduction.lsi, such asdimsandskip_first, a bool.dims, plus the first component thatskip_firstleaves out, must not exceedprevalent_peakstop_n. Cluster selection scores candidates in the LSI coordinates, or in their Harmony correction when the run has Harmony.doublets (
bool|Mapping[str,object]) – Doublet scoring, with the keywords ofqc.doublets; off by default. It weights simulated doublets by TF-IDF and projects them onto the LSI, so it needs the run to normalize with"tf_idf", the ATAC default, and it scores cells by Euclidean distances in the LSI whateverann_indexann_metricis. A run with Harmony scores doublets within each batch unlessdoubletsnames anothersample_column.
- Return type:
The other arguments mean what they mean for
rna(). The run records the selected peaks as itsprevalent_peaksfeature field.
- static describe(recipe, /)#
Describe the stage keywords of a recipe, their settings, and the defaults it uses.
For each stage keyword, in the order of the recipe’s signature, the description says whether the stage runs when the keyword is omitted, the public methods that it passes its settings to, and each setting that its mapping takes: the setting’s type, and the default that the recipe uses when a call omits it. That default is the method’s, except where the recipe sets its own: a key that configures the recipe, such as Leiden
partitions, has its own default, and a default that the recipe fits to its data or to the rest of the call, such as the ATAC recipe’sprevalent_peakstop_n, is given as the rule by which it is set. The description is built from the code that resolves the recipe, so it describes the installed release, and it needs no store:PipelineAccessor.describe("rna")gives the same asds.pipeline.describe("rna").plan()reports what a call on a store would do; a plan’sconfigholds the settings that the run would record, where the defaults that the recipe fits to the store take their values.- Parameters:
recipe (
str) –"rna","atac","adt","multimodal", or"perturbation".- Return type:
- Returns:
The recipe’s stage keywords, whose
to_dict()gives JSON values.- Raises:
ValueError – If
recipenames no recipe.
Example
>>> leiden = ds.pipeline.describe("rna")["leiden"] >>> leiden["partitions"].default (0.5, 0.75, 1.0, 1.25)
- end_paused(run, /, *, reason='ended while paused', release_claim=False)#
End a paused run that will not resume, recorded as interrupted.
A paused run waits for
resume()until a process resumes it. One that never will, because the analysis was dropped or its resume cannot go on, ends here: its status becomes"interrupted", with an interruption of kind"ended_pause"whose message isreason, andlist_runs(status="paused")no longer lists it. The run keeps its stage records and artifacts, sorerun()reuses its finished stages under a new run ID.The end claims the pause as a resume does, so of a resume and an end of one pause, only one goes ahead and the other raises without writing. Two states need
release_claim=True, passed once you have confirmed that the other process stopped, since CyteArc cannot tell a stopped process from a live one: a pause that a resume or an end claimed without recording itself, as a process that stopped between its two writes leaves it, and a pause whose write was cut off, whose process may still be writing it. If that process is alive after all, the write that lands last wins: the end can be lost, or the resume’s next stage fails on the ended record. Nothing is written when the call refuses.- Parameters:
run (
str|PipelineRun) – A paused run of this datastore, or its run ID.reason (
str) – Why the run ends, recorded as its interruption’s message.release_claim (
bool) – End the run although its pause is claimed or not completely written, after you confirmed that the process that claimed or wrote it stopped.
- Return type:
- Returns:
The run, interrupted.
- Raises:
PermissionError – If the store is read-only.
TypeError – If
runis neither a run nor a run ID,reasonis not text, orrelease_claimis not a bool.KeyError – If the store holds no such run.
ValueError – If the run is not paused.
RuntimeError – If the store lacks atomic conditional writes, another process resumed or ended the run first, or, without
release_claim, the pause is claimed or still being written.
Example
>>> paused = ds.pipeline.rna(run_until="pca") >>> ds.pipeline.end_paused(paused, reason="analysis dropped").status 'interrupted'
- list_runs(*, status=None, limit=20)#
List recent runs, newest first, optionally filtered by status.
- Return type:
tuple[PipelineRun,...]
- multimodal(runs, *, label=None, method='wnn', integration=None, embedding_initialization=None, umap=True, localmap=False, tsne=False, leiden=True, paris=False, membership_strength=False, markers=True, snapshot_columns=(), run_until=None, callback=None, cancel=None)#
Integrate completed modality runs of the same cells into one graph.
The recipe combines the runs’ graphs with weighted nearest neighbors (
method="wnn", the default for modalities measured in the same cells) or shared nearest neighbors ("snn"), embeds and clusters the integrated graph, and ranks each modality’s markers for the joint clusters:input_snapshot,integration,embedding_initialization,umap,leiden,paris,cluster_selection(always skipped),membership_strength,tsne,markers.The runs must analyze the same cells: run each modality after the first with
cells=<first run>. WNN needs runs whose graphs were built on PCA, LSI, or Harmony coordinates, and SNN needs runs built with the sameneighborsk. The joint run’s cell view holds the joint UMAP, Leiden, andclustersfields and, for WNN, each cell’sweight_<assay>modality weights. Itsassayandfeature_universeare the first run’s, and its feature view covers that assay’s features withI,ids, andnamesonly, without the first run’s feature field.- Parameters:
runs (
Sequence[PipelineRun]) – Two or more completed runs of different assays, such as[rna_run, adt_run].method (
str) –"wnn"or"snn".integration (
Mapping[str,object] |None) – The keywords ofintegration.modalities:chunk_sizeand, for WNN,l2_normalize.embedding_initialization (
Mapping[str,object] |None) – The keywords ofembeddings.initialization, which starts the joint embedding from the first run’s coordinates.localmap (
bool|Mapping[str,object]) – Must stay False. LocalMAP needs a single assay’s connectivity map, so a call that turns it on is refused before anything is written.leiden (
bool|Mapping[str,object]) – As forrna(), but the integrated graph has no shared coordinates in which to compare candidates by silhouette, sopartitionsdefaults to[1.0]and several partitions need aselectedresolution.markers (
bool) – Rank each run’s assay’s features for the joint clusters, as themarkers_<assay>outputs, with the normalizer that the run of that assay applied. A custom normalizer must be the assay’snormMethod.
- Return type:
The other arguments mean what they mean for
rna().
- open(*, run_id=None, label=None)#
Open one durable run by ID or immutable label.
- Return type:
- perturbation(*, assay=None, guide_assay=None, label=None, cells='I', filtering=None, guide_calling=None, labels, efficiency=True, hvg=None, normalization=None, pca=None, harmony=None, edistance=True, signature=None, mixscape=False, associations=False, profiles=None, clusters=False, snapshot_columns=(), run_until=None, callback=None, cancel=None)#
Analyze a pooled CRISPR screen and return the durable run.
The recipe filters cells on their RNA QC metrics, calls the guides of each cell from the guide counts or imports Cell Ranger’s calls, labels each cell by the genes that its guides target, and measures each perturbation’s efficiency on its own gene. It then selects highly variable genes, normalizes them, reduces them with PCA, optionally corrects batches with Harmony, and measures how far each perturbation moves its cells from the control cells. Optional stages call each target’s knocked-out cells and escapers with Mixscape, test which highly variable genes each target changes, and cluster the perturbations whose profiles agree:
input_snapshot,filtering,guide_calling,perturbation_labels,efficiency,highly_variable_features,normalization,pca,harmony,edistance,signature,mixscape,associations,profiles,perturbation_clusters.The stages from
filteringtoharmonyare those ofrna(), so a run with an RNA run’s settings, or withcells=rna_runand the samehvg,normalization,pca, andharmonysettings, reuses its artifacts. The run’sassayis the RNA assay.The run checks its call before it writes anything. Which cells a stage reads depends on the data, so every sample or split column that a stage reads must label every cell of
cells, with neither a missing value nor empty or whitespace text, every covariate ofassociationsmust hold a finite value for each of them, withassociationseach of them must have counts in the RNA assay, and withassociations={"moi": "high"}guide UMIs too.- Parameters:
assay (
str|None) – The RNA assay. Defaults to the default assay when it is an RNA assay, else the store’s only RNA assay.guide_assay (
str|None) – The guide assay, declaredCRISPR. Defaults to the store’s only assay declaredCRISPR.label (
str|None) – An immutable label for the completed run, unique in the store.cells (
str|ArtifactRef|PipelineRun) – The cells to analyze, as forrna(). The guide assay must have measured them too.filtering (
bool|Mapping[str,object] |None) – QC filtering on the RNA assay’s metrics, as forrna().guide_calling (
Mapping[str,object] |None) – The keywords ofperturbation.call_guides(method,min_umi,fraction_threshold, andsample_column), orpathwithbarcode_prefix,barcode_suffixandbarcode_pattern, which import Cell Ranger’sprotospacer_calls_per_cell.csvwithperturbation.import_guide_callsinstead. The guides of the run’s analysis cells are called. A call file holds the barcodes of one sample, so withbarcode_prefixevery cell ofcellsmust have an ID that starts with it, withbarcode_suffixone that ends with it, and without a prefix,cellsmust not come from several samples of a merged store, whose cell IDs are<sample>__<barcode>.labels (
Mapping[str,object]) – The keywords ofperturbation.labels:controls, the targets of the control guides, which the recipe needs, andtarget_column,targets, andpolicy.efficiency (
bool|Mapping[str,object]) – The efficiency of each perturbation on its target gene, with the keywords ofperturbation.efficiency(byandid_column).hvg (
Mapping[str,object] |None) – The keywords offeatures.hvgs, as forrna().normalization (
Mapping[str,object] |None) –methodand the keywords offeatures.normalize, as forrna().pca (
Mapping[str,object] |None) – The keywords ofreduction.pca.dimsmust be at least 1 and belowhvgtop_n, andfeat_scalingdefaults as forrna().harmony (
Union[Mapping[str,object],Literal[False],None]) – Harmony settings, as forrna(). With Harmony, the E-distances and the signature read the corrected coordinates.edistance (
bool|Mapping[str,object]) – E-distances in the run’s coordinates, with the keywords ofperturbation.edistance(by,n_permutations, andrandom_seed).signature (
Mapping[str,object] |None) – The keywords ofperturbation.signature(dims,n_neighbors,sample_column, andscale_factor) for the signature thatmixscapereads, computed in the highly variable genes.dimsmust be at mostpcadims. Settings withoutmixscapeare refused.mixscape (
bool|Mapping[str,object]) – Mixscape’s knocked-out cells and escapers, with the keywords ofperturbation.mixscape.associations (
bool|Mapping[str,object]) – Tests of every target against every highly variable gene, with the keywords ofperturbation.associationsbutpairsandfeatures;positive_controlsis"targets"or None. With"moi": "high", for a screen whose cells carry several guides,efficiency,edistance,mixscapeandclustersmust be off, since they compare each perturbation with cells that carry control guides only.profiles (
Mapping[str,object] |None) – The keywords ofperturbation.profiles(by,sample_column,min_cells,mask_targets, andid_column) for the profiles thatclustersreads, of the highly variable genes, andcells, the cells that a target’s profile averages:"knocked_out", the default withmixscape, takes its knocked-out cells, and"labeled", the default and only choice withoutmixscape, every cell of its label. Settings withoutclustersare refused.clusters (
bool|Mapping[str,object]) – Clusters of the perturbations whose profiles agree, with the keywords ofperturbation.cluster.snapshot_columns (
Sequence[str]) – Cell columns to freeze into the run’s cell view.run_until (
str|None) – The stage after which the run pauses, as forrna().callback (
Callable[[PipelineEvent],None] |None) – Called with eachPipelineEventof the run.cancel (
CancellationToken|None) – ACancellationTokenthat stops the run.
- Raises:
PermissionError – If the store is read-only.
TypeError – If the call fails its checks; nothing is written.
ValueError – If the call fails its checks, such as a missing sample, split or covariate column; nothing is written.
KeyError – If a column of
cells,filtering,hvg,harmonyorsnapshot_columnsis missing; nothing is written.FileNotFoundError – If
guide_callingpathnames no file.UnmeasuredCellsError – If the RNA or the guide assay did not measure one of
cells; nothing is written.PipelineExecutionError – If a stage fails; the run is recorded failed.
PipelineCancelled – If
cancelis cancelled; the run is recorded interrupted.
Example
>>> labels = {"controls": ["Non-Targeting"]} >>> run = ds.pipeline.perturbation(labels=labels, label="screen") >>> ds.perturbation.load_efficiency(run["efficiency"]).table
- Return type:
- plan(recipe, /, *args, **settings)#
Report what a recipe call would reuse and compute, without running it.
The plan resolves and checks the call as the recipe does before it writes, the label included, and then goes through the stages in run order. A stage whose artifacts all exist, complete and current, is reused with the artifact refs that the run would record. A stage that would compute an artifact reports why: no artifact of its operation, a changed setting or input, a superseded revision, an interrupted or invalid artifact, or one without the diagnostics that its operation saves. A stage that reads what an earlier computed stage would produce waits on that stage: its artifacts depend on ones that do not exist yet, so it is reported computed with the stages it waits on. Each computed stage carries what it took when the latest earlier run of the same recipe and assay computed it, a past measurement.
The plan writes nothing and works on a read-only store. It reads run records, cell and feature metadata, and the stored artifacts that reuse checks read, never a count matrix. It refuses a setting that a stage’s method refuses, with the stage’s name before the method’s message, as the recipe does before it writes. A stage’s method checks the limits that depend on the data only when the stage runs: when every stage before it would be reused, the plan reaches that check and raises its error, as the run would.
- Parameters:
recipe (
str|PipelineRun) –"rna","atac","adt","multimodal", or"perturbation", or a run, whose settings the call takes withsettingschanging them, asrerun()does.*args (
object) – The positional arguments of the recipe’s method: therunsof"multimodal". A plan of a run takes none.**settings (
object) – The keywords of the recipe’s method, as a call would pass them, withoutrun_until,callback, andcancel.
- Raises:
ValueError – If
recipenames no recipe, or the call fails the recipe’s checks.TypeError – If the call passes
run_until,callback, orcancel, a keyword that the recipe lacks, or fails its checks.KeyError – If the call names a missing column.
UnmeasuredCellsError – If an assay did not measure one of the cells.
Example
- Return type:
>>> plan = ds.pipeline.plan("rna", label="tuned", hvg={"top_n": 1000}) >>> [(stage.stage, stage.status, stage.reason) for stage in plan.stages] >>> ds.pipeline.plan(run, leiden={"partitions": [2.0]}).computed
- rerun(run, /, *, label=None, run_until=None, callback=None, cancel=None, **overrides)#
Run a run’s recipe again with the settings it recorded, changing some of them.
Each keyword of the run’s recipe that the call does not pass takes the run’s setting, which
settings()returns, so a call passes only what it changes. A stage whose settings and inputs are unchanged reuses the run’s artifacts, and the stages that read a changed stage compute again with the run’s other settings.plan()with the run and the same keywords reports which stages would compute.A mapping changes a stage’s settings key by key:
leiden={"partitions": [2.0]}keeps the run’s other Leiden settings, among them itsselectedresolution, which must be one of the new partitions or None. A mapping inside a stage’s settings, such as Harmony’sharmony_params, is replaced whole. Any other value replaces the run’s:Falseturns an optional stage off,Trueruns it with its defaults, and None takes the keyword’s default, such asfiltering=Noneto filter newcellsas a call that omits it would. The new run takeslabel, never the run’s label.A run records its settings when it starts, so a run of any status can run again, such as a failed run with the setting that failed changed.
- Parameters:
run (
PipelineRun) – A run of this datastore.label (
str|None) – An immutable label for the new run, unique in the store.run_until (
str|None) – The stage after which the new run pauses, as forrna().callback (
Callable[[PipelineEvent],None] |None) – Called with eachPipelineEventof the run.cancel (
CancellationToken|None) – ACancellationTokenthat stops the run.**overrides (
object) – Keywords of the run’s recipe, which change its settings.
- Raises:
PermissionError – If the store is read-only.
TypeError – If
runis not aPipelineRun, an override is not a keyword of the run’s recipe, or the call fails the recipe’s checks.ValueError – If
runis not recorded in this datastore, this release cannot read its settings, assettings()explains, or the call fails the recipe’s checks.
The recipe raises its other errors as its method documents them.
Example
- Return type:
>>> base = ds.pipeline.open(label="baseline") >>> ds.pipeline.plan(base, leiden={"partitions": [2.0]}).computed >>> fine = ds.pipeline.rerun(base, label="fine", leiden={"partitions": [2.0]})
- resume(run, /, *, run_until=None, callback=None, cancel=None)#
Run the rest of a paused run under the same run ID, on any machine that opens the store.
A recipe called with
run_untilpauses once that stage has completed.resumerebuilds the recipe from the settings that the run recorded, asrerun()does, and restores what the finished stages left from their saved artifacts, computing and writing nothing for them. It then runs the next stages and completes the run, or pauses it again after the stage thatrun_untilnames.plan()of the paused run previews what the resume would compute.A resume reads the store, so the process that resumes can run on a larger machine, with the
nthreadsand memory budget of the store that it opened. It needs two things beside the store: the call file of aperturbationrun that imports its guide calls, at its recorded path, and a custom normalizer of the run’s assay as the assay’snormMethodin the resuming session, since a run applies a custom normalizer only as the assay’snormMethod. The run record’ssegmentshold when each process started and stopped, the stages that it ran, and why it stopped.The run keeps its requested label without reserving it: the label is checked when the run pauses and resumes, and claimed when the run completes. A resume claims the pause with an atomic write, so of two processes that resume one paused run, one runs it and the other raises
RuntimeError.- Parameters:
run (
str|PipelineRun) – A paused run of this datastore, or its run ID, such asds.pipeline.list_runs(status="paused")[0].run_until (
str|None) – The stage after which the run pauses again, one that the run has not run yet. None runs it to the end.callback (
Callable[[PipelineEvent],None] |None) – Called with eachPipelineEventof the run.cancel (
CancellationToken|None) – ACancellationTokenthat stops the run.
- Return type:
- Returns:
The run, completed, or paused again after
run_until.- Raises:
PermissionError – If the store is read-only.
TypeError – If
runis neither a run nor a run ID.KeyError – If the store holds no such run.
ValueError – If the run cannot resume, and nothing is written: it is not paused, as after another process ended it while this one replayed it, another release recorded it, its settings or finished stages no longer match what it recorded, the session’s
normMethodis not its custom normalizer, another run committed its label, orrun_untilnames no stage that it has left to run.RuntimeError – If the store lacks atomic conditional writes, an unfinished run holds the claim of its label, or another process resumed or ended the run first; nothing is written.
FileNotFoundError – If the run imports guide calls from a file that is no longer at its recorded path.
PipelineExecutionError – If a stage fails, or the run cannot pause again; the run is recorded failed.
PipelineCancelled – If
cancelis cancelled; the run is recorded interrupted.
Example
>>> paused = ds.pipeline.rna(label="rna", run_until="pca") >>> ds.pipeline.plan(paused).computed # what the resume computes >>> # Later, on a larger machine that opens the same store: >>> run = ds.pipeline.resume(paused.run_id) >>> run.status, run.report()["run"]["segments"][0]["stages"][-1] ('completed', 'pca')
- rna(*, assay=None, label=None, cells='I', cell_calling=False, hashing=False, filtering=None, cell_cycle=True, hvg=None, normalization=None, pca=None, harmony=None, ann_index=None, neighbors=None, connectivity=None, embedding_initialization=None, umap=True, localmap=False, tsne=False, leiden=True, paris=False, membership_strength=False, doublets=True, markers=True, snapshot_columns=(), species=None, run_until=None, callback=None, cancel=None)#
Analyze an RNA assay and return the durable run.
The recipe optionally calls cells in raw droplets and demultiplexes hashtags, filters cells on their QC metrics, scores the cell cycle, selects highly variable genes, normalizes them, by default by library size and log, reduces them with PCA, optionally corrects batches with Harmony, builds a neighbor graph, embeds it with UMAP, clusters it with Leiden at several resolutions, saves the candidate with the best silhouette, scores doublets, and ranks markers:
input_snapshot,cell_calling,hashing,filtering,cell_cycle,highly_variable_features,normalization,pca,harmony,ann_index,neighbors,connectivity,embedding_initialization,umap,localmap,leiden,paris,cluster_selection,membership_strength,tsne,doublets,markers.- Parameters:
assay (
str|None) – The RNA assay. Defaults to the default assay when it is an RNA assay, else the store’s only RNA assay.label (
str|None) – An immutable label for the completed run, unique in the store.cells (
str|ArtifactRef|PipelineRun) – The cells to analyze: a boolean cell column, a cell-selection artifact, or a completed run, whose analysis cells are reused as they are.cell_calling (
bool|Mapping[str,object]) – EmptyDrops cell calling for a raw droplet matrix, with the keywords ofqc.call_cellsandsample_column, a cell column of captures that are called apart, which must label every cell ofcells.hashing (
bool|Mapping[str,object]) – Hashtag demultiplexing, with the keywords ofqc.hto_demultiplexingandassay, the HTO assay (default: the store’s only assay of typeHTO). The run keeps the cells of one hashtag and, unlessfilteringnames asample_column, computes MAD bounds within each hashtag.filtering (
bool|Mapping[str,object] |None) – QC filtering, with the settings ofqc.auto_filter(method,attrs,n_mads,sample_column,min_cells_per_sample,min_p,max_p) or, withmethod="manual",lows,highs, andkeep_bounds. None filters cells thatcellsnames by column, and the cells thatcell_callingorhashingkeep whatevercellsis; otherwise it keeps a given selection’s or run’s cells as they are.cell_cycle (
bool|Mapping[str,object]) – Cell cycle scoring, with the keywords ofscores.cell_cycle.hvg (
Mapping[str,object] |None) – The keywords offeatures.hvgs;batchnames a cell column, andmin_mean,max_mean,min_var, andmax_varare log2 values.normalization (
Mapping[str,object] |None) –method, the normalizer that every stage of the run applies, and the keywords offeatures.normalize.methodnames a built-in normalizer,"lib_size","lib_size_log","pearson_residuals","clr","tf_idf", or"passthrough"fornorm_dummy, and defaults to the assay’snormMethod. The run records the normalizer by name, or a custom normalizer by its identity, so a rerun normalizes as the run did; a custom normalizer must be the assay’snormMethod.pca (
Mapping[str,object] |None) – The keywords ofreduction.pca.dimsmust be belowhvgtop_n.feat_scalingdefaults to False for a run of Pearson residuals, which are already standardized, and to True otherwise.dims=0skips PCA and builds the graph on the normalized values, which needsdoublets=Falseand no Harmony.feat_scaling=Falseneedsdoublets=False.harmony (
Union[Mapping[str,object],Literal[False],None]) –batch_columns, the cell columns whose batches Harmony corrects, withharmony_params(the options ofcytearc.embeddings.harmony.fit_harmony) andbatch_size. None or False skips Harmony. A run with Harmony scores doublets within each batch unlessdoubletsnames anothersample_column.ann_index (
Mapping[str,object] |None) – The keywords ofgraph.ann_index.ann_metricmust be"l2"or"cosine".neighbors (
Mapping[str,object] |None) – The keywords ofgraph.neighbors, such ask.connectivity (
Mapping[str,object] |None) – The keywords ofgraph.connectivity.embedding_initialization (
Mapping[str,object] |None) – The keywords ofembeddings.initialization.umap (
bool|Mapping[str,object]) – UMAP, with the keywords ofembeddings.umap.localmap (
bool|Mapping[str,object]) – LocalMAP on the UMAP graph and initialization, with the keywords ofembeddings.localmap.tsne (
bool|Mapping[str,object]) – t-SNE on the UMAP graph and initialization, with the keywords ofembeddings.tsne.leiden (
bool|Mapping[str,object]) – Leiden candidates:partitions, the resolutions (default 0.5, 0.75, 1.0, 1.25), an optionalselectedresolution that becomes the saved clustering in place of the silhouette choice, and the keywords ofclusters.leiden. Theleidenstage clusters at every resolution, andrun["leiden"]holds the candidates ordered by resolution.paris (
bool|Mapping[str,object]) – Paris clustering of the graph, for diagnosis, with the keywords ofclusters.paris.membership_strength (
bool) – Score each cell’s membership in its cluster.doublets (
bool|Mapping[str,object]) – Doublet scoring, with the keywords ofqc.doublets. It normalizes simulated doublets by library size and projects them onto the PCA with its feature scaling, so it needs the run to normalize with"lib_size", the RNA default, andpcafeat_scalingto be True.markers (
bool) – Rank markers for each saved cluster.snapshot_columns (
Sequence[str]) – Cell columns to freeze into the run’s cell view.species (
str|None) – A species key recorded with the run.run_until (
str|None) – The stage after which the run pauses, such as"pca": the call returns the run with status"paused"once that stage has completed, andresume()runs the rest under the same run ID, on any machine that opens the store. It must be a stage that the call runs. A run whose only stages after it are skipped completes instead.callback (
Callable[[PipelineEvent],None] |None) – Called with eachPipelineEventof the run.cancel (
CancellationToken|None) – ACancellationTokenthat stops the run.
- Raises:
PermissionError – If the store is read-only.
TypeError – If the call fails its checks; nothing is written.
ValueError – If the call fails its checks; nothing is written.
KeyError – If the call names a missing column; nothing is written.
UnmeasuredCellsError – If the assay did not measure one of
cells; nothing is written.PipelineExecutionError – If a stage fails, or the run cannot pause because another run committed its label; the run is recorded failed.
PipelineCancelled – If
cancelis cancelled; the run is recorded interrupted.
Example
>>> run = ds.pipeline.rna(label="rna", hvg={"top_n": 2000}) >>> run["clusters"], run.cells.fetch("umap_1")
- Return type:
- class cytearc.PipelineRun(owner, record)#
A datastore-bound handle for one durable pipeline invocation.
A recipe returns its completed run, and
ds.pipeline.openandds.pipeline.list_runsreopen runs of every status. A completed run is a read-only mapping of its output keys, such as"clusters", to exactArtifactRefvalues, and itscellsandfeaturesviews hold its frozen fields. Theleidenoutput holds the Leiden candidates, a tuple of refs ordered by resolution. A run of another status raisesRuntimeErrorfor its outputs and views, andreport()gives the persisted facts of a run of any status. A handle keeps the run record that it opened, so open the run again to see a later status.- property assay: str#
The analyzed assay.
A multimodal run’s assay is its first source run’s assay, whose features its feature view covers.
- property cells: PipelineAxisView#
The completed run’s frozen cell fields, over its analysis cells.
The view’s
Iis the run’sanalysis_cell_selection, and its other fields, such asclustersandumap_1, read the run’s artifacts and metadata snapshots, never live columns. Every assay shares the store’s cells, so a field can read an artifact of another assay that was computed on the run’s cell selection, such as the guide calls behind a perturbation run’sguide_call. A run that did not complete raisesRuntimeError.
- property features: PipelineAxisView#
The completed run’s frozen feature fields, over its assay’s features.
The view’s
Iis the run’sfeature_universe, besideids,names, and the recipe’s feature field, such ashighly_variable_features; a multimodal run has no feature field. A run that did not complete raisesRuntimeError.
- property finished_at_ns: int | None#
When the run ended, in nanoseconds since the epoch.
None while the run is running or paused, including a run whose process died without cleanup.
- property label: str | None#
The run’s immutable label, or None.
A run takes its requested label only when it completes, so a running, paused, failed, or interrupted run has None;
report()["run"] ["requestedLabel"]keeps the label that it requested.
- property recipe: str#
The recipe that wrote the run, such as
"rna".The recipes record
"rna","atac","adt","multimodal", and"perturbation", and a run thatpipeline.run()of an earlier release saved records"basic_rna_analysis".
- report(*, format='dict')#
Return the persisted facts of the run, whatever its status.
- Overloads:
self, format (Literal[‘dict’]) → dict[str, Any]
self, format (Literal[‘markdown’]) → str
The report reads the stage records again on each call, so a running run’s report grows as its stages end, while its run entry is the run record that this handle opened.
format="dict"returns three entries:run: the run record, withrunId,recipe,requestedLabel,label,assay,startedAtNs,finishedAtNs,status,complete,cytearcVersion,config,stageOrder,outputs,fields,error,interruption, andoutputLists, the outputs that hold several artifacts, such asleiden. A run that paused also holdssegments: for the process that started it and each that resumed it,startedAtNs,stoppedAtNs, thestagesit ran, thereasonit stopped,"paused"or the status that the run ended with, and itsshutdownsignal protection.stages: each stage record written so far, skipped stages included, with its status, times, outputs andoutputLists, artifact plans with theircreatedorreuseddispositions,metrics,error,interruption,summary, andwarnings. Themetricshold the stage’s wall and CPU time, sampled RSS, the process’s peak RSS, OS threads, network bytes, theresourcesits process had, and atraceof samples.summary:createdArtifacts,reusedArtifacts,uncleanIncomplete, True while the run record is not complete, as for a running run or one whose process died,signalProtection, andwarnings, every stage’s warnings with the stage that logged them, in stage order.
format="markdown"returns the same facts as a Markdown document, with a table of the stages, their wall and CPU seconds, peak RSS and received bytes, a table of the segments of a run that paused, and a section of each stage’s summary and warnings.- Parameters:
format (
Literal['dict','markdown']) –"dict"or"markdown".- Raises:
ValueError – If
formatis another value, or if a stage record holds fields that this release does not know.
- property run_id: str#
The run’s unique identifier, which
pipeline.open(run_id=...)takes.
- settings()#
Return the keywords of the recipe call that this run records.
They are the keywords of the run’s recipe method but
label,callback, andcancel, with the values that the run recorded: the settings that the call gave, and the defaults that the recipe fits to its data resolved, such as an ATAC run’sprevalent_peakstop_n. A run given ascells, and a multimodal run’s sourceruns, are reopened by their run IDs. A keyword or stage setting that the recipe gained after the run started is left out, so the recipe gives it its default, as a call that omits it would, except thenormalizationmethod: a run recorded before it, as by CyteArc 1.4.0, returns the normalizer that its saved normalized values record and, for Pearson residuals or a custom normalizer, the PCAfeat_scalingof True that it applied when its call set none. Passing the keywords to the recipe, asgetattr(ds.pipeline, run.recipe)(**run.settings()), analyzes the run’s cells again and reuses the run’s artifacts while the store’s cell columns and the release’s defaults are unchanged;rerun()takes them with changes. A run records its settings when it starts, so a run of any status returns them.- Raises:
ValueError – If the run’s recipe is not one of this release’s, as for a run that
pipeline.run()of an earlier release saved, the run records a keyword that its recipe no longer takes, or a run recorded before thenormalizationmethodsaved normalized values that do not record their normalizer.
Example
>>> run.settings()["leiden"] {'partitions': [0.5, 0.75, 1.0, 1.25], 'selected': None}
- Return type:
dict[str,Any]
- property started_at_ns: int#
When the run record was created, in nanoseconds since the epoch.
- property status: str#
"running","paused","completed","failed", or"interrupted".A run that a recipe called with
run_untilstopped is"paused"untilds.pipeline.resumeruns the rest, ords.pipeline.end_pausedends it as"interrupted". The status is the one that the run record held when this handle was opened.
- class cytearc.datastore.pipeline_run.PipelineAxisView(owner, record, *, axis)#
A narrow, immutable view over one completed pipeline-run axis.
run.cellsandrun.featuresreturn one. Its fields read the run’s frozen selections, metadata snapshots, and result artifacts, never live columns, and a read fails closed when the stored cell or feature identities changed.- property columns: tuple[str, ...]#
The names of the run’s frozen fields,
I,ids, andnamesfirst.
- fetch(column)#
Return one run field for rows selected by the stored run I.
- Return type:
ndarray
- fetch_all(column)#
Return one run field aligned to the complete stored axis.
- Return type:
ndarray
- head(n=5)#
Return the first selected rows of every frozen run field.
- Return type:
DataFrame
- to_pandas_dataframe(columns)#
Return selected rows for the requested frozen run fields.
- Return type:
DataFrame
- class cytearc.PipelineExecutionError(run_id, stage, cause)#
A handled pipeline failure with a durable run identifier.
A recipe raises it once the run is recorded as failed, together with the failing stage’s record when that stage had one. The exception that failed the run is its
__cause__; a pickled copy keeps it, or a stand-in that names its type and message when the cause cannot be pickled.- run_id#
The failed run’s identifier.
ds.pipeline.open(run_id=...)opens the run, whosereport()holds the persisted failure.
- stage#
The stage that failed, as the run’s stage order names it, or
"finalize"when completing the run record failed after every stage.
- class cytearc.PipelineCancelled(run_id, stage, reason)#
A pipeline run that stopped because its CancellationToken was cancelled.
- run_id#
The interrupted run, or None when the token was cancelled before the run wrote anything.
- stage#
The stage whose work the cancellation cut short, or None when the run stopped between stages or just after a stage’s work finished, which records that stage as completed.
- reason#
The reason given to
CancellationToken.cancel.
- class cytearc.CancellationToken#
Ask a running pipeline to stop at its next safe checkpoint.
Pass the token as a recipe’s
cancelargument and callcancel()from any thread, such as a UI’s stop button. Long operations check for cancellation between bounded blocks of work, so the run stops soon after and raisesPipelineCancelled. The run is recorded as interrupted. A stage whose work had not finished is recorded as interrupted too, and one whose work had finished as completed, so the run stops between stages. Completed stages keep their artifacts, which a later run reuses. A cancellation that arrives after the run completed leaves it completed, and the recipe returns it.A token stays cancelled: a run given a cancelled token raises before it writes anything. One token may cancel several runs at once. A signal that stops a run never cancels the token, and a signal that arrives after a cancellation still takes its usual effect once the run is recorded.
- cancel(reason='cancelled')#
Cancel, and return whether this was the token’s first cancellation.
- Return type:
bool
- cytearc.pipeline_listener(listener)#
Send the events of every pipeline run started in this context to
listener.The registration is context-local: it covers the code in the
withblock, on this thread or in this asyncio task, and nests. A run reads the listeners when it starts and calls them, after its owncallback, on the thread that runs it, so a listener that does slow work should hand each event to a queue. A listener’s exception is logged and never stops the run.- Return type:
Iterator[Callable[[PipelineEvent],None]]
Example
>>> with cytearc.pipeline_listener(events.append): ... ds.pipeline.rna(label="rna")
- class cytearc.datastore.pipeline_accessor.PipelineEvent(kind, run_id, recipe, label, stage, ordinal, stages, time_ns, progress=None, metrics=None, summary=None, outputs=(), reused=(), warnings=(), error=None)#
One step of a pipeline run, as listeners receive it.
A run emits
run_started, then each stage’s events in order, and ends withrun_completed,run_failed, orrun_interrupted, or withrun_pausedonce the stage thatrun_untilnames has completed. A process that resumes a paused run emitsrun_resumedin place ofrun_started, then the events of the stages that it runs. A stage emitsstage_skippedalone, orstage_started, any number ofstage_progressevents, and one ofstage_completed,stage_failed, orstage_interrupted. An interruption that a stage notices just after its work finished records the stage as completed, sostage_completedprecedes arun_interruptedthat names no stage.- kind#
What happened. Run events are
run_started,run_resumed,run_paused,run_completed,run_failed, andrun_interrupted; stage events arestage_started,stage_progress,stage_completed,stage_skipped,stage_failed, andstage_interrupted.
- run_id#
The durable run identifier.
- recipe#
The recipe, such as
"rna".
- label#
The label the run requested, or None.
- stage#
The stage that the event is about. Stage events name their stage, and
run_started,run_resumed,run_paused, andrun_completedname none.run_failedalways names one: the stage that failed,"pause"when pausing the run failed, or"finalize"when completing the run record failed.run_interruptednames the stage whose work the interruption cut short, and none when the run stopped between stages, while a skipped stage was recorded, or just after a stage’s work finished.
- ordinal#
The stage’s position in
run.report()["run"]["stageOrder"], or None when the event names no stage of that order.
- stages#
How many stages the run has, skipped stages included.
- time_ns#
When the event happened, in nanoseconds since the epoch.
- progress#
The stage’s progress, for
stage_progressevents.
- metrics#
What the stage used and what its process had, as its record holds them, for terminal stage events: wall and CPU time, memory, threads, network bytes,
resourcesand atraceof samples.
- summary#
The stage’s diagnostics, as its record holds them, for
stage_completedevents.
- outputs#
The
(key, ref)pairs a completed stage produced.
- reused#
The output keys whose artifacts were reused, not computed.
- warnings#
The warnings logged while the stage ran.
- error#
The exception, for failed and interrupted events.
- to_dict()#
Return the event as JSON-compatible values, for a UI or a log.
- Return type:
dict[str,Any]
- class cytearc.datastore.pipeline_accessor.PipelineProgress(description, completed, total)#
Progress of the bounded work a stage is doing.
- description#
What the work is, such as
"Harmony", or None.
- completed#
Units of the work done so far.
- total#
Units the work has in all, or None when it is not known.
- class cytearc.datastore.pipeline_accessor.PipelinePlan(recipe, assay, label, config, stages)#
What a recipe call would reuse and compute, stage by stage.
- recipe#
The recipe, such as
"rna".
- assay#
The assay that the run would analyze.
- label#
The requested label, or None.
- config#
The settings that the run would record under
config.
- stages#
Every stage in run order, skipped stages included.
- property computed: tuple[str, ...]#
The stages that would compute an artifact, in run order.
- property reused: tuple[str, ...]#
The stages that would reuse every artifact, in run order.
- to_dict()#
Return the plan as JSON-compatible values.
- Return type:
dict[str,Any]
- class cytearc.datastore.pipeline_accessor.PipelineStagePlan(stage, ordinal, status, reason=None, detail=None, operation=None, outputs=(), existing=None, changed_parameters=(), changed_inputs=(), upstream=(), estimate=None)#
What one stage of a planned call would do.
- stage#
The stage, as the run’s
stageOrdernames it.
- ordinal#
Its position in that order.
- status#
"reused"when every artifact the stage plans exists, complete and current;"computed"when the stage would compute one;"skipped"when the call turns the stage off.
- reason#
Why a computed stage 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;"upstream", the stage reads what a stage before it would compute. None for other stages.
- detail#
The reason in one sentence, or None.
- operation#
The operation whose artifact the stage would compute first, or None.
- outputs#
The
(key, ref)pairs that a reused stage would record, the run’s own refs; empty for other stages. An output that holds several artifacts, such asleiden, gives one pair for each, in order.
- 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, such as("top_n",).
- changed_inputs#
For
"changed", the inputs in which it differs.
- upstream#
For
"upstream", the earlier stages that the stage waits on, in stage order.
- estimate#
For a computed stage, what it took when the latest earlier run of the same recipe and assay computed it, or None.
- to_dict()#
Return the stage’s plan as JSON-compatible values.
- Return type:
dict[str,Any]
- class cytearc.datastore.pipeline_accessor.PipelineStageEstimate(run_id, wall_seconds, rss_peak_bytes, rss_incremental_peak_bytes, cpu_seconds=None, threads_peak=None, rss_high_water_bytes=None, network_rx_bytes=None, network_tx_bytes=None, resources=None)#
What a stage took when the latest earlier run of its recipe computed it.
A past measurement, not a model: that run’s cells, settings, and machine may differ from the planned call’s, and
resourcesrecords the machine.- run_id#
The run whose stage record holds the measurement.
- wall_seconds#
The stage’s wall time.
- rss_peak_bytes#
The sampled peak RSS of the process tree, or None where RSS was not sampled.
- rss_incremental_peak_bytes#
That peak above the RSS when the stage started, or None.
- cpu_seconds#
The CPU time of the process and its child processes during the stage, or None from a record that lacks it.
- threads_peak#
The most OS threads that the process tree held, or None.
- rss_high_water_bytes#
The process’s peak RSS when the stage raised the kernel’s mark of it, which includes peaks that no sample saw; None when the stage stayed under an earlier mark of its process, such as one inherited from the process that started it, or where the mark was not read.
- network_rx_bytes#
Bytes that the network namespace received during the stage, or None.
- network_tx_bytes#
Bytes that it sent, or None.
- resources#
What the process had:
workers,memoryBudgetBytes,cpusAvailable,cpuQuotaCoresandmemoryLimitBytes, as the stage record holds them, or None from a record that lacks them.
- class cytearc.datastore.pipeline_accessor.RecipeDescription(recipe, stages)#
The stage keywords of one recipe, in the order of its method’s signature.
- recipe#
The recipe, such as
"rna".
- stages#
One description for each stage keyword.
- to_dict()#
Return the description as JSON values.
- Return type:
dict[str,Any]
- class cytearc.datastore.pipeline_accessor.StageDescription(keyword, methods, runs, rule, settings)#
One stage keyword of a recipe.
- keyword#
The recipe keyword, such as
"hvg".
- methods#
The public methods that the stage runs, whose keywords its settings are, such as
("features.hvgs",); empty for the ADT panel, whose only setting configures the recipe.
- runs#
Whether the stage runs when a call omits the keyword, or None when
ruledecides.
- rule#
When the stage runs if the keyword is omitted, for
runsof None, such asfiltering; None otherwise.
- settings#
The settings that the keyword’s mapping takes, the keys that configure the recipe first and then each method’s keywords in the order of its signature.
- to_dict()#
Return the stage as JSON values.
- Return type:
dict[str,Any]
- class cytearc.datastore.pipeline_accessor.SettingDescription(name, method, annotation, default=None, rule=None, required=False)#
One setting that a stage keyword’s mapping takes.
- name#
The setting’s name, a key of the stage keyword’s mapping.
- method#
The public method whose keyword the setting is, such as
"features.hvgs", or None for a key that configures the recipe, such as Leidenpartitions.
- annotation#
The setting’s type: as the method’s signature annotates it, or as the recipe takes it where the recipe takes less, such as a cell column for
hvgbatch.
- default#
What the recipe uses when a call omits the setting: the method’s default unless the recipe sets its own. None when the setting is required or
rulesets the default.
- rule#
How the recipe sets the default from its data or from the rest of the call, such as the ATAC recipe’s
prevalent_peakstop_n, or when the setting is required; None otherwise.
- required#
Whether every call that passes the stage’s mapping must give the setting, such as Harmony’s
batch_columns.
- to_dict()#
Return the setting as JSON values, a default that is not a finite number as text.
- Return type:
dict[str,Any]
See Quick start for an executable first run and Graph construction API reference for explicit stage-by-stage APIs.