Assays and metadata API reference#

Each assay opens as the class of the preset that its store declares in assayTypes, such as RNA, ATAC, ADT, HTO, GeneActivity, or Assay for a generic assay; see Assay types. DataStore(assay_types=...) accepts only these presets and only names of assays in the store, and a read-only open accepts only the types that the store records. An open assay carries the preset that its DataStore resolved as assayType, which merge, subset, HTO demultiplexing, and DataStore.summary() read. An assay that measured only some cells of its store marks them in the Boolean cell column <assay>_I (Assay membership), which MetaData refuses to write or, while it carries the membership role, to drop.

Assay.score_features(feature_names, cell_key, ctrl_size, n_bins, rand_seed) is computation-only. It computes full-row-order averages blockwise in memory and is safe on read-only counts; it does not plan artifacts or write metadata. With log_transform=True it scores the values of normed(log_transform=True), so only normalizers that take log_transform accept it (see the table below). Persistent cell-cycle outputs belong to DataStore.scores.cell_cycle.

Feature-count percentages belong to DataStore.qc.feature_percentage(cell_selection, features). It derives the assay from the exact feature-selection ref and returns an assay-scoped quality_metric ref whose values array is the per-cell percentage. It does not add a metadata column. A read-only DataStore returns an identical existing result but raises PermissionError instead of computing a new one.

Persisted normalization belongs to DataStore.features.normalize(cell_selection, features), which returns an immutable artifact ref. It saves the values of normed with the configured normalizer. A flag left as None takes the operation’s default only for the RNA library-size normalizers norm_lib_size and norm_lib_size_log, whose scale CyteArc knows, as cytearc.assay.normalization.default_normalization_flags reports: features.normalize applies the flags they take by default. The values of every other normalizer, norm_dummy, CLR, TF-IDF, and custom normalizers, may be signed, already logged, or computed over chosen totals, so their flags stay False unless passed. The artifact records the resolved flags. Assay normalization methods are computation-only and require explicit feature indexes where they do not accept an ArtifactRef.

Every normalized path applies the assay’s configured normMethod: normed, saved normalization, HVG statistics, feature summaries, scores, marker search, pseudotime markers and aggregations, and marker heatmaps. Paths that compute library-size values straight from the counts, such as the subset writer of features.normalize and the RNA feature streams, run only when cytearc.assay.normalization.uses_library_size_normalization(assay) holds: the normalizer is norm_lib_size and sf is set.

The two normalization flags have one meaning on every path. log_transform=True takes log1p of the configured normalizer’s own output, in float64. renormalize_subset=True hands the normalizer each cell’s total over the selected features instead of over every feature. A normalizer accepts only the flags it can apply, as cytearc.assay.normalization.applicable_normalization_flags reports; a flag it cannot apply defaults to False, and passing True raises ValueError:

Assay and normalizer

log_transform

renormalize_subset

RNA norm_lib_size (default) and custom normalizers

yes

yes, through assay.scalar

RNA norm_lib_size_log

no, its values are already logarithms

yes

RNA norm_pearson_residuals and other PearsonResidualNormalizer instances

no, residuals are signed

yes, as each cell’s total in the expected counts

norm_dummy (the generic default) of RNA, ADT, and generic assays, and custom ADT and generic normalizers

yes

no

ATAC norm_tf_idf (default) and custom normalizers

no, ATAC values are never logged

yes, as the term-frequency denominator

norm_clr (the ADT default) on any assay, built-in normalizers of another assay class (norm_tf_idf outside ATAC, library-size and Pearson residual normalizers outside RNA), and norm_dummy of ATAC

no

no

An assay imported from normalized values keeps the normalizer of its class. Its stored values are linear and scaled per cell, since imports undo a log, and norm_lib_size divides each cell by its own total, so it turns them into the counts’ normalized values; normed refuses CLR and Pearson residual normalizers for such an assay. Assay.holdsCounts says whether an assay holds counts, Assay.normalizedValues holds the record of normalized values, and Assay.require_counts raises the refusal that steps that need counts share. A melded assay of an RNA class, such as GeneScores, normalizes with norm_dummy instead, since its TF-IDF values already divide each cell’s counts by its total, so its flags stay False unless passed: pass log_transform=True for the log1p of its gene scores.

A custom RNA normalizer is a callable (assay, counts) that may read each cell’s total from assay.scalar while it builds its result; normed(log_transform=True) returns the log1p of what it returns. Saved results need a module-level function or a callable with an artifact_identity attribute, which provenance records. Pass log_transform=True to take logarithms of the counts that norm_dummy keeps as they are.

Provenance identifies a module-level function defined outside CyteArc, such as one defined in a notebook, by its module, its qualified name, and code, a digest of its bytecode, constants, names, and default values. Editing the function, one of its constants, or a default gives saved results a new identity, so they are computed again rather than reused; the same function moved elsewhere in its file or defined again with the same code keeps its identity. Bytecode differs between Python versions, so another Python version also computes such results again. The digest does not cover the values of the globals that the function reads or the functions that it calls: give a normalizer whose behavior depends on them an artifact_identity that changes with them. A lambda, a nested function or closure, a method, a functools.partial, a callable object, and a function with a default value that provenance cannot record, such as an arbitrary object, raise ValueError unless they define artifact_identity. CyteArc’s own normalizers are identified by name; operation revisions record changes to them.

Releases before 1.3.0 identified such a function by name alone, so its results did not record its code. Operation revision 2 of each operation that records a normalizer (run_normalization, summarize_rna_features, summarize_atac_features, run_marker_search, run_pseudotime_marker_search, run_pseudotime_aggregation, and run_statistical_testing) applies to the results that record a normalizer defined outside CyteArc: their earlier results are reported stale, and planning logs one line when it computes one of them again.

cytearc.assay.norm_pearson_residuals normalizes RNA counts to the analytic Pearson residuals of Lause, Berens and Kobak (2021), the values of scanpy’s normalize_pearson_residuals, with theta=100 and a clip of the square root of the number of normalized cells; PearsonResidualNormalizer(theta=..., clip=...) makes one with other values, and its options are part of the normalization’s identity. The expected count of a gene in a cell is the cell’s total times the gene’s share of the counts of the normalized cells, and a residual whose expected count is 0 is 0. By default the totals are over every gene, as the residuals of the full matrix; with renormalize_subset=True they are over the selected genes, as scanpy’s recipe_pearson_residuals computes them after subsetting to highly variable genes. Set it as the assay’s normMethod, save the residuals of the highly variable genes with features.normalize, and run reduction.pca(normalized, feat_scaling=False): residuals are already standardized.

from cytearc.assay import norm_pearson_residuals

ds.RNA.normMethod = norm_pearson_residuals
hvgs = ds.features.hvgs(cells, flavor="pearson_residuals", top_n=2000)
residuals = ds.features.normalize(cells, hvgs)
pca = ds.reduction.pca(residuals, dims=50, feat_scaling=False)

Every normalized path of the assay applies the residuals while it is the normMethod, including marker search and scores, which then rank or average residuals; set the library-size normalizer back, ds.RNA.normMethod = cytearc.assay.norm_lib_size, for those steps.

A pipeline recipe takes the residuals as normalization={"method": "pearson_residuals"}, which the run records and applies to each of its stages whatever the session’s normMethod, and its PCA scales no feature unless the call sets feat_scaling (Normalization method).

RNA library-size normalization divides each cell by its total, the <assay>_nCounts value or, with renormalize_subset=True, its sum over the selected features, and a cell whose total is zero normalizes to zeros. cytearc.assay.normalization.library_size_divisors holds this rule for every library-size path: normed with norm_lib_size or norm_lib_size_log, normalization artifacts, HVG statistics, feature-group scores, marker search, compare.compute_bulk means, WAGGR, and mapping and doublet projections. Each raises ValueError naming the totals when a total of a selected cell is negative or not finite. normed with a custom normMethod, which need not read the totals, does not check them and replaces a zero total with 1.

class cytearc.assay.Assay(z, workspace, name, cell_data, nthreads, matrix_root=None, resources=None, storageIo=None, *, assay_type=None)#

A generic Assay class that contains methods to calculate feature level statistics and stream normalized values for downstream computation.

Parameters:
  • z (Group) – Zarr hierarchy where raw data is located

  • workspace (str | None) – Workspace name when assays live under matrices/ (None for a root datastore)

  • name (str) – A label/name for assay.

  • cell_data (MetaData) – Metadata class object for the cell attributes.

  • nthreads (int) – number of threads to use for parallel computations

  • assay_type (str | None) – Preset type that the store declares for the assay, such as HTO.

name#

A label for the assay instance

z#

Zarr group that contains the assay

cells#

A Metadata class object for cell attributes

nthreads#

number of threads to use for computations

rawData#

chunked array containing the raw data

feats#

a MetaData class object for feature attributes

attrs#

Zarr attributes for the zarr group of the assay

normMethod#

normalization method to use.

sf#

scaling factor for doing library-size normalization

property assayType: str | None#

Preset type declared for this assay, such as HTO, or None.

property holdsCounts: bool#

Whether the assay stores counts rather than values normalized before import.

iter_normed_feature_wise(cell_idx, feat_idx, batch_size, msg, as_dataframe=True, scratch_itemsize=0, resident_bytes=0, **norm_params)#

Iterate over explicitly selected normalized features in batches.

Parameters:
  • cell_idx (ndarray) – Ordered physical cell indices to include.

  • feat_idx (ndarray) – Ordered physical feature indices to include.

  • batch_size (int | None) – Number of genes loaded at a time. When None, selected features are grouped into chunk-aligned blocks that fit the operation memory budget.

  • msg (str | None) – Message to be displayed in the progress bar

  • as_dataframe (bool) – If true (default) then the yielded matrices are pandas dataframe

  • scratch_itemsize (int) – Bytes of working memory the caller needs per yielded value while it processes one batch. Batches are sized so that this scratch also fits the memory budget.

  • resident_bytes (int) – Bytes the caller keeps allocated for the whole iteration, such as an output buffer.

  • **norm_params (Any) – Extra keyword arguments forwarded to normed.

Return type:

Generator[DataFrame | tuple[ndarray, ndarray], None, None]

Returns:

Generator yielding DataFrames or (matrix, feature index) tuples.

classmethod normalized_values_refusal(name)#

Return the refusal of normalized values for an assay of this class.

Return type:

str

normed(cell_idx=None, feat_idx=None, renormalize_subset=False, log_transform=False)#

This function normalizes the raw and returns a delayed chunked array of the normalized data.

Parameters:
  • cell_idx (ndarray | None) – Indices of cells to be included in the normalized matrix (Default value: All those marked True in ‘I’ column of cell attribute table)

  • feat_idx (ndarray | None) – Indices of features to be included in the normalized matrix. Defaults to the complete physical feature axis.

  • renormalize_subset (bool) – Must be False.

  • log_transform (bool) – Return log1p of the normalized values.

Return type:

ChunkedArray

Returns: A chunked array (delayed matrix) containing normalized data.

Raises:

ValueError – If the configured normalizer cannot apply a requested flag.

require_counts(step, reason, remedy)#

Raise unless the assay stores counts.

Parameters:
  • step (str) – The step that needs counts, such as Doublet scoring.

  • reason (str) – Why the step needs counts.

  • remedy (str) – What to do instead.

Raises:

TypeError – If the assay holds values normalized before import.

Return type:

None

score_features(feature_names, cell_key, ctrl_size, n_bins, rand_seed, *, log_transform=False)#

Calculates the scores (mean values) of selection of features over a randomly sampled selected feature set in given cells (as marked by cell_key)

Names match features without case, and a name matches every feature with that name. A feature matched more than once, by a repeated name or by names that differ only in case, counts once in the score. Controls are drawn by expression bin as binned_sampling describes.

Parameters:
  • feature_names (list[str]) – Names (as in ‘names’ column of the feature attribute table) of features to be used for scoring

  • cell_key (str) – Name of the key (column) from cell attribute table.

  • ctrl_size (int) – Number of reference features to be sampled from each bin.

  • n_bins (int) – Number of bins for sampling.

  • rand_seed (int) – The seed of NumPy’s RandomState that draws the controls, from 0 to 2**32 - 1.

  • log_transform (bool) – Score log1p of the normalized values.

Return type:

ndarray

Returns: Numpy array of the calculated scores

Raises:
  • TypeError – If rand_seed is not an integer.

  • ValueError – If rand_seed is outside 0 to 2**32 - 1, or log_transform is True and the normalizer cannot apply it.

class cytearc.assay.RNAassay(z, name, cell_data, *, workspace=None, nthreads=1, **kwargs)#

This subclass of Assay is designed for feature selection and normalization of scRNA-Seq data.

Parameters:
  • z (Group) – Zarr hierarchy where raw data is located

  • name (str) – A label/name for assay.

  • cell_data (MetaData) – Metadata class object for the cell attributes.

  • **kwargs (Any) – kwargs to be passed to the Assay class

normMethod#

A pointer to the function to be used for normalization of the raw data

sf#

scaling factor for doing library-size normalization

scalar#

This is used to cache the library size of the cells. It is set to None until normed method is called.

iter_normed_feature_wise(cell_idx, feat_idx, batch_size, msg, as_dataframe=True, scratch_itemsize=0, resident_bytes=0, **norm_params)#

Iterate over explicitly selected normalized features in batches.

Parameters:
  • cell_idx (ndarray) – Ordered physical cell indices to include.

  • feat_idx (ndarray) – Ordered physical feature indices to include.

  • batch_size (int | None) – Number of genes loaded at a time. When None, selected features are grouped into chunk-aligned blocks that fit the operation memory budget.

  • msg (str | None) – Message to be displayed in the progress bar

  • as_dataframe (bool) – If true (default) then the yielded matrices are pandas dataframe

  • scratch_itemsize (int) – Bytes of working memory the caller needs per yielded value while it processes one batch. Batches are sized so that this scratch also fits the memory budget.

  • resident_bytes (int) – Bytes the caller keeps allocated for the whole iteration, such as an output buffer.

  • **norm_params (Any) – Extra keyword arguments forwarded to normed.

Return type:

Generator[DataFrame | tuple[ndarray, ndarray], None, None]

Returns:

Generator yielding DataFrames or (matrix, feature index) tuples.

normed(cell_idx=None, feat_idx=None, renormalize_subset=False, log_transform=False)#

This function normalizes the raw and returns a delayed chunked array of the normalized data. Unlike the normed method in the generic Assay class this method is optimized for scRNA-Seq data and supports renormalize_subset with norm_lib_size (default normalization method for this class).

Parameters:
  • cell_idx (ndarray | None) – Indices of cells to be included in the normalized matrix (Default value: All those marked True in ‘I’ column of cell attribute table)

  • feat_idx (ndarray | None) – Indices of features to be included in the normalized matrix. Defaults to the complete physical feature axis.

  • renormalize_subset (bool) – If true, normalize using only feat_idx rather than total expression across all features in a cell. (Default value: False)

  • log_transform (bool) – If True, then the normalized data is log-transformed (Default value: False).

Return type:

ChunkedArray

Returns:

A chunked array (delayed matrix) containing normalized data.

class cytearc.assay.ATACassay(z, name, cell_data, *, workspace=None, nthreads=1, **kwargs)#

This subclass of Assay is designed for feature selection and normalization of scATAC-Seq data.

normed(cell_idx=None, feat_idx=None, renormalize_subset=False, log_transform=False)#

This function normalizes the raw and returns a delayed chunked array of the normalized data. Unlike the normed method in the generic Assay class this method is optimized for scATAC-Seq data. This method uses the normalization indicated by attribute self.normMethod which by default is set to norm_tf_idf. Document frequency is learned from cell_idx. The returned matrix contains feat_idx, while term frequency uses total ATAC counts unless subset renormalization is requested.

Parameters:
  • cell_idx (ndarray | None) – Indices of cells to be included in the normalized matrix (Default value: All those marked True in ‘I’ column of cell attribute table)

  • feat_idx (ndarray | None) – Indices of features to be included in the normalized matrix. Defaults to the complete physical feature axis.

  • renormalize_subset (bool) – If True, use counts among feat_idx as the term-frequency denominator.

  • log_transform (bool) – Must be False.

Return type:

ChunkedArray

Returns: A chunked array (delayed matrix) containing normalized data.

class cytearc.assay.ADTassay(z, name, cell_data, *, workspace=None, nthreads=1, **kwargs)#

This subclass of Assay is designed for normalization of ADT/HTO (feature-barcodes library) data from CITE-Seq experiments.

Parameters:
  • z (Group) – Zarr hierarchy where raw data is located

  • name (str) – A label/name for assay.

  • cell_data (MetaData) – Metadata class object for the cell attributes.

  • **kwargs (Any)

normMethod#

Pointer to the function to be used for normalization of the raw data

cytearc.assay.norm_dummy(_, counts)#

A dummy normalizer. Doesn’t perform any normalization. This is useful when the ‘raw data’ is already normalized.

Parameters:
  • _ (Assay)

  • counts (ChunkedArray) – A chunked array with ‘raw’ counts data

Return type:

ChunkedArray

Returns: A chunked array

class cytearc.assay.PearsonResidualNormalizer(theta=100.0, clip=None)#

Analytic Pearson residuals of RNA counts, a normalizer for normMethod.

The residuals are those of Lause, Berens and Kobak (2021), Genome Biology 22:258, which scanpy’s normalize_pearson_residuals computes. The expected count of a feature in a cell is mu = n_c * p_g: the cell’s total, which normed hands the normalizer in assay.scalar, times the feature’s share of the counts of the normalized cells, its sum over them divided by the sum of their totals. The residual (x - mu) / sqrt(mu + mu**2 / theta) is clipped to [-clip, clip], sqrt(n) over n normalized cells by default, and is 0 where mu is 0. By default the totals are over every feature, so the residuals of selected features are those of the full matrix; renormalize_subset=True takes the totals over the selected features, as scanpy’s recipe_pearson_residuals does after subsetting to highly variable genes. Residuals are already standardized, so they are never log transformed, and PCA should not rescale them (reduction.pca(normalized, feat_scaling=False)).

Use cytearc.assay.norm_pearson_residuals for theta=100 and the default clip, or construct one with other values.

Parameters:
  • theta (float) – The negative binomial overdispersion, greater than 0.

  • clip (float | None) – The largest absolute residual, at least 0, or None for the square root of the number of normalized cells.

class cytearc.metadata.MetaData(zgrp, *, cell_table=False)#

Metadata table for cells and features backed by one Zarr group.

Changes made through this class are synchronized with the backing store.

Parameters:
  • zgrp (Group) – Zarr group of the table.

  • cell_table (bool) – Whether the table is a store’s cell table. Its insert() and update_key() take per-cell values only as a pandas Series keyed by cell ID, because a store’s cells need not be in the order of values computed elsewhere.

active_index(key)#

Return global row indices selected by a boolean column.

Return type:

ndarray

property cell_table: bool#

Whether the table is a store’s cell table, which takes values keyed by cell ID.

property columns: list[str]#

Return all metadata column names.

default_block_rows(column='I')#

Prefer the Zarr chunk length of column for row iteration.

Return type:

int

drop(column)#

Delete an unprotected metadata column.

Return type:

None

fetch(column, key='I')#

Return stored column values for rows selected by key.

Rows flagged by the column’s linked missing mask hold stored placeholders; to_pandas_dataframe shows them as missing.

Return type:

ndarray

fetch_all(column)#

Return all stored values from a metadata column.

Rows flagged by the column’s linked missing mask hold stored placeholders; to_pandas_dataframe shows them as missing.

Return type:

ndarray

fetch_all_columns(columns)#

Return several whole columns; object stores read them concurrently.

Return type:

list[ndarray]

fetch_categorical(column, key='I')#

Return a column’s labels for the rows that key selects as a pandas Categorical.

A categorical column returns its stored codes and categories, every category in its stored order, unused ones included, and whether they are ordered. Any other column returns its distinct values as unordered categories, numbers and times ascending and text in the natural order of plots and marker tables, so "2" precedes "10". Rows that the column’s missing mask flags, and NaN and NaT values, are missing: their code is -1. key=None reads every row.

Raises:
  • KeyError – If the table has no column of that name.

  • TypeError – If key does not name a boolean column.

  • ValueError – If a categorical column’s missing mask disagrees with its codes.

Return type:

Categorical

get_dtype(column)#

Return the dtype of a metadata column.

Return type:

dtype[Any]

get_index_by(value_targets, column, key=None)#

Return row indices for requested values in a metadata column.

Values match as case-insensitive text, as in CaseInsensitiveIndex, and every row that matches a target is returned, in target order. With key, indices are positions among the rows that key selects. A target that matches no row adds no index and is counted in a warning. Rows flagged by the column’s missing mask never match.

Return type:

ndarray

grep(pattern, only_valid=False)#

Return the stored names that match a case-insensitive regex, sorted, once each.

Return type:

list[str]

head(n=5)#

Return the first n rows of all columns, with masked rows missing.

Return type:

DataFrame

index_to_bool(idx, invert=False)#

Convert row indices into a table-sized boolean array.

Return type:

ndarray

insert(column_name, values, fill_value=None, key='I', overwrite=False, force=False)#

Insert a column into the table.

values hold a value for every row, or for the rows that key selects. A pandas Series whose index is not a RangeIndex is assigned by label: its labels must be exactly the ids of those rows, in any order, and each value goes to the row with its label.

The cell table takes per-cell values only as such a Series, keyed by cell ID, because a store’s cells need not be in the order of values computed elsewhere, such as an AnnData’s obs. It refuses arrays, lists, tuples, a bare pd.Categorical or other pandas array, and a Series with a RangeIndex, which would land on cells by position. Key values computed in store order with pd.Series(values, index=ds.cells.fetch_all("ids")). A feature table, whose order does not change, also assigns arrays, lists, and a Series with a RangeIndex by position.

Pandas categorical values, a pd.Categorical or a Series of categorical dtype, are stored as a categorical column: each row’s code beside the categories, every category kept in its order, with whether they are ordered. The categories are typed together, as other values are: text, int64, float64, complex128 or bool. An explicit fill_value must then be one of the categories. I, ids and names store the labels of categorical values. Every read returns a categorical column’s labels, and fetch_categorical() returns its codes and categories.

Raises:
  • TypeError – If the cell table gets values that are not a Series, or a Series with a RangeIndex.

  • ValueError – If column_name is protected, already exists without overwrite, or contains / or \, which Zarr reads as path separators, if a Series is labeled by anything other than those ids, if a value or a category is a list, tuple, set, dict, array or other collection, or if two categories of categorical values read alike once stored or the fill_value of categorical values is not a category.

Return type:

None

iter_row_blocks(*, cell_key='I', columns=None, block_rows=None)#

Yield contiguous row blocks over this table.

Each block covers a half-open global index range [start, stop). active_global_indices lists rows in that range that pass cell_key. Column arrays are aligned to those active indices only.

Return type:

Iterator[MetaDataRowBlock]

multi_sift(columns, lows, highs, keep_bounds=False)#

Return a boolean mask where all column filters are satisfied.

Return type:

ndarray

reset_key(key)#

Set every value in a boolean metadata key to true.

Return type:

None

sift(column, min_v=-inf, max_v=inf, keep_bounds=False)#

Return rows whose values fall within the requested bounds.

Rows flagged by the column’s linked missing mask never pass.

Return type:

ndarray

to_pandas_dataframe(columns, key=None)#

Return requested columns as a DataFrame, optionally filtered by key.

Rows flagged by a column’s linked missing mask are shown as missing: NaN for numeric columns, which become float64, a nullable boolean for boolean columns, and a missing value for other columns.

Raises:

KeyError – If a requested column is not in the table.

Return type:

DataFrame

update_key(values, key)#

Restrict a boolean metadata key using the supplied values.

Values are matched to rows as insert() matches them, so a pandas Series labeled by ids is aligned to its rows by label, and the cell table takes only such a Series, keyed by cell ID.

Raises:
  • TypeError – If the values are not booleans, or the cell table gets values that are not a Series, or a Series with a RangeIndex.

  • ValueError – If key is protected, or a Series is labeled by anything other than the ids of every row or of the rows that key selects.

Return type:

None