CyteArc uses concrete domain packages and a one-way module-load dependency structure. The public API is exposed through package facades, while reusable computation and storage mechanics live in focused implementation modules.
Dependency direction¶
Module-load dependencies point toward the earlier layers in this list:
Foundation:
storage,matrix, andutilsData model:
metadata,assay, andgraphDomain algorithms:
neighbors,embeddings,clustering,trajectory,metrics,features,quality_control,mapping,regulons,perturbation,clones,repertoire, andvariantsImport and export:
readers,writers, andmergeOrchestration:
datastoreanddatastore._operationsPresentation:
plotting
Root facade¶
The root cytearc package is a public import facade.
It does not form another runtime layer and must not eagerly import the implementation graph.
Only modules listed by that facade are available as lazy root attributes.
Presentation and lower-level algorithm packages such as plotting, clustering, neighbors, and trajectory require explicit imports.
This keeps the root surface small and avoids loading optional presentation code.
Plotting and local imports¶
plotting does not import datastore.
Unified plotting consumes a narrow datastore adapter instead of resolving projection paths.
Existing heatmap functions still read Zarr-backed values from their duck-typed store and assay inputs.
Removing that remaining storage coupling is deferred.
Function-local imports may cross toward presentation when a public method explicitly requests a plot. Examples include RNA feature selection and datastore quality-control helpers. These calls do not create module-load cycles.
Package responsibilities¶
Foundation¶
storage/owns stores, layouts, schemas, arrays, sharding, copying, resource budgets, storage profiles, materialization, ANN persistence, selection snapshots, run/stage records, Zarr runtime guards, and artifact lineage reports. It also owns the operation revision registry (storage/operation_revisions.py, see Operation revisions), the finite-value contract of artifact arrays (storage/finite_values.py), and the writer destination contract (storage/destinations.py).storage/diagnostics.pyowns the diagnostics that an artifact saves about its computation, such as the barcodes of a file that match no cell of the store: one flatdiagnosticsattribute of camelCase keys, whose values are integers, finite floats, text, null for a number not measured, or, under a key that ends inExamples, up to five texts. Each operation declares its keys in thediagnosticsclass variable of itsOperationArguments, with thecallthat computes its artifact, and shared pieces contribute theirs: the barcode joinJOIN_DIAGNOSTICS, the clone writerCLONE_DIAGNOSTICSand the groupingGROUPING_DIAGNOSTICS, all inmetadata/arguments.py.write_cell_data_artifactandwrite_clonestakediagnostics=, and every writer checks them withplanned_diagnostics, which refuses other keys before anything is written; planning reuses only an artifact that holds them, andArtifactStatus.diagnostics, whichds.artifacts.inspect(ref)andrequire_complete_artifactread, refuses an artifact whose keys differ or that holds none, naming the call that computes it anew. An artifact of an earlier operation revision reads a diagnostic that a later revision added as None (Diagnostics added after a release). An operation that declares none, such as a Paris cut with its own list under the attribute, reads none. Operations derive their warnings from saved diagnostics withDiagnosticRuleandwarn_diagnostics, after they compute or reuse the artifact, so a reused artifact warns as a computed one does; readers never warn. Diagnostics never enter an artifact’s identity.storage/layout.pyholdscolumn_chunk_rows, by which every writer of a cell table chunks a new column, a saved phylogeny its node names and a saved feature analysis the names and IDs of its features, throughstorage/copy.copy_metadata_array; the writers that cell and feature tables share take their chunk rows from their caller (cell column chunks).storage/cell_order.pyowns the cell order of imports that shuffle cells (cell order): the namesourceRowof the column that holds each cell’s row in the imported file, the permutationshuffled_order, built onutils.digest.mix64_array, and its inversedestination_rows, which imports and the reorder of an export share; what drawing them holds at its peak,SHUFFLE_BYTES_PER_CELL, which every import writer checks withcheck_shuffle_fitsbeside what it holds before it shuffles, and a merge’s row plan charges too; the cell table’scellOrderrecord, with its reader andcopy_cell_order, which subsets, mounts and repacks use; and the order of an export:exported_cell_order, which every export’scell_orderargument reaches,source_order_rows, which sorts a selection’s rows into the file’s order, andsource_order_ranks, from which a merge writes its ownsourceRow.storage/identity.protect_metadata_columnrefuses every change tosourceRow.storage/categorical.pyowns the categorical layout of a metadata column, codes beside their linked__cytearc_categories__<name>array (categorical columns): the codes’ dtype, the reserved entry that keeps a categories array’s length off its table’s row count, the strict reader of the link, andCategoricalColumn, which reads such a column as its labels, the reserved entry left out.storage/identity.replace_metadata_columnwrites and restores both layouts, in an import writer’s storage profile when it passes one,clear_columnremoves the categories with the codes,storage/copycopies codes and categories together, and run snapshots decode the labels.storage/content_stamps.pyreuses a value computed from a stored array, such as the fingerprint of the ordered row IDs that every selection check compares, while a stamp of the array’s metadata document and stored chunk bytes is unchanged; any change to those bytes computes the value again.storage/virtual_arrays.pyis the one seam for arrays that a store computes, such as composite counts: aVirtualArrayStorehands out aVirtualArrayReaderfor such an array. Count selections are read throughread_selection, andstorage.feature_streamhands a virtual array’s feature streams to its reader, so no other module checks for a virtual array.read_selectionruns a read throughrun_array_read, the store check that composite creation’s count pass also uses: on an event loop of its own in the calling thread, throughstorage/async_execution.run_read, when every store the read touches is known to work on any loop: Zarr’s local and memory stores, obstore’sObjectStore, and an fsspec store over Zarr’s wrapper of a synchronous file system, such asHfReadStore; a virtual array’s store names the stores its reads touch throughVirtualArrayStore.stores_read. The readers of a block stream then copy their chunks at once instead of in turn on Zarr’s one loop thread; store calls and decodes still run on Zarr’s codec pool, which each loop borrows, and a loop closes only after every task its read started has ended; an interruption while those tasks run, such as a second Ctrl-C, cancels them and waits for them to stop before it is raised, a further one leaves that wait, andrun_readstill waits for the calls that the read handed to Zarr’s codec pool, which only another interruption leaves. Any other read, such as one through a native asynchronous fsspec file system whose session is bound to the loop it first ran on, runs on Zarr’s loop, throughrun_on_zarr_loop, astests/test_count_read_loops.pychecks. Closing a block stream stops its running reads instead of waiting for them to finish:storage/parallel.pygives each stream aReadStop, set in a context variable while its reads run, which cancels each read’s task on the loop that runs it and stops a read before the next operation of its block, since an operation that runs cannot be interrupted. The stream still returns fromclose()only after its reads have ended, and drops theReadStoppedthey raise. A shared cache fill or listing that a stopped read started still runs to its end for the reads that wait for it, and a read on its own loop also waits for the store calls and decodes it handed to Zarr’s codec pool, which_LentPooltracks. A read through Zarr’s loop shares that pool with every other such read, so a call it had started can end just afterclose()returns. A read whose task anything but its stream’s stop cancels raisesasyncio.CancelledErroron either loop, although Zarr’ssyncreports it asconcurrent.futures.CancelledError, and an error that a read raises itself keeps its class.tests/test_stream_stop.pychecks each of these. A read that fails frees its output and the shards it decoded as its error leaves the runner:run_readandrun_on_zarr_loopclear the finished frames of the error’s traceback, of its causes and contexts, and of the errors of a group, throughrelease_exception_frames, which the composite source cache’s shared fills also use, and drop the read’s task once the read ends. Reference counting then frees what those frames held, without waiting for Python’s cycle collector and even while a caller or IPython still holds the error, whose traceback keeps its lines; a stopped read frees its output the same way, while itsReadStoppedis held and once it is dropped, astests/test_count_read_loops.pychecks.AsyncStorageRunner.runclears the frames of a failed operation’s error the same way, on its own loop and on the helper thread that runs it inside a running loop, and so doeswrite_dense_in_shard_rowsfor each band it reads and writes, which covers the copies, repacks, subsets, normalization and materialization that write dense row bands.storage/async_execution.pydecides which threads of Zarr’s codec pool each read and write decodes and encodes on: those of azarr_decoding_threadscontext, such as a pipeline stage’s or a memory ledger’s, else the fewest that DataStores and writers registered for the store withregister_store_threads, which its codec pipelineStoreThreadsCodecPipelineapplies, else the host’s, as Zarr internals describes under “Memory controls”.matrix/owns the lazy blockwise matrix abstraction used over NumPy and Zarr arrays. Its arithmetic, indexing, and reduction behavior keeps it separate from low-level storage mechanics. An assay’sChunkedArrayovercountscarries the validatedcountsT. Streams that allow it, such as feature value reads, take the selected rows fromcountsTthroughstorage/feature_major_rows.pywhen that touches fewer chunk bytes, and the matrix’s operations transform them exactly as rows ofcounts, so a normalization has one implementation.utils/owns generic array, argument validation, compute, logging, process, and progress helpers.utils/files.pyopens every plain or gzip-compressed file that readers and domain packages read, deciding by the file’s first bytes, never its name, and reading text as UTF-8 without a byte-order mark at its start.utils/delimited.pyreads delimited tables through it, counting each row’s fields and naming a malformed row by its line, for the readers and for domain packages, such as the cisTarget motif annotations ofregulons/, which may not importreaders/. The process-tree RSS sampler of pipeline stages finds a process’s descendants through the/proc/<pid>/task/<tid>/childrenlists, and reads the parent of every process only where the kernel has no such lists. It also owns streamed column moments (utils/moments.py) and the one warning helper (utils/warnings.py), which points each warning at the caller’s code and issues theDiagnosticWarningthat an operation derives from a saved diagnostic, aUserWarningthat names the operation, the diagnostic and its value.utils/errors.pyholdsraise_collected_errors, which raises the errors that a cleanup collected, behind the error that ended the work, and empties its list before the error leaves. A frame that kept an error raised in it would form a reference cycle with the error’s traceback, which keeps the frame’s data until Python’s cycle collector runs, so the block streams ofstorage/parallel.pyandutils/progress.py’siter_progresscatch the ending error withexcept ... asand end through this helper: a stream that stops frees its blocks at once, astests/test_parallel.pychecks.utils/cache.pyholdscache_directory, the one cache root,$XDG_CACHE_HOME/cytearc/<name>or~/.cache/cytearc/<name>, that the gene references offeatures/gene_reference.pyand the networks ofdatasets.pyshare.utils/digest.pyholds the digests that identify the files an import reads,file_sha256,directory_sha256andpath_sha256, which readers and operations share, and SplitMix64’s finalizer,mix64andmix64_array, through which every counter-based random stream and the set hashes of clone calling mix, astests/test_digests.pychecks. Every public flag goes throughutils/arguments.bool_argument, oroptional_bool_argumentfor one that also takes None, first in its function: Python and NumPy booleans pass as Python booleans, and integers and text are refused, astests/test_flag_arguments.pychecks for each flag that a public signature names. The clone stack’s modules quote values throughquoted_value, which cuts a value to 80 characters around..., keeping its start and its end, astests/test_error_messages.pychecks for every!randrepr()outside a__repr__. Native thread counts change through two helpers, astests/test_compute_thread_limits.pychecks:utils/compute.process_thread_limitfor BLAS, OpenMP and the other runtimes that threadpoolctl knows, withuser_api="blas"for BLAS alone, andutils/numba.numba_threadsfor Numba’s count of the calling thread. Streams and the storage runner set no BLAS or OpenMP limit, which would apply to the whole process beside their consumers; work that runs BLAS or OpenMP holds its own.utils/numba.pydefinesnjit, which compiles every CyteArc kernel, and gives third-party Numba kernels compiled without a cache, such as umap-learn’s, an on-disk cache once per process and before their first use. Each cache it gives a kernel keeps its own files for each set of compile options and is tied to the source of the package that defines the kernel: for CyteArc’s kernels, the release part of CyteArc’s version, such as1.3.1of1.3.1.dev35+g1eadbb736, and a digest of every module that usesnjit; for a third-party kernel, a digest of every Python file of its package. A kernel then compiles again when a kernel it calls or a constant it reads changes in another file, which Numba’s own cache misses. It also compiles again after a new release, but not after a commit that changes no module that usesnjit. Constants that kernels read belong in modules that usenjit, astests/test_numba_dispatcher_cache.pychecks. A process digests a package’s files once, when the first of the package’s kernels gets a cache. Once one of those files changes, as with an edit followed by a module reload, the modules that the process imported before and after the change may hold different sources, so from then on the package’s kernels compile in that process without loading or saving cache entries: each load first compares the modification time and size of every file digested, and each save also digests them again. An index file that cannot be read counts as empty, so the next save rewrites it.import_umapimports umap-learn so that the kernels its import compiles, most of them pynndescent’s, get that cache too. A lock on each cache directory, which every process shares, keeps those caches’ saves atomic, so processes that import at once compile each kernel once. On Windows, which has noflock, the lock is the first byte of the same file, locked withmsvcrt, which has no shared locks, so every block holds it alone; there too the system releases the lock of a process that ends. Tests take this path on macOS and Linux with a stand-in formsvcrtbacked byflock.utils/memory_budget.pyholdsMemoryLedger, which an operation charges with what each step will keep or hold for a moment before the step allocates: the arrays and blocks that grow with its data, and the objects of each Zarr read, whichArrayGeometry.heldDecodeBytescounts, but not the runtime’s other objects, buffers or temporaries; its refusal,MemoryBudgetErrorwithneeded_bytes,budget_bytesanditem, which every memory refusal outside the modules of the clone stack raises, astests/test_memory_refusals.pychecks;refusal_words, for a step that restates an inner step’s refusal in terms of its own budget; and the builder of that refusal,memory_refusal, for a step that has no message of its own; and the shared costs of Python strings by their widest character, fixed-width text, object arrays, sorts and pandas’ hash tables, withheld_array_bytes, the bytes of an array that a reader keeps with the objects of an object array, each object once however many rows share it, which the H5AD, Matrix Market and Tapestri readers measure once.metadata/rows.py’sread_rows,read_text_rowsandread_wholeread stored arrays through a ledger, and itsrow_read_bytesstates whatread_rowscharges, for a check that runs before the rows are read, all from the read costs ofstorage/geometry.py’sArrayGeometry, and the repertoire operations, guide calling, the import of guide calls, labeling and the perturbation recipe’s check of a call file charge every step to one ledger. Text of variable width, which another tool can write with Zarr’sdtype=str, reads as Python strings throughread_text_rowsandread_whole_textas fixed-width text does, and every charged read of it counts the extent of its values: its longest value, its most UTF-8 bytes, its widest character, and the totals of every value and of its fullest chunk.storage/geometry.variable_text_extentmeasures it a stored chunk at a time, charging the read’s ledger as it reads, once in each operation, while the validation scope that each public call opens keeps the measure, andarray_geometry(array, measure_text=True, ledger=ledger)gives it to the read’sArrayGeometryastext; its scattered rows are read a stored chunk’s span at a time bystorage/partition.read_variable_text_rows, since Zarr’s selections of scattered rows mishandle such text on NumPy before 2.3.2. The reads that a ledger charges decode withinstorage/async_execution.zarr_decoding_threadson a pool of exactly the ledger’scodec_threads, the store’snthreads, so they decode on as many threads on any machine;ensure_zarr_host_ceilinginstalls those pools as Zarr’s codec pool, as Zarr internals describes under “Memory controls”. The parts that importers and summaries share charge the caller’s ledger in place of an integer budget: the join of barcodes to cells, the grouping of cells,clones/assignments.CloneAssigner,metadata/records.RecordEncoder, the clone writer andmetadata/selection.category_codes, whose natural order of labels costs whatutils/arrays.sort_categories_bytesstates besidesort_categories. Zarr-specific helpers belong instorage, notutils.
Facade aliases do not change implementation ownership.
cytearc.load_zarr is a facade alias for storage.stores.load_zarr.
Data model¶
metadata/owns Zarr-backed metadata tables, row streaming, and table queries. It is shared by datastore cell metadata and assay feature metadata, so neitherdatastore,assay, norstorageowns it.metadata/alignment.pyaligns per-cell values to the cells they describe by cell ID for the cell table, the operations and plotting:align_to_cell_idstakes the values, the ordered IDs of those cells and the name of the call, and refuses values that would land on cells by position.MetaData(..., cell_table=True), whichDataStorebuilds for its cell table, takes per-cell values ininsertandupdate_keyonly keyed by cell ID. CyteArc’s own writers of values computed in store order, the quality metrics of assay preparation and the cell filter of a first writable open, use the private_insert_in_store_orderand_update_key_in_store_order; no public call takes positional per-cell values. A table’s columns are the members that Zarr lists with their metadata, so a stray object such as.DS_Storeis never a column;headand the membership columns reuse the arrays that one listing opened, andto_pandas_dataframeopens only the requested columns, each once. Shared value-selection contracts also live here so domain, orchestration, and presentation code can use one typed contract without reversing dependencies. These include the nullable value contract of metadata columns (metadata/encoding.py), the assay-membership contract (metadata/membership.py), andCELL_VALUE_NAMES, the table of cell-aligned artifact kinds, with the reader that aligns their rows to cells and the reader of a cell column over a cell selection (metadata/selection.py).metadata/records.pyencodes long tables of records that belong to cells, such as the contigs of a V(D)J library or the molecules of a lineage barcode library: it parses their text chunk by chunk, naming the file lines of values it refuses, stores a text field once per distinct value with a sorted code per record and a ragged field record by record as UTF-8 bytes with offsets, and merges the chunks withRecordEncoderinto oneRecordTableordered by cell, source and file row. It never touches storage.metadata/palettes.pyholds the generated colors of categories:category_color, which a display that CyteArc stores for categories without colors of their own takes, Scanpy’s palettes andpalette_for_n, which plots draw for categories without a stored color, andstored_category_colors, which a merge gives the categories that it adds to a column’s display, so the import and export layer reaches them without importingplottingor seaborn.metadata/artifacts.pyplans and writes artifacts of one row per selected cell.write_cell_data_artifactstores text at the width of its widest value, converting and writing one stored chunk at a time, andcell_data_write_bytesstates what a write holds, from the shapes and stored widths of its arrays, for the operations that check it against their memory budget.assay/owns normalization, blockwise feature-summary computation, and the RNA, ATAC, and ADT assay types.assay/hvg_statistics.pystreams the per-batch count statistics of the HVG flavors fromcountsT, andRNAassay._batch_hvg_scoresturns them into each batch’s scores with the trend and residual formulas offeatures.variability.DataStoreowns planning and persistence of feature-summary artifacts; a bareAssay.score_featuresremains computation-only.assay/normalization.pyowns the normalizer flag policy: each assay class declares the flags that itsnormedapplies, and callers resolve flags throughapplicable_normalization_flagsanddefault_normalization_flagsinstead of per-assay branches.graph/owns graph feature projection through named artifact inputs and rejects encoded-path inputs. Analysis execution follows explicit artifact references and must not resolve inputs by parsing encoded paths or choosing an implicit result.
Data-model modules may call domain algorithms from the method that needs them. They must not import those packages at module load time.
Domain algorithms¶
neighbors/owns ANN construction, KNN queries, graph operations, diffusion, and weighted-neighbor integration. It does not own stored KNN graph arrays; persistence lives indatastoreandstorage.embeddings/owns PCA, LSI, Harmony2 batch correction, UMAP, SG-tSNE, embedding initialization, and the narrow storage adapter for imported coordinate artifacts.clustering/owns Leiden clustering, PARIS hierarchy operations, and the graph weight between clusters.connectivity.pysums a cell graph’s weight between each pair of clusters from each cell’s cluster code, forDataStore.clusters.connectivity, which returns the tables, andplots.cluster_connectivity, which draws them on a layout.leiden.pyholds the publicleiden_membershipand dispatches between the native"cytearc"backend and the"igraph"and"leidenalg"backends, whose GPL packages it imports only when one of them is requested (CyteArc does not install them). The native backend lives in the private_leiden_*.pymodules, described incytearc/clustering/README.md, and loads lazily, so importingcytearc.clustering.leidenloads no Numba kernel. After a release, a change that alters the native labels for unchanged parameters needs anOperationRevisionofrun_leiden_clusteringscoped tobackend == "cytearc"(placement rule 10).trajectory/owns pseudotime scoring, feature-profile aggregation, feature module clustering, and pseudotime result records, and inerrors.pythe typed errors of pseudotime scoring and fate mapping. Lineage-resolved statistics weighted by fate probabilities (lineages.py), fate-weighted lineage curves (curves.py), cluster spanning trees (lineage_tree.py), lineage membership and branch points (membership.py), and their result records also live there; their persisted contracts join the others inartifacts.py.lineage_tree.pybuilds a tree without a store,build_cluster_tree, through the steps thatDataStore.trajectory.lineage_treetakes over coordinate blocks, and names a saved tree’s clusters forload_lineage_treeas it names its own, so the two give one tree.DataStore.trajectory.curves_in_layoutdraws fitted curves in a layout withcurves.smooth_against_progress, andplots.lineage_curvesdraws the points it returns.potency.pyscores how differentiated each cell is, the signaling entropy rate or CCAT of its expression on a protein network, a block of counts at a time, and smooths and ranks the scores;DataStore.scores.potencystreams the counts of the network’s genes to it and saves acell_potencyartifact, whose canonical array,differentiation, directs a fate map as it stands.fate.pybiases the walk of a fate map and solves its probabilities, and holds the rules of what directs the walk, a pseudotime or a direction score:direction_scoreschecks that a score covers whole graph components, andfate_map_cellsgives the scored cells of the components that hold a sink, which the map covers, soDataStore.trajectory.fateandload_fateapply one rule.states.pyfinds the initial and terminal states of the walk that a fate map takes, never touching storage: it builds the walk withfate.py’s bias, takes the leading real invariant subspace of the walk by ARPACK, finds the memberships by robust Perron cluster analysis and coarse-grains the walk between the states, then picks each state’s most likely cells, names the states and gives them their roles;search_bytesstates what a search holds.DataStore.trajectory.statesloads the graph and the direction asfatedoes, through_load_fate_direction, searches the largest connected component of the scored cells and saves atrajectory_statesartifact, whose canonical labels givefateits sinks.metrics/owns LISI, silhouette, graph, concordance, and integration scores, including the neighbor label agreement that membership strength stores.features/owns variability selection (the cytearc, seurat_v3, and pearson_residuals flavors, their LOWESS and LOESS trend fits, and batch-aware ranking), feature scoring, enrichment, rank and regression marker searches, group-wise statistical tests, bulk aggregation, GFF parsing, genomic intervals, coordinate-based feature construction, and the name-based gene-family registry.features/genomic/also owns genome sequence access (sequence.py: an indexed FASTA reader and GC content), gene annotations and region-to-gene windows (annotation.py), and motif matrices with MOODS-equivalent thresholds and a two-strand scanner (motifs.py).features/enrichment/chromvar.pyowns chromVAR background peaks and deviation scoring beside AUCell and WAGGR. It also owns presentation-independent feature resolution and normalized value fetching used by datastore workflows and plots.features/statistical.pyowns the statistical design ofcompare.test, andfeatures/aggregation.pythe bulk profiles ofcompare.compute_bulkand theBulkProfilesrecord that holds them; the datastore methods keep grouping resolution, value reads, artifact planning, and persistence.quality_control/owns filtering, HTO demultiplexing, doublet processing, cell-cycle assignment, and the default cell-cycle gene references.cell_calling.pyowns EmptyDrops cell calling of unfiltered droplet matrices: the barcode-rank knee, Good-Turing ambient profiles, the Dirichlet-multinomial precision estimate, and seeded Monte Carlo p-values. Its functions read count blocks that a caller streams, so the datastore operation indatastore._operations.cell_callingowns the Zarr reads and the artifacts.mapping/owns reference artifacts, feature alignment, confidence, Symphony-style correction, label transfer, and mapping results.regulons/owns transcription-factor regulon inference: GRNBoost2-equivalent importance networks (grn.py), co-expression modules (modules.py), cisTarget ranking databases and motif annotations (databases.py), recovery-curve enrichment (cistarget.py), pruning into regulons (pruning.py), cistromes from motifs or binding peaks (cistromes.py), region-to-gene links (links.py), co-regulated gene programs (programs.py), and regulon specificity (specificity.py). Its functions work on in-memory tables and reference files, and every set they return hassourceandtargetcolumns, the network shape that the enrichment scorers read.polarsis an optional dependency for ranking databases, so theregulonsextra does not installpyarrow.results.pyholdsGrnResult, which namesstorage.refsonly.DataStore.regulons.profilessums cell groups withcompare.compute_bulkand writes nothing. The specificity scores and the connection specificity index need a regulon’s activity only through sums over cells:specificity_scoresadds each block of cells to two sums of each group and regulon in a second pass over the cells, after a first sums each regulon’s activity, andactivity_correlationmerges each block’s sums of products of deviations into the correlations.DataStore.regulons.specificityandDataStore.regulons.connection_specificitystream a stored score artifact through them, one block of a stored chunk’s cells at a time, or fewer as the memory budget holds, which they charge to one ledger with the cells’ positions and labels and the sums, and write nothing;regulon_specificityandconnection_specificityrun them on blocks of rows of a table in memory.perturbation/owns the analysis of pooled CRISPR screens.guide_calls.pyturns guide calls into the per-cell arrays of aguide_callsartifact, summarizes each cell’s guide counts from blocks that a caller streams, and holds theGuideCallsrecord thatDataStore.perturbation.load_guide_callsreturns.histograms.pycounts, in one streamed pass, how many cells of each sample hold each UMI count of each guide;mixtures.pyfits the Poisson-Gaussian and two-Gaussian models to those exact histograms and sets each guide’s threshold in each sample;calling.pycalls guides from thresholds, or from each cell’s top guide, in a second streamed pass.guide_thresholds.pyholds the settings of the four methods ofDataStore.perturbation.call_guides(their names, the defaultmin_umiandfraction_threshold, and the parameters that each fitted method stores), raises fitted thresholds tomin_umi, and turns the arrays of aguide_thresholdsartifact into the tables of theGuideThresholdsrecord thatDataStore.perturbation.load_guide_thresholdsreturns.labels.pyresolves each guide’s target from a feature column and the targets given by guide ID, refuses targets other than controls that equal a reserved label and controls that no guide has, turns each cell’s called guides into the arrays of aperturbation_labelsartifact, sorting them in place, estimates the memory that this holds, and holds thePerturbationLabelsrecord thatDataStore.perturbation.load_labelsreturns.efficiency.pycompares each row’s target gene between the cells that carry its perturbation alone and the control cells, from counts and library sizes that a caller reads: the mean UMIs and library-size scaled means of each group, the remaining fraction and its base-2 logarithm, two-sided Mann-Whitney p-values with Benjamini-Hochberg adjustment, and each row’s status, and estimates the memory that this holds; the module also holds the status names and thePerturbationEfficiencyrecord thatDataStore.perturbation.load_efficiencyreturns.edistance.pycomputes each row’s E-distance to the control cells from coordinates that a caller reads, in closed form from each group’s sums and squared norms, and its permutation p-values with a Numba kernel that draws each permuted group by Floyd’s algorithm, rows running on threads; the module also holds the status names and thePerturbationEDistancerecord thatDataStore.perturbation.load_edistancereturns.signature.pyfinds each cell’s nearest control cells exactly, from fast squared distances ranked again exactly with ties to the lower control, computes Mixscape’s perturbation signature of blocks of cells with a parallel Numba kernel, and holds thePerturbationSignaturerecord thatDataStore.perturbation.load_signaturereturns.mixscape.pyscales signatures as Seurat’sScaleDatadoes, fits the two-component normal mixture with a fixed control component by expectation maximization, tests each target’s DE genes a band of features at a time, runs one target’s Mixscape iterations, assembles each cell’s class from the targets’ fits, and holds the status names and theMixscapeResultrecord thatDataStore.perturbation.load_mixscapereturns.associations.pybuilds the covariates of the association tests, fits each gene’s Poisson regression on the control cells and each pair’s on its treatment and control cells with the negative binomial size of the likelihood, scores the treatment cells and the random sets of each group with Numba kernels, draws the calibration groups, counts each pair’s expressing cells for QC and draws the calibration pairs inassociation_pairs, which both tests share, and holds thePerturbationAssociationsrecord thatDataStore.perturbation.load_associationsreturns.p_values.pytakes each pair’s p-value from up to three rounds of random sets instaged_p_values, with skew-normal fits to the second round’s statistics, for both tests, and adjusts the p-values by Benjamini-Hochberg.glm.pyholds the regression kernels of both association tests: the Cholesky factor and its solves, the Poisson fit by Newton’s method, the likelihood and Pearson sizes of the negative binomial, the score statistic and fold change of a set of cells, and the logistic fit of a group’s indicator.random_sets.pykeys each group’s random sets by the seed, the group, the round and the set with a counter-based generator, and draws uniform sets by Floyd’s algorithm and Bernoulli sets, which take each cell with its own probability, by buckets of probability, drawing a Bernoulli set again when it holds no cell or every cell.high_moi.pytests each group of a high-MOI screen against all other cells: it finds each group’s cells from blocks of the cells’ codes that a caller streams, fits each gene once on all cells, holds a band of genes’ scores and weights cell by cell for every group to share, counts the expressing cells of overlapping groups for QC, fits each group’s detection model, and scores conditional or permutation sets in the rounds ofstaged_p_values, so that results depend neither on threads nor on bands.profiles.pyholds the choices that define a perturbation profile in one place, the depth target and the divisor of the control variance, and accumulates, from blocks of counts that a caller streams, each sample’s running control mean and centered sum of squares and each perturbation’s sum of z-scores with Numba kernels that add the cells in order, a tile of features per thread, so the sums depend neither on the blocks nor on the threads; it also holds thePerturbationProfilesrecord thatDataStore.perturbation.load_profilesreturns.clusters.pycomputes the correlation or Euclidean distances between profiles, runs scikit-learn’s HDBSCAN on them, orders them by average linkage, lays them out with CyteArc’s UMAP layout on the graph of each perturbation’s nearest perturbations, estimates the clustering’s peak memory, and holds thePerturbationClustersrecord thatDataStore.perturbation.load_clustersreturns. Each module also holds the checks of its method’s settings, such ascall_settingsofguide_thresholds.pyandmixscape_settingsofmixscape.py, which the datastore method and the perturbation pipeline recipe run alike, with the same messages, the recipe’s after the stage’s name. These modules never touch storage:readers/cellranger.pyreads Cell Ranger’s call file, and the datastore operations in thedatastore._operations.perturbation_*modules own the reads, the join of barcodes to cells throughdatastore._operations.cell_barcodes, the samples, the match of each target to an expression feature, and the artifacts.clones/owns clones, the cells that descend from one ancestor cell, whatever defined them.assignments.pyturns clone labels of any type into text, gathers each cell’s clone from rows that a caller reads chunk by chunk withCloneAssigner, which refuses or drops a cell given two clones and refuses a label that two sources share, ranks the clones by size and then by label, and holds theClonesrecord thatDataStore.clones.load_clonesreturns. The clone summaries work on each cell’s clone and group codes.groups.pynames groups by their labels, builds the table of each group’s labels that every summary’s record holds asgroup_keys, and counts each clone’s cells in each group.expansion.pycounts each clone’s cells within its group, places cells in expansion categories by bounds in cells or on the clone frequency, counts the cells of each group’s clones by rank window, and holds theClonalExpansionrecord thatDataStore.clones.load_expansionreturns.diversity.pycomputes the diversity indices, the richness estimators and the Hill numbers of each group, rarefied with compiled loops and extrapolated, with theClonalDiversityandRarefactionrecords.overlap.pycompares groups by the clones they share through a sparse matrix of each clone’s cells in each group, chooses the largest clones of each group to follow, and holds theCloneOverlapandCloneTrackingrecords.fate.pymeasures the fate coupling of every pair of groups from the same counts with CoSpar’s definitions, and its null with a parallel Numba kernel that shuffles each permutation’s labels within strata from a SplitMix64 stream keyed by the seed and the permutation and adds the permutations to running means in their order, so the null depends neither on threads nor on how many permutations a thread measures at once; it orders the groups by average linkage, plans the null’s threads and batch from the memory left, follows each early cell’s clone to its late cells, tests each clone in each fate with Fisher’s exact test and the Benjamini-Hochberg adjustment, and holds theCloneCouplingandCloneFateBiasrecords.sequences.pyfinds every pair of texts within a Hamming, normalized Hamming or Levenshtein distance, optionally within blocks, through keys that mask positions or runs of positions, whose texts are compared as each run of equal keys is read, deletion-variant keys, whose candidate pairs are sorted and each checked once, or compiled comparisons of every pair, whichever is estimated to take less time, and charges what it holds to the caller’s memory ledger, which refuses a search that would pass its budget; under Hamming it can leave out the positions where either text holds a character of no base, as TREX compares partial cloneIDs, grouping such texts by the positions where they hold none so that each pair of groups is searched on the positions both hold. Of the pairs that the search compares,expected_chance_pairsgives those expected within the maximum distance by chance, from how often the texts of two components agree at each position, one text per component, such as the barcodes that correction links: exactly under substitutions, and under edits through the edit distance’s dynamic programming over pairs of positions treated as independent. Clonotype clusters link similar chains with it, and lineage barcode correction merges near barcodes with it.calling.pycalls clones from any per-cell sets of integer item codes, the rows of a sparse cells-by-items matrix, with each cell’s unknown items, such as uncovered sites, apart: identical sets within groups, the Jaccard graph of the sets that share an item, found through each set’s prefix of the items that the fewest sets hold where that takes fewer steps, and otherwise, as with unknown items, from the sparse product of the sets with their transpose, over the items both cells know, links through any shared item, TREX’s pruning of edges whose ends share no neighbor and removal of local cut vertices as doublets, the removal of nodes whose sets agree with two nodes that disagree where they hold unknown items, as genotype clones need, and connected components, each step charging its bytes to the caller’s memory ledger, so the clones of lineage barcodes, genotypes and recorder alleles share it.barcode_clones.pyholds the presets and rules of barcode clone calling: the resolved settings, each library’s count unit, the molecule filter, correction onsequences.py, the allowlist, TREX’s rules for partial cloneIDs and its pair filters, the pair filters and the cell filter, before it calls the clones throughcalling.py, and records the diagnostics ofBARCODE_DIAGNOSTICSabout its correction and its clones.barcodes.pyholds the records of expressed lineage barcodes, molecules and pairs of a cell and a barcode as aRecordTableofmetadata/records.pywhose sources are libraries:BarcodeCountercollapses rows of reads into molecules chunk by chunk, merging the chunks into the records once they outnumber them, and the module counts each cell’s distinct barcodes, UMIs and reads, collapses records into pairs, and holds theLineageBarcodesrecord thatDataStore.clones.load_barcodesreturns.recorders.pyholds lineage recorder alleles: the five states of a site and the three kinds of site, theSiteRulesthat map a format’s tokens to states, the prefix rule of ordered slots, the records of each chunk, per-cell counts, theLineageAllelesrecord thatDataStore.clones.load_allelesreturns, and the character matrix of integer states that the export writes.allele_clones.pycalls clones from rare recorder alleles: the banks of each character, the rules of DARLIN’s graph and CARLIN’s p_clonal with Benjamini-Hochberg within each group, the frequencies of each group’s cells without a bank, each bank’s coverage, and DARLIN’s limit on a clone’s alleles, with the cells linked throughcalling.py. These modules never touch storage:readers/clone_tables.pyrecognizes and reads the clone files of each tool,readers/lineage_barcodes.pythe barcode files of each extraction tool, with Cell Ranger’smolecule_info.h5read byreaders/cellranger.py,writers/clone_tables.pywrites CoSpar’s clone table and a labeled Matrix Market file, and the datastore operations indatastore._operations.clonesown the join of barcodes to cells, the namespaces of several files, the reading of every kind of clone artifact that the summaries accept,clonesandclonotypes, with the labels that each keeps apart, such as the receptor types of clonotypes, the labels that figures give clones, such as a clonotype’s representative junction, which the repertoire operations read, the memory checks and the artifacts; those indatastore._operations.lineage_barcodesown the import of lineage barcodes from files or an assay, its join, memory checks and artifact, and the calling of clones from them, which reads the records, groups the cells by theirwithinlabels throughdatastore._operations.cell_groups, and writes theclonesartifact throughdatastore._operations.clone_artifacts; and those indatastore._operations.recorder_allelesown the import of recorder alleles, its join, the check that the arrays of one library share cells, the memory checks, the artifact and the export of character matrices, and the calling of clones from them, which reads the records of edited sites, groups the cells by theirwithinlabels throughdatastore._operations.cell_groups, fingerprints the banks and writes theclonesartifact throughdatastore._operations.clone_artifacts.clones/phylogeny.pyholds cell phylogenies, forests stored as arrays over their nodes, each tree in preorder: it resolves each node’s time from the node times and branch lengths a file gives, counts each node’s branchings below its root with single-child nodes merged, finds each node’s clade at a cut, the first node at or past it from the root, names the clones by their roots, holds theCellPhylogenyrecord thatDataStore.clones.load_phylogenyreturns, and collapses a cut phylogeny to a cap of wedges for its figure,collapse_phylogeny, in three compiled passes over the nodes that charge the caller’s memory ledger as they go. It never touches storage:readers/phylogeny.pyreads Newick text without recursion, with a compiled scan that keeps open parentheses on a stack, and TreeData’sobstin.h5tdfiles and.zarrstores throughreaders/_treedata.py, and the datastore operations indatastore._operations.phylogenyown the join of leaves to cells throughdatastore._operations.cell_barcodes, the memory checks, thecell_phylogenyartifact, and theclonesartifact of a cut, which they write throughdatastore._operations.clone_artifacts.repertoire/owns the analysis of single-cell T cell and B cell receptor repertoires.contigs.pyholds the AIRR fields that an import keeps, their kinds and the fields every contig file must provide, and builds the contig encoder ofmetadata/records.py, which identifies each contig by itssequence_id.chains.pyholds scirpy’s receptor model: the loci of the VJ and VDJ arms, the inference of a contig’s locus from its gene calls, the ranking of each cell’s chains into itsVJ_1,VJ_2,VDJ_1andVDJ_2slots, and each cell’s receptor type, subtype and chain pairing.clonotypes.pygroups cells into clonotypes by identical chains under scirpy’s rules: each distinct receptor configuration gets the keys that its chains and the options derive, and clonotypes are the connected components, found by SciPy, of the graph of configurations and keys. Clonotype clusters link chains within a distance instead, through the pairs of similar chains thatclones/sequences.pyfinds, as connected components through each group’s chains or, when both arms must match, by checking each cell’s candidates through its cheaper arm in bounded chunks, both with compiled union-find; the links between chains are counted against the memory budget before they are built. The module also ranks clonotypes, picks each one’s representative cell, and holds theClonotypesrecord thatDataStore.repertoire.load_clonotypesreturns.usage.pynames gene calls by allele, gene or family, measures junctions in characters from their packed bytes, counts chains by group, locus and values as integer codes, and holds theGeneUsageandSpectratyperecords.receptors.pyholds theImmuneReceptorsrecord thatDataStore.repertoire.load_receptorsreturns, with its tables of cells and contigs. These modules never touch storage:readers/cellranger.pyreads Cell Ranger’s contig annotations andreaders/airr.pyAIRR Rearrangement files, both through the shared parser inreaders/_contigs.py, and the datastore operations indatastore._operations.repertoireown the join of barcodes to cells throughdatastore._operations.cell_barcodes, the reads of each cell’s chains, their grouping throughdatastore._operations.cell_groups, the memory checks, and the artifacts.variants/owns per-cell allele evidence at variant sites: the positions of the mitochondrial genome and targets and probes without coordinates.counts.pyholds the vocabulary (count units, depth definitions and allele roles), theSiteTableof sites and alleles that each reader describes,merge_sites, which gives the sites of several files one order and refuses files on different references, theEntryBatchrows andVariantSourceprotocol that readers implement,finish_band, which turns a band of sorted rows into stored depth and counts (summing counts into depth, or keeping a stated depth and deriving the reference count from it), and theVariantCountsrecord thatDataStore.variants.load_countsreturns.sorting.pyholdsCellRowSorter, which gathers rows that arrive in any order and returns them sorted by cell in bands, spilling sorted runs to a temporary folder when they outgrow the memory budget, so an import reads its files once whatever their order.statistics.pyholdsVariantStatisticsAccumulator, which gathers mgatk’s per-variant statistics from the stored rows of bands of cells, exact integer sums and allele-frequency variances merged band by band, the presets and thresholds that select informative variants, variant labels, and theVariantSelectionrecord thatDataStore.variants.load_informativereturns.masks.pyholds the cited lists of variants that NUMTs, RNA-DNA differences and homopolymers mimic, in rCRS coordinates.frequencies.pyturns a band’s rows into allele frequencies, undefined where a cell was not covered, finds each cell’s neighborhood by the cosine similarity of square-root frequencies over the variants two cells both cover, and calls clones withneighbors.graph.shared_neighbor_graph, which weighs each neighbor edge by the Jaccard index of the two neighborhoods as Seurat does, and the Leiden algorithm ofclustering.genotypes.pyholds the vocabulary of genotype calls (CALLS, andSOURCE_CALLS, which maps each tool’s call labels to it), GoT’s threshold rules, GIFT’s per-UMI posteriors and calls, the checked rules of each method, and theVariantGenotypesrecord thatDataStore.variants.load_genotypesreturns.genotype_mixture.pyholds SCClone’s mixture of clone genotypes over calls packed 64 sites to a word, with a dropout and an error rate per site, and its bit-packed kernels: the E-step down a spanning tree of the genotypes, the M-step from each cell’s unread and other-state bits, and a split’s local fit with the lower bound on its gain, each summed over fixed chunks of cells so that results do not depend on the thread count.genotype_clones.pyholds the search for the number of clones by Schwarz’s criterion, its merges and pruning, and the checked rules of both methods. These modules never touch the store:readers/mgatk.py,readers/cellsnp.py,readers/vartrix.py,readers/mito_afm.py,readers/giftwrap.py,readers/got.pyandreaders/tapestri.pyread each tool’s files, with the shared file helpers inreaders/_variant_files.py, the tables of GoT and giftwrap throughutils/delimited.pyand the Matrix Market files of cellsnp-lite, MQuad and VarTrix throughreaders/_matrix_market.py, and the datastore operations indatastore._operations.variantsown the join of barcodes to cells, the memory checks and the artifact.
Domain algorithm packages must not import datastore, plotting, or general import/export packages at module load time.
A domain that persists an artifact may use a narrow, named storage adapter.
Import and export¶
datasets.pyowns the public example-dataset downloads:list_repositories,connect, andRepositorylist and download the example repositories, such ascytearc_docs, in the publicNygen/cytebaseHugging Face bucket. It also downloads the STRING networks of the bucket’scytearc_networksrepository, the one place that names where they are hosted:STRING_NETWORKSrecords each network’s species, STRING version, size and SHA-256 digest, andstring_network_filereturns a network after checking it against that record, whether it was just downloaded into the cache, found there or given as a local path, so a download that fails or does not match leaves nothing in the cache.cytebase.pykeeps the earlier names of those downloads,Repository,connect, andlist_repositories, through CyteArc 1.x. The CyteBase catalog SDK and its build pipeline are the separatecytebasepackage in the CyteBase repository, which depends on CyteArc. CyteArc never imports it, whichtests/test_import_architecture.pyenforces; reading a catalog name such ascytearc.cytebase.Catalograises anAttributeErrorthat names the package. CyteArc opens CyteBase datasets by theirhf://URIs like any other remote store.readers/parses supported input formats, including the clone files of lineage tracing tools (readers/clone_tables.py), the lineage barcode files of extraction tools (readers/lineage_barcodes.py), the allele files of lineage recorder pipelines (readers/recorder_alleles.py), immune receptor contigs (readers/cellranger.pyandreaders/airr.py), and the per-cell allele counts of variant callers and genotyping tools (readers/mgatk.py,readers/cellsnp.py,readers/vartrix.py,readers/mito_afm.py,readers/giftwrap.py,readers/got.pyandreaders/tapestri.py, whoseTapestriReaderalso reads Tapestri’s amplicon and protein reads as aCrReader). One module reads each shared kind of file:utils/delimited.pyevery delimited table of these readers, counting each row’s fields and naming each row by its line in the file;readers/_matrix_market.pythe header and entries of every Matrix Market file,readers/mtx.py’s count matrices among them;readers/_h5ad_columns.pythe names of an AnnData table’s index, throughindex_namesandobs_names; andreaders/_treedata.pyTreeData files, their character matrices and their trees, so the store thatwriters/characters.pyexports is the layout that the reader reads.readers/_contigs.pyparses contigs from the tables thatutils/delimited.pyreads. The parser of Cell Ranger’s guide call file,readers/cellranger.py’sread_protospacer_calls, strips its fields withutils/delimited.py’sstripped_text, without pandas’.straccessor, which pandas 2 keeps in a reference cycle with the table’s text.readers/_sparse.pyholdsSparseRowStore, the one store of rows that arrive out of order: rows tagged with their destination row go to buckets of rows on local disk, in compact blocks, from this and other processes, and reads return canonical CSR, or the bytes of ragged rows, a bucket at a time. The CSC conversion ofH5adReaderand the Seurat sources that store cells out of order, compressed by feature, transposed or counted from fragments, convert through it, every import that shuffles cells sends its rows through it to their destinations, andwriters/export.pysends the rows that it reads in store order through it to write them in the file’s order: the counts ofto_h5adandto_mtxas sparse rows, and the rendered rows of the AIRR export as ragged rows of bytes.readers/_row_spill.pysizes the store of a shuffle and what its writers hold within the import’s budget, the same way for every format: H5AD, 10x HDF5 and Tapestri imports send each row that their value scan reads, and Matrix Market, CSV and Seurat imports send batches of rows that they read in the file’s order. Its plan refuses a budget whose buckets, a quarter of it, cannot read the longest row, which arrives whole in one bucket, andadmitted_spill_plannames the least budget that a refused plan admits, which each import restates beside what it holds.CrToZarrcharges the arrays that its reader reports, so a reader’scount_value_rangesscans and spills within what the import leaves it, and writes its cell table from the reader’s_cell_names_source: the barcodes that a Matrix Market or Tapestri reader keeps, or a 10x HDF5 file’s barcodes as the file holds them, bytes of one width, which the import charges until the table is written.SparseToZarrgathers its rows from the matrices in memory and needs no store.writers/materializes CyteArc stores and exports supported formats, including clone tables and clone matrices (writers/clone_tables.py), AIRR Rearrangement files of immune receptor contigs (writers/airr.py), stores of Tapestri files (writers/tapestri.py, whoseTapestriToZarrextendsCrToZarr), and the character matrices of lineage recorders for Cassiopeia and LAML (writers/characters.py). The count imports write their cell table throughstorage/schema.create_cell_data, which takes a shuffled import’s order and reads the IDs a block at a time, and charge it withcell_table_write_bytesbefore the destination exists;writers/_store.write_metadata_columnwrites a column the same way, andmetadata_column_write_bytesstates what it holds.merge/combines assays and datasets without importingDataStoreduring normal module loading.composite/presents selected source counts through an ordinaryDataStorewithout copying them. It is an adapter: only the storage opener imports it, lazily, and core reads reach it only through thestorage/virtual_arrays.pyseam.create.pyreuses merge alignment, metadata, and storage preparation. Its count pass hands segments of each source’s selected cells, each within one stored shard of the source, tostream_shards, as many at once asadmitted_worker_splitadmits within the budget, and reads each throughrun_array_read, the store check ofread_selection, so segments of sources on stores that work on any event loop are read and summarized at once; each cell’s summary goes to its composite row (CountSummary.update_rows).store.pyis the virtual Zarr store that implements the seam,reader.pyreads selections from the source matrices,streams.pyholds the feature streams, which batch adjacent feature groups into one source read, andsource_cache.pykeeps remote source objects on local disk. These four modules import foundation modules only. Assays and pipeline stages use their existing array interfaces.
Readers parse, writers materialize, and merge combines. Format-specific code belongs in a module named for that format.
Orchestration¶
DataStore remains the primary workflow API.
Its analysis namespaces bind the existing scoped operations in datastore._operations.
DataStore.zw opens a workspace group once, as the root group is opened once: its members are
read from the store on each access, and CyteArc writes the workspace attributes through it or, after
writing them through another handle (a derived assay’s type, a discarded pending assay), opens it
again.
datastore.namespaces owns these small accessors, and datastore.artifact_accessor owns saved
result access and discovery. Public names do not replace persisted operation names, parameters,
or input keys. The namespace boundary does not change computation or artifact reuse.
Its public class chain is kept for compatibility:
BaseDataStore
-> GraphDataStore
-> MappingDatastore
-> DataStoreMethod implementations are grouped by responsibility under datastore._operations:
graph
embeddings
clustering
trajectory
mapping
mapping_reference
quality_control
ambient
cell_calling
features
integration_metrics
presentation
regulons
perturbation_guides
perturbation_effects
perturbation_mixscape
perturbation_associations
perturbation_profiles
clones
lineage_barcodes
recorder_alleles
phylogeny
repertoire
variantsambient binds the ambient RNA methods of ds.qc: it streams counts, persists soup profiles and
contamination estimates, and writes corrected assays, while quality_control/ambient.py owns the
computation, after SoupX (Young and Behjati, 2020).
Shared helpers under the same package include enrichment_store, paris_persistence, perturbation_store, which holds the label, read, reference, memory budget, and status helpers that the five perturbation_* operation modules share, cell_samples, which groups the selected cells into samples by their label in one cell column, charging the read to the caller’s memory ledger, for the perturbation operations and hashtag demultiplexing, record_tables, which stores a RecordTable of metadata/records.py under a prefix, such as the contigs and lineage barcode molecules of an artifact, and reads it back, statistical_store, which owns the layout, reuse check, writer, and reader of stored statistical-test results, and cell_barcodes, which every importer uses to join the barcodes of its files to cells: a file’s prefix, suffix and barcode pattern, the canonical order of files by the SHA-256 that identifies each, from utils/digest.py: file_sha256 of a file’s bytes, or what an importer passes as digest (path_sha256, which takes directory_sha256 of a Zarr store’s paths and bytes, for recorder alleles and phylogenies, and the digests of the files that each source’s reader takes for variant counts), and the join’s diagnostics: fileBarcodes, the files’ distinct barcodes by the cell ID they name, unmatchedBarcodes, those that name no cell of the store, and unselectedBarcodes, those that name a cell of the store outside the selection, each kind with up to five examples that show the barcode beside the cell ID it derives. The join tells the two kinds apart by the 64-bit hashes of the store’s cell IDs, which it reads once, a band of chunks at a time, the first time a barcode matches no selected cell; it charges what that pass holds when it starts, so that what an importer sizes from its ledger afterwards leaves room for it, and neither reads nor charges anything for a selection of every cell of the store; it counts a barcode that the pattern does not match apart from one that names the same ID, so the counts do not depend on the order or the chunks of the rows; it charges the hashes of the barcodes of each kind, the store’s hashes and each block that it hashes to the importer’s memory ledger with its lookup of the cells’ IDs. Only unmatched barcodes give the join’s warning, which a reused import gives again from the saved diagnostics. The join also counts each file’s rows, which file_rows gives in the order of an import’s files, and empty_files_rule is the warning that the clone, receptor, lineage barcode and recorder allele imports give from those counts, saved as rowsPerFile or contigsPerFile, naming the files that hold none, files_with_rows picks from them the files that hold rows, which the warnings of files whose rows give the selected cells no clone or no barcode name, and selected_cells_named counts those cells from the join’s saved counts. cell_groups groups the cells of a cell-aligned artifact for the summaries that count within groups: the combinations of the labels of cell metadata columns, of a cell-label artifact, and of the labels that the artifact keeps apart, coded once in natural order, refusing a key column named twice, and counting the grouping’s diagnostics, the measured cells without a clone, the cells with a clone but no group, and the groups; it charges what it reads and builds to the caller’s memory ledger, beside what the caller holds there. The summaries’ tables name each group, and their records hold the groups’ labels apart in group_keys, which clones/groups.group_key_table builds, so a key column may take any name. clone_artifacts plans the clones artifact with the per-cell arrays that its source adds, states what saving it holds from the writer’s own cost, charges it to the operation’s memory ledger before it writes anything, and writes and logs it for every operation that saves clones, with the operation’s diagnostics and its own, cellsWithClone and largestCloneShare, so clone import, clones from a cell column, barcode clones, clones called from variants, allele clones and the clones of a phylogeny’s cut share one artifact contract. clone_steps holds the steps that the clone operations repeat, each charged to the operation’s ledger: integer codes read whole as int64, the IDs of a cell-aligned artifact’s cells, the labels of clones ranked by size, and the words for an import’s files; it also tells from a lineage barcode import’s saved counts whether its rows of selected cells give none of them a barcode, in words that the barcode import’s warning and the clone summaries’ refusal of clones called from such barcodes share.
Operation mixins have no runtime inheritance from datastore facades, no __init__, and no runtime imports of sibling operation mixins.
TYPE_CHECKING imports of siblings are allowed.
Reusable algorithms must be placed in their domain package before being exposed through a datastore method.
datastore.pipeline_accessor exposes the pipeline recipes rna, atac, adt, multimodal, and perturbation. Each recipe method is thin: it passes its keywords to a resolver in datastore._pipeline.recipes, one module per recipe (rna.py, atac.py, adt.py, multimodal.py, and perturbation.py, with the steps that the single-modality recipes share in common.py). A resolver checks the call against the store without writing anything and returns a RecipePlan: the recorded recipe name, the assay, the label, the configuration that the run records, and every stage in order as a PlannedStage. It checks the keywords, the columns and cells, the stage combinations, and every stage setting with the check that the stage’s method runs on it before it reads anything, so a setting that the method refuses raises the method’s message, after the stage’s name, before the run starts; limits that depend on the data are checked by each stage’s method when the stage runs. A planned stage without an action is recorded as skipped, and its on_skip hook gives later stages the inputs that they would have read from it. _pipeline/stages.py builds the stages that several recipes share, from the input snapshot and filtering through highly variable genes, normalization, PCA, Harmony, the graph, the embeddings, Leiden, Paris, cluster selection, and membership strength to doublets and markers. The perturbation recipe runs the RNA recipe’s stages from filtering to Harmony, so a run with an RNA run’s cells and settings reuses that run’s artifacts, and adds one stage per DataStore.perturbation method. The input snapshot freezes each group of cell columns that a stage reads apart, the QC columns of filtering in cell_snapshot and the others in capture_snapshot, harmony_snapshot, doublet_sample_snapshot, and column_snapshot, so that a column one stage reads never enters the provenance of another stage’s result. _pipeline/settings.py checks each stage keyword against the keywords of the stage’s method, and its settings with the settings function that the method calls, which the method’s domain module holds, such as doublet_settings of quality_control/doublets.py, ann_index_settings of neighbors/index.py, and the *_settings functions of perturbation/, and _pipeline/filtering.py resolves and applies QC filtering. Each recipe module also holds recorded_call, which turns the configuration that its runs record back into its keywords for PipelineRun.settings, with the shared inverses cells_argument of _pipeline/stages.py and filtering_argument of _pipeline/filtering.py, so a recipe that changes what it records changes its recorded_call beside it. A stage recorded under its keyword’s name in config["stages"] passes through recorded_call unchanged, so a new stage or stage setting needs no change there. A run recorded before a keyword or setting existed leaves it out of its settings, and the recipe gives it its default, so a new keyword’s default must reproduce what runs did without it, such as False for a new optional stage. The normalization method is the exception: recorded_settings gives a run recorded without it the normalizer that its saved normalized values record, which recorded_normalizer of _pipeline/normalizers.py reads. A new recipe adds a resolver module and a recorded_call, and reuses the rest.
One generic executor, _pipeline/executor.py, runs every plan. Every stage reads the normalizer from its assay’s normMethod, so a plan’s normalizers names the normalizer that the run applies to each assay, which _pipeline/normalizers.py resolves from the normalization method setting, and the executor and the planner make it the assay’s normMethod while the stages run and give the session’s back however they end. The executor creates the run record, passes a RunState that holds the refs of the stages that ran so far from stage to stage, and completes the run with its outputs and the frozen cell and feature fields that _pipeline/fields.py builds from them. The ledger, _pipeline/ledger.py, runs one stage at a time in plan order on the calling thread, and each stage record is terminal before the next stage starts. A record holds the stage’s artifact-plan receipts, wall time, sampled memory, and the warnings that CyteArc logged or issued while it ran, and a completed stage’s record also holds a summary that _pipeline/summaries.py computes from the stage’s artifacts and the diagnostics they saved, so a reused stage reports what a computed one would; an output of a kind without a summary of its own reports its saved diagnostics. _pipeline/events.py delivers each run’s PipelineEvent values in order, on the run’s thread, to its callback and to the listeners that pipeline_listener registered in the calling context. The event types name datastore.pipeline_accessor, where users import them, as their module, so they are documented and pickled there. While a stage runs, CyteArc’s log records carry the run ID and stage, its progress bars forward throttled stage_progress events, and its Zarr reads and writes decode and encode on a pool of the store’s workers, as Zarr internals describes under “Memory controls”. A CancellationToken passed as cancel requests shutdown on the run’s shutdown token, so the run stops at its next shutdown checkpoint, as it does after a signal, records the run as interrupted, and raises PipelineCancelled. The ledger records the running stage as interrupted when the cancellation cut its work short, and as completed when its work had finished. The shutdown token keeps the first request and the first signal apart, so a signal after a cancellation does not escalate and takes its usual effect once the interrupted run is recorded.
The reusable bounded silhouette comparison lives in metrics.cluster_selection. Its datastore
adapter, _pipeline/cluster_selection.py, validates graph-coordinate lineage, scores the Leiden
candidates in the coordinates that built the graph (PCA, LSI, or Harmony coordinates, or
normalized values), and persists the immutable decision. metrics.cluster_selection is not part
of the public cytearc.metrics facade. datastore.pipeline_run exposes the narrow durable
PipelineRun handle and its frozen cell and feature views. Pipeline execution creates immutable
artifacts and a strict run/stage ledger under pipeline/runs; it does not write live metadata.
DataStore-owned plotting, marker loading, and export consume narrow frozen-run views. Completed
runs can be reopened by their immutable label or exact run ID.
_pipeline/planning.py answers DataStore.pipeline.plan, which reports what a resolved recipe would reuse and compute without executing it. It runs each stage’s action inside artifact_forecast_scope of storage/artifact_writer.py, where plan_artifact reuses as it always does but, instead of planning an artifact to compute, raises ArtifactComputationRequired with the reason: no artifact of the operation, the closest one and the parameters and inputs in which it differs, which nearest_stored_artifacts of storage/artifacts.py finds, a superseding revision, an interrupted artifact, missing diagnostics, or a failed payload check. An operation therefore stops before it computes or writes anything, and the plan learns each reused stage’s refs from the operation’s own planning, with the identities and reuse checks that a run uses. A PlannedStage declares the run-state keys that its action or skip hook reads, inputs, and adds, outputs: artifact keys, COORDINATES and FEATURE_NAMES for those values of the RunState, and keys of its extras. The plan follows them to report a stage that reads what a computed stage would produce as waiting on that stage, without running it, and refuses an action that reads or adds an artifact key that it does not declare, so a new stage declares both. Each computed stage’s estimate comes from the stage records of the latest earlier run of the same recipe and assay that computed the stage.
datastore.trajectory_plan answers TrajectoryAccessor.plan, which plans the trajectory calls made in its block. datastore.namespaces binds the trajectory calls that save results through planned_call, which runs each of them in the same artifact_forecast_scope while a plan is open, and returns the call’s plan in place of a ref when it would compute; a call that takes such a plan is recorded as waiting on it, as _pipeline/planning.py records a stage that reads what an earlier stage would compute. The pipeline accessor refuses to run, rerun or resume a recipe while a forecast is active, since a run writes its records outside plan_artifact.
A recipe called with run_until and PipelineAccessor.resume run through the same executor. The executor pauses a run once the stage that run_until names has completed, with pause_pipeline_run_record of storage/pipeline_runs.py, which fails the run when another run has committed its requested label and otherwise closes the process’s segment of the run record. resume rebuilds the plan from the recorded settings with the resolution that plan uses, and the executor replays each finished stage’s action inside artifact_forecast_scope, as the planner runs it, and requires the refs that the stage’s record names, so the replay restores the RunState without computing or writing anything. Only then does resume_pipeline_run_record claim the pause, with an append-only set_if_not_exists key for each pause, and the ledger starts at the first stage left to run. PipelineAccessor.end_paused ends a paused run that will not resume through end_paused_pipeline_run_record, which claims the pause with the same key and records the run as interrupted, so a resume and an end of one pause cannot both go ahead. The executor and resume_pipeline_run_record read the run record again before the replay and before the claim, and a record that holds more segments than the pause that the process read, or that is no longer paused, means that another process resumed or ended the run.
_pipeline/description.py answers PipelineAccessor.describe, which needs no store. It describes each stage keyword of a recipe’s signature from what resolves the recipe: the settings of STAGE_SETTINGS, and the annotations and defaults of the public methods that STAGE_METHODS of _pipeline/settings.py names for each stage, the method that the stage runs first. It declares the few settings whose default the recipe sets itself, the keys that configure the recipe, such as the Leiden partitions of DEFAULT_LEIDEN_PARTITIONS and MULTIMODAL_LEIDEN_PARTITIONS, and the defaults that a recipe fits to its data or call, stated as rules, such as the ATAC recipe’s prevalent_peaks top_n. A stage setting that no method of its stage takes and that declares nothing cannot be described, which tests/test_pipeline_description.py checks for every recipe.
A cell field may read an artifact of any assay, since every assay shares cellData; the cell view checks the artifact’s recorded cell_selection against the run’s. A feature field must belong to the run’s assay, whose featureData the feature view covers. The executor opens both views on the record that it is about to complete, so a field that a view refuses fails the run at finalize, before complete_pipeline_run_record claims the label.
Presentation¶
plotting/ owns the reusable plotting APIs.
It has no import dependency on datastore.
The removed cytearc.plots, cytearc.plotting._legacy, and DataStore.plot_* APIs must not be restored.
New plots should return the established plotting result types, accept documented data contracts, and use narrow adapters instead of adding storage-path knowledge.
Figures of clones, receptors and variants that split cells by group take the groups from one store adapter, _figure_groups, over the grouping of the clone summaries in datastore._operations.cell_groups, so a figure groups cells by several columns, a label artifact and the labels its artifact keeps apart as the summaries do; a figure of a summary takes the record the summary returns rather than computing it again, and reads its groups’ labels from the record’s group_keys. Beside a table’s own columns, a figure holds groups and fates as values, never as column names.
The figures of clones, immune receptors, lineage records and variants draw through the private charts of plotting/_charts.py, draw_bars, draw_lines, draw_histograms, draw_matrix and draw_tree, which draws a collapsed tree as one path of branches and one path of wedges for each color, so its memory grows by a few numbers for each node drawn, beside capped_counts, which bins counts for a bar chart, log_values, which labels a log axis of values that need not be whole, and legend_of, the legend of a side legend that a figure draws itself, and the palettes of their fixed vocabularies in plotting/_style.py; variants.genotypes draws its embedding panel through the categorical drawing and draw order of plotting/embedding.py; the charts return each legend with its scale for _figure.finish_plot to report, so compose_results can draw a legend that several figures share once; plotting/_groups.py’s PlotGroups gives each figure its groups and their colors, and plotting/_clone_names.py what the figure calls the clones and how it labels them, through the store’s _clone_figure_nouns and _clone_figure_labels.
DataStore.plots is a thin, store-bound accessor over the canonical store-first functions in cytearc.plotting.
The accessor imports concrete plot implementations only when a method is called, so this convenience namespace does not reverse the dependency from plotting to datastore.
Public facade policy¶
Lazy and eager facades¶
The lazy facades in cytearc, features and its subpackages, readers, writers, merge, utils, neighbors, clustering, embeddings, trajectory, regulons, and plotting are architectural boundaries, not temporary deprecation shims.
Their documented 1.x exports preserve stable import paths and defer optional or expensive implementations until an export is accessed.
All of them use one private helper, cytearc._facade: an export wins over a same-named submodule, resolving an export never replaces a bound value, and only readers, writers, merge, and utils present the objects they own under the facade’s __module__.
cytebase is a plain module that keeps the earlier public names of the example downloads, re-exported from datasets, through CyteArc 1.x.
The assay, mapping, matrix, metadata, metrics, and quality_control package initializers are eager domain facades.
API reference pages and public contract tests define which of their exports carry compatibility guarantees.
Reloading a lazy facade clears cached exports before resolving them again. This keeps reload behavior deterministic for tests and interactive work.
Private facade exports used by repository tests are patch seams, not additions to the documented user API. New production code should import its canonical implementation directly unless it intentionally needs a public patch seam.
Invalidation policy¶
Operation revisions are the one explicit mechanism that stops CyteArc from reusing stored results.
storage/operation_revisions.py gives each operation that has revisions an append-only tuple
of them; an operation that is not listed is at revision 1. Planning records a revision in
provenance only when it is 2 or more, so an operation without revisions keeps its identities. A
stored artifact that differs from a request only in its revision is superseded: it is never
reused, it stays listable, loadable, and traceable, and lineage reports mark it stale. Changing
recorded parameters or inputs is not an invalidation mechanism. Operation revisions
holds the decision ladder.
Stored data and API contracts¶
CyteArc validates persisted data and public arguments against the following contracts:
AssayStateandIncompatibleAnalysisStateErrorare removed. A store containing{assay}/stateis rejected on open and must be rebuilt. CyteArc never reads, migrates, or uses that group to choose a current result.The pipeline recipes
DataStore.pipeline.rna,atac,adt,multimodal, andperturbationaccept only their documented keywords and return a durablePipelineRun. Removed options and prior return values have no aliases or adapters.Feature selection, graph construction, embeddings, clusterings, scores, markers, mapping, and trajectory operations exchange exact
ArtifactRefvalues. Consumers do not parse encoded metadata names, resolve an implicit latest result, or accept a live result column in place of an artifact.Analysis producers do not rewrite live
Icolumns and do not insert clustering, UMAP, score, or marker columns. Callers use artifact loaders, frozen run views, and plotting adapters instead.Public result records use their current artifact-based constructors. Older positional layouts and field sets are unsupported.
Pipeline run, stage, and label-claim records have exact fields. Within 1.x a release may only add fields and must still read records without them, so a run of any 1.x release reopens in every later 1.x release. A stage record’s
summaryandwarningsare such added fields: CyteArc writes them on every stage record and reads a stage record without them as one with no summary and no warnings.The recipes cluster their graph at every Leiden resolution in one
leidenstage, andrun["leiden"]holds the candidates as a tuple ofArtifactRefordered by resolution, where each candidate had its ownleiden_<resolution>stage, run output, and cell field. The run and stage records gain the optional fieldoutputListsfor an output of several artifacts, which CyteArc writes on every record; a record without it reads as one without such outputs, so runs of earlier releases reopen, report, plot, and export with the stage, output, and field names they recorded, and have noleidenoutput. A new run’s cells hold only the savedclusters, so its export carries no other candidate, andsnapshot_columnsstill cannot use theleiden_<resolution>names. The Leiden artifacts keep their identities, so a new run reuses the candidates of an earlier run; the cluster-selection decision now keys its candidates by resolution, such as"1.0", where it used their output names, so it is computed once again. The candidates are ordered by resolution whatever orderpartitionsgives, and a run withleiden=Falserecords theleidenstage as skipped.A recipe or
rerungivenrun_untilpauses its run after that stage, andPipelineAccessor.resumeruns the rest under the same run ID in any process that opens the store. A paused run’s record holds the statuspausedand the optional fieldsegments, which CyteArc writes only on a run that paused, so the records of other runs keep their shape; earlier releases skip and refuse a record withsegments. A resume claims its pause with an append-only key belowpipeline/runs/.resume-claims.Pipeline stages run strictly in sequence. UMAP no longer runs on a worker thread beside the Leiden, Paris, cluster-selection, and membership-strength stages; outputs and artifact identities are unchanged. Durable stage records now attribute wall time and sampled memory to one stage at a time, and starting a stage while an earlier stage of its run is incomplete raises
ValueError. Pipeline callbacks receive an enabled stage’sstage_startedand terminal event before the next stage starts; earlier, UMAP’sstage_completedarrived after the events of those stages, with or without a worker thread. Earlier run records whose stage windows overlap still read.cytearc.utils.backgroundis removed.Pipeline recipes replace
DataStore.pipeline.run()in a documented break within 1.x:pipeline.runand itsparamsmapping are removed without an alias.pipeline.rna,pipeline.atac, andpipeline.adteach analyze one modality, andpipeline.multimodalintegrates completed runs of the same cells. Their runs record the recipe names"rna","atac","adt", and"multimodal", where runs of earlier releases record"basic_rna_analysis". Each stage has its own keyword, whose settings are the keywords of the stage’s method. An optional stage (cell_calling,hashing,filtering,cell_cycle,umap,tsne,leiden,paris, anddoublets) takesFalse,True, or a mapping of settings; a stage that always runs, such ashvgorpca, takesNoneor a mapping and raisesTypeErrorfor a bool; andharmonyisNone,False, or a mapping withbatch_columns. The shortcut arguments become settings:hvg_count=nishvg={"top_n": n},pca_dims=nispca={"dims": n},neighbors_k=nisneighbors={"k": n}, andharmony_batch_columns=columnsisharmony={"batch_columns": columns}. Aparamssection is its stage keyword, andparams={"species": s}isspecies=s.cellsreplacescell_keyand takes a boolean cell column, a datastore cell-selection artifact, or a completed run, whoseanalysis_cell_selectionbecomes the new run’s cells as the same ref. Cells given as a selection or a run are not filtered again unlessfilteringasks, or an RNA run calls cells or demultiplexes hashtags, which filters the cells that those stages keep; an ADT run filters only when asked. Paris is off by default (paris=Trueruns it). The RNA stage order gainscell_callingandhashingafterinput_snapshot; likemembership_strengthandtsne, they are recorded as skipped unless requested. The other RNA stages and their outputs are unchanged, and so are their artifact identities in a run without Harmony or snapshot columns, which reuses every artifact of an earlier run with the same settings; the next entry describes runs with them. A run’sconfigrecordscells,snapshotColumns,species, and the resolved settings of each stage keyword understages, in place of the earliercellKey, per-option, andparamskeys. A refusal of unmeasured cells names the operationpipeline.rna,pipeline.atac, orpipeline.adtand thecellsremedy.A pipeline run’s input snapshot freezes each group of cell columns apart. Its
cell_snapshotholds the cell names and the QC columns that filtering reads, andcapture_snapshot,harmony_snapshot,doublet_sample_snapshot, andcolumn_snapshothold the capture column of per-capture cell calling, the Harmony batch columns, the doublet sample columns, and thesnapshot_columns, each written only when the run uses it. Earlier, the cell snapshot also held the Harmony batch columns and the snapshot columns, and filtering and the Harmony fit recorded it as an input, as per-capture cell calling, new with the recipes, did for its capture column. A run with Harmony, snapshot columns, or per-capture cell calling therefore gets new identities for its filtered cells and its Harmony fit, and for every artifact computed from them; a per-capture run also gets new identities for its capture calls. Where an earlier run with the same settings stored the former identities, the first such run computes these artifacts again once; nothing is migrated, and the earlier artifacts stay listable and loadable. Runs without Harmony, snapshot columns, or per-capture cell calling keep their identities. Runs that differ only in their Harmony batch columns or snapshot columns now share their filtered cells and every artifact that does not depend on that difference, and per-capture cell calls no longer change with the filtering or snapshot settings.Pipeline recipes check every stage setting before a run record exists, with the settings function that the stage’s method runs, such as
doublet_settingsorann_index_settings, and refuse a value that the method refuses with the method’s message after the stage’s name. They also check what depends on the store or on other settings: a capture label for every input cell of per-capture cell calling, refusing a missing value or a NaN in a float column; an RNA run’spcadimsbelow itshvgtop_n, and an ADT run’s below its panel’s antibodies; an ATAC run’sprevalent_peakstop_nbelow the assay’s number of peaks, andlsidimswith the first component thatskip_firstleaves out at mosttop_n; and, formultimodal(method="snn"), source runs built with oneneighborsk. Such a call raisesTypeErrororValueErrorand writes nothing, where its stage would otherwise fail after the earlier stages with a failed run recorded, and only limits that depend on the data, such as memory budgets, still fail their stage;pipeline.run()failed in its PCA stage when the PCA dimensions were not below the HVG count. An ATAC run’sprevalent_peakstop_ndefaults tomin(10000, peaks - 1), and its configuration records the resolvedtop_n.Pipeline events are reworked. A
PipelineEventcarries the run ID, recipe, label, stage, stage ordinal, number of stages, and time and, as its kind needs, the stage’s progress, metrics, summary, outputs, reused output keys, warnings, or error;to_dict()returns its JSON values. The kindsrun_started,stage_progress,stage_skipped,run_completed, andrun_failedare added, andpipeline_interruptedis renamedrun_interrupted. A run delivers its events to itscallbackand to the listeners thatcytearc.pipeline_listenerregisters for the runs started in its context, and logs and ignores their exceptions. While a stage runs, CyteArc’s progress bars sendstage_progressevents, even whenconfigure_output(progress=False)hides them, at most one every 0.25 seconds for each bar besides its first update and the one that reaches its total.configure_output(stdlib=True)sends CyteArc’s log records to the standard-library loggercytearc, keeping the module, file, line, and function of the call that logged each record and loguru’s level name, and a record logged during a stage carriescytearc_run_idandcytearc_stage;configure_output(stdlib=False)restores stdout or the file thatset_verbositychose. A recipe’scanceltakes acytearc.CancellationToken. Cancelling the token from any thread stops the run at its next checkpoint, records the run as interrupted with the interruption kind"cancelled", and raisescytearc.PipelineCancelled. The stage that was running is recorded as interrupted when the cancellation cut its work short, and as completed when its work had finished. A token cancelled before a run starts raises before anything is written, and a signal never cancels a token. A signal that arrives after a cancellation does not escalate; only a second signal does. The run stops at its next checkpoint and records the first request’s kind,"cancelled", and once that is written the signal takes its usual effect: its prior handler runs or it is raised again, so with the default handlers the call raisesKeyboardInterruptor the process terminates in place ofPipelineCancelled.run_interruptedandPipelineCancelled.stagename a stage only when the interruption cut that stage’s work short. An interruption that a stage notices just after its work finished records the stage as completed and emits itsstage_completed, and thenrun_interruptedwith no stage, as an interruption between two stages or while a skipped stage is recorded does;PipelineCancelledthen hasstageNone.run_failedalways names a stage: the stage that failed, orfinalizewhen completing the run record failed. Callbacks and listeners run in a copy of the caller’s context, taken before the run’s shutdown and cancellation scopes, so a pending stop never interrupts the CyteArc work that a callback does.Stage records gain the optional fields
summary, the diagnostics of a completed stage, andwarnings, the warnings logged or issued while the stage ran, at most 50 of at most 512 characters each.run.report()addssummary["warnings"], one entry with its stage for each warning, and the markdown report adds a Warnings column and a Diagnostics section. Runs of earlier releases still open, report, plot, and export with the recipe name, configuration, and stage order that they recorded. Cluster selection also scores LSI coordinates. Run exports handle ATAC runs, whose LSI coordinates and their Harmony correction export asobsm["X_lsi"]andobsm["X_lsi_harmony"], and ADT runs.matrix="normed"exports a run’s normalized values over its feature selection: the highly variable genes of an RNA run, the prevalent peaks of an ATAC run, or the panel of an ADT run. A multimodal run exports the raw counts of its first run’s assay and has no normalized values to export.Mapping references and query projections use only their current exact-lineage contracts.
Label transfer is a saved artifact.
get_target_classesandget_target_label_evidenceare removed.mapping.transfer_labelsfreezes the reference labels it reads, from a reference column or a reference cell-label artifact, into the query datastore as areference_labelsartifact and saves alabel_transferartifact;mapping.load_label_transferloads it without the reference. An abstention is a missing label with anabstentionReasonrather than anna_valstring,max_distanceapplies to the saved labels, andtarget_subsetis removed. Evidence renamesisUnknowntoabstainedand addscandidateLabelandnearestDistance. It no longer repeats the projection’sfeatureCoverageandqueryScaledDispersionon every row; read them frommapping.load_result(...).diagnostics. Conformal sets come fromLabelTransferResult.prediction_setsinstead of apredictionSetcolumn.mapping_evidence,mapping_confusion, andmapping_calibrationtake the transfer ref instead of a projection, reference, and threshold.mapping_calibrationkeeps the transfer’s saved rules except the one on the swept metric, and without achosen_thresholdit marks that rule’s own threshold.mapping_confusionnames the abstention column withabstention_label.mapping_scoretakesreference_labelsin place ofreference_class_group.ExternalArtifactRefgainsanchor_assayfor an artifact of another datastore that is not scoped to the assay its dataset fingerprint describes.Integration label metrics are split by input contract.
integration.compute_clisiandintegration.compute_graph_connectivityuse the keywordannotation_columnfor imported cell metadata;clusters.compute_concordance(first, second, metric=...)compares exact clustering artifacts. Their formerlabel_colnamekeywords and column- or array-based concordance inputs are unsupported.DataStore.regulons.grnwrites an assay-scopedgrn_adjacenciesartifact with operationrun_grn_inference: paralleltf_index,target_index,importance, andcorrelationarrays (one row per link with positive importance), aregulator_indexarray of the factors offered to every target, and the method, layout, cell, feature, and regulator digests as attributes. It models raw counts, andearly_stoppingrecords which out-of-bag improvement ended each fit.regulons.load_grnreturns aGrnResultand checks the cell and regulator digests. It fits the targets in the calling process and, withnthreadsabove 1, hands those left after_IN_PROCESS_SECONDSof fitting to a pool of spawned worker processes, since each boosting stage runs Python that holds the GIL and threads beyond about three waited on each other. Each worker receives the float32 regulators once through its initializer, holds its BLAS and OpenMP to one thread, and receives each target’s expression as a task, at most two at a time. The memory check charges the expression, the links and one fit (grn_fit_bytes) in the calling process, or each worker’s copy of the regulators and its fit (grn_process_bytes), and runs as many workers as the budget holds, which it logs;nthreadsstays an execution setting.DataStore.perturbation.import_guide_callswrites an assay-scoped, cell-alignedguide_callsartifact with operationimport_guide_calls, whose identity holds the cell selection, the dataset fingerprint, a fingerprint of the guide IDs, the call file’s fingerprint, which is the SHA-256 of its bytes, the barcode prefix, and the barcode suffix and pattern, recorded only when given, so imports without them keep their identities. Its canonicalvalueslabel each cell with its one called guide,"Negative", or"Multiple";n_guides,top_guide,top_umi,top_fractionandtotal_umidescribe each cell’s guides; the two-dimensionalguide_codesandguide_umishold each cell’s called guides, padded to the largest number of calls, which planning leaves open with aNonedimension; andguides, one row per guide and not cell-aligned, holds the guide IDs, which a reuse validator checks ascell_callingchecksambient. The identity records an emptybarcode_prefixas None, so the two imports reuse each other. Its diagnostics are the join’s, which reuse requires: the barcodes that match no cell of the store, which a warning names, and those of cells outside the selection, which a log message names; a reused import reports both again. The import refuses selected cells that one call file cannot reach with the check that the perturbation recipe runs,_require_call_file_cellsofdatastore._operations.perturbation_guides. Before it parses the file,readers.cellranger.protospacer_calls_sizecounts the file’s rows,|separators and bytes in one streamed pass, and the import charges each step to one ledger before it allocates: the guide IDs and the selected cells’ positions and IDs as read, the parse of the file and what it parsed, the called guides’ positions, the join, which charges its own lookup and its pass over the store’s cell IDs beside the matching of the file’s barcodes, the padded calls, whose width the most calls of one row bound, the count stream and the save.perturbation.load_guide_callsreturns aGuideCallsrecord.DataStore.clones.import_cloneswrites a datastore-scoped, cell-alignedclonesartifact with operationimport_clonesfromCloneImportArguments, whose identity holds the cell selection,multiple, and one record per file in canonical order: its format and the columns it reads, the SHA-256 of its bytes and of a matrix’s cell and clone lists, its barcode prefix, suffix and pattern, and the namespace of its clone labels, so paths are not part of the identity.DataStore.clones.from_columnwrites the same kind with operationimport_clones_from_columnfromCloneColumnArguments, whose identity holds the cell selection, the column and a fingerprint of the selected cells’ labels. Both store the canonicalvalues, each cell’s clone label, the int32codesof the clones by rank, -1 for none, the int64clone_size, andclone_idsandclone_sizes, one row per clone and not cell-aligned, which a reuse validator checks; an import of a source with probabilities addsclone_probability. Its diagnostics, the join’s, the clone writer’s,fileRows,rowsPerFileandcellsInSeveralClones, are required for reuse with then_clonesattribute, and hold what its warnings name, barcodes of no cell of the store, files without a row and files whose rows give the selected cells they name no clone, so a reused import gives them again; revision 2 addedrowsPerFile, so an import of revision 1 is imported anew.clones.load_clonesreturns aClonesrecord;clones.export_clones, and the summaries where they find no measured cell with a clone, refuse clones whose import gave no selected cell a clone from its files, or whose cellsmultiple="drop"all left out, through_require_file_clones.DataStore.clones.expansionwrites a datastore-scoped, cell-alignedclonal_expansionartifact with operationmeasure_clonal_expansionfromClonalExpansionArguments, whose identity holds the clones, the label artifact of the groups, the cells measured (the cell selection given, or the clones’ cells), thegroup_bycolumns with the fingerprint of each measured cell’s group, and the bounds, of which exactly one kind is recorded. It stores the canonicalvalues, each cell’s category, the int64group_clone_size, the float64group_clone_frequencyand the int32group_codes, with thelabels,group_keysandkey_columnsattributes that reuse requires.clones.load_expansionreturns aClonalExpansionrecord;clones.diversityandclones.rarefactionsave nothing.DataStore.clones.fate_biaswrites a datastore-scoped, cell-alignedclone_fate_biasartifact with operationmeasure_clone_fate_biasfromCloneFateBiasArguments, whose identity holds the clones, the label artifact of the fates, the early cells as itscell_selection, the late cells, and thegroup_bycolumns with the fingerprint of each late cell’s fate. It stores the canonicalvalues, each early cell’s dominant fate, the int32codesandfate_codes, the int64n_late_cellsand the float64fractions, one column per fate, and, not cell-aligned,clone_codes,clone_early_cells,clone_fate_cells,clone_p_valuesandclone_q_values, one row per clone with late cells, andfate_cells, one row per fate, which a reuse validator checks, with thegroup_keysandkey_columnsattributes that reuse requires.clones.load_fate_biasreturns aCloneFateBiasrecord;clones.couplingsaves nothing.DataStore.repertoire.import_receptorswrites a datastore-scoped, cell-alignedimmune_receptorsartifact with operationimport_immune_receptorsfromImmuneReceptorImportArguments, whose identity holds the cell selection,productive_only, and one record per contig file in canonical order: its format, the SHA-256 of its bytes and its barcode prefix, suffix and pattern, so paths are not part of the identity. Its canonicalvalueshold each cell’s receptor type, andreceptor_subtype,chain_pairing,multichain,n_vj,n_vdjandn_contigsthe other per-cell values;chain_slots, one row per cell and four columns, holds the contig in each chain slot, and thecontig_*arrays, one row per contig or per distinct text value, are not cell-aligned. Itsfieldsattribute, which a reuse validator checks against the stored arrays, and its diagnostics, the join’s,fileContigs,contigsPerFile,unmatchedContigsandcellsWithChain, are required for reuse, so a reused import gives its warnings about unmatched barcodes and about files without a contig again.repertoire.load_receptorsreturns anImmuneReceptorsrecord, and the calls that read contigs refuse receptors whose import read no contig through_require_file_contigs, after_receptor_groupopens them.DataStore.clones.barcode_cloneswrites a datastore-scoped, cell-alignedclonesartifact with operationcall_barcode_clonesfromBarcodeCloneArguments, whose identity holds thelineage_barcodesartifact, the fingerprint of each barcoded cell’swithinlabels, the fingerprint of the allowlist’s sorted distinct barcodes, and the resolved rules: the preset,min_reads,max_distance,metric,min_umis,min_fraction,barcodes_per_cell,method,similarity, one number or the pair within and across libraries,inclusive,prune,doublets,min_size,withinandtrex_rules. Its cell selection is the barcodes’. It stores the arrays of everyclonesartifact, withn_barcodesanddoublet, and then_clones,library_unitsanddiagnosticsattributes that reuse requires, the diagnostics counting what each rule removed;load_clonesreadsdiagnosticsinto theClonesrecord, whose field stays empty for other clone sources. When it gives no cell a clone, the clone summaries andexport_clonesread the diagnostics of itslineage_barcodesartifact to refuse it, naming the cause when the barcodes give no selected cell a barcode.DataStore.clones.allele_cloneswrites a datastore-scoped, cell-alignedclonesartifact with operationcall_allele_clonesfromAlleleCloneArguments, whose identity holds thelineage_allelesartifact, the fingerprint of each edited cell’swithinlabels, the fingerprint of each character’s bank, its sorted alleles with their frequencies and samples, or None when the frequencies come from the cells, and the rules:method,max_frequency,max_samples,max_alleles,fdrformethod="p_clonal"only, andwithin. Its cell selection is the alleles’. It stores the arrays of everyclonesartifact, withn_alleles, and then_clones,bank_coverageanddiagnosticsattributes that reuse requires, the diagnostics counting what each rule removed.DataStore.clones.import_alleleswrites a datastore-scoped, cell-alignedlineage_allelesartifact with operationimport_recorder_allelesfromRecorderAlleleImportArguments, whose identity holds the cell selection and one record per allele file in canonical order: its format, its one integration or the slots of its shorter integrations, the columns it reads, the SHA-256 of its bytes, or of every file of a.zarrstore, and of the files read beside it, and its barcode prefix, suffix and pattern. Paths are not part of the identity. Its canonicaln_editsandn_integrationsandn_recordsare the per-cell values; therecord_*arrays, one row per site of an allele row, or per distinct integration, site or allele, are not cell-aligned. Itsfieldsandstatesattributes, which a reuse validator checks against the stored arrays,filesand its diagnostics, the join’s,fileRows,rowsPerFile,unmatchedRows,slotsBeyondLengthandrowsWithoutIntegration, are required for reuse, so a reused import gives its warnings again.clones.load_allelesreturns aLineageAllelesrecord, andclones.export_characterswrites a character matrix and saves nothing.DataStore.clones.import_barcodeswrites a datastore-scoped, cell-alignedlineage_barcodesartifact with operationimport_lineage_barcodesfromLineageBarcodeImportArguments, whose identity holds the cell selection and one record per barcode file in canonical order: its format, the level of its rows, the columns it reads and its library, the SHA-256 of its bytes and its barcode prefix, suffix and pattern; or, withfrom_assay, one record of the assay’s name, library, dataset fingerprint and feature IDs. Paths are not part of the identity. Its canonicaln_barcodesandn_umis,n_readsandn_recordsare the per-cell values; therecord_*arrays, one row per molecule or pair, or per distinct barcode or UMI, are not cell-aligned. Itsfieldsattribute, which a reuse validator checks against the stored arrays,librariesand its diagnostics, the join’s,fileRows,rowsPerFile,unmatchedRowsandemptyRows, are required for reuse, so a reused import gives its warnings about unmatched barcodes and, for files, about files without a row and files whose rows give no selected cell a barcode again.clones.load_barcodesreturns aLineageBarcodesrecord.DataStore.variants.import_countswrites a datastore-scoped, cell-alignedvariant_countsartifact with operationimport_variant_countsfromVariantCountImportArguments, whose identity holds the cell selection, the count unit,swap_strands, and one record per source in canonical order: its format, the SHA-256 of each file it reads by role, its barcode prefix, suffix and pattern, and what the reader notes about it, such as the strands it swapped or the variants that a Tapestri or DAb-seq import adds to the passing ones, counted and named by the SHA-256 of their names, so paths, and howinclude_variantsnames the variants, are not part of the identity. Its canonicalmean_depth,n_covered_sitesandlistedhold a row per cell; its sites, alleles, depth, counts and calls are long arrays that a reuse validator checks, with offsets ofn_cells + 1rows that give each cell’s rows. Reuse also requires theformat,count_unit,depth_definition,count_fieldsandcontigsattributes and the import’s barcode counts, so a reused import warns as the first one did.variants.load_countsreturns aVariantCountsrecord.DataStore.variants.informativewrites a datastore-scopedvariant_selectionartifact with operationselect_informative_variantsfromVariantSelectionArguments, whose identity holds the counts, the cell selection given ascell_selectionor None, the preset, each threshold as resolved from the preset and the arguments, and the sorted mask names. It holds one row per variant that a chosen cell shows, which a reuse validator checks for equal lengths:variant_alleles,informative,maskedand the statistics, those of strands and qualities only for counts that hold them. Statistics stream the depth and count rows of the chosen cells in bands that_variant_bandsreads together, so memory follows the alleles rather than the cells.variants.load_informativereturns aVariantSelectionrecord, whose preset, thresholds and masks come from those provenance parameters, their one home.DataStore.variants.frequency_cloneswrites aclonesartifact with operationcall_frequency_clonesfromFrequencyCloneArguments, whose identity holds the counts’ cell selection, the selection, the fingerprint of thewithincolumns’ labels,n_neighbors,resolution,within, and the fixed Leiden seed and pruning of the shared-neighbor graph; it reads the counts that the selection scored. It holds the informative variants’ allele frequencies of the scored cells in memory, checked against the budget, and writes theclonesarrays throughdatastore._operations.clone_artifacts, the allowed operation helper that plans and writes the artifact for every clone source.DataStore.variants.genotypeswrites a datastore-scoped, cell-alignedvariant_genotypesartifact with operationcall_variant_genotypesfromVariantGenotypeArguments, whose identity holds the counts’ cell selection, the counts, the method, the genotyped sites, their alleles and the method’s rules as resolved, whichvariants.load_genotypesreads back as the record’smethodandrules. It reads the counts’ depth, counts or calls in bands of cells through_variant_bandsand appends each band’s calls, sorted by cell, to long arrays thatcall_offsetsdelimits.DataStore.variants.genotype_cloneswrites aclonesartifact with operationcall_genotype_clonesfromGenotypeCloneArguments, whose identity holds the genotypes’ cell selection, the genotypes, the chosen sites, thewithincolumns with the fingerprint of their labels, the method and, for"likelihood", its rules and the priors and error caps of its model, or, for"exact", the fixed settings ofclones.calling.set_clones; it reads the calls in bands into packed bits, codes thewithingroups throughdatastore._operations.cell_groups, callsvariants.genotype_clones._likelihood_cloneson each group orset_cloneson every cell, and writes throughclone_artifacts._likelihood_clonesrecords a search that stops splitting atMAX_CLONESclones without the warning thatlikelihood_cloneslogs for its direct callers; the operation saves the capped searches as thecappedSearchesandcellsInCappedSearchesdiagnostics and warns from them when it computes or reuses the clones.DataStore.clones.import_phylogenywrites a datastore-scopedcell_phylogenyartifact with operationimport_phylogenyfromPhylogenyImportArguments, whose identity holds the cell selection,time_unit, and one record per tree file in canonical order: its format, the SHA-256 of its bytes (of every file below a Zarr store’s directory, each with its path), its barcode prefix, suffix and pattern, and the name its trees take from the file’s name, so paths are not part of the identity. The artifact is not cell-aligned: it holds one row per node, the trees in the natural order of their names and each in preorder, with the int64parent(-1 for a root), the float64time(NaN where unknown), the textnamesand the int64cells(the selected cell that a leaf names, as its position in the selection, -1 for none); and one row per tree withtree_names,tree_unique_names(whether every node of the tree has a name of its own),tree_earliest_leaf_timeandtree_latest_leaf_time, andtree_offsets, where each tree’s nodes start, with the end. Itstime_unit,n_trees,n_nodesandn_leavesattributes describe the forest beside its diagnostics, the join’s,cellsInNoTree,unnamedLeavesandleafTimeSpread, which reuse requires withtime_unit, and a reuse validator checks that the node arrays and the tree arrays agree.DataStore.clones.phylogeny_cloneswrites aclonesartifact with operationcut_phylogeny_clonesfromPhylogenyCloneArguments, whose inputs are the phylogeny and its cell selection and whose parameters aretimeanddepth, one of them None, with the arrays of imported clones, then_clonesandtime_unitattributes, and the clone writer’s diagnostics withcellsBeforeCut, from which it warns when it cuts and when it reuses a cut.clones.load_phylogenyreturns aCellPhylogenyrecord.DataStore.plots.phylogenydraws a cut through the store’s_phylogeny_figure, which finds the phylogeny and the cut in the clones’ provenance, reads the node arrays and the clones’ codes, collapses them throughclones.phylogeny.collapse_phylogenyand checks the drawing’s bytes, whichplotting/phylogenies.pystates, all on one memory ledger.DataStore.perturbation.call_guidescalls guides from the counts of the guide assay and plans both of its artifacts before it reads any count. The fitted methods,poisson_gaussianandgaussian, plan an assay-scopedguide_thresholdsartifact with operationfit_guide_thresholdsfromGuideThresholdArguments, whose inputs are the cell selection, the dataset fingerprint, the guide-ID fingerprint and the fingerprint of each selected cell’s sample (None withoutsample_column), and whose parameters aremethodandsample_columns. Theguide_thresholdsartifact is not cell-aligned: it holds the samples x guides arraysstatus,threshold,n_umi_cells,max_umi,iterationsand the fitted parameters of the method,n_cellsfor each sample, the guide IDs inguides, and each guide’s histogram in each sample ashistogram_offsets,histogram_countsandhistogram_cells; itssamplesandstatus_namesattributes name the rows and the status codes, and a reuse validator checks the guides and that the offsets end at the length of the histograms. The calls are aguide_callsartifact with operationcall_guidesfromGuideCallArgumentsand the arrays of an imported one. The inputs of the calls are the cell selection, the dataset and guide-ID fingerprints, and theguide_thresholdsartifact, None forfixedandtop_guide; their parameters aremethod, the resolvedmin_umiand, fortop_guideonly, the resolvedfraction_threshold.min_umiandfraction_thresholdbelong to the calls, so another value plans new calls on the same fits. The calls save their diagnostics:guideFits;fitsCallingNoCell, the fits whose status is not"fitted";fitsNoCells,fitsTooSparse,fitsNoFitandfitsNoPositive, those of each such status; andfitCallingNoCellExamples, up to five of them, all read from the statuses of the fits that the calls computed or reused, and None and empty forfixedandtop_guide; andcellsWithCallandcellsWithSeveralGuides. The fits save none, so new calls reuse saved fits. After the plan, computed or reused, the calls warn throughwarn_diagnosticsof fits that call no cell and, withgaussian, of a majority of called cells with several guides.metadata.selection.sample_codes, moved there from the doublet operation, groups the selected cells into samples by their labels and fingerprints each cell’s sample forqc.doubletsandcall_guides. The fits run on the store’snthreadsNumba threads, and Numba’s previous thread count is restored afterwards. The histograms hold the dense counts, a buffer of the larger counts and 32 bytes for each distinct count, asperturbation.histograms.histogram_bytescounts them, and the distinct counts are known only once the counts are read.call_guidescharges each step to one ledger: the guide IDs, the selected cells’ positions, their samples asmetadata.selection.sample_codesnumbers them, and before the first read the least that the histograms hold beside a block of the rows of a stored chunk of counts. The counts then stream in such blocks, the histograms take the rest and charge the ledger as they grow, andguide_count_histogramsraisesHistogramMemoryError, the ledger’sMemoryBudgetErrorwith the distinct counts that the histograms hold, dense and larger, before an allocation would take more;call_guidesthen names the budget at which the histograms get those bytes, or, when a merge stops them while rows remain, the error’sestimated_needed_bytes. Each sample has histograms of its own, so each sample’s distinct counts, dense and larger, are scaled from its rows read to its cells, with at mostDENSE_COUNTSdense counts per histogram, and a sample not read yet takes the counts of the sample read most, scaled up only where it has more cells than those rows; at those counts the estimate is the larger of what a later merge holds, the buffer and 32 bytes per larger count, and what the assembly holds. The distinct counts and the estimate are computed only when the ledger refuses. A rerun at that budget gets past the histograms unless the cells read later hold more distinct counts per cell than those read, as a deeper-sequenced sample stored after the others can. The last merge of the larger counts also checks the assembly after it, so that one refusal names what both need. The calling pass is charged before it reads a count: each cell’s detected guides, the assay’snFeaturescell column, bound its calls and the padded width underfixedand the fitted methods, whose fits count the calls, andtop_guidemakes at most one call per cell. The fits are saved once the calls that they make, their padding and their save have passed the budget, so that a refused call writes nothing.perturbation.load_guide_thresholdsreturns aGuideThresholdsrecord, read through the calls or from theguide_thresholdsartifact.DataStore.perturbation.labelslabels the cells of aguide_callsartifact by the genes that their called guides target and writes an assay-scoped, cell-alignedperturbation_labelsartifact with operationlabel_perturbationsfromPerturbationLabelArguments. Its inputs are the cell selection of the calls, theguide_callsartifact, and a fingerprint of every guide’s target in assay order, resolved fromtarget_columnandtargets, so the identity follows the resolved targets rather than how they were given; its parameters are the controls, sorted without repeats, and the policy. Its canonicalvalueshold each cell’s label:"Negative","control", the gene, or"Multiple", whichpolicy="combinations"replaces with the genes joined by"+".guide_labelcopies the labels of the calls;is_controlandn_targetsdescribe each cell’s targets; and the two-dimensionaltarget_codesholds each cell’s genes as positions intargets, ascending and padded with -1 to the largest number of genes, which planning leaves open with aNonedimension.targets(the distinct target names, sorted, controls included),target_is_controlandguide_target_codes(each guide’s position intargets, or -1) are not cell-aligned, and a reuse validator checks the shapes oftargetsandguide_target_codes. A target that is not a control and equals"control","Negative"or"Multiple", or under"combinations"holds"+", a control that no guide has, and a called guide without a target raiseValueError, and nothing is written; a control target may take a reserved name or hold"+", since control targets never become labels. Labeling charges each step to one ledger before it allocates: the guide IDs and the target column as read, the calls’ guide codes and the flags that check their targets, whatperturbation.labels.label_memory_bytescounts for the labels, with joined labels as long aslongest_labelallows, the calls’ labels and the write of the artifact. Labeling reads the calls and the guide assay’s target column, not the counts, so it does not check assay membership.perturbation.load_labelsreturns aPerturbationLabelsrecord.DataStore.perturbation.efficiencycompares each target gene of aperturbation_labelsartifact, or withby="guide"each guide’s target gene, between the cells that carry the perturbation alone and the"control"cells, and writes aperturbation_efficiencyartifact with operationmeasure_perturbation_efficiencyfromPerturbationEfficiencyArguments, scoped to the expression assayfrom_assayrather than to the guide assay of the labels. Its inputs are the labels, the dataset fingerprint of the expression assay, and a fingerprint of each row’s name beside the ID of the feature matched to its target, so the identity follows the matches rather thanid_column; its parameter isby. A target matches the feature whose ID its guides give inid_column, when they give one ID and the expression assay’s feature IDs are unique, and otherwise the one feature whose name equals the target. The artifact is not cell-aligned. It holds one row per target that is not a control, in the sorted order of the labels’targets, or one row per guide of such a target, in assay order:names,targets,features(the matched feature ID, empty without one),status(positions in itsstatus_namesattribute),n_cells,n_control_cells, and the floating-pointmean_umi,control_mean_umi,mean_expression,control_mean_expression,remaining_fraction,log2_fold_change,p_valueandadjusted_p_value. Itsbyattribute names the rows, and reuse requires the names, status, count and floating-point arrays with one entry per row and the samestatus_namesandby. The compared cells are found a block of labeled cells at a time, so that only their arrays grow with the cells, and only their matched genes are read, throughassay.normalization.feature_value_blocks, after one memory check that covers the whole call: the reads of the feature columns, finding the compared cells, the counts gathered beside one block of the count stream, asChunkedArray.stream_bytescounts it, and whatperturbation.efficiency.efficiency_memory_bytescounts for the comparison. Each cell is scaled to the median library size of the compared cells that hold a UMI. Labels without a control cell, and compared cells without a UMI of the expression assay, raiseValueError, and nothing is written; a row whose target matches no feature keeps the status"no_feature". The table saves its diagnostics,rowsWithoutFeatureand up to five of those rows inrowWithoutFeatureExamples, which the identity determines, since its fingerprint records each row’s match, and warns from them when measured and when reused.perturbation.load_efficiencyreturns aPerturbationEfficiencyrecord.efficiencyandedistanceread the rows and the compared cells through the same helpers,_label_rowsand_compared_cellsofperturbation_store, which reads each cell’s row from its first target code, or by guide from its first guide code in the calls, a block of cells at a time.DataStore.perturbation.edistancemeasures, for each target of aperturbation_labelsartifact or withby="guide"each guide, the E-distance between the cells that carry the perturbation alone and the"control"cells in a coordinate artifact of a kind ingraph.feature_projection.NATIVE_COORDINATE_KINDS, and writes aperturbation_edistanceartifact with operationmeasure_edistancefromPerturbationEDistanceArguments, scoped to the assay of the coordinates. Its inputs are the labels and the coordinates; its parameters areby,n_permutationsandrandom_seed. The compared cells of the labels are found in the cell selection of the coordinates, and those without coordinates are left out and counted in a log message. The artifact is not cell-aligned. It holds one row per target that is not a control, or per guide of such a target, in the order that efficiency uses:names,targets,status(positions in itsstatus_namesattribute),n_cells,n_control_cells, and the floating-pointedistance,p_valueandadjusted_p_value. Itsbyattribute names the rows, and reuse requires the status, count and floating-point arrays with one entry per row and the samestatus_namesandby. The compared cells are found a block of labeled cells at a time and placed among the cells of the coordinates a block of their selection at a time, so that only their arrays grow with the cells, and only their coordinates are read, as float64 and one chunk of rows at a time. One memory check comes before that read and takes the largest of what checking the cell order of imported coordinates holds, a band of the cell IDs as read and as selected; what finding and placing the compared cells holds; what reading holds, 8 bytes for each compared cell and dimension, 17 bytes for each compared cell, and the chunk that one read holds asmetadata.rows.array_row_selection_partscounts it; and what the measurement holds, 16 bytes for each compared cell and dimension, 41 bytes for each compared cell and 128 bytes for each row, plus, for each thread that tests a row, and no more threads than rows are tested, one block of at mostn_permutationspermutations of the smaller group of the largest row, up to 8 MiB or one permutation when that is larger, and 9 bytes for each control cell. Each thread fills its block again for each block of permutations, takes the next row when it finishes one, and writes the row’s results into the table, so that nothing else grows with the rows. Labels without a control cell, and fewer than two control cells with coordinates, raiseValueError, and nothing is written. Each row draws its permutations from a generator seeded withrandom_seedand the row, so the table does not depend onnthreads.perturbation.load_edistancereturns aPerturbationEDistancerecord.DataStore.perturbation.signaturecomputes Mixscape’s perturbation signature of every cell of a coordinate artifact against its nearest"control"cells of aperturbation_labelsartifact, and writes an assay-scopedperturbation_signatureartifact with operationcompute_perturbation_signaturefromPerturbationSignatureArguments, scoped to the assay offeatures, which default to the feature selection in the coordinates’ lineage. Its inputs are the labels, the coordinates, the feature selection, the dataset fingerprint of the expression assay, the fingerprint of each cell’s sample (None withoutsample_column) and, as for cell data, the coordinates’ cell selection; its parameters aredims,n_neighbors,sample_columnsandscale_factor. It holdsvalues, a float32 cells x features array written in row bands bystorage.sharding.write_dense_from_row_batches;neighbors, each cell’s nearest controls as positions among its cells;is_control;samples, codes into itssample_namesattribute; andfeatures, the physical feature indices, which a reuse validator checks with the sample names. The neighbors are found within each sample over the firstdimscoordinates, in blocks of cells thatperturbation.signature.nearest_controlssizes from the memory left, asnearest_control_bytescounts them; the controls’ scaled counts are held in memory, and every cell’s raw counts of the features are streamed throughassay.normalization.feature_value_blocksbeside the writer’s band of at most 8 MiB, the height of the stored row bands. The memory check covers the largest step: the coordinates as read, the search with blocks of one cell, the control cells’ read, every cell’s read beside the writer’s band, and the neighbors as written; each read counts one block of a stored chunk of rows with its decode, asChunkedArray.stream_bytesdoes. The kind is not listed inCELL_VALUE_NAMES, so cell readers refuse it.perturbation.load_signaturereads the values a stored row band at a time, every feature of it, and its memory check covers the values read, one band and the IDs of the cells and their neighbors as text in the frames; it returns aPerturbationSignaturerecord.DataStore.perturbation.mixscapewrites a cell-alignedmixscape_classesartifact with operationrun_mixscapefromMixscapeArguments, scoped to the signature’s assay and aligned to the signature’s cell selection. Its inputs are the signature, the dataset fingerprint of the assay and the fingerprint of each cell’s split (None withoutsplit_column); its parameters aresplit_columns,min_de_genes,min_cells,logfc_threshold,min_fraction,p_value_cutoff,scale,max_iterationsandperturbation_type. Each cell’s label and single target come from the signature’s labels. One streamed pass over bands of every feature, for the cells of the targets and the control groups, finds the DE genes: in each band, each group’s sums of normalized counts and detected cells give each target and split’s tested genes, which the Wilcoxon tests then compare in the same band with the control cells of the split, whose sorted values serve every target of the split. The signatures of DE genes outside the signature’s features are computed from its stored neighbors. The per-cell arrays arevalues,global_class,posterior,scoreandsplits, withsplit_namesandstatus_namesattributes; the per-row arrays, one row per target and split ordered by target, aretargets,row_splits,status,n_cells,n_ko,n_de_genes,iterations,converged, the mixture’scontrol_mean,control_sd,perturbed_mean,perturbed_sdandperturbed_weight, and the DE genes asde_offsetsintode_features, which a reuse validator checks with the split names. The first memory check covers one feature’s values, the control cells’ sorted values, the groups’ sums and the read of its counts beside the cells’ labels, classes and neighbors, and the classes as written; the DE pass reads bands of features that leave room for their read. Each batch of targets is checked before its read: its float32 signatures, read a stored row band at a time, one DE gene outside the signature’s features with its values, signatures and read, and its largest classification.perturbation.load_mixscapereturns aMixscapeResultrecord.DataStore.perturbation.associationswrites aperturbation_associationsartifact with operationtest_perturbation_associationsfromPerturbationAssociationArguments, scoped to the expression assay. Its inputs are the labels, the dataset fingerprint of the assay, the feature selection of trans pairs, fingerprints of explicit pairs and positive controls as target and feature IDs, and the fingerprints of each tested cell’s sample and covariates (None without them); its parameters areintegration,moi, theresamplingresolved from None,side,n_resamples,stage_threshold,approximation,min_nonzero, the requestedn_calibration_pairs,alpha,seed,sample_columnsandcovariate_columns. At low MOI the tested cells are the control cells of the labels, then the cells that carry each tested target, or withintegration="singleton"each guide, alone. One streamed pass over the tested features, every feature of the assay when a calibration check runs, counts each feature’s cells with counts in each tested row, each control guide and the other control cells, from which every pair’s QC follows; the counts are held as float32 for the tests when they fit half the memory left and leave room for a feature’s read, and otherwise read again in bands, and the reads leave room for the held counts; the bands of both passes leave room for their read. The memory check covers each labeled and tested cell’s arrays, the treatment cells of every group, the QC counts, every pair’s arrays, with at most as many calibration pairs as requested or as the discovery pairs, each thread’s buffers of one pair’s fit, one group’s random sets of the largest round, and twice the second round’s statistics, which a working copy no larger than them joins, or one feature’s read when that is larger; the counts and the inputs of the tests are released before the tables are written. Only the control cells’ guide labels are read, as guide codes. The artifact is not cell-aligned: it holds one row per pair, the discovery, then the calibration, then the positive-control pairs, withsets,groups(the pair’s group of treatment cells),features,n_cells,n_control_cells,n_nonzero_cells,n_nonzero_control_cells,pass_qc,significant,stageand the floating-pointz,p_value,adjusted_p_value,log2_fold_change,se_log2_fold_change,skew_location,skew_scaleandskew_shape; one row per group, the tested rows and then the calibration groups, withgroup_targetsandgroup_guides, so that each name is stored once; andset_namesandcalibration_group_sizeattributes. Its diagnostics arecalibrationStatus("checked","off", or why no check ran),controlGuides,calibrationGrade,falseDiscoveries,negativeControlPairs, androwsWithoutStatisticandcalibrationGroupsWithoutStatistic(the tested rows and calibration groups whose pairs pass QC without a statistic, withstage0) with up to five of each inrowWithoutStatisticExamplesandcalibrationGroupWithoutStatisticExamples; the tests warn from them throughwarn_diagnosticswhen computed and when reused, andload_associationsand the stage summary read the grade, the false discoveries and the status from them. The identity records the positive pairs, which a table of the same pairs shares withpositive_controls="targets", so the targets without a feature for a positive control are not a diagnostic: the call names them in a warning after its checks and before it plans. Every group draws its random sets from a generator keyed byseed, the group and the round, so the tests do not depend onnthreadsor the memory budget. Withmoi="high", every labeled cell is tested: each tested row’s group holds the cells whosetarget_codeshold its target, or whose calledguide_codeshold its guide, and each calibration group the cells that carry any of its control guides, from the control guides called in any labeled cell;perturbation.high_moi.code_countscounts each code’s cells before the memory check andcells_by_codeplaces them after it, both from the stored codes a chunk at a time; the covariates add the guide assay’s_nFeaturesand_nCounts, which its dataset fingerprint covers through the labels’ calls. One streamed pass counts, withperturbation.high_moi.nonzero_group_counts, each row’s expressing cells over the features of its pairs and each calibration group’s over every feature, and each pair’s comparison cells are the total less the group’s. The groups of the tested pairs keep their codes forcomplement_tests, which takes bands of genes sized by the memory left beside each labeled cell’s arrays, the groups, every pair’s arrays, each thread’s conditional sets and copy of a group’s genes, and twice the second round’s statistics, or, while a band’s counts are read, their read; the counts are held as float32 when they fit half of it and leave room for a feature’s read. The memory check also covers, in place of the tests’ share, the groups’ placement: one stored chunk of codes as stored, decoded and read, the control guides’ cells, and the merge of one calibration group’s guides.perturbation.load_associationsreturns aPerturbationAssociationsrecord, with themoiandresamplingof the parameters.DataStore.perturbation.profileswrites aperturbation_profilesartifact with operationcompute_perturbation_profilesfromPerturbationProfileArguments, scoped to the assay of its feature selection. Its inputs are the labels, aperturbation_labelsormixscape_classesartifact, the feature selection, the dataset fingerprint of the assay, the fingerprint of the sample of each cell it reads (None for one sample), and the fingerprint of each profiled row’s masked target feature (None without masking); its parameters areby,min_cells,mask_targetsandsample_columns. The rows are the targets that are not controls, or withby="guide"every guide with a target, control guides included; with Mixscape classes, only the knocked-out cells of a row that is not a control guide count, among the cells of the classes. Each cell’s depth is the<assay>_nCountsrow sum of its stored counts. The control cells and then the cells of the profiled rows are read in bands of features whose float64 sums and moments, with the read of their counts, fit the memory budget beside the float32 profiles and each sample’s control statistics, and the memory check covers a band of one feature; a sample with fewer than 2 control cells is refused. The artifact is not cell-aligned: it holdsvalues(rows x features, float32),perturbations,targets,is_control,n_cellsandmasked_features(the assay position of each row’s masked feature, -1 for none) for the profiled rows,left_out,left_out_targetsandleft_out_n_cellsfor the rows undermin_cells,features(assay positions),n_zero_sd,n_control_cells,control_meanandcontrol_sd(samples x features), and asample_namesattribute. Its diagnostics areleftOutPerturbations, the rows undermin_cells, and up to five of them with their cells inleftOutPerturbationExamples, from which the profiles warn when computed and when reused.perturbation.load_profilesreturns aPerturbationProfilesrecord.DataStore.perturbation.clusterwrites aperturbation_clustersartifact with operationcluster_perturbationsfromPerturbationClusterArguments, scoped to the assay of the profiles. Its inputs are the profiles and the fingerprint of the clustered names (None when every profile is clustered, named or not); its parameters aremetric,min_cluster_size,min_samples,selectionandseed. The memory check covers the float32 profiles read, 4 P F bytes for P perturbations in F features, and the peak ofperturbation.clusters.cluster_memory_bytes, the largest of 16 P² + 16 P F bytes while the distances are computed, 36 P² + 8 P F while HDBSCAN and the linkage run, and 8 P² + 56 P F + 384 F while the layout’s PCA runs, the last term for four float64 matrices of F x 12 from scikit-learn’s randomized solver; the last is the largest once F exceeds about 7P/12. The artifact holdsperturbations,cluster,probability,order(positions in leaf order) andembedding(rows x 2, float32).perturbation.load_clusterscomputes the distances again from the recorded profiles and returns aPerturbationClustersrecord.DataStore.pipeline.perturbationrecords runs of the recipe"perturbation", whoseassayis the RNA assay and whose cells were measured by the RNA and the guide assay, as the operationpipeline.perturbationchecks. It adds no artifact kind: its stages callDataStore.perturbation.call_guidesorimport_guide_calls,labels,efficiency,edistance,signature,mixscape,associations,profilesandclusterwith the run’s refs and settings, so they record the provenance of those calls, and the stages before them are the RNA recipe’s. Its outputs are those of the RNA recipe’s head withguide_thresholds,guide_calls,perturbation_labels,efficiency,edistance,signature,mixscape,associations,profilesandperturbation_clusters; itsconfigaddsguideAssayandprofileLabels, the output whose cells the profiles average. Its cell view holdsguide_call, thevaluesof the guide calls, andperturbation_labelandis_control, thevaluesandis_controlof the labels, which belong to the guide assay and record the run’s analysis cell selection, beside Mixscape’smixscape_classandmixscape_posterior; the recipe reserves all five names fromsnapshot_columns. Its stage summaries read the per-row tables whole and the per-cell and per-pair arrays in bounded blocks.enrichment_scoresartifacts gain thechromvarmethod, written byscores.chromvarwith operationrun_chromvaron an ATAC assay. Itsscoresare chromVAR z-scores and may hold NaN for a cell that expects fewer than one fragment in a set; adeviationsarray of the same shape holds the bias-corrected deviations, andbackground_index(selected peaks by iterations, physical indices) holds the drawn background peaks.gc_digestrecords the GC content of the selected peaks as an input.scores.loadaccepts ATAC assays for this method, andEnrichmentResult.deviationsis set only for it. WAGGR and AUCell artifacts are unchanged.Derived assays are published atomically.
add_grouped_assayandadd_melded_assaystage the assay under acytearc:pending_assaymarker and remove what they created when an error stops them. Counts written bycreate_zarr_count_assaycarrycomplete=Falseuntil they are finalized. A pending group left by a hard kill, an interruption, or a failed publication write blocks its name in every workspace, and repack refuses it, untilDataStore.discard_interrupted_assayremoves it.Ambient RNA results are artifacts and a derived assay.
qc.ambient_profilewrites an assay-scopedambient_profileartifact (operationestimate_ambient_profile) of the summedcountsand thefractionof each feature over its empty droplets, which records the dataset fingerprint and either theempty_dropletsselection or thetotal_countsrange.qc.ambient_contaminationwrites a cell-alignedambient_contaminationartifact (operationestimate_ambient_contamination) whosevaluesare each cell’s contamination fraction, with per-gene-set evidence arrays and the global, gene-set, and cluster estimates as attributes.qc.correct_ambientpublishes a derived RNA assay withcountsTthrough the derived-assay transaction, which can now write a membership mask: the assay measures only the estimated cells, and its attributes record the source assay, both artifacts, and therandom_seedof its rounding. Each gene’s removal is rounded at random by systematic sampling, with one draw per cell keyed by the seed and the cell’s row in the store, so the counts do not depend on the row bands and another seed gives another assay identity. Nothing earlier changes.Mounted targets resolve their source’s artifacts read only. A mount lists, loads, traces, and reuses the complete artifacts of its identity-checked source after its own, so a recipe that matches saved provenance reuses the source’s results instead of recomputing them, and labels and embeddings imported into the source, such as the CyteBase
X_umap, are visible on the mount. Nothing is migrated because no record changes:ArtifactRefstays a location-free name with a random ID, provenance and run records are unchanged, andExternalArtifactRefstays the cross-dataset identity. Every write goes to the target, and a write inside a source artifact group raisesPermissionError. Pipeline runs and their labels stay per store. ThematrixSourcetop level is exact (location,workspace,assays), so a mount record with any other field fails to open and asks for a fresh target.repack_zarrreads a mount through the same namespace and writes a self-contained store. A read-only open of an unprepared store, such as the source thatmount_datastoreopens, asks for one writable open instead of a rebuild.local_cachefollows the store that holds the normalized artifact rather than the datastore location, so a local mount stages a normalized artifact that it reuses from a remote source and never one that the target holds; staging on stores that are not mounts is unchanged.A mount opens its source with
source_storage_options, whichmount_datastore,DataStore, andrepack_storetake, and with the target’sstorage_optionswhen they are None, as every mount did before. ThematrixSourcerecord holds no options and keeps its shape. A composite’ssource_storage_optionsmap each source’s name to its options, and a name that matches no source, as a mount’s options would, is refused before any source opens.A mount and a composite record a source in the directory that holds them, or below it, by its path relative to that directory, when both are local or both are URLs of one scheme and host, and any other source by its absolute path or URL.
record_source_locationandresolve_source_locationinstorage/stores.pyhold the rule. Opening resolves a relative location against the directory of the path or URL that the store is opened from, whichresolve_matrix_sourceandopen_compositetake aslocation, so a directory of stores can be moved, copied, or served from a bucket. The records keep their shape and the identity checks still refuse a source with other content.mount_datastore,create_compositeandcreate_matrix_sourcerecord relative locations by default,relative_sources=True, from the release after 1.4.0, which is the first release that resolves them. An earlier release resolves a relative location against its working directory, so it finds such a source only when run from the directory that holds the store.relative_sources=Falserecords every source by its absolute path or URL, as 1.4.0 did by default.create_compositewrites to any destination that the store layer opens, a local path, a URL withstorage_options, or a Zarr store, and gives its new arrays the storage profile of that destination, as other writers do; a destination that holds anything raisesFileExistsError.source_column,datasetby default, names the cell column of source names and is checked asDataStoreMergechecks its own. The composite record keeps its shape.Public cell filters apply the pipeline filtering rules.
qc.filterandqc.auto_filterexclude rows whose metric is missing and raise on missing sample labels among active cells, non-finite metrics used for automatic bounds, invalid bounds, duplicate attributes, and empty inputs or results. Selections over masked metadata columns recordmissing_mask_fingerprints; identities on unmasked stores are unchanged. Earlier selections over masked columns remain valid artifacts and must be recomputed.Cell-aligned artifact readers carry the linked missing mask.
select_cells, groupings used by statistical testing and distribution plots, and integration metrics exclude or reject missing labels, andqc.doubletsrejects clusterings with missing labels. These readers, trajectory cell-data inputs, and pipeline filtering accept only the canonical__cytearc_missing__<name>mask link.Readers show rows that a linked missing mask flags as missing.
MetaData.to_pandas_dataframeandhead,get_cell_vals, liveto_anndataandto_h5ad, and plots show them as missing: numeric values become float64 NaN, and in H5AD files booleans become nullable booleans and text gets a missing category.MetaData.fetchandfetch_allstay raw.compare.compute_bulkleaves masked cells out of every group, dot and matrix plots reportdropped_group_cells, andcluster_connectivityrejects masked inputs.markers.search,clusters.membership_strength,clusters.relabel_by_overlap,imputation.compute_imputedof a metadata column, andsilhouette_scoringof a metadata column reject masked inputs before any reuse or write, so results from unmasked inputs keep their identities.clusters.membership_strengthandclusters.relabel_by_overlapaccept only categorical label kinds.DataStore.snapshot_cluster_labels(labels, cell_selection=...)freezes a cell metadata column, or a cell-label artifact read for a subset of its cell selection, into a datastore-scopedcluster_labelsartifact with operationsnapshot_cluster_labels. Floating-point labels that are whole numbers within the int64 range, such as the float64 ids that pandas writes for integer ids with missing values, are stored as int64; other floating-point labels raiseTypeError, and missing, masked, and blank labels raiseValueError. Text is stored at the width of the selected labels, and integer and boolean labels keep their dtype. The identity recordssource_columnas a parameter orsource_labelsas an input, the cell selection, and thevalues_fingerprintof the stored labels, and a snapshot is reused only while its payload holds exactly those labels. A new snapshot’svaluesarray keeps the categories thatlabel_categoriesreads from the source, as thelevels,orderedanddisplayattributes thatrecorded_categoriesreads, whichwrite_cell_data_artifactwrites througharray_attributes: a column’s attributes, a categorical column’s categories andorderedflag beside itsdisplay, or a label artifact’s attributes, with whole-number float categories as int64, other float categories left out, and none for a source of more thanMAX_STORED_CATEGORIES(10,000) categories, the cap of the H5AD import. They are no part of the identity, so a reused snapshot keeps the categories it was made with, and one of an earlier release keeps none. The missing-label errors ofmarkers.search,clusters.membership_strength, andclusters.relabel_by_overlapname this method and the cell selection that each consumer needs, and so does the blank-label error ofmarkers.search.Query projections record the input
query_dataset_fingerprint, which replacesselected_expression_fingerprint. A query cell with no counts in any shared reference feature is uninformative. The diagnosticzeroNormCellCountis renameduninformativeCellCount, andqueryScaledDispersionuses shared features only. Older projections fail to load with a request to rerunmapping.run.mapping.run(feature_key="names")matches query features to the reference features by exact name, reading the reference features’ names from the reference assay at the reference’s feature selection. It refuses a reference whose features share a name, naming their IDs, and sums query features that share a name, asDataStoreMerge(feature_key="names")does. The projection and itsselect_mapping_overlapselection recordfeature_keyonly when it is"names", so projections that match by ID keep their identities, andfeatureCoveragecounts the reference features that some query feature matches.Mann-Whitney uses the exact permutation null when the two groups can be formed in at most 100,000 ways. Its statistical-test artifacts record
p_value_policy, and results carryp_value_method; identities of other tests are unchanged. Saved Mann-Whitney results withoutp_value_methodfail to load with a request to recompute. AStudyDesignpairing column applies only to the paired Wilcoxon test.densMAP embeddings symmetrize neighbor distances.
embeddings.umaprecords float parameters as floats and integer parameters as Python integers, somin_dist=1andmin_dist=1.0identify the same embedding. The defaultsmin_dist=1andnegative_sample_rate=5were recorded as integers, so every saved UMAP embedding recomputes on its next run. Numeric parameters reject booleans and non-finite values,umap_dims,n_epochs, andrandom_seedmust be integers, andparallelanduse_density_mapmust be booleans.Clustering inputs are canonical and strict.
clusters.leidenrecords resolutions as finite positive floats and requires a non-negative integerrandom_seed. Paris is never refitted silently: a reused hierarchy that cannot be read raisesArtifactResolutionError(code="corrupt_payload"), hierarchies missing required arrays or attributes and cuts whose diagnostics do not match the schema are not reused, andclusters.load_parisrejects such cuts with the same error. A fixed Paris cut needsn_clustersof 1 or at least the number of connected components; merges tied at the cut height are applied in hierarchy order, so exactlyn_clustersclusters are returned. Clustering and doublet entry points reject graph references that are not connectivity maps or integrated graphs.Leiden clustering defaults to CyteArc’s own backend,
"cytearc", inclusters.leiden,cytearc.clustering.leiden_membership, the pipeline’s Leiden stages, gene programs, and the profilingleidenBackend. igraph and leidenalg are no longer dependencies of CyteArc, in no extra either: users who wantbackend="igraph"or"leidenalg"install the GPL packages themselves, and asking for those backends without them raisesImportErrorthat says so.LeidenArguments.backendgains"cytearc", and the backend stays part of the artifact identity: a default call recordsbackend="cytearc"and computes new labels instead of reusing an artifact recorded with"igraph". Such artifacts stay valid and are reused by calls that passbackend="igraph", without the packages. No operation revision is needed, because the GPL backends compute what they did before.leiden_membershipgains a keyword-onlynthreads, whichclusters.leidensets to the datastore’snthreads; the thread count is an execution option, not part of any identity, and the native labels do not depend on it. Native labels are numbered from 1 by decreasing cluster size.markers.loadreturns stringgroup_idvalues in plot category order (numeric labels first in numeric order) and raises for an unknown group.markers.export_csvuses the same column order. Only plain decimal labels are numeric, so plots no longer read"1_10"as 110; other labels sort naturally, with digit runs before text and case-only ties broken by the exact text.scores.waggrandscores.aucelltakeambiguous_targets="drop"and recorddropped_ambiguous_targets. Enrichment artifacts withoutlayoutordropped_ambiguous_targetsfail to load.cytearc.metrics.silhouette_scoringandprocess_clustertake no positionalann_objand nodata_is_reducedkeyword.silhouette_scoringrequires the keyword-onlydistance_metricand compares rows as given.trajectory.fatetreatssolver_tolas an absolute bound on the largest Bellman residual of each solved sink column. Existing fate artifacts remain valid; this change alone does not stop their reuse.trajectory.fatetakesdirection, a per-cell score of the cells ofgraphthat directs the walk in place ofpseudotime: a cell-aligned artifact of real values, or a pandas Series indexed by cell ID that it aligns to the graph’s cells and saves as ametadata_snapshotof operationsnapshot_fate_direction. A map directed by a score records the inputsconnectivity_map,direction,sink_labelsandcell_selection, whichtrajectory.artifacts.FATE_DIRECTION_INPUTSnames; a map directed by a pseudotime records what it recorded before, so it keeps its identity, and the loader accepts either set.pseudotimeandsink_labelsdefault to None,sink_labelsis still required, andFateMappingResultgainsdirection, None for a map directed by a pseudotime, while itspseudotimeis None for a map directed by a score.trajectory.pseudotimetakessolver_tolandmax_iterations, the tolerance and iteration bound of its solve, and records each only when set; the loader accepts a record with or without them. A solve that reachesmax_iterationsraisesPseudotimeConvergenceError, aRuntimeErrorwith the cells, operator products and bounds of the solve, and the solve’s products advance a progress bar and an INFO record every 30 seconds.component_policy="sources"scores the component that holds the most source cells, and a source or sink label without cells in the selected cells or in the scored component raisesSourceSinkLabelsError, aValueErrorwithmissing_sources,missing_sinks,missing_fromandcomponent_sizes, frompseudotime, its loader andfate.PseudotimeScoreResultgainscomponent, each cell’s connected component numbered by decreasing size, andcomponent_sizes, which the loader computes from the stored graph, so no stored data changes.cytearc.trajectory.select_pseudotime_componentlists the sizes largest first.trajectory.pseudotimetakesmethodand records it. The default,"untruncated", applies the pseudoinverse of the random-walk graph Laplacian to the source-sink vector over all of its modes, whichcytearc.trajectory.pba_potentialsolves by MINRES on the symmetric Laplacian;solver_tolandmax_iterationsare then MINRES’srtoland iteration bound."truncated"keeps the potential of the smallest singular modes that earlier releases computed, andsvdstakes the bounds astolandmaxiter.n_singular_valsandrandom_seedapply only to"truncated"and are recorded only with it; they default to None, which it reads as 30 and 4444, and a call that sets either without it raises. The new default is revision 2 ofrun_pseudotime_scoring, scoped to pseudotimes that do not recordmethod="truncated". Pseudotimes saved before record no method, which the loader reads as truncated: a default call computes them anew and lineage marks them stale, while pseudotimes that record"truncated"stay current.PseudotimeConvergenceErrortakes keyword fields, gainsmethodand, for MINRES,relative_residual, and holds None in the fields of the other solve.trajectory.pseudotimeandtrajectory.lineage_treetakecells, a cell selection within the graph’s cells, which becomes the result’scell_selectioninput, so a call without it, or with the graph’s own selection, records what it recorded before and reuses every saved result. The pseudotime scores the subgraph that those cells induce and numbers that subgraph’s components, and its loader andfatetake that subgraph again. Labels may hold the graph’s cells or the result’s, and so may the coordinates ofcurvesandlineage_tree, which read only the result’s rows. A lineage tree records no graph, so its loader takes labels and coordinates of any cells that include its own.curves_in_layoutand the lineage plots take a layout that holds the trajectory’s cells and may hold more, throughcytearc.trajectory.curves.layout_rows.cytearc.neighbors.diffusion_operatoris removed; it formed a powered operator with no memory bound.bounded_diffusion_operatoris the only powered builder, andneighbors.diffusion.transition_matrixreturns the graph-sized single step. The removal changes no doublet score and no diffusion or pipeline artifact identity.Assays are no longer
DataStoreinstance attributes.ds.<name>resolves an assay only when noDataStoreattribute has that name and the name does not start with an underscore;get_assay(name)returns any assay. Assays named like members, such ascellsorzarr_mode, no longer break opening or replace the member.Producers that cannot reuse a saved result raise
PermissionErroron a read-only store before computing or writing. This covers every artifact producer, including marker search,clusters.relabel_by_overlap, membership strength, cell filters and selections, graph, embedding, trajectory, and mapping producers, and derived assays. Leiden, Paris, UMAP, and t-SNE refuse before they read the graph.features.universe,features.snapshot,features.detected,features.hvgs,features.prevalent_peaks,scores.cell_cycle,scores.potency,mapping.build_reference, andmapping.runplan first, so a read-only store returns a result that it holds; a feature summary that must be computed is refused before the counts are read, andscores.potencyrefuses before it downloads its network.mapping.build_referenceraises thisPermissionErrorwhere it raisedValueErrorbefore planning, andmapping.runraises it where it raisedValueError. WAGGR, AUCell, chromVAR, andregulons.grnstill refuse a read-only store before planning.Public arguments are validated before any artifact is written:
graph.load(use_k=...),reduction.lsiskip_firstandrand_state,reduction.customloadings,reduction.harmonyparameters,integration.modalities(chunk_size=...),features.hvgskeywords, andembeddings.umaparray initializations.Normalization arithmetic is independent of the count storage dtype. Library-size, CLR, and TF-IDF calculations use float64 for integer and floating-point counts. Persisted normalized values and the library-size values ranked by marker search are rounded once to float32; marker search ranks values of other normalizations unrounded. Library sizes, subset totals, TF-IDF term totals, and feature percentages accumulate in float64.
Assay.score_features(log_transform=True)takes logarithms in float64, including for assays without a normalization. Sums over cells combine partial sums of stored row blocks orcountsTcell bands, so their last float64 bits can depend on count layout.compare.compute_bulkand synthetic doublet counts add integer counts in an integer dtype and floating-point counts in float64. RNA normalization maps a zero library total to 1, so a zero-count cell normalizes to zero.Grouped assays store counts, and rebuilding a store copies those values. Recompute a grouped assay with
add_grouped_assayunder a newassay_label. A grouped assay containing NaN cannot pass the count writers, including a data-only repack; re-import its source and build the assay there.Pseudotime markers and aggregations compute streamed library-size values in float64. Statistical tests compare the fingerprints of their input values for reuse.
invalidate_cache=Trueforces recomputation.Library-size marker search ranks raw counts of every storage dtype with one zero-aware kernel, with or without
renormalize_subset. The kernel validates its input while reading it: a negative or non-finite normalized value of a tested feature, or a negative or non-finite total of a selected cell, raisesValueErrornaming the feature or totals before anything is written. Cell totals come from<assay>_nCounts, or from the tested features withrenormalize_subset=True. Rank statistics use float64 group sizes, and the two groups of a two-group search have equal p-values. Library-size statistics use float64 values rounded once to float32.cytearc.features.find_markers_by_rankreturns aRankMarkerResultof the sorted group ids, their sizes, the ascending feature index, and the features-by-groups rank statistics instead of one DataFrame per group, and raisesIndexErrorfor a cell or feature index past the end ofcountsTinstead of ranking an unwritten column as a cell. ARankMarkerResultrequires at least two groups, at least one of them tested (at least two cells, and at least two other cells, as a saved marker table needs), and at least one feature; itstablemethod gives the ranked table of one tested group, with the stringgroup_id, that a saved marker table reads back. Feature-stream plans charge what Zarr holds while it reads a band (ArrayGeometry.readBytes) and the streams’ band indices, and size read-group destinations by the selected cells, so tight budgets admit fewer reads in flight and budgets that fitted only uncharged read buffers raiseMemoryError. The marker search also reserves its result, the stored tables its writers finish, and kernel scratch. Read-group streams process one group at a time in order while the next is read, or withorderedCompute=Falseup to the policy’s compute workers each process one group while one more is read, in completion order. The band reads of the groups in flight share the requested read width,StorageIoPolicy(readWorkers=...)or eight reads per worker, whichWorkShape.maxUnitsInFlightlets the planner split into inner reads, and an execution report names the cause inreductionReasonwhen memory or the band count leaves fewer reads in flight. The library-size kernel uses as many threads asnthreads, which now caps them, and the budget admit: it splits the features of one group over the threads of one compute worker, or, when groups are too narrow to keep those threads busy, ranks whole groups at once with one serial kernel each. It reserves scratch for every kernel call that can run, so marker memory grows with the threads only as far as the budget allows, and a search that cannot rank one group with one thread raisesMemoryErrornaming the bytes it needs.map_feature_read_groupsloses itsextraItemsizeargument, and itsorderedComputeargument defaults toTrue.find_markers_by_regression, whichtrajectory.markerscalls, scales the regressor and each feature’s values by a power of two below one in magnitude before it sums them. Pearson r does not depend on that exact scale, so ordinary inputs give bit-identical results, but a regressor or feature values whose squared deviations overflowed float64 (magnitudes above about 1e150 to 1e154, depending on the number of cells) now give their correlation instead of r = 0 with p = 1, or NaN, and a regressor whose squared deviations underflowed (below about 1e-160) is tested instead of reported as untested. Two-cell searches report r of exactly 1 or -1 instead of a least-squares value that could round below one. Pseudotime marker identities are unchanged. It treats a feature as constant, and untested, when its values span at most float64 epsilon times their largest magnitude; the rule was an absolute span of epsilon.Row-block streams over a sharded array reserve what Zarr holds while it reads a block: a shard-level copy of the selection, the compressed bytes of every chunk the block touches in a shard, charged at the bound of their encoded size, the one chunk decoded at a time, and the objects of Zarr’s read beside it, next to the block and the output of its first operation. Each later operation of a chain holds the previous output beside its own, and a block reserves the larger of these steps, so row blocks of CLR and TF-IDF values, which hold two float64 outputs at once, reserve 16 bytes per value of uint8 or uint16 counts instead of 10 or 12. Library-size scaling takes
log1pin place within its own operation, so row blocks of log-normalized RNA values hold one float64 output beside the read of their counts, 10 to 12 bytes per value of uint16 counts instead of 16, and give the values that logging in a second operation gave. Normalization writes, row-block streams, and reductions over such values therefore run fewer blocks at once and raiseMemoryErrorwhere only the smaller reservation fitted; single operations, and chains over counts of 32 bits or more, reserve what they did.ArrayGeometry.readBytestakes the number of chunks decoded at once and charges an unsharded read its result and each chunk it decodes at once as stored and decoded, and a read of either kind whatArrayGeometry.heldDecodeBytescounts, the objects of Zarr’s read, and where Zarr’s opt-inFusedCodecPipelinedecodes on a pool of its own one previous decoded chunk for each decode under way, aswholeReadBytesandbandReadBytescharge the same read, so row-block streams over normalized data, the local staging copy of normalized data, and copies of cell and feature columns reserve about twice the decoded chunk for each decode, run fewer blocks at once, and raiseMemoryErrorwhere only the decoded chunk fitted.plan_feature_streamsizes the feature blocks of a sharded array by the same read. Normalization, PCA, LSI, graph construction, quality control, export, subset, materialization, melding, and merge plan or size their row blocks with these bytes, so a budget admits fewer blocks at once and raisesMemoryErrorwhere only the uncharged read buffers fitted; outputs and identities are unchanged. A row-block stream keeps no block after it yields it, feature streams drop their own references to a unit before they release its reservation, and no thread of CyteArc’s pools, the storage runner’s or the codec pools that Zarr’s reads decode on, keeps a call or its result once the call has returned it. HVG feature statistics reserve the selected cells’ inverse totals, the outputs, every band’s partial statistics, and each compute worker’s band scratch, and no longer keep the totals beside their inverses.compare.compute_bulkmeans that stream normalized row blocks reserve their group sums and divide them in place.Sparse count imports that write several assays from one source, such as Cell Ranger, MTX, and H5AD files with antibody or peak features, no longer raise
MemoryErrorwhen a band of a wider assay arrives while bands of a narrower assay are pending and every band fits on its own. The writer writes the longest run of pending bands that fits, so the earlier bands are written first.Storage operations run outside an event loop no longer chain their errors to a
RuntimeError: no running event loop, and a storage read that its own I/O loop cancels raises oneCancelledErrorinstead of a group of two.cytearc.storage.async_execution.ensure_zarr_host_ceilingloses itsmaxWorkersargument, which nothing passed, and thewrite_counts_tmetrics dropsourceRepeatedDecodeCountandsourceRepeatedDecodeBytes, which paired count layouts always left at 0 because everycountsTshard holds wholecountschunks.When anything but its block stream’s stop cancels the task of a read through
read_selectionon Zarr’s event loop, the read raisesasyncio.CancelledError, as a read on its own event loop does, instead ofconcurrent.futures.CancelledError, and an error that a read raises itself keeps its class. Reads run on Zarr’s loop for fsspec’s HTTP and S3 file systems and from any thread that already runs an event loop, such as a Jupyter cell’s. Zarr’s own synchronous calls, such asarray[...],get_orthogonal_selection, metadata reads and every write, still raiseconcurrent.futures.CancelledErrorwhen they are cancelled, and CyteArc now treats that class as an interruption, as it treatsasyncio.CancelledError: on every path a cancelled run ends interrupted, with interruption kindasyncio_cancelled, instead of failed, the artifact or derived assay being written stays, marked incomplete or pending, instead of being deleted, a cancelled read of a stored neighbor or connectivity payload is no longer reported as a corrupt payload, and a cancelled write of a store’s preparation claim stops the open instead of preparing the store without the claim.except Exceptionno longer catches a cancelledread_selection, and code that reads synchronously in a task on a running event loop now has that task cancelled: anasyncio.TaskGroupends without an error and without the task’s remaining work, where it raised anExceptionGroupofconcurrent.futures.CancelledError.ATAC
normedno longer leaves its fitted TF-IDF state (n_term_per_doc,n_docs,n_docs_per_term) on the assay after the call, and RNAnormednever changesnormMethod. ADataStoreis not designed for concurrent use from several threads.Count storage dtype: each assay’s counts are stored unsigned, in the narrowest of uint8, uint16, uint32, and uint64 that holds the assay’s largest value, exactly when every canonical (duplicate-summed) value of the assay is a non-negative integer. Other counts keep their source dtype: float32 or float64, or the signed integer dtype of a source with negative values. float16 is not a count storage dtype; count writers reject it, and H5AD imports read float16 sources as float32.
cytearc.storage.count_dtypeholds the one policy, andcytearc.utils.count_valuesthe value scans that readers and writers share; a scan takes the group of each feature and returns one range per group. Every import applies the policy to every encoding: H5AD, 10x HDF5 and Matrix Market (CrToZarrandMtxToZarr), CSV,SparseToZarr, andSeuratToZarr. Integral float, signed, and wider unsigned sources, unsorted or duplicate coordinates, CSC, and dense matrices therefore store the same dtype and content fingerprint at any memory budget, and 10x HDF5 and Matrix Market imports, which stored uint32, and Seurat imports, which kept float64, store the narrowest unsigned dtype of each assay. Imports that split one source matrix into assays (10x HDF5 and Matrix Market feature types, H5ADassay_split_key) resolve each assay’s dtype from its own features, so an assay’s dtype and identity do not depend on the other assays of the source: an antibody, guide, or ATAC assay stores its own narrowest dtype beside RNA counts that need a wider one, and integral assays stay unsigned beside an assay with fractional or negative values. The count dtype arguments are removed:CrToZarrandMtxToZarrdtype,MtxReaderdtypeand itsconsumedtype,CSVtoZarrdtype,SparseToZarrmatrix_dtype, andDataStoreMergedtype(merge manifests no longer record it);create_zarr_count_assay,create_empty_zarr_count_assay, andDerivedAssayTransaction.create_countsrequire the dtype.CrReadersubclasses implementmatrix_dtypeandcount_value_ranges(maxBytes, featureGroups=None), which returns the range of each group of features over the selected cells, andH5adReaderhas the same method.MtxReaderscans the matrix once at construction for every orientation and filter mode, which replaces its coordinate-order probe, and keeps the largest count of each feature; it reads the file once more only when it dropped cells and an import splits its features into several assays. Its batches hold the counts of the kept cells in the narrowest unsigned dtype that holds them.H5adReaderloses itsdtypeargument and itsmatrixDtype,storageDtype, andinfer_storage_dtypemembers, andH5adToZarr.storageDtypebecomesstorageDtypes, the dtype of each imported assay;consumeyieldssourceMatrixDtypevalues for every encoding, except that the converted rows of a CSC integer source hold their duplicate-summed values in int64 or uint64 (consumeDtype), so duplicate sums past a narrow source dtype import as they do from CSR. Seurat count sources compressed over features, transposed, or stitched from Assay5 layers keep the duplicate coordinates of a cell in the source dtype, as sources compressed over cells do, and the writer sums them in 64 bits: such duplicates no longer raise OverflowError, and Assay5 duplicates whose sum exceeds a narrow source dtype, which were stored wrapped, store their sums. Subset and repack keep the source dtype, because they rebuild an existing dataset whose identity and copied artifacts must stay valid. Merges store the common type of the source count dtypes, widened when features summed by name could overflow it, instead of float64 for differing dtypes, and reject integer sources without a common integer dtype; an assay without features in any source stores uint8 instead of uint32. Derived assays (grouped and melded) keep their float64 values. Dense writers (CSV and dense Seurat counts) no longer cast batches before the checked cast, so a count that the stored dtype cannot hold raises OverflowError instead of wrapping. The CyteBase build no longer forces the source dtype, and its records dropstorageDtypePolicy. Count matrices hold finite values: every count writer, including subset, merge, repack, and derived assays, rejects NaN and infinity, and the H5AD, 10x HDF5, Matrix Market, CSV, sparse, and Seurat imports read every value and reject them before they create the destination. Stores whose counts contain NaN or infinity cannot be subset, merged, or repacked, even with--data-only; re-import their sources. Negative values stay storable.H5adToZarrscans a matrix of about 67 million stored values or more for its value ranges in spawned processes, each over its own rows, or columns of a CSC matrix: as many as the import’s workers, at mostio.readWorkers, and as the budget holds a whole scan window of about 75 MB and the longest row or column in each.H5adReader.count_value_rangestakesprocesses, and each window runsscan_file_windowofreaders/_h5ad_values.py, which imports only the scan, so the processes start in about half a second.CountValueRange.mergecombines ranges in any order, and a range keeps nomaximumonce a value is fractional or negative, where it kept the largest value of the blocks read before, so a range does not depend on where the scan’s blocks end. The ranges, storage dtypes, the row counts of a dense matrix and the index order of CSR rows are the same for any number of processes.Operations trust that prepared counts and artifacts do not change during a call. Writing to prepared data in place is outside the contract and is not detected.
Minimum versions rise to scipy 1.15, statsmodels 0.14.5 (earlier releases fail to import with scipy 1.16), threadpoolctl 3.5 (earlier releases cannot see the OpenBLAS in NumPy and SciPy wheels, so BLAS thread limits had no effect), and huggingface-hub 2.0.
Count layout: plans whose countsT chunks fell below half the chunk target (awkward cell counts such as primes) now use whole-target chunks, so stores written with those plans fail layout replay and must be re-imported. Count assays require Zarr format 3. Every count writer admits its layout against
mem_budgetbefore it creates its destination:H5adToZarr,CrToZarrandMtxToZarr,CSVtoZarr,SparseToZarr,SeuratToZarr,SubsetZarr,subset_assay_zarr,repack_zarr,DataStoreMerge, andadd_grouped_assay. The imports write the default layout unless they are given apolicy, as before, and a layout that does not fit raises MemoryError naming the largest halving of it, withunitBytesandchunkByteshalved together, that fits. That error is aCountLayoutMemoryError, which holds the halving asfittingPolicy, and an import givenpolicy="fit"writes the halving instead of refusing. Every import writer reports the layout it wrote as itspolicyattribute. The other writers, which wrote the default layout at every budget, now halve the defaultunitBytesandchunkBytestogether until the counts write and the countsT transpose fit, and a write that does not fit with one-row count shards, or with its explicitpolicy, raises MemoryError before the destination exists. Sparse writers admit their sparse band writes and dense writers their dense row bands. Writers that choose their source batches (the sparse imports, the Seurat imports, and merge) admit batches of one destination row band, the batch their write starts from, so a layout never starves the write to narrower batches; only one-row shards get one-row batches.add_melded_assaykeeps sizing its shards to the melding band that fitsmem_budget. The writers raise from their constructors, andDataStoreMergefromplan, instead of fromdump;SeuratToZarrconstruction also prepares every selected source and reads its counts once, so source preparation errors surface there.CrToZarrandMtxToZarrtakelines_in_memin the constructor, anddumpno longer accepts it, so the fit reserves the Matrix Market parse buffer that the write of a file sorted by cell uses and a smaller buffer fits a smaller budget; a feature-major file’s parse is admitted on its own, before the write, as the contract on Matrix Market parse charges below records. An explicitdump(batch_size=...)reads at most one destination row band per batch, so it can no longer exceed what the fit admitted. Writers that write their assays one at a time (Seurat, subset, repack, and merge) admit each assay on its own. The fitted or named layout depends only on the budget, the data, the dtypes, and for Matrix Market imports of files sorted by celllines_in_mem, never on the worker count. A resumed merge keeps the layout persisted with its completed counts, so a budget change between attempts cannot block it, and fits the layout of the counts it rewrites. Sparse imports admit the producer’s buffering and the band writes as separate phases, so budgets that the summed plan refused now import.write_counts_t,finalize_writer_counts_t,finalize_writer_counts_t_many, and the merge writer’swrite_assay_counts_tlose theirpolicyargument and replay the persisted layout. Arepack_zarrthat fails after it creates its destination removes it, so a failed copy, such as an unreadable label claim copied last, no longer leaves a store that opens without all its data. Identity does not depend on the layout: content, counts, and dataset fingerprints are unchanged, and only the layout fingerprint incytearc:countMatrixLayoutdiffers. Existing stores are never rewritten and keep their dtype, layout, and identity. A re-import can store a different dtype and therefore get different counts and dataset fingerprints and new artifact ids; mounts and mapping references bound to a replaced store fail closed.SubsetZarrlosesoverwrite_cell_data. The parameter had no effect: the constructor always opens the destination empty, so a subset never found cell data to keep or replace. Passing it now raises TypeError. Explicit cells are named bycell_ids, which must be distinct cell IDs of the store, at least one; invalid IDs raise ValueError, and one string or values that are not one-dimensional raise TypeError, before the destination is created or overwritten. Acell_keythat selects no cells still writes a subset without cells.subset_assay_zarrrequires one-dimensional distinct in-range integers incells_idxandfeat_idx, raising IndexError, ValueError, or TypeError, and requires at least one feature, before it createsout_grp; it wrapped negative indices and repeated duplicates before. The docstrings ofH5adToZarr.dump,CrToZarr.dump(andMtxToZarr.dump),SparseToZarr, andCSVtoZarr.dumpno longer list an AssertionError for a row-count mismatch, because that check could not fail. The shard writers raise ValueError for a count stream with more or fewer rows than the destination, or for a batch of another width. A CSV file that changes after the reader’s pass reports this ValueError, whichCSVtoZarr.dumpnow documents.Stored contracts are strict. ANN indexes carry their complete metadata record including
byte_length;graph.neighborsrequires recordedann_efandann_parallel; mapping references requireann_ef; building and loading a Symphony mapping reference require recorded Harmonybatch_levels,batch_columns, andharmony_parameters. HVG selections recordblacklist_fingerprintand, for adaptive binning,variance_estimatorandvariance_quantile. Statistical-test artifacts missing any recorded attribute fail to load. Earlier artifacts without these records fail to load or are rebuilt.A metadata column stores its values, or a categorical column’s codes beside its categories (categorical columns).
MetaData._get_arrayhands a categorical column out as aCategoricalColumnthat reads as its labels, so every read of a column, and every reader that plans from a column’s dtype and chunks, sees the labels of either layout without knowing it. The ledger reads ofmetadata/rows.pyread the codes and charge the codes, the categories and the labels they return, andread_rows_bytesstates that charge for the checks that plan a read of selected cells.metadata_column_fingerprint, run snapshots and their column fingerprints decode a categorical column at the dtype of a text column of the same labels, so fingerprints and artifact identities do not change with the layout;metadata_column_stampstamps codes and categories as stored.MetaData.insertwrites the categorical layout for pandas categorical values, andMetaData.fetch_categoricalreads any column as a pandasCategorical.read_categorical_rowsandread_metadata_label_rowsofmetadata/rows.pyread a categorical column’s rows as aCategoricalof their codes, andresolve_cell_columnandresolve_groupingdo withcategorical=True;valid_category_mask,category_codesandsample_codestake such aCategoricaland work through its codes and categories, with the results of its labels.cell_groups,read_cell_samplesandcompare.compute_bulkread a categorical column so, and plots decode the codes of the plotted cells alone. Live exports read a categorical column throughMetaData.fetch_categorical, and anH5adColumnofwriters/exportcarries it as a pandasCategorical, whichto_anndatareturns andto_h5adwrites as an AnnData categorical of the same codes and categories; a text column exports its labels, and a run export the labels that its snapshots froze. Subset, repack and mount keep the layout; a merge writes labels as values.H5adToZarrwrites each categorical ofobsandvarin the categorical layout by default,categorical_columns=True, throughwriters/_store.write_categorical_column:metadata/encoding.stored_categorical_codestypes every category asstored_categorical_valuestypes the labels of the rows, from the categories that rows hold, and each assay of a split from its own codes, andreplace_metadata_columnwrites them in the import’s storage profile. The codes keep thelevels,orderedanddisplayattributes of the column of labels, so labels, attributes, fingerprints and identities equal those of an import withcategorical_columns=False, whose stored tables do not change. A categorical of more than 10,000 categories, or whose categoriesstored_categorical_codesrefuses withUnstorableCategoriesError, aValueErrorraised before anything is written, is stored as the column of labels thatcategorical_columns=Falsestores, with a warning that names the column, its table and the reason. Other imports write values.SeuratToZarrkeeps its label columns because a Seurat factor stores its labels at the width of its widest level, used or not, so the categorical layout would change the run-snapshot fingerprints of an import whose widest level no cell holds. CyteArc 1.4.0 is the first release that reads the layout. An earlier release refuses a table that holds a categorical column, sincestorage/categorical.stored_categoriesgives every categories array a length other than its table’s row count, with a reserved entry, recorded aspadded, when the categories number exactly the rows, andstorage/copygives a copy the entry for the rows it holds.Metadata copies, column clearing, and run snapshots accept only the canonical
__cytearc_missing__<name>link and reject multi-dimensional columns. Copies and snapshots store text as unicode and text fingerprints decode bytes as UTF-8, so identities over byte-string columns change.MetaData.columnslistsI,ids,names, then the other columns sorted.MetaData.sift,multi_sift, and covariate partitions treat masked rows as missing, andinsertstores an explicitfill_valueas a real value without a mask (see the partial-insert entry below).MetaData.get_index_bymatches values that are not text by their text and always returns int64 indices.MetaData.insertrejects names that are empty,.or.., contain/or\, because Zarr would nest them into groups, or start with the__cytearc_missing__mask prefix;reset_keyandupdate_keyapply the same rule. A lookup of a name with a separator suggests the_spelling that imports store, and a lookup of an empty,.or..name raisesKeyError. A cell or feature table that holds such a nested group from an earlier import raises an error that asks for the source to be re-imported on every read, write, and drop of that name; stores are not migrated.Storage operations raise a single task failure as itself and a cooperative shutdown as
ShutdownRequested, not as an exception group. A pipeline stage whose exception group holdsKeyboardInterruptorShutdownRequestedis recorded as interrupted and raises that interruption. CyteArc keeps no process-wide execution report history; collect reports withexecution_report_scope.Recorded artifact inputs have one strict reader,
ArtifactStatus.input_ref(name). A missing or malformed input raisesArtifactResolutionError(code="corrupt_payload")naming the owning kind and input, in mapping references and projections, graph lineage, trajectory and cluster-selection inputs, plots, and pipeline run records. Query projections validatecell_selectionwith the stored-selection validator, and connectivity-map payloads follow the neighbor dimension rules, son_cellsabove 2**32 - 1 is rejected.A failed or interrupted artifact write deletes its incomplete slot when the failure comes before the write that marks the artifact complete, so
artifacts.listno longer shows orphaned incomplete artifacts after an error; once that publication write is issued nothing is deleted.ProjectionWriter.abortdeletes an unfinished projection before its publication write. Starting any artifact on a read-only store raisesPermissionErrorbefore writing, soreduction.harmonyandtrajectory.pseudotime(ss_vec=...)no longer surface the Zarr read-onlyValueError.Gene families:
cytearc.features.gene_familiesis the one registry of name-based families, andribosomalalways means RPS, RPL, MRPS, and MRPL.DEFAULT_PERCENT_PATTERNSmoves there fromcytearc.assay.classification, and newly prepared stores record the ribosomal percentage pattern as^RPS|^RPL|^MRPS|^MRPL. Genes, percentage values, and the HVG blacklist are unchanged. Feature identity requires a digit after a registry ID prefix, asprefix_speciesdoes, so IDs of other Ensembl species such as chickenENSGALGare no longer release-drift misses.ChunkedArrayfollows NumPy broadcasting: a one-dimensional operand aligns with columns and rows are scaled with an(n_rows, 1)operand. Scalar keys, other axes, ufunc keywords other thandtype, and arithmetic between two ChunkedArrays raise; zero-row reductions return NumPy shapes.reduction.pcafits exactly with the Gram solver up to 4096 features, for every block layout, and with a randomized block Krylov solver above, which recordssolver="randomized". IncrementalPCA and theincremental_block_rowsparameter are removed, and revision 2 ofrun_pcamarks the IncrementalPCA fits that recorded it as stale. PCA artifacts store thevarianceandvariance_ratioof theirdimscomponents, whichshow_elbow_plotreads for a reused fit. Reuse does not require them, so an artifact of an earlier release is still reused, and its elbow plot is replaced by a warning. Embedding initialization seeds its PCA and keeps rarely used streamed k-means centroids. Default cell-cycle genes use CENPU, PIMREG, and JPT1 (mouse Cenpu, Pimreg, Jpt1); parameter tuning’s native doublet graphs use the candidate ANN seed.Integer arguments share one validator: NumPy integers are accepted, integer-like objects such as 0-d arrays are rejected, and messages read
<name> must be an integeror<name> must be at least N. It also validatesDataStore(min_features_per_cell=...)andFeatureRef(value, by="index").Paris fits raise each merge to at least its child heights, so hierarchies of tied graphs validate, and straight and fixed cuts number equal-size clusters by hierarchy node order.
clusters.load_parisrejects cuts that do not name their hierarchy.Inputs are validated before any lookup or write. Graph flags accept only booleans (NumPy booleans included).
markers.searchrejects blank labels.clusters.relabel_by_overlapsuffixes continue pastz(aa,ab) and colliding names raise.select_cellsraises when no cell is retained.compare.compute_bulkand integration metrics leave out or reject NaN, None, blank, and masked labels. Doublet, cell-cycle, prevalent-peak, membership, and statistical-testing arguments are checked first, and two-group tests rejectcomparisonsthat reverse the resolved group order.mapping.runrejectsquery_batchesvalues that share text, such as1and"1", and treats nested store locations as one store.get_cell_valsclipping covers every real numeric column. A storeddefaultAssaymust name an assay.Validation corrections that change only which error is raised, never a result or an artifact identity:
trajectory.pseudotimecompares the graph’s recorded cell count with its stored cell selection, asimputation.diffusiondoes, andcytearc.trajectory.select_pseudotime_componentchecks that the graph is square with one row per selected cell, so mismatches raiseValueErrorinstead ofIndexError.trajectory.markersraisesValueErrorwhen a correlation is not finite (a raw pseudotime near the float64 limit) instead of writing an unloadable table.select_cellsraisesValueErrorfor anincludeinteger beyond the float64 range on a floating artifact, instead ofOverflowError.integration.modalitiesraisesValueErrorfor sources over different cell selections, whatever their sizes, instead of reporting a healthy source ascorrupt_payload.graph.neighborsrefuses exactly 2**32 cells, which graph payloads cannot hold.CYTEARC_ZARR_PROFILEaccepts onlyfast_localandcloud; any other non-empty value, such asCloud, raisesValueErrorinstead of being ignored.Feature selections must select at least one feature, and every reader applies that one rule. For a stored selection that selects none, including the feature universe of an assay without features,
DataStore.features.resolveand every operation that takes a feature selection raiseArtifactResolutionError(aValueError) with codecorrupt_payload:Feature selection must select at least one feature. Before, such a selection resolved and its index read back empty, andscores.waggr,scores.aucell,markers.search,trajectory.markers,trajectory.aggregation,features.normalize, andqc.feature_percentageeach raised their own error. No CyteArc producer writes such a selection, so only records written or edited outside CyteArc are affected.features.hvgsandfeatures.detectedno longer read a reused selection back to check it: a reused record that was emptied outside CyteArc is returned, and its consumers refuse it. Results and artifact identities do not change.scores.waggrraises the sameValueErrors with clearer messages. A selected cell total that is negative or not finite now reads<assay>_nCounts holds negative or non-finite totals of selected cells; library-size normalization requires finite non-negative counts; before, it said only that the normalization scalars must be finite. An RNA assay whosesfisNonenow readsWAGGR requires a finite positive size factorinstead of claiming a non-default normalization. Results and artifact identities do not change.reduction.lsiwith the streaming solver reduces its block so that both the fit and the coordinate write fit the memory budget; budgets that logged a reduction and then raisedMemoryErrorfinish with smaller blocks. The block size is an execution option, so identities do not change. A parallel UMAP layout runs onmin(nthreads, NUMBA_NUM_THREADS)Numba threads even when the calling thread had fewer, a serial one on one thread, andAssay.score_featuresno longer warns for an empty CLR cell selection.DataStoreMergerefuses destinations that alias, contain, or lie inside a source or that already hold content, and creates destinations with mode “w-”. Source names cannot contain__.overwrite=Truerefuses destinations with a prepared assay and clearsdefaultAssay. Manifests requiresourceCountFingerprints; without them, restart withoverwrite=True. Differing unordered cell-columnlevelsare unioned; other differing attributes are dropped with a warning.DataStoreMergerecords, for each merged assay, the type that every source declares, soHTOstaysHTO,GeneActivitystaysGeneActivity, andCRISPRstaysCRISPR; sources that declare different types for one assay raiseValueErrorbefore anything is written. Merged ADT and ATAC assays therefore open asADTassayandATACassayand keep CLR and TF-IDF normalization. The manifest requiresassayTypes; without it, restart withoverwrite=True.plan()reports a destination whose prepared assay has incomplete counts as blocked (canDump=False, “A damaged prepared assay requires a fresh destination”), the refusal thatdump()already raised, instead of planning a resume. A merged matrix group counts as complete only when itscompleteattribute istrue, as every other merge component does.Imports: H5AD import stores missing categorical, nullable, and string values under linked masks and keeps nullable booleans as booleans.
inspect_h5adreads group-encoded AnnData indexes and prefers an ID column such asgene_ids, and reads a one-elementunstext dataset as its element;H5adReaderreads the index named by_index. H5AD sparse matrices need an encoding and a stored shape. H5AD, CSV, and Cell Ranger readers reject missing or repeated identifiers. CSV import types values over every row and rejects missing or negative counts. Matrix Market BED sidecars givechrom:start-endPeaks, and feature references are left-joined. Cell Ranger HDF5 readsmatrixand rejects several genome groups. Import writers acceptassay_type. RDS parsing rejects malformed character vectors and xz payloads that need more than 256 MiB of decoder memory.Reader edge corrections:
CSVReaderraisesValueErrorfor a file without count columns, where every column is the ID column or is listed incell_data_colsorskip_cols, instead of importing an assay without features thatDataStorecannot open, and it copiespandas_kwargsinstead of adding itsread_csvsettings, such aschunksize, to the caller’s dictionary.CrH5Reader.matrix_dtypeis the stored dtype in native byte order, with float16 read as float32 asH5adReaderreads it, andconsumeyields that dtype, so float16 and big-endian 10x HDF5 counts import (integral counts unsigned, other counts float32 or the native float dtype) instead of failing in SciPy after the destination was created.H5adReader.sourceMatrixDtypeis likewise the stored dtype in native byte order, with float16 read as float32, so an H5AD file whoseXis big-endian (sparsedatain CSR or CSC, or a dense matrix) imports with the count storage dtype instead of failing in SciPy after the destination was created.CrReader._read_dataset(key)takes a required key and returns a list: the base reader no longer accepts None from it, which no shipped reader returned, so the unreachable fallback from missing feature names to feature IDs and its warning are removed. A Matrix Market cell sidecar emptied afterinspect_mtxraises the cell-count mismatch error (Cell sidecar has 0 rows, expected N) instead ofCell sidecar must contain at least one column.CSV rows have the header’s field count:
CSVReadercounts the fields of every row at construction and raises ValueError naming the line (CSV line 3 has 4 fields, but line 1 has 3) for a row with more or fewer fields than the header, or than the first row of a file without one. pandas reads the file in chunks ofbatch_sizerows and compares a row only with the row before it in the same chunk, so a row that started a chunk lost its extra fields, a short row was padded with missing values, and a header without a field for the row names, as Rwrite.tablewrites it, made pandas take the first column as an implicit index and drop the cell names; each of these files used to import without an error. The check reads the text thatread_csvopens, with the same decompression, encoding, and byte order mark handling, afterskip_rowsrows and without blank lines, and splits rows withsepand thequotechar,quoting,doublequote,escapechar, andskipinitialspacesettings ofpandas_kwargs.sepmust be one character, so a regular-expression separator such as\s+raises ValueError, andpandas_kwargscannot setcomment,dialect, orlineterminator. The check reads the file once more at construction, about 16 percent of the reader’s pandas pass.CSVReaderraises KeyError forskip_colsnames that are not CSV columns, as it does forcell_data_cols.CSVtoZarrno longer compares the reader’s cell IDs with its row count, because aCSVReaderreturns one ID per row.MtxReaderlosescell_metadata_path, which had no effect: the reader extracted the named file from a ZIP archive but never read it; passing it raises TypeError, andMtxCandidate.cellMetadataPathstays as the inspection report of a Parse candidate’s cell metadata file.CrH5Readerraises ValueError (filtering_cutoff cannot be negative) for a negativefiltering_cutoffbefore it opens the file, asMtxReaderdoes, whether or notis_filteredis set; an unfiltered read used to keep every barcode with such a cutoff.H5AD geometry:
H5adReaderchecks the matrix geometry when it is constructed, before a writer opens its destination. The matrix must be two-dimensional, a sparse group needs a stored shape even whenobsandvarare present, itsindptrmust have one entry more than the rows (CSR) or columns (CSC) of that shape, and the shape must equal theobsandvarlengths; an absent table takes the matrix’s length. Such files used to import with the rows pastobsdropped or an empty feature for each extravarrow, or failed after the destination existed. Denseconsumerejects abatch_sizebelow one, as sparseconsumedoes. Anobsorvarstored as a dataset without fields reads as a table without columns, asinspect_h5adreads it, and cell IDs that are not text, such as an integercell_ids_keycolumn, import with embeddings.Matrix Market coordinates may come in any order.
MtxReaderandCrDirReaderread cell-major and feature-major files as before. Any other order, such as the descending features within each barcode that Cell Ranger 1 and 2 write, used to raiseValueError(coordinates are neither cell-major nor feature-major); it now setscoordinateOrderto"unordered", and construction reads the file once more to write the entries of each kept cell to temporary rows undertemp_dir, sorted by feature with duplicate coordinates summed wherever they appear, which an import then reads. The totals, and so the filtering cutoff, are exact in any order, and the entries of each cell and the largest counts, and somax_window_nnzand the count dtype, come from the summed rows, so such a file stores the counts, dtype, and fingerprints of the same matrix in sorted order. The rows hold each count in a dtype that holds the largest kept total, which bounds every sum. They taketemporaryDiskBytesof disk, which construction checks, and the end of an import orcloseremoves them, as does the garbage collection of a reader that is never closed. A later import sorts the file again and raisesValueError,RuntimeError, orOverflowErrorwhen the file holds a different number of entries than at construction, when a kept cell holds a different number of entries or of distinct features, or when a count exceeds the largest one that construction found. Other changes, such as a lower count, import as the file now holds them, as the sorted paths import them.CrDirReadergainstemp_dir.MtxReader,CrDirReader,CrH5Reader, andH5adReadertake a keyword-onlyduplicate_feature_ids. The default"error"rejects repeated feature IDs, as before, with a message that names the option."make_unique"keeps the first occurrence of each ID and renames each later one, in file order and across assays, by appending-1,-2, and so on, skipping a name that is already an ID, and logs a warning with the number of renamed IDs; an antibody that repeats the ID of an earlier gene becomes, for example,CD4-1. Feature names are not changed, so an H5AD file without a feature name column takes the names from the IDs it holds; a Matrix Market feature reference matches the IDs of the feature sidecar; and repeated cell IDs still raise.H5adReader.from_inspectpasses the option to the reader, andH5adReadercaches the resolved IDs, so it warns once per reader.Metadata column names: H5AD readers and inspection list dataframe columns from
column-orderand resolve each listed name as an HDF5 path, so columns that old AnnData versions nested under/are imported instead of skipped. Tables withoutcolumn-orderstill list their direct children, and a nested index named by_indexresolves either way.H5adReaderrejects acolumn-orderattribute that does not hold names when it is constructed, before a writer opens its destination. Every import writer stores a source cell or feature column whose name contains/or\under the name with_in their place, and logs the rename. Source names that are already valid keep their name; a renamed column whose name is taken gets the first free_2,_3, and so on, in source order. Reserved names are checked after renaming. Matrix Market feature-reference columns with separators are renamed instead of rejected.inspect_h5adsees such columns, anduns/batch_conditioncolumns map to stored names. CyteBaseobs_summaryuses stored names whileh5ad_keyskeeps source names. The original name is not recorded in the store, andto_h5adexports the stored names.DataStoreMergerejects asource_columnorprepend_textwith a separator or the mask prefix, at construction and again when planning, and run snapshots and stored selections treat\like/and name the_spelling. H5AD listing keeps a nested group visible when resolved names do not cover all of it, so the reader reports it, and leaves datasets with more than one dimension out of the planned names. A 10x feature-reference column that is empty for every feature is not planned.Seurat:
SeuratReaderandinspect_seuratresolve sidecars only insidesidecar_root(default: the.rdsdirectory), and stream sources need it for sidecar-backed layers. Counts containing RNAraisemissing_count_value. Dimnames and LogMap identifiers override names stored in sidecars. Factor metadata keeps empty levels. Transposed BPCells nodes, MergeFragments peak counts, and RegionSelect boundaries follow BPCells, so re-imported counts can differ. TileMatrixfragmentsmode counts each tile that holds one of a fragment’s insertions, atstartandend - 1, so a fragment whose insertions fall in two tiles of one range counts in both instead of only the first; stores imported from such matrices must be re-imported. HDF5 sidecars in H5AD layout needencoding-typeorh5sparse_formatand take axis names only from the index named by_index; other HDF5 sparse groups ignoresparse_layoutandlayoutattributes.Seurat partial imports: metadata columns decode one at a time, so a column that cannot be decoded (a list or matrix column, an empty or repeated name) is left out with a
skipped_metadata_columnnotice, andSeuratReader(cell_metadata=...)includes or excludes columns by name; a column named in an include list must decode.integer64columns import as 64-bit integers andDateandPOSIXctcolumns as ISO 8601 text;as.character()of doubles (adeferred_string) is formatted with 15 significant digits as R does. Row names, Dimnames, and list names may be ALTREP. A legacy assay with an emptycountsslot, such asIntegrateData’sintegratedassay, reportscounts_layer_missing. With the default selection,SeuratToZarrskips assays and reductions that cannot be imported, withskipped_assayandskipped_reductionnotices, and takesdefault_assay, which an active assay that is not imported requires; an activeSCTAssaygives way to the assay of raw counts that its models were fitted to. A reduction needs itsassay.usedonly for loadings: without it, the coordinates import under the default assay without loadings. Reductions of some cells, or of the cells in another order, align by name over a cell selection of their cells, and Assay5 cells may follow any order. A reduction is a display embedding when it has two or three columns and its key names UMAP or t-SNE (or it is namedumap,tsne, ort-sne), or asreduction_rolesmaps it. The RDS parser rejects attributes that are not a pairlist withRdsFormatError, reads small values through its read-ahead window, scans character vectors in bulk, and hashes compressed input while it decompresses it.Exports:
to_h5adwrites AnnData 0.2.0 encodings and omits_indexfromcolumn-order;to_mtx(compress=True)adds a feature-type column.Plotting:
dotplotandmatrixplotpool only features of one assay that share an explicit label and raise for other shared labels;matrixplotorders groups likedotplot.marker_heatmapclusters unclipped z-scores. Continuous color limits follow one policy across plots, category scales show only observed categories,compose_resultskeeps panel and raster colorbars and honors log scales, and plot functions close the figures they created when they raise.distributionreports a missing pair value with thecompare.testmessage. Default category colors range over every value of the colored column or label artifact, so subsets keep their colors. Embeddings draw categories and unsorted continuous colors in a seeded shuffle (seed=0,Nonekeeps stored order) and sort feature colors high on top; they settle layout without rendering points, and on-data labels move at most about one label height and stay nearest their own cluster.cytearc.agent, the bounded single-RNA agent workflow, is removed together with theagentextra and its pydantic-ai dependency. AI-assisted analyses call the public API, guided by the skills inskills/. CyteArc neither reads nor migrates the run directories and theagent_resultsgroups that earlier releases wrote, and writer destinations no longer countagent_resultsamong the groups that CyteArc writes.Removed public API:
cytearc.system_call,cytearc.get_log_level,cytearc.GffReader,cytearc.coordinate_melding,cytearc.utils.iter_column_blocks,cytearc.utils.rss_peak_tracker,cytearc.matrix.Block,ChunkedArray.blocks,map_blocks,dot,std,chunks, andnthreads,Assay.to_raw_sparse,Assay.mean_features,cytearc.assay.rna_assay_type_names,MetaData.mount_location,unmount_location,remove_trend, andinsert(location=),cytearc.cytebase.Repository.list_filesandopen_zarr,DataStore.set_default_assay,last_execution_report,calibrate_label_transfer_threshold,metric_lisi, andload_metric_lisi(usecytearc.metrics.compute_lisi),cytearc.clustering.balanced_cut,BalancedCut, andparis_dendrogram,cytearc.neighbors.wnn_integration,cytearc.embeddings.run_harmony(usefit_harmonyorDataStore.reduction.harmony),cytearc.metrics.compute_simpson,knn_to_csr_matrix, andreport_technical_nesting,cytearc.mapping.array_hash,array_store_hash, andconformal_prediction_sets,MappingReference.fetch_layout,cytearc.quality_control.write_doublet_target_zarr,cytearc.readers.get_file_handleandread_file,H5adReader.open_clone,LoomReaderandLoomToZarr(Loom import, including agent ingest; convert Loom files to H5AD first), import-resultartifactRefs,cytearc.writers.bed_to_sparse_array,create_cell_data,load_count_store, andload_zarr,cytearc.utils.load_zarr(usecytearc.load_zarr),storage.parallel.map_shards,cytearc.plotting.collect_legends,FeatureSummary, andregister_theme,recipes.run_plot_recipe,PlotOutput.step_nameandwritten_path,PlotRecipeResult.results, severalSeuratReadermembers, the parameter tuning handoff, Pareto, WNN, and refinement exports,AgentRunConfig.thinkingOffProfile, andAgentOrchestrator.initialize_request.Pipeline records keep at most 512 characters of an error or interruption message and end a longer one with
.... An interruption with a longer message now ends the run as interrupted instead of raisingValueError.Pipeline signal handling never waits for a lock, so a second signal cannot deadlock a run.
A pipeline stage setting means exactly what the same keyword means on the stage’s method, and an omitted setting takes that method’s default, except where a recipe fits it to its data: an ADT run’s
pcadimsdefaults to one fewer than its panel’s antibodies, at most the PCA default, an ATAC run’sprevalent_peakstop_nto at most one fewer than the assay’s peaks, and with Harmony an RNA run’sdoubletssample_columnto the Harmony batch columns. Non-finite settings raise before a run record is created.Pipeline t-SNE settings get the checks of
embeddings.tsnewhen the recipe is resolved, before a run record exists. A missingsgtsnepionly logs a warning there, because a stored embedding can be reused without it.Several processes may write one store at once: analysis calls and runs write only their own artifacts and run records, and the calls that rewrite shared state, such as table edits, assay changes and
artifacts.prune_incomplete(dry_run=False), need the store to themselves (Several processes on one store).Importers no longer delete their destination (
cytearc.storage.destinations). They andSubsetZarrraiseFileExistsErrorfor a destination that holds any key, andValueErrorfor a local destination inside a Zarr store or a destination whose root group is an assay group. Each importer gainsoverwrite: bool = False, which replaces only a CyteArc store that noDataStorehas opened, asSubsetZarr(overwrite_existing_file=True)now does; a prepared store and content that CyteArc did not write are never replaced. A subset source is prepared, sooverwrite_existing_file=Trueno longer deletes it through another path or store object.Local paths reach Zarr as
pathlib.Path, so names that hold#,?, or;open as written.SubsetZarrraisesValueErrorbefore it writes anything unless all its assays come from oneDataStore. It compared only their numbers of cells, so assays of two datastores of one size were accepted and the subset paired one dataset’s cell IDs with the other’s counts.SubsetZarr,DataStoreMerge,mount_datastore, andrepack_storerefuse a source store that holds a pending derived assay before they write anything.subset_assay_zarrnever replaces anything in its store: anout_grpthat overlapsin_grpraisesValueError, and an existingout_grpraisesFileExistsError.to_h5adwrites a temporary file in the target’s directory and moves it over the target once complete, so a failed export leaves an earlier file of the same name intact.Replacing a metadata column (
MetaData.insert(..., overwrite=True),update_key,reset_key) encodes the new values first and restores the previous column on any failure or interruption. Text that is not valid UTF-8 raisesValueError.MetaData.insertrecords missing values in the column’s missing mask instead of inventing them: itsfill_valuedefault changes fromnp.nantoNone. An explicitfill_valuemust fit the column’s dtype exactly, orValueErroris raised before the store changes.I,ids, andnamesnever hold missing values.Per-cell values reach a store only keyed by cell ID, in every store, a breaking change within 1.x: a store’s cells need not be in the order of values computed elsewhere, as a merge reorders them, and positional values landed on the wrong cells without an error.
MetaData.insertandupdate_keyon the cell table take a pandas Series whose index holds the cell IDs of every row or of the rows thatkeyselects, and raiseTypeErrorfor arrays, lists, tuples, pandas arrays, a barepd.Categorical, and a Series with aRangeIndex.DataStore.reduction.import_coordinatestakes only a DataFrame indexed by cell ID, andSubsetZarrreplacescell_idxwithcell_idsand keeps store order, whatever order the IDs come in. Each refusal names the call and shows the fix,pandas.Series(values, index=ds.cells.fetch_all("ids"))or its DataFrame form. The per-cell inputs of computations and plots follow the same rule and leave out values of other cells: theinitializationDataFrame ofembeddings.umap,tsneandlocalmap,trajectory.pseudotime(ss_vec=),trajectory.fate(direction=), thequery_batchesDataFrame ofmapping.run, thetarget_groupsofmapping.compute_scores,plots.mapping_scoreandplots.mapping_evidence, theknown_labelsofplots.mapping_confusionandplots.mapping_calibration,LabelTransferResult.label_vote_shares, whose record gains thecell_idsof its cells, and thepoint_sizesofplots.embedding. Feature tables keep positional values, because feature order does not change, andsubset_assay_zarrandwrite_renorm_subset_to_zarrkeep taking store rows.Every import writes its cells in a uniformly random order by default,
shuffle_cells=Truewithshuffle_seed=0, a breaking change within 1.x, so that any contiguous slice of a store is a random sample of its cells. Each cell keeps its row in the file in the protected int64 cell columnsourceRow, the cell table records the seed incellOrder, and exports write the cells in the file’s order by default,cell_order="source"(cell order).shuffle_cells=Falsewrites the store that CyteArc 1.4.0 writes, file for file apart from the artifact IDs and creation times that every import changes, givencategorical_columns=Falsefor an H5AD import. A file imported again with the shuffle gets a store in another order, so its dataset fingerprint differs from the store that an earlier release imported. Stores imported before keep their order, hold nosourceRowand export in stored order, which is their file’s order.MetaData.multi_siftraisesTypeErrorfor a stringcolumns,lows, orhighs(a stringcolumnswas split into characters), andValueErrorwhen the columns and bounds differ in number.CSVtoZarrrequires onecellDataDtypesentry for eachcellDataColscolumn and raisesValueErrorotherwise; unpaired columns used to be dropped silently.Assay types are strict presets:
RNA,ATAC,ADT,HTO,CRISPR,ANTIGEN,CUSTOM,GeneActivity,GeneScores,URNA, orAssay.DataStore(assay_types=...)raisesValueErrorfor an unknown key or value, and a read-only open whose explicit type differs from the recorded one raisesValueErrornaming the remedy (open once withzarr_mode='r+'). Each assay exposes its resolved type asAssay.assayType.DataStore.summary()reports each assay’s resolved type (Assay.assayType) instead of the rawassayTypesrecord.DataStore(min_features_per_cell=...)must be an integer of at least -1. A writable open keepsI, with a warning, when the filter would remove at least half of the active cells; the earlier guard compared the threshold with the median, so an ADT panel of ten features lost every cell. Derived assays no longer filterI. A writable open prepares assays and recordsassayTypesanddefaultAssay; only the first writable open of a store filtersI, and it records the threshold in the cell table. A read-only open writes nothing.mount_datastorechecks its forwardedDataStoreoptions before it creates the target, and deletes a target whose first open fails, so the mount can be retried.DataStoreMergekeeps per-cell assay membership: the merged<assay>_Iis False for the cells whose source lacks the assay.Membership survives export and import.
to_h5adandto_anndatawithoutrundeclare the exported assay’s<assay>_Iinuns["cytearc"]["assayMembership"], andH5adToZarrrestores it. Import writers skip, with a warning, other source columns named<assay>_I.Membership columns are protected:
MetaData.insert,update_key, andreset_keyrefuse<assay>_Iof any assay, anddroprefuses a column that records membership.add_grouped_assayandadd_melded_assaycopy the source assay’s membership to the new assay.Seurat imports with
assay_layersrecord a cell that only an unselected layer holds as unmeasured (False in<assay>_I).Analysis fails closed on cells that an assay did not measure (
<assay>_IFalse): every operation that reads an assay’s values raisesUnmeasuredCellsError, aValueErrorthat names the counts and the remedy, before it plans or writes. Build analyses over a selection fromselect_measured_cells.DataStore.select_measured_cells(assay, *, cell_selection=None)keeps the cells of a selection that an assay measured, and returns the selection itself when the assay measured every cell.Display reads show unmeasured cells as missing: their feature values are NaN, normalization is fitted over measured cells only, embedding plots draw them in
missing_color, and summary plots leave them out of every statistic and ofn_cells.Plots of feature values record
provenance.extras["unmeasured_cells"]when an assay did not measure some plotted cells, and an embedding color without any value records None inextras["color_limits"]and draws no colorbar unless its scale sets limits.Quality-control filters treat
<assay>_nCounts,<assay>_nFeatures, and the assay’s percentage columns as reads of that assay, soqc.auto_filter,qc.filter, and pipeline filtering refuse unmeasured cells withUnmeasuredCellsError. Earlier, their zero metrics set the MAD bounds.compare.compute_bulkchecks only the cells that it reads. A metadata grouping withoutcell_selectionreads the liveIcells without a snapshot, socompare.compute_bulkwrites nothing.An operation checks its arguments and assay type before membership, and both before the
PermissionErrorof a read-only store.Exports that cannot declare membership refuse unmeasured cells:
to_mtx, andto_anndatalayers of an assay other than the exported one.to_h5adandto_anndatawithout layers declare membership.cytearc.metadata.selection.CELL_VALUE_NAMESnames the canonical per-cell array of every cell-aligned artifact kind and replacesGROUPING_VALUE_NAMES. Readers no longer fall back to avaluesarray, and other kinds raiseValueError.select_cellsacceptspseudotimeartifacts.DataStore.artifacts.load_values(ref, *, value=None, cell_selection=None, cell_ids=True)returns acytearc.metadata.CellValues(values, cell ids, and missing mask) for any cell-aligned artifact. The read is checked against the memory budget before anything is read.cell_ids=Falseleaves the cell ids out of the read and of that check, soCellValues.cell_idsis None andto_pandasraisesValueError; the lineage tree plot reads its labels this way.select_cellsreads its values through the reader ofartifacts.load_values, so its refusals take that reader’s messages, and the read is checked against the memory budget.FeatureRefchecksvalueagainstby: an index must be an integer and a name or id must be text, elseTypeError.1.9,True, and"2"no longer select features.clip_fractionofget_cell_valsand of embedding plots must be at least 0 and less than 0.5, checked before any value is read.cytearc.rescale_arrayrequiresfracgreater than 0.5 and at most 1.DataStore.to_anndataraisesImportErrorwhenanndatais not installed, instead of logging an error and returning None.to_h5addoes not needanndata.to_anndata(run=run, matrix="normed")andto_h5ad(..., run=run, matrix="normed")export the run’s storednormalizedartifact over its feature selection, such as the highly variable features of an RNA run: the values that the run’s reduction read. Before, a run export normalized again over the whole feature universe and never matched the run.One streaming H5AD writer (
cytearc.writers.export) writes every export with h5py block by block and converts dense blocks to CSR in bounded steps, so no complete matrix is held. Live export files are unchanged.Run exports decide their categoricals themselves: repeated or missing text becomes a categorical with naturally ordered categories, so
to_anndata(run=...)and the H5AD file agree. Run-export files differ from those that AnnData wrote before:Xis compressed with int64 indexes, text isstring-array, and empty groups are not written.Artifact provenance gains an optional
revision, an integer of at least 2; revision 1 is recorded by omission, so no existing identity changes until an operation gains a revision (Operation revisions). A superseded artifact is not reused, and planning logsRecomputing <operation>: ....ArtifactStatusgainsrevision,current_revision,is_current, andsuperseded_by, and lineage reports mark superseded artifactsstale.Producers check the arrays that must hold only finite values as they write them (
cytearc.storage.finite_values): normalized data, reductions, batch corrections, embeddings, neighbor distances, and graph weights. A non-finite value raisesNonFiniteArtifactError, aValueErrorthat names the operation, the array, and the row, and nothing is published.Reuse never checks for non-finite values: an artifact is reused when its provenance matches. To recompute a normalized artifact that holds NaN, pass
invalidate_cache=True.Normalized data is held to the finite-value contract: a NaN from a custom normalizer, or the
log1pof a count below -1, raisesNonFiniteArtifactErrorfromfeatures.normalizeinstead of being stored. The publiccytearc.writers.chunked_to_zarrandwrite_renorm_subset_to_zarrdo not check.Saved normalization applies the configured normalizer: with
norm_dummyor a custom RNA normalizer,renormalize_subset=Trueno longer stores library-size values.log_transformmeanslog1pof the configured normalizer’s output, in float64, on every path. A normalizer applies only the flags that it supports (applicable_normalization_flags), and defaults turn flags on only for the RNA library-size normalizers (default_normalization_flags).log_transform=Truewith CLR,norm_lib_size_log, or an ATAC normalizer, andrenormalize_subset=Truewith CLR,norm_dummy, or an ADT or generic assay, raiseValueError. To plot the logged stored values of any assay, its counts or the values of an assay imported from normalized values, useNormalizationSpec(source="raw", transform="log1p").Every library-size path divides by one definition,
cytearc.assay.normalization.library_size_divisors: a zero total becomes 1, and a negative or non-finite total raisesValueErrornaming its source before any result is saved. Results for valid totals are unchanged.scores.aucelland query projections accept bool count stores, and query projections reject complex counts withTypeError.ChunkedArray.meanaccumulates in float64 on every axis, and variances merge per-block moments, so a constant feature’s variance is exactly zero.Connectivity weights follow umap-learn: each cell’s kernel is fitted with the cell itself at distance zero, so rows sum to
bandwidth * log2(k + 1).UMAP identities record only machine-independent settings.
nthreadscontrols execution, andsymmetric_graphandgraph_upper_onlyaccept only booleans.ANN thread counts control execution;
ann_parallelidentifies a parallel index. A serial index is still built on one thread, whilegraph.neighborsqueries any index on the datastore’snthreads, which never changes the neighbors.embeddings/umap.pydrives the layout’s epochs with a loop adapted from umap-learn’soptimize_layout_euclidean. A serial layout runs umap-learn’s epoch function compiled with the same options and Numba’snogil, cached like umap-learn’s kernels, so other Python threads run during an epoch and the layout is umap-learn’s to the bit.qc.doubletssimulates its samples one at a time and scores as many at once as the workers and the memory budget hold, each charged its points, index, and the larger of its index’s build and a query block of at most 4,096 points. A simulation plans its steps as it would alone and waits for each to fit beside the samples being scored, and each index is built on one thread: a sample of_INDEX_SPLIT_POINTSpoints or more is indexed in_INDEX_PARTSparts, pointiin parti mod _INDEX_PARTS, so each part holds cells and simulated doublets of every stretch of the sample, built at once on the sample’s threads from contiguous copies of their rows, which the build is charged, searched to the depth that they share and merged by each candidate’s uint64 key of distance and position, so the artifacts do not depend onnthreads, andDoubletIndexSettingstakes noparallel.graph.ann_indexdefaults toann_m=24,ann_efc=200, andann_ef=200(before, 48, 50, and 50). Anef_constructionbelow2 * Mbuilt indices whose searches missed every true neighbor of some cells between well-separated clusters, 4.5% of 200,000 clustered cells (recall 0.916). On about 1,000,000 cells (Tabula Sapiens and a lupus PBMC atlas at 21 and 50 PCs, and a clustered mixture), the earlier defaults gave recall@11 of 0.896 to 0.991, with up to 0.92% of cells without a true neighbor. The new defaults keep recall@11 and recall@30 at or above 0.995 and such cells below 0.05% on four of the five sets, and reach recall@30 of 0.988 on 50-PC PBMCs, whose remaining misses lie within 1% of the exact k-th distance. The search depth of 200 is the larger gain on homogeneous cells;ann_m24 matched 32 there and builds faster in less memory. The serial build takes about three times as long as with the earlier defaults. Defaults record their own values, so default graphs, and the pipeline’s, get new identities, and explicit settings keep theirs. The index’sann_ef(default 200) is the smallest default search depth of its queries; it never changes the index.graph.neighborstakesann_ef, by defaultmax(index ann_ef, 2 * k), never fewer thank + 1. Its identity records the depth it used as the parameterann_efonly when that differs frommax(index ann_ef, k + 1), the depth of the index’s ownann_efas hnswlib applies it, which every earlier query searched. This is the one canonical rule: a neighbors artifact withoutann_efsearched its index’s depth. An earlier neighbors artifact whose depth is unchanged, such as a default query ofkup to 25 on an index ofann_ef50, or up to 100 on one of 200, therefore keeps its identity; it is reused, on a read-only store too, when it holds the query’s diagnostics. An explicitann_efequal to that depth names the same artifact. A query whose depth grew, such askof 30 at depth 60, records the depth and is computed again from the same index. Mapping projections still query with the index’sann_ef. A query saves the percentage of cells that it found among their own neighbors as itsselfHitRatediagnostic, and a rate below 99.5% warns each time the query is computed or reused.embeddings.umapforms the fuzzy union of the graph itself, sosymmetric_graph=True, which united an already symmetrized graph a second time (each weightwbecame2w - w**2), andgraph_upper_only=True, which left the union unchanged, raiseValueError. UMAP embeddings saved withsymmetric_graph=Truestay loadable but can no longer be requested; recompute them without the flag.clusters.leiden,embeddings.tsne, and the pipeline’sleidenandtsnesettings refusegraph_upper_only=Truewithoutsymmetric_graph=True, which loaded the graph unchanged under a second identity. No accepted request computes anything new, so neither change needs an operation revision.graph.ann_indexandembeddings.initializationacceptrand_state=0.embeddings.umapandembeddings.tsnecheck that an initialization reference is an assay-scopedembedding_initializationbefore they read the graph, and nameembeddings.initialization; they read the initialization before the graph.SNN integration refuses connectivity maps of different
kbefore it plans or loads any of them, naming the remedy; before, it failed after loading them.densMAP over equal local radii adds no density term and returns the UMAP layout of the same seed instead of NaN coordinates; a non-finite radius raises
ValueError.t-SNE has one backend, the optional
sgtsnepipackage, andembeddings.tsnenever runs ansgtsneexecutable.temp_file_loc,parallel, andnthreadsare removed, so t-SNE identities change and earlier embeddings are recomputed.export_knn_to_mtxis removed.embeddings.tsnevalidates its numeric settings before it reads the graph and recordslambda_scaleandbox_has floats.embeddings.tsneraisesImportErrornaming thetsneextra whensgtsnepiis missing (wheels exist for Linux x86_64 and for macOS 26 or newer on arm64). Reusing an existing embedding needs no backend.pca={"dims": 0}builds an RNA run’s graph on the normalized artifact instead of an identity reduction, so the run has nopcaoutput and no reduction artifact. It needsdoublets=False, noharmony, and no other PCA settings; otherwise the recipe raisesValueErrorbefore the run starts.Harmony: a cluster whose cells cancel keeps a zero centroid instead of NaN,
fit_harmonyraisesValueErrorfor non-finite results, andbatch_levelsfollows design order.clusters.membership_strengthstores the fraction of a cell’s graph neighbors that carry the cell’s own label.Marker
fold_changeismean / mean_rest:+inffor a feature that no other cell expresses, and NaN when both means are 0 or either is negative.load_marker_tablerefuses tables withoutfold_change_policy.features.hvgsand the RNA recipe’shvgsettings check every option before anything is written:min_cellsan integer of at least 0,top_nandn_binsintegers of at least 1,lowess_fracfrom 0 to 1,keep_boundsa boolean, andbin_strategy"adaptive"or"fixed". Floats such asmin_cells=20.0now raise.features.hvgstakesflavor("cytearc", the earlier method and default;"seurat_v3";"pearson_residuals") andbatch, a cell column that it snapshots or a label artifact, and combines batches by the number of batches in which a gene is highly variable, then its median rank. Selections of the cytearc flavor over all selected cells keep their provenance; the other flavors and batch-aware selections recordcell_selection,dataset_fingerprint,feature_snapshot, andbatchinputs, recordflavorand its options only for the new flavors, and storemean_nonzero,detected, and with batchesbatch_countandmedian_batch_rank.min_mean,max_mean,min_var, andmax_varfilter candidates beforetop_n; before, a finitemin_varignoredtop_nandmax_varapplied after the cut.min_cellsdefaults to None: the cube root of the number of selected cells rounded up and at least 20, or for a selection of fewer than 381 cells 5% of them rounded up and at least 5, andmax_cellsNone excludes genes detected in more than 99.5% of them, recorded as the resolved integers. Before, the defaultmin_cellswas 1% of the selected cells from 3 to 20, and earlier still the bounds were 20 andn_selected - 20. Defaults record their resolved values, so a default selection of fewer than 1,901 or more than 8,000 cells records a newmin_cellsand is computed again. The gene-family blacklist spares CCN1 to CCN6 (^CCN[A-Z]) and matches the current histone symbols.select_hvgsrevision 2 covers selections with a finite variance bound, withmin_cells20 (every selection with the earlier default bounds), or with the earlier default blacklist. Revision 3 covers every selection: selections save theselectedDetectionRatiodiagnostic, which a selection of an earlier revision reads as None (Diagnostics added after a release), so the next call computes a saved selection again, with the same genes for the parameters it records. Batch-aware selections of the cytearc flavor score each batch’s values under the assay’s normalizer and size factor and record them asnormalization_methodandsize_factor, as cytearc selections that leave out unmeasured genes do; revision 4 covers the batch-aware cytearc selections that record no normalizer, so a call under any normalizer computes them again and lineage shows them stale.norm_pearson_residualsis an RNA normalizer that takes onlyrenormalize_subset.features.prevalent_peakskeeps the peaks whose prevalence ties at thetop_ncutoff in feature order, and selections keep their identities (Results that change while identities stay the same).compare.compute_bulk(aggr_type="mean")on RNA divides each cell by its library-size divisor, asnormeddoes, which is 1 for a cell without counts. Before, such a cell made its group NaN, which was returned as zeros.compare.compute_bulkno longer replaces NaN with 0 and raisesValueErrorfor a non-finite mean or sum. Recompute saved bulk tables of groups that hold cells without counts.A stored statistical-test result is reused only when it records every attribute that the request determines,
sample_by,pair_by, andsummary_scopeincluded.Doublet simulation meets its heterotypic fraction (
simulate_doublet_pairslosesmax_tries), andqc.doubletsraisesValueErrorwhen every selected cell has one cluster label andheterotypic_fractionis above 0.qc.doubletsfollows Scrublet (revision 2 ofrun_doublet_detection, for every artifact). Each sample of the newsample_columnsimulates doublets from its own cells, every cell by default (cluster_sample_fraction=1.0,max_cells_per_cluster=None), and scores its cells and doublets on an hnswlib index of the sample’s PCA rows and doublets only, with the graph’s ANN settings. The former pool of 5% of each cluster, at most 100 cells, reused every parent dozens of times and made rare clusters parent as many doublets as common ones. The artifact keeps the doublet probability invaluesand addsraw_scores,predicted_doublets,simulated_scores,simulated_parents, and asamplesattribute with each sample’s threshold, its method, calls, and estimated doublet rate;CELL_VALUE_NAMESlistsraw_scoresand the label arraypredicted_doublets, whichselect_cells(value=...)reads. Provenance recordssample_columns,expected_doublet_rate, andthresholdparameters and thesample_assignments_fingerprintinput;save_kis recorded as the neighbors used, at most the largest sample’s cells minus 1, so larger requests share one artifact. Defaults change:simulation_ratio=2.0,heterotypic_fraction=0.0,save_k=30,smoothing_t=0(0 is now allowed and keeps each cell’s score), andnormalize_scores=False; smoothing and scaling changevaluesonly. Doublets whose parents have ten or fewer features are scored like the others, and a doublet’s library size for unrenormalized references is the sum of its parents’<assay>_nCounts. A Harmony-corrected graph is accepted withsample_column, and its samples are scored on the PCA it corrected. The RNA recipe scores a Harmony run within its batches on the corrected graph, without the formerdoublet_graphstage and itsuncorrected_*artifacts, freezes the sample labels as the input stage’sdoublet_sample_snapshot, recordsdoubletSampleColumnsin its configuration, and adds the frozen cell fieldpredicted_doublet.select_cellsgainsvalue, recorded only when it names another array than the canonical one, so existing selections keep their identities.lisi_batch_mixing_scoreignores declared categories that no cell has, so labels from one observed batch raiseValueErrorinstead of returning NaN or 1.0.mapping_calibrationcounts every cell with a known label in its coverage, cells without evidence included. Provenance recordsn_without_evidence.Harmony, WNN, and SNN check their memory need against the datastore budget before they read coordinates or graphs, and raise
MemoryErrornaming the bytes needed.graph.ann_indexandgraph.neighborscheck the hnswlib index against the memory budget before they build or load it. An index without a recordedann_mraisesValueErrorasking to re-rungraph.ann_index.Leiden clustering, UMAP, t-SNE, and
graph.connectivitycheck the graph or neighbor matrices they load, and what they compute beside them, against the memory budget before they read them, and raiseMemoryErrornaming the bytes, the cells, the edges, and the limit. The estimates live in the domain packages (neighbors.graph.graph_load_memoryandconnectivity_peak_bytes,embeddings.umap.umap_peak_bytes,clustering.leiden.native_leiden_peak_bytes,embeddings.sgtsne.sgtsne_input_bytes); the native Leiden estimate leaves out the per-worker scratch that a hub raises, and the t-SNE one the working memory ofsgtsnepi.The trajectory loaders of a pseudotime and of a fate map’s direction score, and the calls that score a pseudotime or a fate map, check their graph’s load against the memory budget before they read it, beside what their caller holds and the numbering of the graph’s components (
trajectory.pseudotime.component_numbering_bytes) or the scoring (trajectory.pseudotime.pseudotime_working_bytes), so every trajectory call that reads a graph refuses before it reads it;imputation.diffusion, potency smoothing (trajectory.potency.smoothing_bytes) andgraph.loaddo too. They read source and sink labels, vectors, IDs and direction scores first through charged reads, and keep the listed labels as codes (trajectory.artifacts.listed_labels).trajectory.membership.membership_bytesstates whatlineage_membershipholds with its inputs, andmembership_load_byteswhat loading a saved membership holds; the calls size them from their records and pass them to the graph’s check as its least, so one refusal names a budget that runs them, asfatepassestrajectory.fate.fate_mapping_bytes, what mapping its fates holds in the larger of its steps, taking the mapped cells’ graph and the solve. The curves’ loader keeps the fate map’s inputs that it validated, solineage_membership,load_lineage_membershipandbranch_cellsload the graph once. The loaders of saved feature analyses,load_markers,load_aggregation,load_lineage_markers,load_driversandload_lineage_aggregation, size what checking and reading their saved table of every feature holds from its stored arrays (trajectory.artifacts.marker_load_bytes,aggregation_load_bytes,lineage_statistics_load_bytes,lineage_aggregation_load_bytes) and pass it to their graph’s check as its least, which names the saved table where it needs more, asplots.pseudotime_heatmapandplots.lineage_heatmapadd what drawing holds (plotting.heatmaps.pseudotime_heatmap_bytes,plotting.lineages.lineage_heatmap_bytes); the calls that compute them charge the check of a complete saved result (marker_check_bytesand the others) before they read it to reuse it.A Matrix Market import charges each parse of its file where the parse runs, at what
readers._matrix_market.matrix_market_parse_bytescounts: pandas’ reader buffers, the floats that pandas before 3.0 keeps for each chunk, and each line of a chunk, never more lines than the file declares. The producer of a file sorted by cell holds its parse beside its batches. A feature-major file, and an unordered file whose sorted rows a release removed, are parsed into rows before the counts write, so their producer copies batches out of those rows and is charged no parse;CrToZarradmits that sorting on its own (MtxReader._sparse_import_preparation_bytes) before it creates the destination and again before it prepares the rows, and a shuffled import before it reads the cells. The construction of a reader still sorts an unordered file’s rows unchecked, before any budget exists.run_cluster_selectionreads its sampled coordinates under the memory budget and raisesMemoryErrorbefore reading when they do not fit.Dotplot size legends draw
SizeScale.areasexactly, without the 180 pt² cap, and composite size legends show the child’s 25% to 100% entries.cluster_treekeeps constant fill values (a fill of 5 has limits 5 to 6) and draws a single text, categorical, or boolean value as one category instead of a colorbar.Dot plot and matrix plot tables name their grouping columns by role (
group,subgroup,sample), sogroup_bykeys named like summary columns work. Withstandardize="feature",meankeeps the raw means and a newzscorecolumn holds the plotted values. Thetables["matrix"]ofmatrixplotandmarker_heatmapis indexed byfeature, with one column pergroup.With
run=,DataStore.plots.embeddingcolors by frozen cell fields, run outputs asArtifactRef, or genes with an explicitnormalization=, andfacet_by,subset_by,Highlight, andDensityOverlaytake frozen fields. Run plots record the run inprovenance.extras["run"].matrixplotandmarker_heatmapvalidatecluster_methodandcluster_metricbefore they read any data;centroid,median, andwardrequirecluster_metric='euclidean'and raiseValueErrorotherwise.CyteArc’s warnings point at the caller’s own line (
cytearc.utils.warnings.warn), so a warning filter that matches a CyteArcmoduleno longer matches them; filter by message or category instead.CyteArc imports on Windows: no module imports a POSIX-only module when it loads.
cytearc.utils.process_rss_mbreturns None where/procis absent, and pipeline stages there record no RSS samples.The wheel is pure Python: the
sgtsneexecutable,bin/, andsetup.pyare gone, andsgtsnepiis the optionaltsneextra. The Docker image installs only theextraextra; build it with--extra tsnefor t-SNE.A GitHub release uploads to PyPI only after the test and documentation workflows, the build, and a wheel smoke check pass on the tagged commit.
Ensembl GFF3 file names whose assembly contains dots are recognized, so fly and rat references download again.
A Seurat matrix specification that holds a mapping where a vector belongs raises
MatrixSourceErrornaming the slot, instead ofKeyError.Profiling fixtures name ribosomal features, so their files and checksums change; prepare fixtures under a new
datasetPrefixUri.A forced profiling
createStorejob deletes its store prefix before it downloads; an unforced one refuses any non-empty destination. The stage imports in the file’s order and does not measure the shuffle that imports apply by default, asprofiling/AGENTS.mddescribes.Harmony is CyteArc’s implementation of Harmony2: k-means++ seeding, a stabilized diversity penalty, a dynamic ridge penalty of
ridge_alphatimes each batch level’s expected mass in a cluster, and batch pruning.harmony_paramsand thefit_harmonykeywords renamenclustton_clusters,max_iter_kmeanstomax_iter_cluster, andlambtoridge_penalty, removecluster_fn, and addridge_alphaandprune_threshold. The datastore callsvalidate_harmony_parametersbefore it reads data, and the pipeline when it resolves its recipe, before it creates a run record; it raisesValueErrorfor an earlier key, naming its replacement or why it was removed, andfit_harmonyraisesTypeErrorfor it.max_iter_harmonymust be at least 1 andridge_penaltypositive.HarmonyResult.ridgeis replaced byridge_penaltyandactive_levels, both clusters by batch levels.harmony_peak_bytestakesn_cells,dims,n_clusters,column_levels, and the keywordsn_combinationsandblock_size, withoutnthreads; the second parameter ofharmony_cluster_countisn_clusters. These two andvalidate_harmony_parametersare public incytearc.embeddings.harmony. TheHarmonyclass (incytearc.embeddingsandcytearc.embeddings.harmony),moe_correct_ridge,safe_entropy, andClusterFnare removed.batch_correctionartifacts replace theridgearray withridge_penalty(float64) andactive_levels(bool), both clusters by batch levels, and add thefit_parametersattribute. Reuse requires both arrays, so a correction saved by the earlier implementation is never reused but stays loadable, and the next request recomputes the correction and everything built on it. The arrays and attributes that Symphony mapping references copy are unchanged, so references built from either implementation load and map without a compatibility branch.qc.hto_demultiplexingandcytearc.quality_control.hto_demuxtake a keyword-onlypositive_quantile, Seurat’spositive.quantile, with the default 0.99: a real number, not a boolean, strictly between 0 and 1. Each HTO’s negative-binomial cutoff is that quantile of its background fit.hto_identityartifacts already recorded the fixed 0.99 asmethod.cutoff.quantile, and the quantile is recorded there, so artifacts of the default keep their identities and are reused without a compatibility branch, while each other quantile has its own artifact.qc.hto_demultiplexingchecks the quantile before it reads the selection.HTO demultiplexing assigns a singlet the one tag that its negative-binomial cutoff calls positive, not the tag with the highest CLR value, which in unbalanced pools could be a tag called negative.
hto_identityartifacts gain the diagnostic arraysmax_id,second_id(labels), andmargin(float64), whichartifacts.load_valuesreads withvalue=. This is revision 2 ofrun_hto_demultiplexingfor every artifact; the method record keeps its fields,singlet_assignmentincluded, so revision 1 artifacts are superseded matches that are logged and recomputed. The HTOs whose positive calls overlap their background, where fewer than half of the positive cells exceed the count that the background fit exceeds with probability(1 - positive_quantile) ** 3, are saved as theoverlappingHtosdiagnostic, each counted in every sample where it overlaps, with up to five named with their sample inoverlappingHtoExamples, and a warning names them each time the identities are computed or reused.A background cluster of only zero counts, or a fit whose cutoff is 0, calls every nonzero count of its HTO positive. That cutoff stands only for counts without ambient tags: no background cluster holds counts of its HTO in most of its cells, and at most half of the cells hold counts of more than one HTO, as doublets do. Otherwise every HTO with a cutoff of 0 is refused in one
ValueErrorthat names them, the evidence of ambient tags and the remedy, since such an HTO is unused in the cells of its background, as when pools of cells use different hashtags. This is revision 3 ofrun_hto_demultiplexing, for every artifact.qc.hto_demultiplexingtakessample_column, the cell column of each cell’s sample, read throughdatastore._operations.cell_samplesand charged to the operation’s ledger; each sample is demultiplexed on its own, as a call on its cells would be, and the artifact records the column as a parameter and the fingerprint of the cells’ samples as the inputsample_assignments_fingerprint, both only when given. Errors from a sample’s demultiplexing name the sample. It also takeshashtags, the hashtag IDs to demultiplex, as one list or, besidesample_column, as a mapping from each sample’s label to its own, which must name every sample of the selected cells and no other, checked against the assay’s IDs after the selection is read and before the counts are. The artifact records them in the assay’s order, and only when given, so calls without them keep their identities. Hashtags without a count in the selected cells are left out, with an INFO log, instead of refused, and a selection in which no chosen hashtag has a count is refused. Thesamplesattribute of anhto_identityartifact lists, for each sample, itslabel(None withoutsample_column), its cells, the hashtags demultiplexed, each one’s integer cutoff, and those left out aswithoutCounts; reuse requires the attribute, with a label in every entry, and the write checks it. Thernarecipe’shashingstage takeshashtagsandsample_columnand checks them before the run.qc.auto_filtertakesmetric_policies, the MAD policy of named metrics:transform(log1poridentity) andbound_direction(two_sided,upper, or the newlower). Default policies follow what CyteArc wrote:<assay>_nCountsand<assay>_nFeaturesare counts, an assay’spercentFeaturescolumns andquality_metricartifacts ofrun_feature_percentageare percentages. Other metrics keep the name rule of earlier releases, with a warning. Default calls record the policies and bounds they recorded before, so their results and identities are unchanged; a percentage artifact whose name the rule did not recognize, such aspercentHb, now records an upper bound only, a different identity. Only a percentage keeps its upper bound within 0 to 100, so an explicit raw upper bound of another metric is not cut to 100. Automatic filtering warns when its bounds remove more than half of the selected cells, and the MAD bounds of a log1p metric warn when they miss a second population, as empty droplets of a raw droplet matrix cause; provenance records neither warning.A writable open that skips its
min_features_per_cellfilter because at least half of the active cells would go issues aUserWarningthat names a small antibody panel and a raw droplet matrix as causes, instead of only logging it.qc.filterchecks bound types against the column before it reads metadata: a numeric or boolean column takes numbers, a text column text, and other columns no bounds. A mismatch raisesTypeErrornaming the column instead of a NumPy comparison error. Bounds stay exclusive unlesskeep_bounds=True, unlike scanpy’sfilter_cells.Cell-cycle scoring and
Assay.score_featurescount a repeated target feature once, at its first position. The recordeds_gene_indicesandg2m_gene_indiceskeep the repeats, and revision 2 ofrun_cell_cycle_scoringapplies only to scores that record a repeated index, so other scores keep their identities and results. A default gene that its symbol misses matches its previous HGNC symbol, fromcytearc.quality_control.cell_cycle_previous_symbols, and the artifact records such matches as thegene_aliasesparameter, which is omitted when empty. Matched aliases change the recorded indices, so they change identities without a revision. S and G2M scores read their genes and controls in one pass, fromcountsTwhen its bands touch fewer chunk bytes, with bit-identical results.qc.feature_percentagereads only the selected features and divides by the prepared<assay>_nCountsinstead of summing every count of each cell (see Results that change while identities stay the same).H5AD categoricals keep their categories:
H5adToZarrstoreslevels,ordered, and, for cell columns, a categoricaldisplaywith the colors ofuns["<column>_colors"]on each imported categorical column of at most 10,000 categories and on imported cluster labels. Exports write such a column as that categorical, with its colors inuns. Earlier imports stored plain values and are not migrated; they export as before.A dataframe index that is neither the ID nor the name column no longer imports as a column named
_index: it is left out when it repeats the IDs or names, and imports assource_indexotherwise. Exports rename a store’s_indexcolumn tosource_indexand a column whose name the export already uses to<name>_2, with a warning, instead of raising; stores are not changed.inspect_h5adranks count matrices by conventional name (raw/X,layers/counts,layers/raw_counts, thenX,layers/spliced, others, andunsplicedandambiguouslast), then by estimated total, samples up to 32 windows of 1,024 values across a matrix to decide whether it holds counts, which must be finite, non-negative, and whole, and warns when several matrices hold counts. It never takes a floating-point column as cell IDs, and when the obs index repeats IDs it says so and namesduplicate_cell_ids="make_unique", a new keyword ofH5adReader. A missing feature name takes the feature ID.embedding_rolesaccepts"coordinates", which imports anobsmarray asimported_coordinates, andDataStore.reduction.import_coordinatesimports a DataFrame aligned by cell ID, recording an optionalsourcerecord in its parameters.write_imported_coordinatesrecordssourceonly when given, so Seurat and earlier imported coordinates keep their identities.to_anndataandto_h5adtakecell_selection,obsm,obs,graph, anddtype. Run exports write label fields with a categorical display (clusters,leiden_*,paris,cell_cycle_phase) as categoricals of string labels in natural order, with the display colors, where they wrote numbers before, and add the run’s PCA asobsm["X_pca"]withvarm["PCs"](an ATAC run’s LSI asobsm["X_lsi"]). Rawuint8anduint16counts export asfloat32unlessdtypenames another dtype.to_mtxwrites a feature-type column without compression too, one type per assay, formats integer counts with NumPy, and compresses its three files with gzip level 6; the matrix text is unchanged.CSVReaderreads its ID column as the text that the file holds,NAincluded, and rejects an empty or blank ID, and a count column whose name is missing or blank or reads as the same text as another’s, such as10and"10". It rejects bytes that the file’s encoding, UTF-8 unlesspandas_kwargsnames one, cannot decode, with aValueErrorthat names the first line that holds them, anencoding_errorsofsurrogateescapeorsurrogatepass, which can keep such bytes as text that UTF-8 cannot encode, column names innamesof bytes that are not UTF-8, andpandas_kwargsthat set what the reader sets from its own arguments, such assep,header,skiprows,chunksizeandindex_col, or a converter for the ID column.SparseToZarrrejects missing or repeated cell and feature IDs and converts COO, CSC, and dense input to CSR.run_marker_searchis at operation revision 2, so marker tables of earlier releases are recomputed rather than reused. Tables store their statistics at full float64 precision instead of rounding them to five decimals, which kept one or two significant digits of ATAC TF-IDF means.MARKER_STAT_COLUMNSends withneg_log10_p_value,-log10of the p-value, taken in log space for the normal approximation so that it neither underflows nor ties wherep_valuereaches 0. A group that can be split from the other cells in at most 100,000 ways gets exact p-values from the permutation null of its rank sum, ties included, by the counting kernel that the exact Mann-Whitney test ofcompare.testshares; slots record that policy asp_value_policy. A group of fewer than two cells, or with fewer than two other cells, is skipped with a warning naming it instead of failing the search; the slot records each skipped group’s cell count inskipped_groups, its cells stay in the rest of every tested group, andmarkers.loadgives it no rows.RankMarkerResultgainsexact_p_values,tested_group_ids, andskipped_group_ids.Marker tables of revision 1 stay loadable under an explicit read policy. A slot without
p_value_policymust store exactlyMARKER_REVISION_1_STAT_COLUMNS, the columns beforeneg_log10_p_value, and record noskipped_groups.load_marker_table,markers.load,markers.export_csv, andmarker_heatmapread it with the five-decimal statistics and the asymptotic p-values it stored;MarkerSlot.p_value_policyreportsMARKER_REVISION_1_P_VALUE_POLICY,"asymptotic_tie_and_continuity_corrected", whichmarkers.loadlogs, andneg_log10_p_valueis derived as-log10(p_value),+infwhere the p-value underflowed to 0, before the filters andsort_byapply. The reuse validator rejects that layout, somarkers.searchrecomputes such a table at revision 2 on a writable store and never reuses it, even under current provenance. Any other slot withoutp_value_policy, and any table withoutfold_change_policy, raisesValueError.A marker table names the child group of each tested group by the group’s label, as earlier releases did, while every label can name one (
can_name_marker_group). A table with a label that cannot, one that is empty or contains/,\or a NUL character,.,.., a Zarr metadata document (zarr.json,.zattrs,.zgroup,.zarray,.zmetadata) or the name of one of the slot’s arrays, stores its groups by code beside the labels in itsgroup_labelsattribute and records skipped groups by code inskipped_group_codes(marker tables).MarkerSlot.groupsmaps the label of each tested group to its child group in either layout, andmarkers.load,markers.export_csv,marker_heatmap, the reuse check ofmarkers.searchand the run summary read labels through it. The layout adds no operation revision: a table whose labels can all name child groups is written byte for byte as before and is reused as before, and earlier releases refused the other labels before they searched, so no stored table changes its meaning or stops being reused. Other labels that start with a dot, such as.x, keep the label layout, so an earlier release reads their tables. Earlier releases stored the Zarr v2 documents.zattrs,.zgroup,.zarrayand.zmetadataby label in a Zarr v3 store; this release stores them by code, and still reads and reuses those tables.markers.loadandmarkers.export_csvfilter by default onfrac_exp >= 0.2,auc >= 0.6, andp_value_adjusted <= 0.05;min_scoredefaults toNonebecause the score falls with the number of groups and is capped by a group’s size, andNonedisables any filter. They read the slot’s metadata and feature index once for all groups, andsort_byorders rows by"score","auc","fold_change", or"p_value"with deterministic ties, ascytearc.features.sort_marker_results(table, sort_by)does.compare.compute_bulkleaves out bulk columns without cells, which it returned as zeros, keeps them as NaN withremove_empty_columns=False, and reports the cells of each column in thecolumnstable of its record. It raises for apseudo_repsbelow 1, which it treated as 1, and for an unknownfeature_label, which fell back to positions.compare.testvalidates and encodes its design once per call, throughprepare_group_comparison, instead of once per key;compare_group_distributionsgives each array the same result, bit for bit. A design withoutsample_bywarns that it treats each cell as an independent observation:compare.testgives the warning before it reuses or computes its result, so a reused result warns as a computed one does, and prepares its design with_warn_cell_level=False, while both functions warn their direct callers.read_gmtdrops a UTF-8 byte order mark.create_bed_from_coord_idsparses ids withparse_coordinate_ids, so chromosome names may contain:and other id forms raiseValueErrornaming the id.binary_searchraisesValueErrorfor ranges that are not sorted by start, for which it returned wrong overlaps.qc.call_cellscalls cells in an unfiltered droplet matrix with EmptyDrops (Lun et al. 2019, Genome Biology 20:63), implemented from the paper and its supplementary materials. It writes an assay-scopedcell_callingartifact with operationrun_cell_calling(parameterslower,retain,n_iter,alpha, andrandom_seed, recorded as requested, so None stands for the knee and the estimated precision; inputscell_selectionanddataset_fingerprint), whose arrays holdtotal,log_probability,p_value,fdr, andlimitedfor each barcode (NaN and False at or belowlower) and the feature-lengthambientprofile, and whose attributes hold the resolvedretain,knee,inflection,alpha(None for the multinomial), andn_ambient. Reuse requires these attributes and the ambient profile.cell_callingis a cell-aligned kind whose canonical array isfdr. The called cells are acell_selectionwith operationcall_cells, parameterfdr, and inputscell_callingandprior_cell_selection; its default barcodes are aselect_all_cellsselection of every row, narrowed byselect_measured_cells. Random draws are counter-based SplitMix64 streams keyed by the seed and the iteration, so p-values do not depend on the thread count.write_cell_data_artifactgainsattributes, stored before publication. The warning of a writable open that keepsIbecausemin_features_per_cellwould remove at least half of the active cells now points toqc.call_cellsfor unfiltered droplet matrices.Calls that take features tell apart features that share a name by their IDs.
imputation.compute_imputedtakesFeatureRefvalues beside names and resolves features throughresolve_feature_batch, as plots andcompare.testdo: a name that several features share raisesValueErrornaming their IDs, where it imputed their mean, whichFeatureRef(value=name, reduction="mean")now asks for, and a feature that the assay does not hold raisesKeyErrorinstead ofValueError. The refusal ofresolve_feature_batchnames the features’ IDs.markers.loadaddsfeature_id, the ID that the marker table froze, afterfeature_name.plotting.lineage_trendstakesFeatureRefvalues infeatures, andlineage_heatmapandpseudotime_heatmaptake them inshow_features. These plots find features among the aggregation’s retained features throughresolve_feature_rowsoffeatures/values.py, and a name that several retained features share raisesValueErrornaming their IDs, wherelineage_trendsdrew the first of them and the heatmaps labeled the last.compare.compute_bulkreturns aBulkProfilesrecord offeatures/aggregation.pyinstead of a frame or a tuple of frames, in one step and without an adapter:profiles, the frame it returned;columns, each bulk column’sn_cellsas int64; and, withcount_detected=True, which replacesreturn_fraction=True,detected, the int64 number of each column’s cells whose raw count of each feature is above zero, from whichdetected_fractionderives the share that it returned as floats.return_n_cellsis removed. A bulk column is labeled by its group label, or by a MultiIndex of the levelsgroup,subgroupandreplicatethat the call uses, where its name joined the labels with_and_Rep1, so labels that joined into one name, which it refused, give distinct columns, and numeric labels stay numbers where1.0became the text"1.0".regulons.profilesindexes its rows by the same group labels.artifacts.load_valuestakes aCellFieldbeside an artifact and reads the column over acell_selection, which it then requires, with its linked missing mask, throughresolve_cell_columnofmetadata/selection.py, the read of a metadata grouping inresolve_groupingtoo; the read is charged against the memory budget as an artifact’s values are.DataStore.trajectory.curves_in_layout(curves, layout, *, lineages=None, df=None)returns lineage curves drawn in a two-dimensional layout as a table oflineage, the sink label,point,xandy, whichplots.lineage_curvesdraws under the text of the labels, and saves nothing.cytearc.trajectory.build_cluster_tree(coordinates, labels, *, root=None, ends=None)returns the tree thattrajectory.lineage_treesaves, as acytearc.trajectory.ClusterTreeof the fields ofLineageTreeResultwithout its artifacts. Both join the trajectory facade’s 1.x exports, while the building blocks oftrajectory/lineage_tree.py, among them the index-basedSpanningTreethat was namedClusterTree, stay internal. On a store opened read-only,lineage_treerefuses to save a tree with aPermissionErrorthat says why and namesbuild_cluster_tree.DataStore.trajectory.lineage_membership(curves, *, band=0.5, distance_score=5.0, n_bins=10)writes alineage_membershipartifact, scoped as its curves, with operationcall_lineage_membershipfromLineageMembershipArguments, whose identity holds the curves, their cell selection and the rule’sband,distance_scoreandn_bins. It is cell-aligned: its canonicalvaluesname the lineage each cell follows,"shared"or"none", besidemembers, cells by lineages, andvalid; it also storesdistance_limits, lineages by bins, and for every pair of lineages in orderbranch_pairs,branch_pseudotime,branch_progressandbranch_cells, the counts of shared and parted cells.load_lineage_membershipreturns aLineageMembershipResult, which joins the trajectory facade’s 1.x exports, andtrajectory.branch_cells(membership, lineages, *, window=0.2)writes acell_selectionwith operationselect_branch_cellswhose inputs are the membership and its cell selection.cytearc/trajectory/membership.pyholds the rule and the branch points, which never touch storage.DataStore.trajectory.states(graph, direction, *, n_states, labels=None, cells_per_state=30, beta=10.0, max_iterations=None)writes atrajectory_statesartifact, scoped as its graph, with operationfind_trajectory_statesfromTrajectoryStatesArguments, whose identity holds the graph, the direction, as an artifact or as thesnapshot_fate_directionsnapshot thatfatesaves of a Series, the graph’s cell selection,n_states,cells_per_stateandbeta, and, only when set,labelsandmax_iterations. It is cell-aligned over the graph’s cells: its canonicalvaluesname the state whose most likely cells a cell is among, missing elsewhere through a linked mask, besidememberships, cells by states, NaN outside the searched cells, andvalid; one row per state it storesstate_names,roles,coarse_transitions,cell_share,walk_share,directionandcells, and theeigenvaluesas real and imaginary columns, with the diagnosticssearchedCells,cellsLeftOut,terminalStates,statesShortOfCells,crispness,crispnessOptimizationandboundaryGap, from which it warns;crispnessOptimizationis"converged", or"stopped_at_limit"when Nelder-Mead used all of its trials before converging.load_statesreturns aTrajectoryStatesResult, which joins the trajectory facade’s 1.x exports, andfate(sink_labels=states, sinks=...)reads the artifact’s labels as any label artifact’s.regulons.regulon_specificityandregulons.connection_specificitycompute through the blockwise kernels ofDataStore.regulons.specificityandDataStore.regulons.connection_specificity, so their specificity scores equal earlier releases’ up to rounding, about 1e-15, and their connection specificity indices equal them except where rounding moves a correlation across a pair’s threshold.connection_specificityrefuses amarginthat is not a finite real number, and issues no NumPy warning for a regulon of constant activity, which still correlates 0.regulon_specificityrefuses a missing or blank label withValueErrornaming how many cells lack one, asDataStore.regulons.specificitydoes, where earlier releases scored None as a group of its own, gave NaN and a missing categorical value an all-NaN row, and failed onpd.NAwithTypeError.These functions refuse with
ValueErrorlabels that would group otherwise than their text,str(label), reads: values that would form one label but print differently, such as1,1.0andTrue, which earlier releases took for one label, and values that print alike but would form separate labels, such as1and"1", ornp.float32(0.1)and0.1, which they kept apart:regulons.regulon_specificity; the batch columns ofembeddings.fit_harmony, and so ofDataStore.reduction.harmony; thequery_batchesofDataStore.mapping.run;metrics.cramers_v,directional_mapping,eta_squaredandcoefficient_estimability, and soassociation_pairandreport_confounding;metrics.label_concordance_score,graph_connectivity,compute_lisi,ilisi_knn,clisi_knn,lisi_batch_mixing_score,silhouette_scoring,evaluate_cluster_separability,calculate_knn_cluster_similarityandcalculate_weighted_cluster_similarity; andtrajectory.build_cluster_tree,make_source_sink_vectorandvalidate_source_sink_labels. Labels of several types that print as they compare, such as"a"beside1, keep their groups,0.0and-0.0form one label, and a list’s labels keep their own types where NumPy would cast them to one.utils.arguments.require_labels_match_their_textholds the rule.PipelineAccessor.describe(recipe), alsods.pipeline.describe(recipe), returns aRecipeDescriptionof the recipe’s stage keywords: for each, aStageDescriptionof whether it runs when omitted, or the rule that decides, the public methods that it passes its settings to, and aSettingDescriptionof each setting’s name, method, annotation, default, the rule of a default that the recipe fits, and whether a mapping must give it, withto_dict()for JSON values.cytearc.quality_controlexportsmatch_gene_names, which matches the cell cycle stage’s gene lists to feature names, and itsGeneMatchrecord.PipelineAccessor.rerun(run, *, label, callback, cancel, **overrides)runs a run’s recipe with the keywords thatPipelineRun.settings()returns, every keyword of the recipe butlabel,callback, andcancelas the run recorded them, with an override mapping merged into a stage’s recorded mapping key by key and any other override replacing the run’s value.PipelineAccessor.plantakes a run in place of a recipe’s name.PipelineRun.settings()raisesValueErrorfor a run whose recipe this release lacks, and for one whose recorded keywords differ from its recipe’s keywords in this release.qc.doubletsscores ATAC assays._simulate_samplemaps each block of summed parent counts through aDoubletProjectionofquality_control/doublets.py:PcaDoubletProjectionnormalizes an RNA assay’s doublets by library size and projects them through the graph’s mapping reference, as before, so RNA scores and artifact identities are unchanged, andLsiDoubletProjectionweights an ATAC assay’s doublets by TF-IDF, each peak’s document frequency that of the graph’s cells, and multiplies the sparse rows by the LSI loadings. A session that normalizes withnorm_tf_idfreads the document frequencies from the cells’ feature summary, which prevalent peaks saves, and another session counts them in one pass, since its summary would count other values. An ATAC graph must be built on arun_lsireduction ofnorm_tf_idfvalues, andqc.doubletsrefuses another before it plans anything; each sample is scored by Euclidean distances in the LSI, whatever the graph’s metric. A sample whose automatic threshold leaves fewer than 1% of its simulated doublets above it gives aDiagnosticWarning, read from the savedsamplesattribute, so saved scores of either assay give it too and are still reused; since revision 3doublet_thresholdreplaces a minimum that leaves fewer thanTHRESHOLD_SIDE_SHAREof the simulated doublets on a side with Otsu’s threshold. Since revision 4, scoped to scores with an automatic threshold,doublet_thresholdtakes the minimum only where its estimated doublet rate is at mostTHRESHOLD_MAX_DOUBLET_RATE, then Otsu’s threshold under the same bound, and otherwise returns None and"none": the sample’s calls are none by construction, and its record holdsthresholdMethod"none"andthresholdNone. Such samples give aDiagnosticWarningof their own, whose diagnosticnoThresholdSamplescounts them, and the doublet stage’s summary shows each sample’sthresholdMethod. Theatacrecipe gains thedoubletsstage, off by default, which_pipeline/stages.pynow builds for both recipes, with the sample columns thatresolve_doublet_samplesofrecipes/common.pyresolves; its runs recordstages.doubletsanddoubletSampleColumns, and runs recorded without them replay with the stage off.Doublet scoring and mapping references take the values of every built-in RNA normalizer and PCAs without feature scaling.
assay/normalization.pysplits each built-in normalizer into a fit, what it takes from the cells it normalizes (LibrarySizeFit,PearsonResidualFit,ClrFit,TfIdfFitandPassthroughFit), and anapplythatnormedruns lazily andnormalize_rowsruns on rows that are not stored cells, simulated doublets and query cells;normalize_reference_countsis gone, andbuiltin_normalizerfinds the built-in normalizer that provenance records, which the pipeline’s lookup of a run’s normalizer also reads. Each fit’scolumnsgives its fit of some features, for a query that lacks reference genes. Normalized artifacts save no fit. A mapping reference fits Pearson residuals’ or CLR’s numbers from the counts of its cells withfit_normalization, the function that normalized them, when it is written, and saves them in the array that the fit class’sarray_namenames,pearson_feature_fractionsorclr_feature_scales, beside its PCA arrays;fitted_array_nameofmapping/features.pysays which a reference holds, and those arrays enter its payload fingerprint and model digest only when present, so library-size references keep both.reference_normalizationofmapping/features.pygives the fit of a loaded reference to mapping and doublet scoring, and a query of a Pearson residual or CLR reference must hold counts. A reference of a PCA without feature scaling holds infeature_meansandfeature_scalesthe statistics that scaling would have used, from the normalized artifact’sfeature_sumandfeature_m2throughfeature_scaling_statistics, its model projects withfeature_scaling=False, centering only, and its projections recordalgorithmVariantpca. A reference ofnorm_dummymaps only a query whose assay holds counts when its own does. The RNA recipe refuses doublet scoring only for custom normalizers.trajectory.aggregationandtrajectory.lineage_aggregationtake each feature’sn_neighborsnearest features in the graph that forms the modules by distances summed over the bins in order, the earlier of two equally near features first, where an hnswlib search found approximate neighbors whose level draws depend on the C++ standard library, so the same profiles give the same modules on every platform.trajectory/feature_dynamics.py’snearest_feature_profilespicks each feature’sn_neighbors + max(n_neighbors, 8)nearest by distances that BLAS computes from the profiles’ products, ranks them by those sums, and also ranks every feature whose distance from BLAS lies within the bound on rounding of then_neighbors-th sum, the bound ofperturbation.signature.nearest_controlssplit between the two profiles of each pair, so the neighbors are those that summing every distance gives; profiles whose squared norms near the largest float, and searches that would leave no profile out, sum every distance. Each ofnthreadsthreads multiplies its share of a block’s columns on one BLAS thread before the Numba kernel runs on as many, so BLAS’s threads never spin beside the kernel’s. The search runs over blocks of features, between which it reports progress and honors a shutdown request, and the memory budget of both calls counts what it holds. Modules whose features’ median peaks tie are numbered in the order of the cut, the larger first, andknn_clusteringtakes the profiles as an array and the distance asspace.ann_paramstakesspace, the distance; the search settingsef_construction,M,random_seed,ef,num_threadsandmax_elementshave no effect and are left out with oneFutureWarningthat names them, another name raisesValueError, and an artifact recordsann_paramsas itsspaceanddim. Revision 3 ofrun_pseudotime_aggregationand revision 2 ofrun_lineage_aggregationapply to every artifact, so modules saved by earlier releases still load and are computed anew.
Compatibility exists only where a current public facade or an explicit file-schema test says it does. There are no silent migrations, implicit compatibility branches, or forwarding shims for retired internal modules. Incompatible stores and artifacts fail with an actionable error.
Placement rules¶
Use these rules when adding code:
Put Zarr mechanics in
storage, blockwise matrix behavior inmatrix, and generic operational helpers inutils.Keep metadata and assay focused on table access, normalization, and persistence.
Put reusable computation in a concrete domain package.
Keep domain packages independent of datastore and plotting.
Use a named storage adapter when a domain persists an artifact.
Put parsing in readers, materialization in writers, and combination in merge.
Keep plotting free of datastore imports and use narrow adapters for new storage-backed inputs.
Add compatibility only at an existing public facade.
Use a concrete biological or computational package name. Do not introduce catch-all packages such as
coreoranalysis.Record a change to what an operation computes as an
OperationRevisioninstorage/operation_revisions.py(Operation revisions), with a test of the revision; never change recorded parameters to invalidate results.
Architecture boundaries are enforced in tests/test_import_architecture.py.
Public imports, result records, facade behavior, and wheel contents have separate contract tests.
Accepted and deferred decisions¶
Accepted¶
The datastore class chain remains for public compatibility.
Same-path package facades remain part of the public architecture.
A small set of domain modules has narrow storage dependencies for persisted artifacts.
Marker statistics, statistical-test design, bulk aggregation, and genomic feature construction live under
features.Pseudotime-specific feature aggregation and module clustering live under
trajectory.feature_dynamics.metadataremains a root data-model package because assays and datastore orchestration both depend on it.Unified plotting uses a datastore adapter instead of reading Zarr paths.
Arrays that a store computes are read through
storage/virtual_arrays.pyonly. A virtual array may supply its own feature streams, which keep the contract ofstorage.feature_streamand are built from its public stream building blocks; composite streams batch reads there instead of adding composite cases to the core streams.Store-backed plotting is available through the lazy
DataStore.plotsaccessor without moving implementation ownership out ofplotting.Old flat compatibility modules remain deleted.
Operation revisions are the only explicit invalidation mechanism; reuse stays exact on canonical provenance, and superseded artifacts remain inspectable.
D8:
assayTypesvalues are semantic labels, such asRNA,ADT,HTO, orGeneActivity, each naming the preset class that the store declares for an assay. CyteArc records no second type attribute, such as a modality or a measurement technology, beside them.D11: pipeline recipes share one protocol. A recipe resolves its call against the store into a
RecipePlanofPlannedStagevalues without writing anything, and one generic executor and ledger run every plan, with stages that several recipes share. Therna,atac,adt,multimodal, andperturbationrecipes implement it.D12: an assay group’s
normalizedValuesattribute records values normalized before import. It describes the stored values rather than the assay’s type, so it sits beside D8’s labels. Imports undo logs, so the stored values are always linear andnormMethoddoes not depend on the record; steps that need counts read it throughAssay.require_counts.
Deferred¶
Deferred to a later structural phase:
The graph and mapping operation modules remain large. Splitting them requires a separate behavioral and performance gate.
metadataandassayretain established convenience methods, with their domain imports deferred to call time.Function-local cycles inside
assayandreadersremain accepted because there are no module-load cycles.Heatmap plotting still reads Zarr-backed values from duck-typed store and assay inputs. Replacing those reads requires a separate plotting adapter design.
D5 pure open: deferred to 2.0. A writable open still prepares assays, records
assayTypesanddefaultAssay, and, the first time only, filtersIbymin_features_per_celland records the threshold, because the destination contract decides whatoverwrite=Truemay replace by whether a store is prepared. The 2.0 plan is an explicitprepare_storethat writers call, withmin_features_per_cellreplaced by recorded cell selections.D7 per-cell panels wait until an operation consumes them.
D9 persisted ATAC TF-IDF state waits for an ATAC mapping reference, which can recompute it from what the normalized artifact records.
D10 WNN sources keyed by artifact reference wait for a 1.x design;
select_measured_cellsalready gives one selection that every assay measured.
Rejected¶
A vague
coreoranalysispackage.Restoring forwarding modules for retired private import paths.
Restoring legacy plotting modules or datastore plotting methods.
Moving storage-aware algorithms into datastore orchestration.
Implementation references¶
Read Zarr internals for the on-disk implementation boundary and the public API reference for current contracts. Use Contributing for the test, documentation, and review workflow before making a change.