Import and export API reference#
Readers#
- class cytearc.readers.CrReader(grp_names)#
A class to read in CellRanger (Cr) data.
- Parameters:
grp_names (
dict[str,Any]) – A dictionary that specifies where to find the matrix, features and barcodes.
- autoNames#
Specifies if the data is from RNA or ATAC sequencing.
- grpNames#
A dictionary that specifies where to find the matrix, features and barcodes.
- nFeatures#
Number of features in dataset.
- nCells#
Number of cells in dataset.
- assayFeats#
A DataFrame with information about the features in the assay.
- cell_names()#
Returns a list of names of the cells in the dataset.
- Return type:
list[str]
- abstractmethod consume(batch_size, lines_in_mem)#
Yield CSR matrix chunks of cell rows.
- Parameters:
batch_size (
int) – Number of cells per yielded chunk.lines_in_mem (
int) – MTX lines buffered in memory (Matrix Market readers only).
- Yields:
scipy.sparse.coo_matrix chunks.
- abstractmethod count_value_ranges(maxBytes, featureGroups=None, *, destinationRows=None)#
Return the range of the canonical values of each group of features.
The ranges cover the selected cells, with duplicate coordinates summed as the import stores them. Pass a range to
count_storage_dtype()to resolve the storage dtype of its group’s counts.With
destinationRows, the reader also sends each selected cell to its destination row in temporary files on local disk, for an import that shuffles cells, andconsumethen yields the cells once in destination order.maxBytesalso holds what the files’ writer holds.- Parameters:
maxBytes (
int) – Memory available to the scan, beside the arrays that_sparse_import_resident_bytesreports, which an import charges itself.featureGroups (
ndarray|None) – Group, numbered from zero, of each feature, such as the assay that stores it. None puts every feature in one group.destinationRows (
ndarray|None) – The destination row of each selected cell, a permutation, or None to keep the cells in place.
- Return type:
list[CountValueRange]
- feature_ids(assay=None)#
Returns a list of feature IDs in a specified assay.
- Parameters:
assay (
str|None) – Select which assay to retrieve feature IDs from.- Return type:
list[str]
- feature_names(assay=None)#
Returns a list of features in the dataset.
- Parameters:
assay (
str|None) – Select which assay to retrieve features from.- Return type:
list[str]
- feature_types()#
Returns a list of feature types in the dataset.
- Return type:
list[str]
- get_cell_columns()#
Yield optional cell metadata columns supplied by the reader.
- Return type:
Iterator[tuple[str,ndarray]]
- get_feature_columns()#
Yield source feature types and optional feature metadata.
- Return type:
Iterator[tuple[str,ndarray]]
- abstract property matrix_dtype: dtype[Any]#
Return the dtype in which
consumeyields count values.
- max_window_nnz(window_rows)#
Bound nnz in any source row window.
- Return type:
int
- producer_staging_bytes(batch_size, lines_in_mem)#
Return source-reader bytes retained while a matrix batch is yielded.
- Return type:
int
- reclassify_features(indexes, feature_type, *, require_previous='Antibody Capture')#
Reclassify global feature rows before a writer captures the schema.
- Return type:
None
- rename_assays(name_map)#
Renames specified assays in the Reader.
- Parameters:
name_map (
dict[str,str]) – A Dictionary containing current name as key and new name as value.- Return type:
None
- class cytearc.readers.CrH5Reader(h5_fn, is_filtered=True, filtering_cutoff=500, *, duplicate_feature_ids='error', temp_dir=None)#
A class to read in CellRanger (Cr) data, in the form of an H5 file.
Subclass of CrReader.
- Parameters:
h5_fn (
str) – File name for the h5 file.is_filtered (
bool) – Whether the barcodes are already filtered. When False, only barcodes whose total count exceedsfiltering_cutoffare kept.filtering_cutoff (
int) – Total count that a barcode must exceed to be kept whenis_filteredis False.duplicate_feature_ids (
Literal['error','make_unique']) –"error"rejects repeated feature IDs."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 names that are already IDs), as AnnData’svar_names_make_uniquedoes, and logs a warning. Feature names are never changed, and repeated barcodes always raise.temp_dir (
str|Path|None) – Parent directory of the temporary files of an import that shuffles cells. None uses the system temporary directory.
- autoNames#
Specifies if the data is from RNA or ATAC sequencing.
- grpNames#
A dictionary that specifies where to find the matrix, features and barcodes.
- nFeatures#
Number of features in dataset.
- nCells#
Number of cells in dataset.
- assayFeats#
A DataFrame with information about the features in the assay.
- h5obj#
A File object from the h5py package.
- grp#
Current active group in the hierarchy.
- duplicateFeatureIds#
How repeated feature IDs are treated.
- Raises:
ValueError – If a barcode, feature ID, feature name or feature type is not UTF-8 text, or a barcode or feature ID is missing, blank or repeated. The refusal names the dataset and the rows that hold them, except for a repeat.
- cell_names()#
Returns a list of names of the cells in the dataset.
- Return type:
list[str]
- close()#
Closes file connection and removes any shuffled cells.
- Return type:
None
- consume(batch_size, lines_in_mem=None)#
Yield CSR chunks from the Cell Ranger H5 matrix.
After an import’s scan shuffled the cells, the chunks hold its shuffled cells, once.
- Parameters:
batch_size (
int) – Number of cells per chunk.lines_in_mem (
int|None) – Unused; kept for CrReader API compatibility.
- Return type:
Generator[coo_matrix,None,None]
- count_value_ranges(maxBytes, featureGroups=None, *, destinationRows=None)#
Return the range of the canonical values of each group of features.
Each barcode is one compressed vector of the matrix. Selected barcodes whose values are contiguous in the matrix are scanned together, as
consumereads them; the barcodes between them hold no values. WithdestinationRows, the scan also sends each selected barcode to its destination row as it reads it, so an import that shuffles cells reads the file once.- Raises:
MemoryError – If one barcode holds more values than fit in
maxBytes, or withdestinationRowsits spill does not.OSError – If the temporary disk lacks room for the shuffled cells.
ValueError – If a value is NaN or infinite, or
destinationRowsis not a permutation of the selected barcodes.
- Return type:
list[CountValueRange]
- get_feature_columns()#
Yield source feature types and optional feature metadata.
- Return type:
Iterator[tuple[str,ndarray]]
- property matrix_dtype: dtype[Any]#
Return the stored dtype in native byte order, with float16 as float32.
SciPy sparse matrices hold neither float16 nor another byte order, so
consumereads the values in this dtype.
- max_window_nnz(window_rows)#
Return the largest selected-cell row-window nnz, in the order
consumeyields them.- Return type:
int
- producer_staging_bytes(batch_size, lines_in_mem)#
Count row-pointer arrays created while one H5 batch is produced.
Shuffled cells are read a bucket at a time with the next one loading ahead.
- Return type:
int
- class cytearc.readers.CrDirReader(loc, mtx_separator=' ', index_offset=-1, is_filtered=True, filtering_cutoff=500, *, temp_dir=None, duplicate_feature_ids='error')#
Bases:
MtxReaderRead a Cell Ranger output directory in Matrix Market format.
The directory must contain exactly one complete matrix, feature, and barcode triplet, such as
matrix.mtx.gz,features.tsv.gz, andbarcodes.tsv.gz. Useinspect_mtx()andMtxReaderto choose among several triplets. All reading and streaming methods come fromMtxReader.Cell Ranger 1 and 2 list the features of each barcode in descending order, so construction sorts their matrices into temporary rows, as
MtxReadersorts every unordered matrix.- Parameters:
loc (
str) – Path to the directory that contains the Cell Ranger output.mtx_separator (
str) – Column delimiter in the MTX file.index_offset (
int) – Value added to each MTX coordinate. The default turns one-based coordinates into zero-based indexes.is_filtered (
bool) – Whether the barcodes are already filtered. When False, only barcodes whose total count exceedsfiltering_cutoffare kept.filtering_cutoff (
int) – Total count that a barcode must exceed to be kept whenis_filteredis False.temp_dir (
str|None) – Parent directory of the temporary files thatMtxReaderdescribes. None uses the system temporary directory.duplicate_feature_ids (
Literal['error','make_unique']) –"error"rejects repeated feature IDs, and"make_unique"renames each later occurrence, asMtxReaderdescribes.
- cell_names()#
Returns a list of names of the cells in the dataset.
- Return type:
list[str]
- consume(batch_size, lines_in_mem=100000)#
Yield chunks of cell rows from the Matrix Market file.
After an import shuffled the cells, the chunks hold its shuffled cells, once.
- Parameters:
batch_size (
int) – Number of cells per yielded chunk.lines_in_mem (
int) – Number of Matrix Market lines parsed at a time.
- Yields:
scipy.sparse.coo_matrix chunks in
matrix_dtype.
- count_value_ranges(maxBytes, featureGroups=None, *, destinationRows=None)#
Return the range of the counts of each group of features.
Matrix Market counts are non-negative integers, and construction already scanned them with duplicate coordinates summed and kept the largest count of each feature, so this does not use
maxBytes. When the reader dropped cells from a sorted matrix, several groups need one more read of the file to find the largest counts of the kept cells.With
destinationRows, the kept cells are read here, in the order thatconsume()would yield them, and each is sent to its destination row in temporary files;consumethen yields them once in destination order, from those files. The pass holds what one batch of about a million counts holds as it is read and sent, withinmaxBytes, which an import gives beside the reader’s arrays.- Raises:
MemoryBudgetError – With
destinationRows, ifmaxBytescannot hold the batch of the longest cell.OSError – If the temporary disk lacks room for the shuffled cells.
ValueError – If
destinationRowsis not a permutation of the kept cells.
- Return type:
list[CountValueRange]
- feature_ids(assay=None)#
Returns a list of feature IDs in a specified assay.
- Parameters:
assay (
str|None) – Select which assay to retrieve feature IDs from.- Return type:
list[str]
- feature_names(assay=None)#
Returns a list of features in the dataset.
- Parameters:
assay (
str|None) – Select which assay to retrieve features from.- Return type:
list[str]
- feature_types()#
Returns a list of feature types in the dataset.
- Return type:
list[str]
- get_cell_columns()#
Yield optional cell metadata columns supplied by the reader.
- Return type:
Iterator[tuple[str,ndarray]]
- get_feature_columns()#
Yield source feature types and optional feature metadata.
- Return type:
Iterator[tuple[str,ndarray]]
- property matrix_dtype: dtype[Any]#
Return the dtype in which
consumeyields count values.
- max_window_nnz(window_rows)#
Bound nnz in any source row window.
- Return type:
int
- producer_staging_bytes(batch_size, lines_in_mem)#
Return source-reader bytes retained while a matrix batch is yielded.
- Return type:
int
- reclassify_features(indexes, feature_type, *, require_previous='Antibody Capture')#
Reclassify global feature rows before a writer captures the schema.
- Return type:
None
- rename_assays(name_map)#
Renames specified assays in the Reader.
- Parameters:
name_map (
dict[str,str]) – A Dictionary containing current name as key and new name as value.- Return type:
None
- class cytearc.readers.MtxReader(matrix_path, feature_path=None, cell_path=None, *, feature_reference_path=None, cell_id_key=None, mtx_separator=' ', index_offset=-1, is_filtered=True, filtering_cutoff=500, temp_dir=None, duplicate_feature_ids='error')#
Read a selected Matrix Market triplet as cell-row sparse batches.
Construction reads the matrix to validate it and to find its coordinate order, the entries of each cell, and the largest count of each kept cell and each feature, with duplicate coordinates summed. Batches hold the counts in the narrowest unsigned dtype that holds the largest kept count.
Coordinates may come in any order. A matrix sorted by cell or by feature is read once at construction. Any other order, such as the descending features within each cell that Cell Ranger 1 and 2 write, is unordered, and construction reads it once more to write the entries of each kept cell to temporary rows on disk, sorted by feature and with duplicate coordinates summed wherever they are in the file. Imports read the cells of an unordered or feature-major matrix from these rows; a feature-major matrix is sorted into them when an import starts.
temporaryDiskBytesreports the size of the rows, which the end of an import andcloseremove. An import that shuffles cells reads the kept cells in this order before it creates its store, as its counts write would, and sends each to its destination row in temporary files intemp_dir; the counts write then reads them back in shuffled order instead of the file.- Parameters:
matrix_path (
MtxCandidate|str) – A candidate returned byinspect_mtx(), or the path of a Matrix Market file.feature_path (
str|None) – Feature sidecar of a matrix path. Not allowed with a candidate.cell_path (
str|None) – Cell sidecar of a matrix path. Not allowed with a candidate.feature_reference_path (
str|None) – Optional 10x Feature Reference CSV whose columns are added to the features it lists.cell_id_key (
str|None) – Parse Biosciences cell metadata column that holds the cell IDs. Required unless the metadata holds exactly one ofbc_wellsandbc_index.mtx_separator (
str) – Column delimiter in the MTX file.index_offset (
int) – Value added to each MTX coordinate. The default turns one-based coordinates into zero-based indexes.is_filtered (
bool) – Whether the cells are already filtered. When False, only cells whose total count exceedsfiltering_cutoffare kept.filtering_cutoff (
int) – Total count that a cell must exceed to be kept whenis_filteredis False.temp_dir (
str|None) – Parent directory of the temporary files: the selected members of a ZIP archive, the sorted rows, and the rows of an import that shuffles cells. None uses the system temporary directory.duplicate_feature_ids (
Literal['error','make_unique']) –"error"rejects repeated feature IDs."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 names that are already IDs), as AnnData’svar_names_make_uniquedoes, and logs a warning. Feature names are never changed, and repeated cell IDs always raise.
- coordinateOrder#
"cellMajor"or"featureMajor"for sorted coordinates, otherwise"unordered".
- temporaryDiskBytes#
Bytes of the temporary rows that the reader prepared most recently.
- consume(batch_size, lines_in_mem=100000)#
Yield chunks of cell rows from the Matrix Market file.
After an import shuffled the cells, the chunks hold its shuffled cells, once.
- Parameters:
batch_size (
int) – Number of cells per yielded chunk.lines_in_mem (
int) – Number of Matrix Market lines parsed at a time.
- Yields:
scipy.sparse.coo_matrix chunks in
matrix_dtype.
- count_value_ranges(maxBytes, featureGroups=None, *, destinationRows=None)#
Return the range of the counts of each group of features.
Matrix Market counts are non-negative integers, and construction already scanned them with duplicate coordinates summed and kept the largest count of each feature, so this does not use
maxBytes. When the reader dropped cells from a sorted matrix, several groups need one more read of the file to find the largest counts of the kept cells.With
destinationRows, the kept cells are read here, in the order thatconsume()would yield them, and each is sent to its destination row in temporary files;consumethen yields them once in destination order, from those files. The pass holds what one batch of about a million counts holds as it is read and sent, withinmaxBytes, which an import gives beside the reader’s arrays.- Raises:
MemoryBudgetError – With
destinationRows, ifmaxBytescannot hold the batch of the longest cell.OSError – If the temporary disk lacks room for the shuffled cells.
ValueError – If
destinationRowsis not a permutation of the kept cells.
- Return type:
list[CountValueRange]
- get_cell_columns()#
Yield optional cell metadata columns supplied by the reader.
- Return type:
Iterator[tuple[str,ndarray]]
- get_feature_columns()#
Yield source feature types and optional feature metadata.
- Return type:
Iterator[tuple[str,ndarray]]
- property matrix_dtype: dtype[Any]#
Return the dtype in which
consumeyields count values.
- max_window_nnz(window_rows)#
Bound nnz in any source row window.
- Return type:
int
- producer_staging_bytes(batch_size, lines_in_mem)#
Return source-reader bytes retained while a matrix batch is yielded.
- Return type:
int
- class cytearc.readers.H5adReader(h5ad_fn, cell_attrs_key='obs', cell_ids_key='_index', feature_attrs_key='var', feature_ids_key='_index', feature_name_key='gene_short_name', matrix_key='X', obsm_attrs_key='obsm', category_names_key='__categories', embedding_roles=None, cluster_keys=(), *, temp_dir=None, duplicate_feature_ids='error', duplicate_cell_ids='error')#
A class to read in data from a H5ad file (h5 file with AnnData information).
- Parameters:
h5ad_fn (
str) – Path to H5AD filecell_attrs_key (
str) – H5 group under which cell attributes are saved.(Default value: ‘obs’)feature_attrs_key (
str) – H5 group under which feature attributes are saved.(Default value: ‘var’)cell_ids_key (
str) – Key in obs group that contains unique cell IDs. By default the index will be used.feature_ids_key (
str) – Key in var group that contains unique feature IDs. By default the index will be used.feature_name_key (
str) – Key in var group that contains feature names. (Default: gene_short_name)matrix_key (
str) – Group where in the sparse matrix resides (default: ‘X’)category_names_key (
str) – Looks up this group and replaces the values in var and ‘obs’ child datasets with the corresponding index value within this group.temp_dir (
str|Path|None) – Parent directory for temporary CSC row storage. None uses the system temporary directory.duplicate_feature_ids (
Literal['error','make_unique']) –"error"rejects repeated feature IDs."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 names that are already IDs), as AnnData’svar_names_make_uniquedoes, and logs a warning. Feature names are never changed: without a feature name column they are the IDs before any rename.duplicate_cell_ids (
Literal['error','make_unique']) –"error"rejects repeated cell IDs."make_unique"renames each later occurrence of a repeated cell ID asduplicate_feature_idsrenames feature IDs, as AnnData’sobs_names_make_uniquedoes, which suits files thatanndata.concatwrote withoutindex_unique.
A table’s dataframe index that is neither the ID nor the name column imports as a metadata column only when it holds other values: an index that repeats the IDs or the names is left out, and AnnData’s unnamed index, which no dataframe column may be named, imports as
source_index(source_index_2and so on when that name is taken). Categorical columns keep their category order, unused categories, andorderedflag, whichH5adToZarrstores with the column;obscategories also keep the colors thatuns["<column>_colors"]holds. A missing or blank feature name takes the feature’s ID before any rename.- h5#
A File object from the h5py package.
- matrixKey#
Group where in the sparse matrix resides (default: ‘X’)
- cellAttrsKey#
Group wherein the cell attributes are present
- featureAttrsKey#
Group wherein the feature attributes are present
- groupCodes#
Used to ensure compatibility with different AnnData versions.
- nFeatures#
Number of features in dataset.
- nCells#
Number of cells in dataset.
- cellIdsKey#
Key in obs group that contains unique cell IDs. By default the index will be used.
- featIdsKey#
Key in var group that contains unique feature IDs. By default the index will be used.
- featNamesKey#
Key in var group that contains feature names. (Default: gene_short_name)
- catNamesKey#
Looks up this group and replaces the values in var and ‘obs’ child datasets with the corresponding index value within this group.
- sourceMatrixDtype#
dtype in which the source holds the matrix values, in native byte order. float16 is not a count storage dtype, so float16 source values are read as float32.
- embedding_roles#
Exact
obsmkeys to import as immutable artifacts:"umap"and"tsne"layouts becomeembeddingartifacts, and"coordinates", such asX_pca,X_scVI, orX_pca_harmony, becomeimported_coordinatesartifacts that graph construction, embeddings, and mapping accept.
- cluster_keys#
Exact
obskeys to import as immutable cluster-label artifacts instead of raw cell metadata.
- duplicateFeatureIds#
How repeated feature IDs are treated.
- duplicateCellIds#
How repeated cell IDs are treated.
- assay_feature_slices(key, name_map=None)#
Resolve feature ranges and metadata for each assay.
- Return type:
dict[str,_H5adAssayFeatures]
- assay_membership()#
Return the membership column of each assay that the file declares.
- Raises:
ValueError – If the declaration is not a mapping from assay name to one text value, a column name is bytes that are not UTF-8 text, naming the file and where the bytes are, or it names a column other than
<assay>_I.- Return type:
dict[str,str]
- cell_ids()#
Return the cell IDs in the file’s order, as the text that an import stores.
The IDs are a NumPy array of
str, whatever the file holds: byte strings are decoded as UTF-8, and numbers become text, so101becomes"101". Per-cell values keyed by these IDs, such aspd.Series(values, index=reader.cell_ids())for values in the file’s order, match the imported store’s cells inds.cells.insert.Repeated IDs raise ValueError, or are renamed with
duplicate_cell_ids="make_unique". IDs that an import cannot store raise ValueError that names the file, the table, the column and the rows: missing IDs, such as NaN in an index of numbers, blank IDs, and bytes that are not UTF-8 text.- Return type:
ndarray
- cell_sources()#
Return the
obscolumn that the file declares as each cell’s source, or None.- Raises:
ValueError – If the declaration is not one text value, or it is bytes that are not UTF-8 text.
- Return type:
str|None
- consume(batch_size)#
Returns a generator that yield chunks of data.
- Return type:
Generator[coo_matrix,None,None]
- property consumeDtype: dtype[Any]#
Return the dtype in which
consumeyields the matrix values.It is
sourceMatrixDtype, except that the converted rows of a CSC integer source yield their duplicate-summed values in int64, or uint64 for unsigned and boolean sources.
- consume_dataset(batch_size=1000, row_start=0, row_end=None)#
Returns a generator that yield chunks of data.
- Return type:
Generator[coo_matrix,None,None]
- consume_dense_rows(batch_size, row_start=0, row_end=None)#
Yield rows
[row_start, row_end)of a dense matrix,batch_sizeat a time.Each batch is a NumPy array of the values in
sourceMatrixDtype.- Raises:
TypeError – If the matrix is sparse, whose rows
consumeyields.ValueError – If
batch_sizeis not positive or the rows lie outside the matrix.
- Return type:
Generator[ndarray,None,None]
- consume_group(batch_size, row_start=0, row_end=None)#
Returns a generator that yield chunks of data.
- Return type:
Generator[coo_matrix,None,None]
- consume_row_range(batch_size, row_start, row_end)#
Yield source batches covering
[row_start, row_end).After an import’s scan shuffled the rows, the batches hold its shuffled rows, as sparse rows also for a dense matrix.
- Return type:
Generator[coo_matrix,None,None]
- count_value_ranges(maxBytes, featureGroups=None, *, processes=1, destinationRows=None)#
Return the range of the canonical values of each group of features.
Duplicate coordinates of a sparse matrix are summed, as the import stores them, so the ranges depend neither on the order of distinct coordinates, nor on orientation or encoding. Pass a range to
count_storage_dtype()to resolve the storage dtype of its group’s counts. The scan of a dense matrix also counts the nonzero values of each row, whichmax_batch_nnz()plans from, and the scan of a CSR matrix finds whether every row holds its indices sorted without repeats, so that an import plans no sort or sum of its batches.A matrix large enough that starting processes saves time is scanned in up to
processesnew processes at once, each over its own rows, or columns of a CSC matrix, with an equal share ofmaxBytes: as many as that share holds a whole scan window and the longest row or column, whichscan_processesofcytearc.utils.count_valuescounts. The ranges and records are the same for any number of processes.With
destinationRows, the scan of a dense or CSR matrix also sends each row it reads to its destination row in a row bucket store on local disk, from whichconsumethen yields rows in destination order, so an import that shuffles cells reads the file once. Each scan process writes its own part of the store, andmaxBytesalso holds the parts’ pending rows and the store’s row counts. A CSC matrix’s rows take their destination inmaterialize_csc().- Parameters:
maxBytes (
int) – Memory available to the scan.featureGroups (
ndarray|None) – Group, numbered from zero, of each feature, such as the assay that stores it. None puts every feature in one group.processes (
int) – Most processes that scan at once. 1 scans in this process.destinationRows (
ndarray|None) – The destination row of each row of the matrix, a permutation, or None to keep the rows in place.
- Raises:
MemoryError – If one compressed vector or dense row does not fit in
maxBytes, or withdestinationRowsits spill does not.OSError – If the temporary disk lacks room for the spill.
ValueError – If the matrix holds NaN or an infinite value,
processesis below 1, ordestinationRowsis not a permutation of the rows.TypeError – If
processesis not an integer.
- Return type:
list[CountValueRange]
- feat_ids()#
Return the feature IDs in the file’s order, as the text that an import stores.
The IDs are a NumPy array of
str, converted ascell_ids()converts cell IDs.Repeated IDs raise ValueError, or are renamed with
duplicate_feature_ids="make_unique". IDs that an import cannot store raise ValueError, ascell_ids()describes.- Return type:
ndarray
- feat_names()#
Return the feature names in the file’s order, as the text that an import stores.
The names are a NumPy array of
str, converted ascell_ids()converts cell IDs. Without the feature name key, the names are the feature IDs before any repeated ID is renamed. A missing or blank name, such as a missing category, takes the ID of its feature before any rename. Bytes that are not UTF-8 text raise ValueError that names the file, the table, the column and the row.- Return type:
ndarray
- feature_types(key)#
Return decoded feature types from a var column.
- Raises:
KeyError – If the column is absent.
ValueError – If it does not hold one value per feature, it is a categorical whose categories are not one text value, number or boolean each, or a value is bytes that are not UTF-8 text, naming the file, the table, the column and the row.
- Return type:
list[str]
- classmethod from_inspect(inspection, **overrides)#
Open a reader with the keys that
inspect_h5ad()found.- Parameters:
inspection (
H5adInspectResult) – Result ofinspect_h5ad().**overrides (
Any) – Constructor arguments that replace or add to the inspected ones, such asembedding_roles,temp_dir,duplicate_feature_ids, orduplicate_cell_ids.
- Return type:
- get_cell_columns()#
Yield the
obsmetadata columns, excluding selected cluster keys.Text comes back as
strin an object array, the text that an import stores: byte strings are decoded as UTF-8. Missing categorical and text values areNone; missing numeric values are NaN.- Raises:
ValueError – If a column holds bytes that are not UTF-8 text, naming the file, the table, the column, and the row, or the category of a categorical, that holds them, before any column is yielded.
- Return type:
Generator[tuple[str,ndarray],None,None]
- get_feat_columns()#
Yield the feature metadata columns, as
get_cell_columns()yields those of cells.- Raises:
ValueError – If a column holds bytes that are not UTF-8 text, as
get_cell_columns()refuses them.- Return type:
Generator[tuple[str,ndarray],None,None]
- materialize_csc(maxBytes=67108864, *, destinationRows=None)#
Convert CSC into temporary row storage in bounded blocks.
One pass over the columns sends each entry to the bucket of its row on local disk, and reads join each bucket’s rows. The rows hold the source values with duplicate coordinates summed. Floating-point values keep
sourceMatrixDtype; integers are held in the 64-bit integer dtype in which their duplicates are summed, so a sum past the range of a narrow source dtype is kept, as a CSR import keeps it.With
destinationRows, the destination row of each row of the matrix, a permutation, each entry goes to its row’s destination, soconsumeyields the rows of an import that shuffles cells in their shuffled order at no extra cost. The conversion then also keeps the file’s first rows, which decide what the values are.- Raises:
MemoryBudgetError – If
maxBytescannot hold the conversion. A budget too small for the column pointers and one entry is refused before any entry is read, naming the budget that converts every row, as the row indices give it.- Return type:
None
- materialized_csr_bytes()#
Return bytes retained by the materialized CSC-to-CSR conversion.
They are its row pointers; reading its rows holds more, which
producer_batch_staging_bytes()counts.- Return type:
int
- max_batch_nnz(batch_size)#
Return the most nonzero values of any
batch_sizeconsecutive rows.CSR row pointers, converted CSC rows and shuffled rows give the count without reading values, the latter two in the order that
consumeyields the rows. A dense matrix plans from the nonzero values of each row, which its value scan counts, or which are counted here before the scan. CSC columns not yet converted bound a window by its rows times the features.- Return type:
int
- measured_features()#
Return each assay’s record of which features each source measured that the file declares.
- Raises:
ValueError – If the declaration is not a mapping from assay name to a mapping from column name to one text value, a source name is bytes that are not UTF-8 text, naming the file and where the bytes are, or a column is not
measured_in_<source>.- Return type:
dict[str,dict[str,str]]
- producer_batch_staging_bytes(batch_size)#
Bound what a producer holds beside one batch.
It holds the batch’s sparse row pointers, and converted CSC rows and shuffled rows are read a bucket at a time with the next bucket loading ahead, which the producer holds as it reads.
- Return type:
int
- class cytearc.readers.CSVReader(csv_fn, has_header=True, id_column=None, rows_are_cells=True, sep=',', skip_rows=0, skip_cols=None, cell_data_cols=None, batch_size=10000, pandas_kwargs=None, *, temp_dir=None)#
A class to read in data from a CSV file.
Construction checks that every row has as many fields as the header, or as the first row of a file without one, and raises ValueError otherwise: pandas reads in chunks, pads a short row with missing values, and drops the extra fields of a row that starts a chunk. Python’s csv module counts the fields with
sepand thequotechar,quoting,doublequote,escapechar, andskipinitialspacesettings that pandas splits the rows with.- Parameters:
csv_fn (
str) – Path to the CSV filehas_header (
bool) – Whether the first row names the columns. Without a header,namesinpandas_kwargscan name them. (Default value: True)id_column (
int|None) – The position of the column that holds the cell IDs, counted from 0. Its fields are the IDs as the file holds them, so001stays"001"andNAis an ID; an empty or blank ID raises ValueError. (Default value: None)rows_are_cells (
bool) – If True then each row represents a cell and hence each column is a feature. If False then each row is feature and each column in a cellsep (
str) – The column separator in the CSV file, one character. (Default value: ‘,’)skip_rows (
int) – Number of rows to skip from the top of the file. (Default value: 0)skip_cols (
list[str] |None) – Names of columns to skip. Must be provided as a list even if just one column. A name is a column’s label as pandas holds it, or its text, asfeature_ids()gives it, so"10"also names a column thatnamesinpandas_kwargsnames10. A name of no column raises KeyError. (Default value: None)cell_data_cols (
list[str] |None) – Names of columns to include in cell metadata rather than count matrix. Must be provided as a list even if just one column. Columns are found as forskip_cols, and each name, which the cell metadata column takes, must be text. (Default value: None)batch_size (
int) – Number of lines to read at a time. Decrease this value if you have too many columns. (Default value: 50,000)pandas_kwargs (
dict[str,Any] |None) – A dictionary of keyword arguments to be passed to Pandas read_csv function. It cannot setcomment,dialect,lineterminator, orusecols, nor what the reader sets from its own arguments:sep,delimiteranddelim_whitespacefromsep,headerfromhas_header,skiprowsfromskip_rows,chunksizefrombatch_size,index_colfromid_column, and a converter of the ID column, which the reader reads as the text of its fields.namesnames every column of the file, with or without a header, or withid_column=0every column after the ID column. Withoutcompressionhere, the file’s first bytes decide whether it is gzip, bzip2, xz, Zstandard or ZIP-compressed, or a tar archive, whatever its name. The file must be text inencodinghere, or UTF-8 without it: bytes that this encoding cannot decode raise ValueError, naming the first line that holds them, unless pandas reads them underencoding_errorshere.encoding_errorscannot besurrogateescapeorsurrogatepass, which can keep such bytes as text that UTF-8 cannot encode: a store that holds such text cannot be opened or exported.temp_dir (
str|Path|None) – Parent directory of the temporary files of an import that shuffles cells. None uses the system temporary directory.
- nFeatures#
Number of features in dataset.
- nCells#
Number of cells in dataset.
- countDtype#
Dtype that holds the count values of every row.
- countRange#
Range of the count values of every row, which decides their storage dtype.
- cellDataDtypes#
Dtype of each
cell_data_colscolumn across every row;objectmarks a text column.
- cellDataWidths#
Characters of the widest value of each
cell_data_colscolumn as text, missing values left out, which an import holds a text column at.
- tempDir#
Parent directory of the temporary files of an import that shuffles cells, or None for the system temporary directory.
- cell_ids()#
Return the cell IDs in the file’s order, as the text that an import stores.
The IDs are a new NumPy array of
stron each call: the fields of the ID column as the file holds them, orcell_0,cell_1, and so on withoutid_column. Per-cell values keyed by these IDs, such aspd.Series(values, index=reader.cell_ids())for values in the file’s order, match the imported store’s cells inds.cells.insert.- Return type:
ndarray
- consume()#
Returns a generator that yield chunks of data.
- Return type:
Generator[tuple[ndarray,ndarray|None],None,None]
- feature_ids()#
Return the feature IDs in the file’s column order, as the text that an import stores.
The IDs are a new NumPy array of
stron each call: the names of the count columns, whichnamesinpandas_kwargsgives, or else the header, orfeature_0,feature_1, and so on without either. A name that is not text, such as the number10innames, becomes itsstrtext,"10", and a byte string is decoded as UTF-8. Names of bytes that are not UTF-8 text, a count column whose name is missing, such asNoneinnames, or blank, and count columns whose names read as the same text, such as10and"10", raise ValueError when the reader is built. Values keyed by these IDs, such aspd.Series(values, index=reader.feature_ids()), match the imported assay’s features infeats.insert, for exampleds.RNA.feats.insert.- Return type:
ndarray
H5AD inspection#
Use this before H5adReader when you do not know which matrix and metadata keys an H5AD file uses.
Review the result before importing: matrixKey names the matrix that will become the counts, and
matrixCandidates lists every candidate in rank order.
inspect_h5ad ranks the candidate matrices so that counts come first. A matrix holds counts when a
sample of its stored values, up to 32 windows of 1,024 values spread over the whole matrix, is
finite, non-negative, and whole. Among counts, a conventional name wins: raw/X, layers/counts,
and layers/raw_counts, then X, then layers/spliced, then other matrices, and the unspliced
and ambiguous layers of velocity data last. Matrices of one tier rank by their total, estimated
from the same sample, so the one that holds the most reads wins. When other matrices of the same
cells also hold counts, a warning lists them with their estimated totals; pass matrix_key to
choose another. A velocity file whose X, spliced, and unspliced are normalized imports its
matrix layer, the total counts, rather than its ambiguous reads.
The cell IDs are the obs index when it holds unique text or integers, else a preferred ID column such as cell_id or barcode that does, else the first unique text column. Another column of distinct floating-point values, such as a score, is never chosen. When no column holds unique IDs, cellIdsKey names the index anyway, and a warning says what an import does with it. IDs that repeat, as anndata.concat writes them without index_unique, import with H5adReader.from_inspect(inspection, duplicate_cell_ids="make_unique"), which renames each later occurrence of a repeated ID by appending -1, -2, and so on, as AnnData’s obs_names_make_unique does. An import refuses missing or blank IDs, such as NaN, and stores any other value, such as a floating-point number, as its text, so 0.5 becomes the ID "0.5". A column of IDs that holds missing or blank values, such as an index of unique text but for one missing ID, gets a warning that an import refuses them. When no var column holds text feature IDs or names, the var index gives both, and its warning says the same of the feature IDs, which duplicate_feature_ids="make_unique" renames when they repeat. Only a table without an index gets generated IDs.
H5adReader checks the matrix shape against the lengths of obs and var when it is constructed, and a mismatch raises ValueError. Overriding matrix_key, for example with raw/X, in the constructor or through H5adReader.from_inspect, therefore also needs the matching feature_attrs_key, here raw/var. inspect_h5ad(path, matrix_key="raw/X") returns reader arguments that pair them. The constructor also raises ValueError for a file without the matrix that matrix_key names, X by default, and for a sparse matrix group that declares its layout in neither encoding-type nor h5sparse_format, since a CSR and a CSC group hold the same arrays.
H5adReader decodes AnnData categorical columns and pandas nullable columns, including the nullable string arrays that AnnData writes for dataframe indexes. By default it reads the index that the dataframe’s _index attribute names. get_cell_columns and get_feat_columns return text as str, the text that an import stores, in object arrays. Missing categorical or object values become None; missing numeric values become NaN. Unsupported group encodings, multi-dimensional columns, and columns or categoricals whose values or categories are not one text value, number or boolean each, such as an array, a record or an HDF5 reference each, are skipped with a warning that names the column and the reason. Named in cluster_keys, such a column raises TypeError when the reader is constructed, before an import writes anything. H5adToZarr keeps missing rows under a linked missing mask and stores nullable booleans as booleans.
Categorical columns keep their categories. H5adToZarr stores, with each imported categorical column of obs or var that has at most 10,000 categories, a levels attribute that lists every category in its order, unused ones included, and an ordered attribute, as SeuratToZarr stores factor levels. A cell column also gets a categorical display attribute in that order, with the colors of uns["<column>_colors"] when the file holds a color for each category, or else CyteArc’s palette; plots of the column show its categories in that order and colors. Categories that read alike once stored, such as text that the file repeats or -0.0 beside 0.0, name one label, which levels and display list once, at the place of the first of them; with the file’s colors, the label takes the color of the first. Exports write such a column as the same categorical. Imported cluster labels keep the same attributes on their values array, and plots of the labels show the same order and colors. A store that CyteArc 1.3.0 or 1.4.0 imported lists such a label once for each of its categories, without a display, and exports, plots and merges read its repeated levels as the first of them. H5adToZarr stores each such column as its codes beside its categories by default, as Storage controls describes.
A dataframe index that is neither the ID nor the name column imports as metadata only when it holds
other values: an index that repeats the IDs or the names is left out, and AnnData’s unnamed index,
which no AnnData column may be named, imports as source_index, or source_index_2 and so on when
that name is taken. A missing or blank feature name, such as a missing category, takes the
feature’s ID as the file holds it, with a warning.
Pass embedding_roles and cluster_keys to select analytical H5AD values for artifact import.
Selected obsm arrays and cluster labels are excluded from live metadata and returned as exact
refs by H5adToZarr.dump(). Other supported obs columns remain literal metadata. The role
"umap" or "tsne" makes an embedding artifact, and "coordinates" an imported_coordinates
artifact, such as of X_pca, X_scVI, or X_pca_harmony, which graph.ann_index, embedding
initialization, and mapping accept as they accept a PCA. Coordinates computed after an import enter
a store through import_coordinates()
(Graph construction API reference).
A matrix stored by column (CSC) is converted to rows on local disk before its counts are written: one pass over the columns sends each value to a bucket of its cell’s rows, compressed to about a byte per stored value for whole-number counts, and the write reads the rows back a bucket at a time. Before it writes, the conversion checks that the disk has room for the values uncompressed. Pass temp_dir to H5adReader or H5adReader.from_inspect to choose the parent directory; the default uses the system temporary directory, including TMPDIR. The temporary files are removed when the reader closes.
- cytearc.inspect_h5ad(h5ad_fn, *, matrix_key=None)#
Report the matrix and metadata layout of an H5AD file.
Candidate matrices are ranked so that the counts come first. A matrix holds counts when a sample of its stored values, up to 32 windows of 1,024 values spread over the whole matrix, is finite, non-negative, and whole. Among counts, a conventional name wins:
raw/X,layers/counts, andlayers/raw_countsfirst, thenX,layers/spliced, other matrices, and theunsplicedandambiguouslayers of velocity data last. Matrices of one tier rank by their total, estimated from the sample, so the one that holds the most reads wins. When other matrices of the cells also hold counts, a warning lists them with their estimated totals; reviewmatrixKeyandmatrixCandidatesand passmatrix_keyto choose another.When no column holds IDs, inspection names the table’s index anyway, and a warning says what an import does with it: it refuses missing or blank IDs, renames repeated ones only with
duplicate_cell_idsorduplicate_feature_idsset to"make_unique", and stores other values, such as floating-point numbers, as their text. A column of IDs that holds missing or blank values, such as an index of unique text but for one missing ID, gets a warning that an import refuses them. Only a table without an index gets generated IDs. An import never reads the title or description inuns, so one that is not UTF-8 text is left out with a warning.- Parameters:
h5ad_fn (
str) – Path to the H5AD file.matrix_key (
str|None) – Optional matrix path to force (for exampleXorraw/X). When set, that candidate must exist and match obs/var dimensions.
- Return type:
- Returns:
Keys, shape, and column names needed to configure
H5adReader.- Raises:
ValueError – If no matrix matches the
obsandvartables,matrix_keynames no matrix, or what an import refuses is not UTF-8 text: a column that inspection reads to find the IDs and names, or thecolumn-orderor_indexattribute or a member name of a table.
- class cytearc.H5adInspectResult(h5adFn, matrixKey, matrixCandidates, matrixEncoding, integerLike, cellAttrsKey, cellIdsKey, featureAttrsKey, featureIdsKey, featureNameKey, categoryNamesKey, assaySplitKey, suggestedAssays, layers, title, description, nCells, nFeatures)#
- class cytearc.H5adImportResult(assayNames, analysisAssay, cellSelection, embeddingArtifacts, clusterArtifacts)#
Immutable outputs created while importing one H5AD file.
- assayNames#
Assay groups written to the destination store.
- analysisAssay#
Assay owning explicitly selected analytical outputs.
- cellSelection#
Artifact covering the imported cell axis.
- embeddingArtifacts#
Artifacts of the selected
obsmarrays keyed by exactobsmkey:embeddingartifacts for the"umap"and"tsne"roles, andimported_coordinatesartifacts, whichgraph.ann_indexaccepts, for the"coordinates"role.
- clusterArtifacts#
Cluster artifacts keyed by exact
obskey.
Matrix Market inspection#
inspect_mtx reports every complete matrix, feature, and cell triplet in a supported source.
Pass one returned candidate to MtxReader.
Matrix Market coordinates may come in any order, and duplicate coordinates are summed wherever
they appear. MtxReader and CrDirReader stream a matrix sorted by cell, as Cell Ranger 3 and
later write it, straight from the file, and sort a matrix sorted by feature into temporary rows
on local disk when an import starts. Any other order, such as the descending features within each
barcode that Cell Ranger 1 and 2 write, or shuffled entries, is read once more at construction to
sort the entries of each kept cell into the same temporary rows. An import that shuffles cells reads the kept cells once more in this order before it creates the store. The totals, the filtering
cutoff, and the count dtype follow the summed counts, so every order imports the counts and
identity of the same matrix in sorted order. coordinateOrder reports cellMajor,
featureMajor, or unordered, and temporaryDiskBytes the size of the rows, a count and a
feature index for each entry. Pass temp_dir to choose their parent directory; the default uses
the system temporary directory, including TMPDIR. The rows are removed at the end of an import
and when the reader closes, and a later import sorts the file again.
- cytearc.inspect_mtx(source)#
Return complete Matrix Market import candidates found in one source.
- Return type:
tuple[MtxCandidate,...]
- class cytearc.readers.MtxCandidate(source, matrixPath, featurePath, cellPath, matrixOrientation, nCells, nFeatures, nEntries, archivePath=None, cellMetadataPath=None, featureReferencePath=None, cellIdKeys=(), relatedFiles=())#
One complete Matrix Market matrix, feature, and cell selection.
Seurat import#
Import a serialized Seurat object from an .rds file.
Inspect with inspect_seurat, open SeuratReader, then write with SeuratToZarr.
This path does not attach to a live R session and does not read or write .h5seurat.
Sidecar matrices such as BPCells directories and HDF5 files resolve inside sidecar_root, which
defaults to the directory of the .rds file. A reader opened from a stream needs an explicit
sidecar_root before it reads sidecar-backed layers.
Without assays or reductions, SeuratToZarr imports every assay and reduction that can be
imported and reports the others as skipped_assay and skipped_reduction notices; named ones
must import. cell_metadata includes or excludes cell metadata columns, and a column that cannot
be decoded is otherwise left out with a skipped_metadata_column notice. default_assay chooses
the store’s default assay, which an active assay that is not imported, such as an integrated
assay without raw counts (counts_layer_missing), requires. reduction_roles sets whether a
reduction imports as a UMAP or t-SNE embedding or as graph coordinates.
Counts that a Seurat object stores out of cell order, such as a matrix compressed by feature, a transposed matrix or counts derived from fragments, are read once and converted to rows on local disk in the same compact buckets as a CSC H5AD matrix. SeuratReader’s temp_dir chooses their parent directory, and they are removed when the reader closes. SeuratToZarr(shuffle_cells=True) shuffles the cells, its per-cell arrays with them.
See Import a saved Seurat object for a worked import and CyteArc for Seurat users for
workflow mapping.
- class cytearc.SeuratReader(source, *, limits=None, temp_dir=None, assays=None, assay_layers=None, reductions=None, sidecar_root=None, sidecar_path_remaps=None, matrix_limits=SourceLimits(maxFeatures=2147483647, maxCells=2147483647, maxNnz=9223372036854775807, maxBlockBytes=536870912, maxMetadataBytes=268435456, tileCells=1024, compressedChunkNnz=4194304), cell_metadata=None, reduction_roles=None)#
Open a serialized Seurat object.
- Parameters:
source (
Any) – Path, bytes, or seekable binary stream of an.rdsfile.limits (
RdsLimits|None) – Parser and scratch-space limits.temp_dir (
str|PathLike[str] |None) – Directory for scratch files. None uses the system temporary directory.assays (
Sequence[str] |None) – Assays to read. None selects every assay, andSeuratToZarrthen skips, with a notice, those that cannot be imported; named assays must all be importable.assay_layers (
Mapping[str,Sequence[str]] |None) – Raw count layers to read, by assay.reductions (
Sequence[str] |None) – Reductions to read. None selects every reduction, andSeuratToZarrthen skips, with a notice, those that cannot be imported; named reductions must all be importable.sidecar_root (
str|PathLike[str] |None) – Directory that sidecar files resolve inside.sidecar_path_remaps (
Mapping[str|PathLike[str],str|PathLike[str]] |None) – Prefixes that replace absolute sidecar paths.matrix_limits (
SourceLimits) – Memory limits of matrix sources and of metadata indexes (maxMetadataBytes).cell_metadata (
Sequence[str] |Mapping[str,Sequence[str]] |None) – Cell metadata columns to read. None reads every column that can be decoded and leaves out the others with askipped_metadata_columnnotice. A sequence of names reads exactly those columns, in the table’s order, and raises the error of one that cannot be decoded;{"exclude": names}reads every decodable column but those, and{"include": names}equals the sequence. Unknown names raiseValueError.reduction_roles (
Mapping[str,Literal['umap','tsne','coordinates']] |None) – Import role of a reduction, by name:"umap"or"tsne"makes it a display embedding and"coordinates"graph coordinates. A reduction that is not mapped is a display embedding when it has two or three columns and its DimReduc key names UMAP or t-SNE (such asUMAP_,wnnUMAP_,rnaUMAP_, ortSNE_) or its name isumap,tsne, ort-sne; other reductions are graph coordinates.
A reduction needs the assay that it was computed on (
assay.used) only for its feature loadings. When that assay is not selected or cannot be imported, the reduction keeps its cell coordinates and drops its loadings, with a notice. Cell metadata columns decode one at a time, so one that cannot be decoded, such as a list column, leaves the others readable.Sidecar files such as BPCells directories and HDF5 seeds resolve inside
sidecar_root, which defaults to the directory of a pathsource. A reader opened from a stream refuses sidecar-backed layers unlesssidecar_rootis given.
- cytearc.inspect_seurat(source, *, limits=None, temp_dir=None, assays=None, assay_layers=None, reductions=None, sidecar_root=None, sidecar_path_remaps=None, matrix_limits=SourceLimits(maxFeatures=2147483647, maxCells=2147483647, maxNnz=9223372036854775807, maxBlockBytes=536870912, maxMetadataBytes=268435456, tileCells=1024, compressedChunkNnz=4194304), cell_metadata=None, reduction_roles=None)#
Report what a Seurat object holds and what of it can be imported.
The arguments are those of
SeuratReader. Each assay and reduction reports whether it is importable, with the diagnostic that blocks it and notices about what it leaves out;cellMetadata.noticeslists the cell metadata columns that cannot be decoded.- Return type:
- class cytearc.SeuratInspectResult(source, sourceDigest, payloadDigest, compression, activeAssay, nCells, assays, reductions, cellMetadata, activeIdentity, notices=())#
- class cytearc.SeuratImportResult(assayNames, defaultAssay, cellSelection, activeIdentity, reductionArtifacts, notices=())#
Result of writing a Seurat object into a CyteArc Zarr store.
- assayNames#
Assay groups written to the destination store.
- defaultAssay#
Default assay of the store:
default_assay, or else the Seurat object’s active assay, except that an active SCTAssay gives way to the assay of raw counts that its models were fitted to.
- cellSelection#
Artifact for the imported cell filter column.
- activeIdentity#
Imported Seurat active identity as immutable cluster labels.
- reductionArtifacts#
Imported reductions keyed by result name.
- notices#
Non-fatal import notices, from the reader and of the assays and reductions that the import skipped.
- class cytearc.SeuratToZarr(reader, zarr_loc, workspace=None, storage_options=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None, *, overwrite=False, default_assay=None, values=None, shuffle_cells=True, shuffle_seed=0)#
Convert a serialized Seurat object into a CyteArc Zarr store.
- Parameters:
reader (
SeuratReader) – OpenSeuratReaderfor the source.rdsfile.zarr_loc (
str|Store) – Destination Zarr path or store.workspace (
str|None) – Workspace name in the destination store. None uses the legacy layout without a workspace group.storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.mem_budget (
int|str|None) – Memory available to the conversion. Accepts bytes, a suffixed size (e.g. ‘8G’), or a fraction of total system memory (e.g. ‘0.6’). When None, auto-detected.nthreads (
int|None) – Worker count for write-time concurrency. When None, auto-detected.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
Union[CountMatrixPolicy,Literal['fit'],None]) – Count-matrix layout of every assay: aCountMatrixPolicy, used exactly; None, the default layout; or"fit", for each assay the largest halving of the defaultunitBytesandchunkByteswhose counts write andcountsTfitmem_budget. A policy or the default that does not fit raisesCountLayoutMemoryError, aMemoryError, before the destination is created, with the largest halving that fits as itsfittingPolicy.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths. Unset values stay under automatic planning.overwrite (
bool) – Replace an existing CyteArc store that noDataStorehas opened.default_assay (
str|None) – Default assay of the store, one of the imported assays. None uses the Seurat object’s active assay, except that an activeSCTAssay, whose counts are SCTransform-corrected, gives way to the assay of raw counts that its models were fitted to when that assay is imported, with ansct_default_assaynotice. An active assay that is not imported, such as theintegratedassay ofIntegrateData, which holds no raw counts, requires it.values (
Union[Literal['counts','normalized','log_normalized','log2_normalized'],Mapping[str,Literal['counts','normalized','log_normalized','log2_normalized']],None]) – What the matrix holds,"counts","normalized","log_normalized"or"log2_normalized", as the import reference’s normalized values section describes. None decides from the values.shuffle_cells (
bool) – If True, the default, write the cells in a uniformly random order, so that any contiguous slice of the store, such as one shard or a training mini-batch, is a random sample of its cells. Every per-cell array follows the one order: counts, cell IDs and names, cell metadata, assay membership, the active identity and reductions; each cell keeps its position among the object’s cells, from 0, in the int64 cell columnsourceRow. The value scan sends each cell’s counts to temporary files on local disk, intemp_dirof the reader, as it reads them. The import holds every per-cell array other than counts whole while it writes it, and refuses before the destination exists if one does not fit inmem_budget. False writes the cells in the object’s order.shuffle_seed (
int) – The seed of the shuffle, from 0 to 2**64 - 1. One seed gives the same order on every platform.
The import writes the assays and reductions that the reader selected. With the reader’s default selection (
assaysorreductionsNone), an assay or reduction that cannot be imported is skipped with askipped_assayorskipped_reductionnotice; one that the caller named raises instead. A reduction is stored under the assay that it was computed on (assay.used) when that assay is imported, otherwise under the default assay, without feature loadings. A reduction of only some of the cells, or of the cells in another order, is aligned to the cells by name and stored over a cell selection of its cells. A display embedding (UMAP or t-SNE) becomes anembeddingartifact and any other reductionimported_coordinates.Construction prepares every selected assay’s counts and reads them once. Each assay stores its counts in the dtype that
count_storage_dtype()resolves from their canonical values, and a count that the stored dtype cannot hold raises instead of wrapping.- Raises:
FileExistsError – If
zarr_locis not empty and may not be replaced.ValueError – If the default assay is not imported, or a selected assay or reduction cannot be imported; an assay raises its own
SeuratImportError, which is aValueError; or ifshuffle_seedlies outside its range.TypeError – If
shuffle_cellsis not a boolean, orshuffle_seedis not an integer.OSError – If
shuffle_cellsis True and the temporary disk lacks room for the shuffled cells.MemoryBudgetError – If
shuffle_cellsis True and the shuffle of the cells does not fit in memory beside the count sources, before the shuffle runs, or a per-cell array that the import holds whole does not fit beside what it holds throughout.
- policy#
The count-matrix layout that each imported assay was written with, by assay name.
- shuffleCells#
Whether the import shuffles the cells.
- shuffleSeed#
The seed of the shuffle.
- dump(batch_size=None)#
Write assays, RNA
countsT, and importable reductions.A shuffled import reads each assay’s shuffled counts once, deleting them as it goes, and removes them once they are written or the dump fails, so it dumps once.
- Parameters:
batch_size (
int|None) – Number of source cells per batch, at most one destination row band, which is the default.- Return type:
- Returns:
Imported assay names, cell selection, and reduction artifacts.
- Raises:
ValueError – If
batch_sizeis not positive.RuntimeError – If a shuffled import was already dumped, or holds no shuffled cells of an assay with cells.
Tapestri import#
Mission Bio’s Tapestri genotypes hundreds of amplicons in each cell, often beside surface proteins. TapestriReader reads a Tapestri Pipeline 2.0 <sample>.dna+protein.h5, or a .dna.h5 without proteins, in the layout that Mission Bio documents, and TapestriToZarr writes it to a store of its own. Each cell’s reads of each amplicon (assays/dna_read_counts) form the CNV assay, a generic Assay, with each amplicon’s CHROM, start_pos and end_pos as feature metadata, and the reads of each antibody tag (assays/protein_read_counts) form the ADT assay. Each cell’s sample_name and its filtered flag, True for a cell that the pipeline’s default filters removed, become cell metadata. all_barcodes, the reads of every barcode, cells or not, is not read, and the reader warns about any other assay group, which the store does not hold.
A cell’s ID is its sample and barcode, <sample>__<barcode>, as a merged store names its cells, so the cells of several samples in one file stay apart where their barcodes repeat. The store’s tapestri attribute, of the workspace when one is given, records the samples and the scalar metadata of each assay group, such as its panel_name, genome_version and pipeline_version, which can differ between the DNA and the protein libraries, and the file’s own metadata group. The DNA variants go into the store with ds.variants.import_counts(path, format="tapestri"), which names the file’s cells as the store does; Variants API reference describes them.
reader = cytearc.TapestriReader("sample.dna+protein.h5")
cytearc.TapestriToZarr(reader, zarr_loc="sample.zarr").dump()
reader.close()
ds = cytearc.DataStore("sample.zarr", default_assay="ADT")
counts = ds.variants.import_counts(
"sample.dna+protein.h5", cell_selection=ds.snapshot_cell_selection()
)
The default count layout writes shards of up to 1 GB, which the narrow assays of a large run fill with many cells at once. The import plans that write from the nonzero reads, which it counts as it checks the file’s values before writing: 200,000 cells of 600 amplicons and 45 antibodies need about 26 GB to write that way when nearly every read is nonzero, and less the more of the reads are zero. Below that, TapestriToZarr raises MemoryError before it writes, naming the largest smaller layout that fits the budget, such as policy=CountMatrixPolicy(unitBytes=62_500_000, chunkBytes=6_250_000) from cytearc.storage.count_matrix, which wrote those cells in 25 seconds within a budget of 24 GB. policy="fit" writes that layout without the refusal.
- class cytearc.TapestriReader(h5_fn, *, temp_dir=None)#
Read a Tapestri Pipeline 2.0 file of single-cell DNA and protein.
The amplicons’ reads (
dna_read_counts) become theCNVassay, of feature type"Amplicon", and the antibody tags’ reads (protein_read_counts) theADTassay, of feature type"Antibody Capture"; a file without proteins gives theCNVassay alone. Each feature’scavalues other than itsid, such as an amplicon’sCHROM,start_posandend_posor an antibody’santibody_sequence, become feature metadata of its assay. Each cell’ssample_nameand, when the file holds DNA variants, itsfilteredflag (True for a cell that the pipeline’s default filters removed) become cell metadata. Cells are named<sample>__<barcode>. Pass the reader toTapestriToZarr, which also records the file’s metadata, such as its panel, genome and pipeline version. Variants are imported into a store withds.variants.import_counts(path, format="tapestri"). The reader warns about any other assay group of the file, which the store does not hold.- Parameters:
h5_fn (
str) – The Tapestri.h5file.temp_dir (
str|Path|None) – Parent directory of the temporary files of an import that shuffles cells. None uses the system temporary directory.
- samples#
The samples of the file’s cells, in order of first appearance.
- metadata#
The file’s metadata:
assays, the scalar metadata of each assay group, such as itspanel_name,genome_versionandpipeline_version, and the file’s ownmetadatagroup, such assdk_version.
- Raises:
ValueError – If the file holds neither the amplicon nor the protein reads, lacks an assay’s arrays, its assays list other cells, a sample’s barcode repeats, an assay lists no features, a feature ID repeats or is blank, a barcode, sample name or feature ID is not UTF-8 text, or a
caorfilteredarray does not align with its assay.
- close()#
Close the file and remove any shuffled cells.
- Return type:
None
- consume(batch_size, lines_in_mem=None)#
Yield the reads of
batch_sizecells at a time, cells by features.After an import’s scan shuffled the cells, the chunks hold its shuffled cells, once.
- Parameters:
batch_size (
int) – Number of cells per chunk.lines_in_mem (
int|None) – Unused; kept for CrReader API compatibility.
- Return type:
Generator[coo_matrix,None,None]
- count_value_ranges(maxBytes, featureGroups=None, *, destinationRows=None)#
Return the range of the reads of each group of features.
The scan also counts each cell’s nonzero reads, which
max_window_nnz()plans from. WithdestinationRows, it also sends each cell’s nonzero reads to the cell’s destination row as it reads them, so an import that shuffles cells reads the file once.- Raises:
MemoryError – If one cell’s reads do not fit in
maxBytes, or withdestinationRowstheir spill does not.OSError – If the temporary disk lacks room for the shuffled cells.
ValueError – If a value is NaN or infinite, or
destinationRowsis not a permutation of the cells.
- Return type:
list[CountValueRange]
- get_cell_columns()#
Each cell’s sample and, with DNA variants, its
filteredflag.- Return type:
Iterator[tuple[str,ndarray]]
- get_feature_columns()#
The feature types, then each assay’s
cavalues beside the IDs.A column holds None for the features of the other assay, so it reaches only its own assay’s feature metadata.
- Return type:
Iterator[tuple[str,ndarray]]
- property matrix_dtype: dtype[Any]#
the layers’ common one.
- Type:
The dtype in which
consumeyields the reads
- max_window_nnz(window_rows)#
Return the most nonzero reads of any
window_rowsconsecutive cells.count_value_ranges()counts each cell’s nonzero reads as it scans them; before it runs, the cells are read here to count them. After an import’s scan shuffled the cells, the windows are of shuffled cells.- Return type:
int
- producer_staging_bytes(batch_size, lines_in_mem)#
Count what one batch of cells holds as it is read, per value.
A batch reads each assay’s cells by features and joins them, two dense copies; finds the nonzero entries’ rows and columns, 16 bytes each, and takes their values; and builds the sparse batch, whose 32-bit indices are copied from the 64-bit ones. Every value counts the most of these at once: its dtype’s bytes and 24. Shuffled cells are read a bucket at a time with the next one loading ahead.
- Return type:
int
- class cytearc.TapestriToZarr(reader, zarr_loc, workspace=None, storage_options=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None, assay_types=None, *, overwrite=False, shuffle_cells=True, shuffle_seed=0)#
Convert a Tapestri file of single-cell DNA and protein to a store.
The store holds the amplicons’ reads as the
CNVassay, recorded as a genericAssay, and the antibody tags’ reads as theADTassay, with each cell’ssample_nameandfilteredflag as cell metadata and the amplicons’ intervals as feature metadata, asTapestriReaderreads them. The file’s metadata, such as each assay’spanel_name,genome_versionandpipeline_version, is recorded in the store’stapestriattribute, of the workspace when one is given. A store of two assays opens withDataStore(path, default_assay="ADT")or"CNV". The DNA variants are imported into the store withds.variants.import_counts(path, format="tapestri"), whose cells are named as the store names them.- Parameters:
reader (
TapestriReader) – ATapestriReaderof the file.zarr_loc (
str|Store) – The file name for the Zarr hierarchy or a store.workspace (
str|None) – Workspace name in the destination store. None uses the layout without a workspace group.storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.mem_budget (
int|str|None) – Memory available to the conversion. Accepts bytes, a suffixed size (e.g. ‘8G’), or a fraction of total system memory (e.g. ‘0.6’).nthreads (
int|None) – Worker count for write-time concurrency. When None, auto-detected.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
Union[CountMatrixPolicy,Literal['fit'],None]) – Count-matrix layout: aCountMatrixPolicy, used exactly; None, the default layout; or"fit", the largest halving of the defaultunitBytesandchunkByteswhose counts write andcountsTfitmem_budget.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths.assay_types (
dict[str,str] |None) – Preset assay types, such as{"CNV": "CUSTOM"}, that replace the defaults:"Assay"for the amplicons’ assay, andADT’s own type for the proteins.overwrite (
bool) – If True, replace a CyteArc store that noDataStorehas opened.shuffle_cells (
bool) – If True, the default, write the cells in a uniformly random order, each keeping its row in the file in the cell columnsourceRow, asCrToZarrdescribes. False writes the cells in the file’s order.shuffle_seed (
int) – The seed of the shuffle, from 0 to 2**64 - 1.
- Raises:
TypeError – If
readeris not aTapestriReader.ValueError – If
assay_typesnames an assay that is not imported or a type that is not a preset.FileExistsError – If
zarr_locis not empty, unlessoverwritereplaces it.MemoryError – If the import does not fit
mem_budget, before the destination is created: aCountLayoutMemoryError, whosefittingPolicyis the largest halving of the layout that fits, when a policy or the default layout does not fit.
- policy#
The count-matrix layout that every imported assay was written with.
Storage controls#
Writers, merge, subset, and DataStore accept the same optional storage controls. profile chooses the physical encoding. policy chooses paired count-matrix geometry, and a writer uses it exactly. Without it, the imports write the default geometry, so the geometry of an imported store does not depend on the budget of its import, and an import whose counts write or countsT transpose does not fit mem_budget raises CountLayoutMemoryError, a MemoryError, naming the largest policy, with the default unitBytes and chunkBytes halved together, that fits; the error holds that policy as fittingPolicy. With policy="fit", an import writes that policy instead of refusing, and the default geometry whenever it fits. Each import writer reports the geometry it wrote as its policy attribute: SeuratToZarr, and SparseToZarr given a mapping of matrices, fit each assay on its own and report a mapping of assay names to geometries. A smaller geometry makes every later countsT read slower. Subset, repack_zarr, merge, and add_grouped_assay instead fit the geometry to mem_budget: they halve the default unitBytes and chunkBytes together until their writes fit. Writers that choose their source batches (the sparse and Seurat imports, and merge) admit batches of one destination row band, so a geometry never leaves the write narrower batches than its bands. H5adToZarr writes a dense matrix through dense row bands, as CSVtoZarr does, copying about a million values at a time, or whole rows of its HDF5 chunks, into a band of each assay, so its plan holds no sparse copy of the values and does not grow with the share of nonzero values. A float32 matrix of 310,385 cells by 8,563 genes with 42% of its values nonzero writes the default geometry within a 3 GiB budget this way, where the sparse writer needs 33 GiB. A write that does not fit, with one-row count shards or with its explicit policy, fails before it creates the destination: writers raise when they are constructed, and merge when it plans. MtxToZarr and CrToZarr take lines_in_mem in the constructor, so the import reserves the Matrix Market parse buffer, never for more lines than the file holds, where the parse runs: in the counts write of a file sorted by cell, and, before the write and on its own, in the sorting of a feature-major file’s entries into rows of cells; an unordered file’s entries are sorted when its reader is built. A resumed merge keeps the geometry of its completed counts. The geometry never changes the store’s identity. io overrides automatic read, compute, and write widths. Unset values stay under automatic planning from mem_budget and nthreads.
A budget must hold what an import’s reader keeps while the import runs: about 200 MB for a raw Matrix Market directory of 3 million 18-character barcodes, whose reader keeps every barcode of the file as Python text, 67 bytes each, and 24 bytes for each cell it keeps; 8 bytes for each barcode of a raw 10x HDF5 file and 16 for each cell kept; the samples, barcodes and IDs of a Tapestri file’s cells; and a CSV file’s cell IDs, 4 bytes a character of the longest, and its cell_data_cols columns, text at 4 bytes a character of a column’s widest value. Imports charge these at their scan, spill, counts and countsT writes and at the write of the cell table’s IDs and names, which reads them a block at a time, in a shuffled import’s order. A 10x HDF5 import reads the file’s barcodes for that write as bytes, 18 bytes for each barcode of 16 bases and a suffix, beside a copy of the kept cells’ when it keeps only some, and charges both. A CSV import also charges them at the writes of its cell columns, and an in-memory import charges its array of the cell IDs at its scan and at the check of its cell and feature IDs, which checks a copy of their NumPy text and first makes IDs that are not unicode text Python strings and then NumPy text. A step that the budget cannot hold beside them is refused before it runs, naming the budget that holds both.
H5adToZarr stores each categorical column of obs and var as a categorical column by default, one code per row beside every one of its categories, in place of a column of its labels. A cell column of 600,000 cells with 300 labels of 20 characters then holds 1.8 MB of values instead of 48.6 MB, and 0.75 MB of compressed chunks instead of 3.8 MB. Every read returns the same labels, fingerprints and artifact identities equal those of an import of label columns, and the column keeps its levels, ordered and display attributes. Each assay of a split import keeps every category and types them from its own features, as it types their labels. A categorical of more than 10,000 categories, which AnnData makes of nearly unique text, or one whose categories a categorical column cannot store, such as categories that read alike once stored, NaN, or numbers beside text, is stored as a column of its labels with a warning that names the column and the reason. CyteArc 1.4.0 and later open a store with categorical columns, and earlier releases refuse to open a table that holds one. categorical_columns=False stores every column as its labels, which keeps the store readable by those releases.
- class cytearc.storage.io_policy.StorageIoPolicy(readWorkers=None, computeWorkers=None, writeWorkers=None)#
Requested widths for one store or writer. Unset values mean automatic planning.
- readWorkers#
Maximum concurrent read units. None uses automatic memory-admitted read width.
- computeWorkers#
Maximum concurrent compute workers. None uses the worker budget.
- writeWorkers#
Maximum concurrent destination writers. None uses automatic write width.
- class cytearc.storage.count_matrix.CountMatrixPolicy(unitBytes, chunkBytes)#
Byte targets that determine paired
counts/countsTgeometry.- unitBytes#
Target bytes for one destination shard and one all-cell feature read group.
- chunkBytes#
Target bytes for one inner Zarr chunk.
- property chunksPerShard: int#
Inner chunks packed into one shard from the byte targets.
Count storage dtype#
Every import stores each assay’s counts in a dtype resolved from the values of that assay, whatever the reader and source encoding, and no import takes a count dtype argument. When every canonical (duplicate-summed) value is a non-negative integer, the counts are stored in the narrowest of uint8, uint16, uint32, and uint64 that holds them. Other counts keep their source dtype in native byte order, with float16 read as float32; values normalized before import are stored this way too, as Normalized values describes. Assays split from one source matrix (10x HDF5 and Matrix Market feature types, H5AD assay_split_key) each resolve their own dtype. Each import reads every count once before it creates the destination: CrReader subclasses and H5adReader report the range of each group of features over the selected cells through count_value_ranges, CSVReader records it as countRange in its first pass, and SparseToZarr and SeuratToZarr scan their sources. H5adToZarr scans a matrix of about 67 million stored values or more in processes of its own, each over its own rows, or columns of a CSC matrix: one for each worker, at most io.readWorkers, as long as each process has about 75 MB of mem_budget for its scan. Starting them takes about half a second, and the scan’s results do not depend on how many run. Count matrices hold finite, non-negative values, so imports reject NaN, infinity, and negative values before they create the destination. Writers cast through a checked cast, so a count that the stored dtype cannot hold raises instead of wrapping.
Subset and repack keep the source dtype. Merge stores the common type of the
source count dtypes, widened so that features summed by name cannot overflow
it, and rejects integer sources without a common integer dtype. Grouped and
melded assays keep their float64 values.
- cytearc.storage.count_dtype.count_storage_dtype(sourceDtype, valueRange)#
Return the dtype that stores counts with
valueRange.- Parameters:
sourceDtype (
Any) – Dtype in which the source holds the values.valueRange (
CountValueRange) – Range of every canonical value of the matrix.
- Return type:
dtype[Any]- Returns:
The narrowest unsigned dtype that holds every value when all are non-negative integers; otherwise the source dtype in native byte order, with float16 read as float32.
- class cytearc.utils.count_values.CountValueRange(integral=True, maximum=0, negative=False, largest=0.0)#
Running summary of canonical count values.
A summary does not depend on how the values were split into blocks, nor on their order, so the summaries of disjoint parts of a matrix merge into the summary of the whole.
- integral#
Whether every value seen is a non-negative integer.
- maximum#
The largest value seen while
integralholds, and 0 once it does not.
- negative#
Whether any value seen is negative.
- largest#
The largest value seen, which bounds the values that undoing a log gives.
- merge(other)#
Add the values that
othersummarized, in any order.- Return type:
None
- update(values)#
Add a block of canonical values, in any shape.
A fractional or negative value settles
integral; later blocks are checked only for NaN, infinity, and negative values.- Raises:
TypeError – If the values are not real numbers.
ValueError – If a value is NaN or infinite.
- Return type:
None
Normalized values#
Some deposits hold only normalized values, such as LARRY’s in vitro matrix on GEO or the X of a CELLxGENE file. H5adToZarr, CrToZarr, CSVtoZarr, SparseToZarr, and SeuratToZarr take values=: "counts", "normalized" for counts scaled by one factor per cell, "log_normalized" for their natural log (log1p, as scanpy and Seurat write it), or "log2_normalized" for log2(x + 1), as scater writes it. The default, None, decides each assay from its values before the destination is created:
A negative value is refused: centered or scaled values, as prepared for PCA, have them.
Whole numbers are counts.
Otherwise the first 100 cells are read three ways: as they are, after undoing a natural log, and after undoing a base-2 log. A reading fits when every cell sums to one total within 1%, or when 99% of the values lie within 0.05 of a whole multiple of their cell’s smallest value, as counts scaled per cell do. Exactly one fitting reading decides the values, and anything else refuses and asks for
values=.
A declaration is checked against the readings that fit. "counts" imports fractional counts, such as alevin’s or RSEM’s estimates, as counts, and is refused only for values that fit a log alone. "normalized" accepts normalized values rounded to whole numbers. A declared kind that is not among the readings that fit is refused, and so are a log declared for whole numbers and a log whose largest value would overflow when undone, before the destination is created. For a split import, values may map assay names to kinds, and an assay that the mapping leaves out is decided from its values. An H5AD import of normalized values names the file’s other matrices that hold counts.
Logs are undone once, at import, so every stored value is linear and scaled per cell. The assay group records the import in its normalizedValues attribute, such as {"importedAs": "log_normalized", "cellTotal": 10000.0}, where cellTotal is the total that every sampled cell shares, or null; DataStore.summary() reports it, and Assay.holdsCounts is False. Library-size normalization divides each cell by its own total, which cancels the factor that scaled the cell, so CyteArc normalizes these values as it normalizes counts and the RNA recipe gives the counts’ highly variable genes, PCA, and clusters.
Steps that need counts refuse a normalized assay with a TypeError that says why and what to do instead: cell calling, barcode ranks, ambient RNA, doublet scoring, seurat_v3 and Pearson residual gene selection, bounds on <assay>_nCounts, pseudobulk sums, CLR and Pearson residual normalization, guide calls, and association tests. ADT, HTO, and ATAC assays need counts, so they refuse normalized values at import and when a store opens. The RNA and perturbation recipes check these stages before a run starts, and one refusal names the argument that turns off each stage the run would use: gene selection by a flavor other than cytearc, a filtering bound on RNA_nCounts, cell calling and doublet scoring in the RNA recipe, and association tests and guide calling from a guide assay of normalized values in the perturbation recipe. Doublet scoring is on by default, so an RNA run of a normalized assay passes doublets=False; its default filtering leaves out RNA_nCounts.
Mount, repack, and subset stores carry the record. A merge or composite holds normalized values when any source does, keeps the import kind only when every source shares it, and keeps no cell total. Grouped and melded assays hold normalized values whatever their source. Matrix Market readers read whole numbers only: read a normalized Matrix Market file with scipy.io.mmread and write it with SparseToZarr(values=...). Seurat imports read counts layers only. A store imported from normalized values by an earlier version of CyteArc holds no record and reads as counts; re-import it with values=.
Shuffled cells#
Files usually group their cells by sample, donor or plate, so a contiguous slice of a store imported in the file’s order, such as one count shard of about 11,000 cells or a training mini-batch, holds the cells of few groups. Every import writer therefore writes the cells in a uniformly random order by default, shuffle_cells=True, so that every contiguous slice of the store is a random sample of its cells: H5adToZarr, CrToZarr and MtxToZarr for 10x HDF5 and Matrix Market files, TapestriToZarr, CSVtoZarr, SparseToZarr and SeuratToZarr. Every per-cell array follows the one order: counts and countsT, the cell IDs and names, the cell metadata columns, assay membership, and imported embeddings, cluster labels, reductions and active identities. shuffle_seed, an integer from 0 to 2**64 - 1 and 0 by default, chooses the order, which one seed gives on every platform. shuffle_cells=False writes the cells in the file’s order, as CyteArc 1.4.0 and earlier releases do, and writes neither sourceRow nor cellOrder. Why CyteArc shuffles cells gives the reasons, the costs and when to keep the file’s order.
Each cell keeps its row in the file, from 0, in the int64 cell column sourceRow, and the cell table records the seed in its cellOrder attribute, as cell order describes. For a reader that drops cells, such as CrH5Reader or MtxReader with is_filtered=False, sourceRow is the row of each kept cell in the file, its barcode’s index there, so it finds the cell in the file without filtering again; the rows of the dropped cells are missing from the column. Exports write the cells back in the file’s order (Cell order in exports). insert, update_key, reset_key and drop refuse sourceRow, and a shuffled import skips a source cell column of that name with a warning. The import decides what the values are from the file’s first 100 cells, shuffled or not, so the shuffle never changes that decision.
The shuffled rows wait in temporary files on local disk, in the reader’s temp_dir, which hold counts in about one byte per stored value. The counts write reads them back in shuffled order and deletes each file once read, so the temporary files never take disk beyond the final store of a local destination. Each import sends its rows to the files at one of these points:
Import |
When the rows go to the temporary files |
|---|---|
H5AD of CSR or dense values, 10x HDF5, Tapestri |
As the value scan reads them, so the file is read once. |
H5AD of CSC values |
As the conversion to rows, which writes such files anyway, places each value at its destination row. |
Matrix Market |
As the import reads its kept cells for the counts write, which it does before the store is created, since construction scanned the file before any import asked for a shuffle. The file is parsed as often as in the file’s order. A matrix sorted by feature, or unordered, keeps its sorted rows on local disk beside the temporary files until that read ends. |
CSV |
As the import reads the file’s rows for the counts write, which it does before the store is created, keeping the cell columns in memory. |
Seurat |
As the value scan of each assay reads them. Counts stored out of cell order pass through their own conversion first, so they take one more local pass. |
In-memory matrices |
Never: each batch of |
On a CELLxGENE sample of 10 million cells, 17 billion stored counts in a 40 GB gzip H5AD file, imported with 8 workers and a 24 GiB budget, the shuffle added 4% to the import’s 24 minutes: the scan took 127 seconds longer and wrote 18.5 GB of temporary files, and the counts write took 72 seconds less. On 1 million cells of the same dataset, 1.7 billion stored counts written as a 4.0 GB gzip 10x HDF5 file and imported the same way, the shuffled imports took 411 and 427 seconds against 474 and 455 in the file’s order: the scan took about 30 seconds longer and wrote 1.8 GB of temporary files, and the counts write, which reads them instead of the gzip file, took 46 to 81 seconds less. The shuffled store’s countsT takes 4% more disk. An import whose budget cannot hold the memory of drawing the random order beside the arrays that it already holds, such as an H5AD import’s IDs, is refused before it draws the order. The import also refuses before it writes anything when the budget cannot hold its share of the row spill, or a per-cell array that it holds whole to write it in shuffled order, such as an H5AD embedding or a Seurat reduction, and when the temporary disk lacks a quarter more than the rows are estimated to take from the source’s first million values, beside 16 bytes for each cell’s place and length in the files and their record of it, up to 26 bytes and 9 more for each value-scan process of an H5AD import beyond the first; for dense values, such as those of Tapestri, CSV and dense H5AD or Seurat counts, those values also estimate how many of the rows’ values are not zero.
An H5AD, 10x HDF5, Matrix Market or Tapestri reader holds the shuffled rows of one import at a time. Another import of the same reader releases them when it is created, and an import in the file’s order also when it writes its counts, so that it always writes the file’s rows. The shuffled import whose rows were released raises a RuntimeError when it writes its counts, instead of writing rows in another order; create a new writer to import the file again. CSV and Seurat imports keep their shuffled rows themselves, so several imports of one reader never share them. A shuffled import that is refused after it sent its rows to the temporary files removes them.
Writers#
Every writer owns the reserved metadata columns ids, names and I and the __cytearc_missing__ prefix of missing-value masks. Source cell or feature metadata columns with these names are skipped with a warning, so imported identifiers are never replaced. Zarr reads / and \ in a column name as path separators, so writers store a source column whose name contains either one under the name with _ in their place and log the rename. A source name that is already valid keeps its name; a renamed column whose name is taken gets the first free _2, _3, and so on. SeuratToZarr raises for reserved names instead of skipping them. The H5AD, CSV, Matrix Market, and Cell Ranger readers reject missing or repeated cell IDs, and so does SparseToZarr, which also rejects missing or repeated feature IDs and converts a COO, CSC, or dense matrix to CSR before it scans it. CSVReader reads its ID column as the text that the file holds, so 001 stays "001" and NA is an ID, and it takes an empty field as a missing ID. H5adReader renames repeated cell IDs on request (duplicate_cell_ids="make_unique"). The readers also reject missing or repeated feature IDs. For CSVReader these are count columns whose names are missing or blank, or read as the same text, as 10 and "10" in names of pandas_kwargs do; names read from a header never repeat, since pandas renames each later occurrence of a repeated name by appending .1, .2, and so on, without a warning, and names a column with an empty header Unnamed: <position>. Some exporters use gene symbols as feature IDs, and these repeat. Pass duplicate_feature_ids="make_unique" to MtxReader, CrDirReader, CrH5Reader, or H5adReader, also through H5adReader.from_inspect, to keep the first occurrence of each feature ID and rename each later one, in file order, by appending -1, -2, and so on, as AnnData’s var_names_make_unique does. A suffixed name that is already an ID is skipped, so the result is unique, and the reader logs how many IDs it renamed. IDs are made unique across all features, whatever their assay, so an antibody that repeats the ID of an earlier gene is renamed in its own assay, for example to CD4-1. Feature names are not changed: an H5AD file without a feature name column takes the names from the IDs it holds, and a Matrix Market feature reference matches the IDs of the feature sidecar. Cell IDs must be unique in either mode.
H5adToZarr reads and checks the cell IDs, feature IDs and feature names before it reads the matrix, so an import that refuses them writes nothing. NaN in an index or column of numbers counts as a missing ID, and IDs and names must be UTF-8 text. So must the text of every obs and var column that the import stores as metadata, and of each cluster key, which the import reads a block of rows at a time after the IDs: the values of a column of text, except in missing rows, and every category of a categorical, used or not, since the import stores them all. The refusal of a missing ID or of text that is not UTF-8 names the file, the table, the column and the rows, or the category of a categorical. An import split by feature type refuses feature types that are not UTF-8 text in the same way. inspect_h5ad refuses text that is not UTF-8 in the columns that it reads to find the IDs and names, as an import would, and leaves out with a warning a title or description in uns that is not UTF-8 text, which an import never reads. H5adReader, when it is constructed, and inspect_h5ad refuse a column-order or _index attribute or a member name of obs or var that is not UTF-8 text, naming the table and the attribute or the member. The reader keeps the IDs and names for the import, which charges them to mem_budget beside each later step, from the scan of the counts to the countsT write: 18-character barcodes take 59 bytes a cell, about 590 MB for 10 million cells.
CrH5Reader, MtxReader, CrDirReader and TapestriReader read and check the cell IDs, feature IDs, feature names and feature types that their files hold when they are created, so an import refuses them before it writes anything. They must be UTF-8 text, as must every field of a Matrix Market sidecar or feature reference, which pandas decodes whole. The refusal of text that is not UTF-8, or of a missing or blank ID, names the file, the dataset or the column, and the rows, and a sidecar without a header names its columns by position, counting from 1. inspect_mtx counts the rows of a sidecar that is not UTF-8 text and leaves the refusal to the reader. The IDs and names of a Parse Biosciences gene table, the cell IDs of a Parse cell table and the IDs of a 10x feature reference are the text that the file holds, as in CSVReader: 007 stays "007", NA is an ID, and an empty field is a missing ID.
The cell column <assay>_I of every assay that an import writes is reserved for the membership of that assay (Assay membership), because a merge reads a column of that name as which cells the assay measured. H5adToZarr restores such a column as the membership of the assay only when the file declares it in uns["cytearc"]["assayMembership"], which maps each assay to its column, as CyteArc’s exports write it; the declared column must be boolean without missing values, and a declaration that names another column, a column that obs lacks or a column whose name is not UTF-8 text raises ValueError before the destination is created. Every other source column named for an imported assay, in an H5AD file without the declaration or from CSVtoZarr, CrToZarr, or MtxToZarr, is skipped with a warning, as I is. SeuratToZarr writes the membership itself and raises for a metadata column named for any imported assay. A column named for an assay that the import does not write, such as ADT_I in an RNA-only import, stays an ordinary column. SparseToZarr imports no cell metadata; add columns afterwards with ds.cells.insert, as a pandas Series keyed by cell ID.
Tables of several modalities held in memory, such as RNA, guide, hashtag and protein counts read from GEO, become one store through SparseToZarr without a file between them. Pass a mapping of assay names to matrices of the same cells, with feature_ids mapping each assay to its IDs, and feature_names, assay_type and values mapping the assays they apply to. Each assay resolves its own dtype, values decision and count layout, and a feature ID needs to be unique only within its assay, so a gene and an antibody may both be CD86. assay_name names the assay of a single matrix and is refused beside a mapping.
from cytearc.writers import SparseToZarr
SparseToZarr(
{"RNA": rna_counts, "CRISPR": guide_counts, "ADT": protein_counts},
"screen.zarr",
cell_ids,
{"RNA": gene_ids, "CRISPR": guide_ids, "ADT": antibody_ids},
).dump()
Import writers take their assay type from the assay name. Pass assay_type (or
assay_types on CrToZarr) to declare a custom-named assay as a preset such as RNA. A value
that is not a preset raises ValueError; use Assay for a generic assay. DataStore(assay_types=...)
and add_melded_assay(assay_type=...) apply the same rule. The presets and the persisted
assayTypes attribute are described in Assay types.
Writers create a new store and replace only a store that no DataStore has opened. CrToZarr,
MtxToZarr, H5adToZarr, SparseToZarr, CSVtoZarr, SeuratToZarr, and SubsetZarr accept an
absent path, an empty directory, or an empty store, and raise FileExistsError for a destination
that holds any key, such as an earlier store or a .DS_Store file. With overwrite=True
(overwrite_existing_file=True for SubsetZarr) they replace a store whose root group holds no
prepared assay, no matrixSource, and only members that CyteArc writes (cellData, matrices,
artifacts, pipeline, assays, and workspaces of them).
A store that a DataStore has opened and content that CyteArc did not write, also inside its groups
and arrays, are never replaced, and SubsetZarr refuses a destination that overlaps a source. A
local destination inside a Zarr store, such as s.zarr/RNA or s.zarr/new.zarr, given as a path
or a local store, and a destination whose root group is an assay group raise ValueError.
CrToZarr, MtxToZarr, H5adToZarr, and SeuratToZarr check their destination before they
read the counts, and SubsetZarr when it is constructed. Each checks again as it creates the store
with Zarr mode "w-", which refuses keys that appeared since the check, or with mode "w" for the
store that overwrite=True replaces. A local path is opened as it is written, also when it holds
#, ?, or ;. subset_assay_zarr adds one count array to an existing store and replaces
nothing: out_grp must not exist and must not be, contain, or lie inside in_grp, and its parent
group must not already record the layout of another count matrix.
SubsetZarr, DataStoreMerge, mount_datastore, and repack_store refuse a source store that
holds a pending derived assay, one that add_grouped_assay or add_melded_assay has not
published, and raise ValueError naming it before they write anything. Once no process is
writing it, remove it with discard_interrupted_assay on a DataStore of its workspace.
- cytearc.storage.destinations.check_destination(location, *, overwrite=False, storage_options=None)#
Raise unless a writer may create its store at
location; write nothing.- Parameters:
location (
str|Store) – Destination path, URI, or Zarr store.overwrite (
bool) – Accept a CyteArc store that noDataStorehas opened.storage_options (
dict[str,Any] |None) – Backend options used to open a URI.
- Raises:
ValueError – If the destination lies inside a Zarr store or is an assay group.
FileExistsError – If the destination is not empty and may not be replaced.
- Return type:
None
- cytearc.storage.destinations.create_destination(location, *, overwrite=False, storage_options=None)#
Check a destination with
check_destination()and create its store.- Parameters:
location (
str|Store) – Destination path, URI, or Zarr store.overwrite (
bool) – Replace a CyteArc store that noDataStorehas opened.storage_options (
dict[str,Any] |None) – Backend options used to open a URI.
- Return type:
Group- Returns:
The new, empty root group, open for writing.
- cytearc.storage.destinations.refuse_pending_assays(root, *, operation, subject='The source store')#
Raise unless a source store holds no derived assay left pending.
- Parameters:
root (
Group) – Root group of the source store, as the writer reads it.operation (
str) – What the store cannot be, such as"subset"or"repacked".subject (
str) – How the message names the store.
- Raises:
ValueError – If the store holds a pending derived assay.
- Return type:
None
- class cytearc.writers.CrToZarr(cr, zarr_loc, workspace=None, storage_options=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None, assay_types=None, lines_in_mem=100000, *, overwrite=False, values=None, shuffle_cells=True, shuffle_seed=0)#
A class for converting data in the Cellranger format to a Zarr hierarchy.
- Parameters:
cr (
CrReader) – A CrReader object, containing the Cellranger data.zarr_loc (
str|Store) – The file name for the Zarr hierarchy or a storeworkspace (
str|None) – Workspace name in the destination store. None uses the legacy layout without a workspace group.storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.mem_budget (
int|str|None) – Memory available to the conversion. Accepts bytes, a suffixed size (e.g. ‘8G’), or a fraction of total system memory (e.g. ‘0.6’).nthreads (
int|None) – Worker count for write-time concurrency. When None, auto-detected.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
Union[CountMatrixPolicy,Literal['fit'],None]) – Count-matrix layout: aCountMatrixPolicy, used exactly; None, the default layout; or"fit", the largest halving of the defaultunitBytesandchunkByteswhose counts write andcountsTfitmem_budget. A policy or the default that does not fit raisesCountLayoutMemoryError, aMemoryError, before the destination is created, with the largest halving that fits as itsfittingPolicy.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths. Unset values stay under automatic planning.assay_types (
dict[str,str] |None) – Preset assay types, such as{"GEX": "RNA"}, for assays whose names are not presets. Other assays take their type from their name.lines_in_mem (
int) – Matrix Market lines parsed at a time (Matrix Market readers only). A file sorted by cell is parsed as its counts are written, and a feature-major file before the write, as its entries are sorted into rows of cells; an unordered file’s entries are sorted when its reader is built. The import reserves this parse buffer for the step that parses, never for more lines than the file holds.overwrite (
bool) – If True, replace a CyteArc store that noDataStorehas opened.values (
Union[Literal['counts','normalized','log_normalized','log2_normalized'],Mapping[str,Literal['counts','normalized','log_normalized','log2_normalized']],None]) – What the matrix holds,"counts","normalized","log_normalized"or"log2_normalized", as the import reference’s normalized values section describes. None decides from the values. Matrix Market readers read whole numbers only.shuffle_cells (
bool) – If True, the default, write the cells in a uniformly random order, so that any contiguous slice of the store, such as one shard or a training mini-batch, is a random sample of its cells. Every per-cell array follows the one order, and each cell keeps its row in the file, from 0, in the int64 cell columnsourceRow: for a reader that drops barcodes, such as one withis_filtered=False, its barcode’s index in the file. The reader sends each cell to temporary files on local disk, in itstemp_dir, as it reads it: a 10x HDF5 or Tapestri reader during its value scan, a Matrix Market reader as it reads its cells for the counts write, before the store is created. A reader holds the shuffled cells of one import at a time, and an import in the reader’s order of a reader that another import shuffled reads the reader’s order. False writes the cells in the file’s order.shuffle_seed (
int) – The seed of the shuffle, from 0 to 2**64 - 1. One seed gives the same order on every platform.
Each assay stores its counts in the dtype that
count_storage_dtype()resolves from the canonical values of its own features over the selected cells.- Raises:
FileExistsError – If
zarr_locis not empty, unlessoverwritereplaces it.TypeError – If
shuffle_cellsis not a boolean, orshuffle_seedis not an integer, orshuffle_cellsis True and the reader’scount_value_rangestakes nodestinationRows.ValueError – If
shuffle_seedlies outside its range.OSError – If
shuffle_cellsis True and the temporary disk lacks room for the shuffled cells.MemoryBudgetError – If
mem_budgetcannot hold the shuffle of the cells beside the reader’s arrays, whenshuffle_cellsis True, the sorting of a feature-major Matrix Market file’s entries into rows of cells, or the write of the cell table’s IDs and names, a block of the reader’s names at a time. Each is refused before it starts and before the destination exists, naming the budget that holds it; the sorting also names a smallerlines_in_memwhen one fits.
- cr#
A CrReader object, containing the Cellranger data.
- z#
The Zarr hierarchy (array or group).
- policy#
The count-matrix layout that every imported assay was written with.
- shuffleCells#
Whether the import shuffles the cells.
- shuffleSeed#
The seed of the shuffle.
- dump(batch_size=None)#
Writes the count values into the Zarr matrix.
A shuffled import reads its shuffled cells once, deleting them as it goes, and removes them once the counts are written or the write fails, so it writes its counts once. An import in the reader’s order removes the shuffled cells that another import of the reader left.
- Parameters:
batch_size (
int|None) – Number of source cells per batch, at most one destination row band, which is the default.- Raises:
ValueError – If
batch_sizeis not positive.RuntimeError – If the shuffled cells of this import were already written, or another import of the reader replaced them.
MemoryBudgetError – If the reader must sort a Matrix Market file’s entries into rows again, as after another import of it removed them, and
mem_budgetcannot hold that.
- Return type:
None- Returns:
None
MtxToZarr is an alias of CrToZarr for use with MtxReader.
- class cytearc.writers.H5adToZarr(h5ad, zarr_loc, assay_name=None, workspace=None, storage_options=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None, assay_split_key=None, assay_name_map=None, analysis_assay=None, assay_type=None, *, overwrite=False, values=None, categorical_columns=True, shuffle_cells=True, shuffle_seed=0)#
A class for converting data in anndata’s H5ad format to Zarr hierarchy.
- Parameters:
h5ad (
H5adReader) – Reader for the source H5AD file.zarr_loc (
str|Store) – The file name for the Zarr hierarchy or a storeassay_name (
str|None) – the name of the assay (e. g. ‘RNA’)assay_split_key (
str|None) – A var column used to split features into assays.assay_name_map (
dict[str,str] |None) – Feature type to assay name overrides.workspace (
str|None) – An optional workspace id. None uses the legacy layout without a workspace group.storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.mem_budget (
int|str|None) – Memory available to the conversion. Accepts bytes, a suffixed size (e.g. ‘8G’), or a fraction of total system memory (e.g. ‘0.6’).nthreads (
int|None) – Worker count for write-time concurrency. When None, auto-detected.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
Union[CountMatrixPolicy,Literal['fit'],None]) – Count-matrix layout: aCountMatrixPolicy, used exactly; None, the default layout; or"fit", the largest halving of the defaultunitBytesandchunkByteswhose counts write andcountsTfitmem_budget. A policy or the default that does not fit raisesCountLayoutMemoryError, aMemoryError, before the destination is created, with the largest halving that fits as itsfittingPolicy.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths. Unset values stay under automatic planning.analysis_assay (
str|None) – Imported assay that owns explicitly selected H5AD embeddings and clusters. Required for multi-assay imports with analytical outputs.assay_type (
str|None) – Preset assay type, such asRNA, for a single imported assay whose name is not a preset. When None, the assay name decides the type. Not allowed withassay_split_key.overwrite (
bool) – If True, replace a CyteArc store that noDataStorehas opened.values (
Union[Literal['counts','normalized','log_normalized','log2_normalized'],Mapping[str,Literal['counts','normalized','log_normalized','log2_normalized']],None]) – What the matrix holds,"counts","normalized","log_normalized"or"log2_normalized", as the import reference’s normalized values section describes. None decides from the values.categorical_columns (
bool) – If True, the default, store each categorical column ofobsandvaras a categorical column, its codes beside every one of its categories, instead of a column of its labels. Every read returns the same labels either way. A categorical of more than 10,000 categories, or whose categories a categorical column cannot store, such as NaN or categories that read alike once stored, is stored as a column of its labels with a warning that names the column and the reason. CyteArc 1.4.0 and later open a store with categorical columns; False stores every column as its labels, which keeps the store readable by earlier releases.shuffle_cells (
bool) – If True, the default, write the cells in a uniformly random order, so that any contiguous slice of the store, such as one shard or a training mini-batch, is a random sample of its cells. Every per-cell array follows the one order, and each cell keeps its row in the file, from 0, in the int64 cell columnsourceRow. The shuffle reads the file once, sending each row to temporary files on local disk, intemp_dirof the reader, as the value scan reads it. The import holds each selected embedding and each key’s cluster labels whole, and refuses before it writes anything if they do not fit inmem_budget. An import in the file’s order of a reader that another import shuffled reads the file’s rows. False writes the cells in the file’s order.shuffle_seed (
int) – The seed of the shuffle, from 0 to 2**64 - 1. One seed gives the same order on every platform.
Each assay stores its counts in the dtype that
count_storage_dtype()resolves from the canonical source values of its own features, so the same counts import identically from every H5AD encoding.- Raises:
FileExistsError – If
zarr_locis not empty and may not be replaced.TypeError – If
categorical_columnsorshuffle_cellsis not a boolean, orshuffle_seedis not an integer.ValueError – If
shuffle_seedlies outside its range, or the file holds IDs or names that the reader refuses, or bytes that are not UTF-8 text in a metadata column or a cluster key, which are refused before anything is written, naming the file, the table, the column and the row, or the category of a categorical.OSError – If
shuffle_cellsis True and the temporary disk lacks room for the shuffled rows.MemoryBudgetError – If
shuffle_cellsis True and the shuffle of the cells, before it runs, or an embedding or a key’s cluster labels do not fit in memory beside what the import holds.
- h5ad#
A h5ad object (h5 file with added AnnData structure).
- assayName#
Name of the imported assay; None with
assay_split_key.
- z#
The Zarr hierarchy (array or group).
- storageDtypes#
Count storage dtype of each imported assay.
- policy#
The count-matrix layout that every imported assay was written with.
- shuffleCells#
Whether the import shuffles the cells.
- shuffleSeed#
The seed of the shuffle.
- dump(batch_size=None)#
Write h5ad matrix data into Zarr
countsand RNAcountsT.- Parameters:
batch_size (
int|None) – Number of source cells per batch, at most one destination row band, which is the default for a sparse matrix. A dense matrix is copied into dense row bands, so its batches hold about a million values or whole rows of its HDF5 chunks by default, and this caps them.- Raises:
ValueError – If
batch_sizeis not positive.- Return type:
- Returns:
Explicit selection, embedding, and cluster artifact references.
- class cytearc.writers.SparseToZarr(csr_mat, zarr_loc, cell_ids, feature_ids, assay_name=None, workspace=None, feature_names=None, storage_options=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None, assay_type=None, *, overwrite=False, values=None, shuffle_cells=True, shuffle_seed=0)#
Write count matrices held in memory to a new store.
A single matrix writes one assay. A mapping of assay names to matrices writes one assay for each, over the same cells, so tables of several modalities, such as RNA, guide, hashtag and protein counts read from GEO, become one store without a file between them;
feature_ids,feature_names,assay_typeandvaluesthen take the same keys, and a feature ID need be unique only within its assay.- Parameters:
csr_mat (
csr_matrix|Mapping[str,Any]) – A cells-by-features matrix: a SciPy sparse matrix or array of any format, or a dense two-dimensional array; or a mapping of assay names to such matrices, all of the same cells. Other formats are converted to CSR; a CSR matrix is used as given.zarr_loc (
str|Store) – Output Zarr filename with pathcell_ids (
ndarray|list[str]) – Cell IDs for the cells in the dataset. They must be present and unique, as every reader requires.feature_ids (
ndarray|list[str] |Mapping[str,Any]) – Feature IDs for the features in the dataset, present and unique; with a mapping of matrices, a mapping of each assay to its feature IDs.assay_name (
str|None) – Name for the output assay of a single matrix. If not provided then automatically set to RNA. A mapping of matrices names its assays by its keys and takes none.workspace (
str|None) – Workspace name in the destination store. None uses the legacy layout without a workspace group.feature_names (
ndarray|list[str] |Mapping[str,Any] |None) – Optional display names aligned withfeature_ids; with a mapping of matrices, a mapping of the assays that have them.storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.mem_budget (
int|str|None) – Memory available to the conversion. Accepts bytes, a suffixed size (e.g. ‘8G’), or a fraction of total system memory (e.g. ‘0.6’).nthreads (
int|None) – Worker count for write-time concurrency. When None, auto-detected.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
Union[CountMatrixPolicy,Literal['fit'],None]) – Count-matrix layout of every assay: aCountMatrixPolicy, used exactly; None, the default layout; or"fit", for each assay the largest halving of the defaultunitBytesandchunkByteswhose counts write andcountsTfitmem_budget. A policy or the default that does not fit raisesCountLayoutMemoryError, aMemoryError, before the destination is created, with the largest halving that fits as itsfittingPolicy.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths. Unset values stay under automatic planning.assay_type (
str|Mapping[str,str] |None) – Preset assay type, such asRNA, for an assay whose name is not a preset, or a mapping of assays to types. When None, the assay name decides the type.overwrite (
bool) – Replace an existing CyteArc store that noDataStorehas opened.values (
Union[Literal['counts','normalized','log_normalized','log2_normalized'],Mapping[str,Literal['counts','normalized','log_normalized','log2_normalized']],None]) – What a matrix holds,"counts","normalized","log_normalized"or"log2_normalized", as the import reference’s normalized values section describes, or a mapping of assays to these. None decides from the values.shuffle_cells (
bool) – If True, the default, write the cells in a uniformly random order, so that any contiguous slice of the store, such as one shard or a training mini-batch, is a random sample of its cells. Every assay’s counts and the cell IDs follow the one order, and each cell keeps its row in the matrices, from 0, in the int64 cell columnsourceRow. The matrices are in memory, so each batch gathers its rows from them; nothing is written to temporary files. False writes the cells in the matrices’ order.shuffle_seed (
int) – The seed of the shuffle, from 0 to 2**64 - 1. One seed gives the same order on every platform.
Each assay’s counts are stored in the dtype that
count_storage_dtype()resolves from the canonical (duplicate-summed) values of its matrix, and each takes its own count layout. Every matrix stays in memory until the import ends, so each assay’s plan charges the others’ matrices too.- Raises:
ValueError – Raised if number of input cell or feature IDs does not match a matrix, if an ID is missing, blank, or repeated, if a matrix is not two-dimensional, if a count is NaN or infinite, or if a per-assay argument names an assay that the matrices do not.
TypeError – If per-assay arguments are mappings beside a single matrix, or
feature_idsis not a mapping beside a mapping of matrices,shuffle_cellsis not a boolean, orshuffle_seedis not an integer.FileExistsError – If
zarr_locis not empty and may not be replaced.MemoryBudgetError – If
mem_budgetcannot hold the check of the cell or feature IDs, which checks a copy of their NumPy text and first makes IDs that are not unicode text Python strings and then NumPy text, the shuffle of the cells whenshuffle_cellsis True, or the write of the cell table’s IDs and names, a block at a time, each beside the matrices and the import’s array of the cell IDs. Each is refused before it runs and before the destination exists, naming the budget that holds it.
- assayNames#
The names of the output assays, in the order written.
- mat#
The input CSR matrix, or a mapping of assay names to them.
- assayName#
The name of the output assay of a single matrix, or None for a mapping of matrices.
- z#
The Zarr hierarchy (array or group).
- values#
What the assay holds, or a mapping of assay names to it, decided before the store was created.
- policy#
The count-matrix layout that the assay was written with, or a mapping of assay names to it.
- shuffleCells#
Whether the import shuffles the cells.
- shuffleSeed#
The seed of the shuffle.
- dump(batch_size=None)#
Write out each assay’s matrix into the Zarr hierarchy, one assay at a time.
- Parameters:
batch_size (
int|None) – Number of source cells per batch, at most one destination row band, which is the default.- Raises:
ValueError – If
batch_sizeis not positive.- Return type:
None- Returns:
None
- class cytearc.writers.CSVtoZarr(cr, zarr_loc, assay_name, workspace=None, storage_options=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None, assay_type=None, *, overwrite=False, values=None, shuffle_cells=True, shuffle_seed=0)#
A class for converting data from CSV format to a Zarr hierarchy.
- Parameters:
cr (
CSVReader) – A CSVReader objectzarr_loc (
str|Store) – The file name for the Zarr hierarchy.assay_name (
str) – A label for the assay. Ex. “RNA” or “ATAC”workspace (
str|None) – Workspace name in the destination store. None uses the legacy layout without a workspace group.storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.mem_budget (
int|str|None) – Memory available to the conversion. Accepts bytes, a suffixed size (e.g. ‘8G’), or a fraction of total system memory (e.g. ‘0.6’).nthreads (
int|None) – Worker count for write-time concurrency. When None, auto-detected.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
Union[CountMatrixPolicy,Literal['fit'],None]) – Count-matrix layout: aCountMatrixPolicy, used exactly; None, the default layout; or"fit", the largest halving of the defaultunitBytesandchunkByteswhose counts write andcountsTfitmem_budget. A policy or the default that does not fit raisesCountLayoutMemoryError, aMemoryError, before the destination is created, with the largest halving that fits as itsfittingPolicy.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths. Unset values stay under automatic planning.assay_type (
str|None) – Preset assay type, such asRNA, for an assay whose name is not a preset. When None, the assay name decides the type.overwrite (
bool) – If True, replace a CyteArc store that noDataStorehas opened.values (
Union[Literal['counts','normalized','log_normalized','log2_normalized'],Mapping[str,Literal['counts','normalized','log_normalized','log2_normalized']],None]) – What the matrix holds,"counts","normalized","log_normalized"or"log2_normalized", as the import reference’s normalized values section describes. None decides from the values.shuffle_cells (
bool) – If True, the default, write the cells in a uniformly random order, so that any contiguous slice of the store, such as one shard or a training mini-batch, is a random sample of its cells. The counts, the cell IDs and thecell_data_colscolumns follow the one order, and each cell keeps its row in the file, from 0, in the int64 cell columnsourceRow. Before the store is created, the writer reads the file’s rows, as its counts write would, sending each to temporary files on local disk, intemp_dirof the reader, and keeping the cell columns in memory; the counts write then reads the rows from those files. False writes the cells in the file’s order.shuffle_seed (
int) – The seed of the shuffle, from 0 to 2**64 - 1. One seed gives the same order on every platform.
The counts are stored in the dtype that
count_storage_dtype()resolves from the range the reader found in its first pass over every row. A count that the stored dtype cannot hold raises instead of wrapping.- Raises:
FileExistsError – If
zarr_locis not empty and may not be replaced.TypeError – If
shuffle_cellsis not a boolean, orshuffle_seedis not an integer.ValueError – If
shuffle_seedlies outside its range, or a shuffled import finds that the file no longer holds the rows that the reader counted.OSError – If
shuffle_cellsis True and the temporary disk lacks room for the shuffled rows.MemoryBudgetError – If
mem_budgetcannot hold a step beside the cell IDs and thecell_data_colscolumns that the import holds: for a shuffle, drawing the order, and one chunk of rows and their spill beside the order and its inverse; the counts write and itscountsTtranspose; and the writes of the cell table’s IDs and names, a block at a time, and of the cell columns. Each is refused before the store is created, naming the budget that holds it.
- csvr#
A CSVReader object
- z#
The Zarr hierarchy (array or group).
- policy#
The count-matrix layout that the assay was written with.
- shuffleCells#
Whether the import shuffles the cells.
- shuffleSeed#
The seed of the shuffle.
- dump()#
Writes the count values into the Zarr matrix.
A shuffled import reads its shuffled rows once, deleting them as it goes, and removes them once the counts are written or the write fails, so it writes its counts once.
- Raises:
OverflowError – If a count no longer fits the stored dtype because the file changed after the reader’s pass.
ValueError – If the file no longer holds the rows that the reader’s pass counted.
RuntimeError – If the shuffled rows of this import were already written.
- Return type:
None- Returns:
None
- class cytearc.writers.SubsetZarr(zarr_loc, assays, in_workspace=None, out_workspace=None, cell_key=None, cell_ids=None, reset_cell_filter=True, overwrite_existing_file=False, storage_options=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None)#
Split Zarr file using a subset of cells.
- Parameters:
zarr_loc (
str|Store) – Path for the output (subsetted) Zarr fileassays (
list[Any]) – Source assays to be subsetted. These assays must be from the same DataStorein_workspace (
str|None) – Source workspace name (None for legacy layout).out_workspace (
str|None) – Target workspace name in the output Zarr file.cell_key (
str|None) – Name of a boolean column in cell metadata. The cells with value True are included in the subset. Pass cell_key or cell_ids, not both. A column without True values writes a subset without cells.cell_ids (
Sequence[str] |ndarray|None) – IDs of the cells to include in the subset, such as values ofds.cells.fetch_all("ids"): at least one, each a cell of the store, given once. The subset keeps the cells in store order, whatever order the IDs come in.reset_cell_filter (
bool) – If True, then the cell filtering information is removed, i.e. even the filtered out cells are set as True as in the ‘I’ column. To keep the filtering information set the value for this parameter to False. (Default value: True)overwrite_existing_file (
bool) – If True, replaces an existing CyteArc store that noDataStorehas opened. (Default value: False)storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.mem_budget (
int|str|None) – Memory available to the conversion. Accepts bytes, a suffixed size (e.g. ‘8G’), or a fraction of total system memory (e.g. ‘0.6’).nthreads (
int|None) – Worker count for write-time concurrency. When None, auto-detected.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
CountMatrixPolicy|None) – Count-matrix geometry policy, used exactly for every assay. When None, each assay uses the default policy with unitBytes and chunkBytes halved together until its subset write and countsT transpose fitmem_budget. Either way, a subset that does not fit raises MemoryError before the destination is created.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths. Unset values stay under automatic planning.
Each assay keeps the dtype of its source counts, so the subset holds the source values exactly.
- Raises:
FileExistsError – If
zarr_locis not empty and may not be replaced.
- dump()#
Write subsetted cell metadata and count matrices, including RNA
countsT.- Return type:
None- Returns:
None
- cytearc.writers.to_h5ad(assay, h5ad_filename, embeddings_cols=None, skip_recalc_nfeats=True, nthreads=4, *, run=None, matrix='raw', cell_selection=None, obsm=None, obs=None, graph=None, dtype=None, cell_order='source', temp_dir=None)#
Save an assay or a completed pipeline run as an H5AD file.
The file is streamed block by block with h5py and needs no AnnData. Cells are written in the order of the file that the store imported, by default, as their
sourceRowrecords it; a store that holds nosourceRowis in that order already. Its counts are read in store order and sent to their rows of the file through temporary files on local disk, intemp_dir, about the size of the counts in the file, each deleted once its rows are written. The export takes the number of stored values first, from the store’s count summaries, or in a pass over the counts when they can be negative in a store written by an earlier CyteArc version, and raisesOSErrorbefore it writes a row whentemp_dirlacks the disk that the files take.cell_order="stored"writes the cells in store order and needs no temporary files. Rows that a nullable metadata column’s linked missing mask flags are written as missing values: NaN in a float64 column for numeric columns, a nullable boolean for boolean columns, and a missing category for other columns. A categorical column, which a store keeps as codes beside its categories, is written with AnnData’s categorical encoding from its codes and categories: every category in its stored order, unused ones included, itsorderedflag, and code -1 in its missing rows. A column that keeps a source categorical’s categories, as H5AD and Seurat imports store them, is written as that categorical, with its category order, unused categories, andorderedflag. Either takes the colors of itsdisplayinuns["<column>_colors"]. A column that AnnData reserves,_index, exports assource_index, and a column whose name the export already uses, such as agene_short_namebeside the feature names, takes the next free_2name, with a warning.- Parameters:
assay (
Any) – Assay to save in H5ad formath5ad_filename (
str) – Name for the H5ad file to be created.embeddings_cols (
list[str] |None) – Cell-metadata column prefixes treated as embeddings (for example UMAP, tSNE). When None, uses["UMAP", "tSNE"]. Pass an empty list to skip embeddings.skip_recalc_nfeats (
bool) – Skip a preliminary count of the stored values, for which the file’s arrays are allocated: from the store’s count summaries, or in a pass over counts that can be negative in a store written by an earlier CyteArc version. An export in source order counts them either way, once. (Default value: True)nthreads (
int) – Threads that read the counts and compress them into the file. (Default value: 4)run (
object|None) – Completed pipeline run opened from the datastore that ownsassay. The frozen run selections and fields are exported. Consecutive frozen UMAP fields are inobsm['X_umap']and the run’s PCA inobsm['X_pca'], as into_anndata(run=...); cluster labels, such asclustersandparis, are categoricals inobs, and so are thesnapshot_columnswhose order and colors the run records, in that order, with those colors. Live embedding columns, a cell selection, and feature-count recalculation options do not apply to run export, which reads and compresses on the threads of the run’s datastore.matrix (
Literal['raw','normed']) –"raw"counts, or"normed"values, which requirerun: the run’s stored normalized values over its highly variable features.cell_selection (
ArtifactRef|None) – Cell-selection artifact whose cells are exported. None exports every cell of the assay.obsm (
Mapping[str,ArtifactRef|tuple[ArtifactRef,str]] |None) – Artifacts to export asobsmarrays, such as{"X_pca": pca, "X_umap": umap}.obs (
Mapping[str,ArtifactRef|tuple[ArtifactRef,str]] |None) – Cell-aligned artifacts to export asobscolumns, such as{"leiden": leiden}; labels become categoricals.graph (
ArtifactRef|None) – Connectivity map or integrated graph to export asobsp["connectivities"]andobsp["distances"]withuns["neighbors"], over exactly the exported cells.dtype (
Any|None) – Dtype of the exported raw counts, inXand every layer. None keeps the stored dtype, except thatuint8anduint16counts becomefloat32. A count that the dtype cannot hold raisesOverflowError.cell_order (
Literal['source','stored']) –"source"writes the cells in the order of the imported file,"stored"in store order.temp_dir (
str|PathLike[str] |None) – Directory of the temporary files of an export in source order. None uses the system’s temporary directory.
- Return type:
None- Returns:
None
Every artifact is resolved and aligned to the exported cells before anything is written, so a misaligned artifact raises
ValueErrorand leaves no file.
- cytearc.writers.to_mtx(assay, mtx_directory, compress=False, *, cell_order='source', temp_dir=None)#
Save an assay as a Matrix Market directory.
The features file holds a feature ID, name, and type column, as Cell Ranger 3 writes them, whether or not it is compressed, so an import keeps the assay’s type:
features.tsv.gzwithcompress=True, andgenes.tsv, the Cell Ranger 2 name, without compression. Every feature takes one type: the assay’sfeature_typecolumn when every feature holds the same value, such asAntibody Capture, elseGene Expressionfor an RNA assay and the assay name for another, so gene biotypes that CELLxGENE keeps infeature_typedo not split the assay on import. Withcompress=True, the three files are compressed with gzip level 6.Cells are written in the order of the file that the store imported, by default, as their
sourceRowrecords it; a store that holds nosourceRowis in that order already. The entries are sorted by cell, then feature. Counts are read in store order and sent to their cells’ rows through temporary files on local disk, intemp_dir, each deleted once its rows are written.cell_order="stored"writes the cells in store order and needs no temporary files.Each of the three files is written to a temporary file in
mtx_directoryand moved onto its name once all three are complete, so a failed export leaves no partial file, keeps the files that the directory held, and removes the directory if it made it. A replaced file keeps its permissions.- Parameters:
assay (
Any) – CyteArc assay. For example: ds.RNAmtx_directory (
str) – Out directory where MTX file will be saved along with barcodes and features filecompress (
bool) – If True, then the files are compressed and saved with .gz extension, using Cell Ranger 3 names. (Default value: False).cell_order (
Literal['source','stored']) –"source"writes the cells in the order of the imported file,"stored"in store order.temp_dir (
str|PathLike[str] |None) – Directory of the temporary files of an export in source order. None uses the system’s temporary directory.
- Return type:
None- Returns:
None
- Raises:
UnmeasuredCellsError – If the assay did not measure a cell.
MemoryBudgetError – If an export in source order cannot hold the order of the cells within the assay’s memory budget.
OSError – If the temporary directory lacks the disk that the counts take there.
- cytearc.writers.write_airr_rearrangements(table, path, *, columns=None)#
Write a table of contigs as an AIRR Rearrangement TSV file.
The required fields come first, in the schema’s order, empty when the table lacks them, then the table’s other columns in their order, or
columnswhen given. Values are written as they are, unquoted. A value that holds a tab, a newline or a carriage return, which the AIRR format forbids, is refused before the file is opened, as is a logical field’s value that is not logical, so a refused table leaves no file. A path ending in.gzis gzip-compressed.- Parameters:
table (
DataFrame) – One row per contig, its columns AIRR field names.path (
str|PathLike[str]) – The file to write.columns (
Sequence[str] |None) – The columns after the required fields, or None for the table’s other columns.
- Return type:
- Returns:
The file written, its
rows, the contigs written, and itsdiagnostics, named inAIRR_EXPORT_DIAGNOSTICS, from which it warns of values that start with a double quote or hold characters that the format advises against.- Raises:
TypeError – If
tableis not a DataFrame,pathis not a path, orcolumnsis not a sequence of column names.ValueError – If
tablerepeats a column’s label, holds nosequence_idor asequence_idmore than once, which the schema forbids, a value or a column’s name holds a tab, a newline or a carriage return, a logical field holds a value that is not logical, orcolumnsnames a column more than once or one that the table lacks.
cytearc.writers.airr writes AIRR Rearrangement files one block of contigs at a time, for contigs that do not fit in one table, and names repeated contig IDs from their hashes. Both writers write each value as it is, unquoted, as the AIRR file format asks. A value that holds a tab, a newline or a carriage return raises ValueError, from write_airr_rearrangements before the file is opened and from the writer before any row of its block is written. Values that hold @, #, ' or a double quote past their first character, which the format advises against, are written and counted, outside the Phred scores of quality and quality_alignment, which hold these characters by the format’s own encoding. Values that start with a double quote are counted apart, in every field, since airr’s read_rearrangement, scirpy’s read_airr and pandas’ default reader take such a value for an opening quote and can join or drop rows without an error. The writer counts both in its diagnostics, with their fields, and write_airr_rearrangements returns them in an ExportSummary and warns of each count above 0 with a DiagnosticWarning.
- class cytearc.writers.airr.AirrRearrangementWriter(path, columns=(), *, whole=())#
Write an AIRR Rearrangement TSV file one block of contigs at a time.
Opening the writer writes the header: the required fields, in the schema’s order, then
columnswithout them. Each block is a table of contigs, a DataFrame or a mapping of column names to equal-length values, rendered aswrite_airr_rearrangementsrenders a table: logical fields asTandF, missing values empty, the real-number columns ofwholeas integers, and other values as they are, unquoted. A column may also beEncodedText, whose code for each row names one of its packed values, -1 for a missing value; the values’ bytes are copied without being decoded, and need not be sorted or distinct. A block may lack required fields, which are written empty. A path ending in.gzis gzip-compressed at level 6.A block that holds a value with a tab, a newline or a carriage return, which the AIRR format forbids, is refused before any of its rows is written. Values that hold
@,#,'or a double quote past their first character, which the format advises against, are written as they are and counted, outsidequalityandquality_alignment; values that start with a double quote, which readers that take quotes read as an opening quote, are counted apart, in every field.diagnosticsholds each count and its fields, from which an export warns.The schema requires unique
sequence_idvalues, and the writer writes each block as given, so a caller whose contigs’ IDs may repeat gives the later ones suffixes first, assuffix_repeated_ids()chooses them.writerenders a block and writes its rows;render()renders a block without writing it andwrite_rendered()writes rows that it rendered, so a caller can write the rows of several blocks in another order. Close the writer, or use it as a context manager:with AirrRearrangementWriter("contigs.tsv.gz", ["cell_id"]) as writer: for block in blocks: writer.write(block)
- Parameters:
path (
str|PathLike[str]) – The file to write.columns (
Sequence[str]) – The columns after the required fields.whole (
Collection[str]) – Real-number columns to write as integers, such as counts that pandas reads as floats because one is missing. Decide them from every row before writing, so the blocks agree.
- Raises:
TypeError – If
pathis not a path, orcolumnsis not a sequence of column names.ValueError – If
columnsnames a column more than once, or a name holds a tab, a newline or a carriage return.
- close()#
Close the file; closing again does nothing.
- Return type:
None
- property closed: bool#
Whether the file is closed.
- property columns: tuple[str, ...]#
The columns of the file, in order.
- property diagnostics: dict[str, int | str]#
What the file holds, by the names of
AIRR_EXPORT_DIAGNOSTICSbutrenamedContigIds.contigscounts the rows written,leadingQuoteValuesanddiscouragedValuesthe values thatn_leading_quotesandn_discouragedcount, andleadingQuoteFieldsanddiscouragedFieldsname their fields in the file’s order, such as"v_call, c_call and junction_aa", empty for none.
- property n_discouraged: int#
The values written that hold
@,#,'or an inner".The AIRR format advises against these characters. A double quote counts here past a value’s first character, and values of
qualityandquality_alignmentare not counted.
- property n_leading_quotes: int#
The number of values written that start with a double quote, in any field.
- property n_rows: int#
The number of rows written.
- render(block)#
Render a block of contigs as rows of the file, without writing them.
The block’s values that
diagnosticscounts are counted aswrite()counts them, and its rows oncewrite_rendered()writes them.- Parameters:
block (
DataFrame|Mapping[str,Any]) – One row per contig, its columns AIRR field names.- Return type:
tuple[ndarray,ndarray]- Returns:
The rows’ bytes, each row ending with a newline, and the offset of each row in them, the last their end.
- Raises:
ValueError – As
write()raises it.
- write(block)#
Write a block of contigs.
- Parameters:
block (
DataFrame|Mapping[str,Any]) – One row per contig, its columns AIRR field names.- Return type:
int- Returns:
The number of rows written.
- Raises:
ValueError – If the writer is closed,
blockholds nosequence_id, lacks a column after the required fields, holds columns of different lengths or, as a DataFrame, repeats a column’s label, a logical field holds a value that is not logical, or a value holds a tab, a newline or a carriage return; the block is then not written.
- cytearc.writers.airr.suffix_repeated_ids(hashes, ids_at)#
Give each later occurrence of a repeated contig ID a unique suffix.
The schema requires unique
sequence_idvalues, but Cell Ranger names contigs<barcode>_contig_<n>in the TCR and the BCR files alike. In row order, the second occurrence of an ID gets_2, the third_3and so on; a suffixed ID that some row holds, or that an earlier occurrence took, takes the next number instead. The IDs are compared by their hashes, and only the rows whose hashes repeat, or equal the hash of a suffixed ID, are read as text, so a collision never merges two IDs.- Parameters:
hashes (
ndarray) – Thesequence_id_hashesof every row’s ID, in row order.ids_at (
Callable[[ndarray],ndarray]) – Return the IDs of rows, as text, given their positions in ascending order.
- Return type:
tuple[ndarray,ndarray]- Returns:
The rows whose ID repeats an earlier row’s, ascending, and their new IDs.
- cytearc.writers.airr.sequence_id_hashes(ids)#
Return a 64-bit hash of each contig ID, as
suffix_repeated_idstakes.- Parameters:
ids (
Any) – Contig IDs as text.- Return type:
ndarray- Returns:
The hashes as uint64.
- cytearc.writers.airr.AIRR_REQUIRED_FIELDS = ('sequence_id', 'sequence', 'rev_comp', 'productive', 'v_call', 'd_call', 'j_call', 'sequence_alignment', 'germline_alignment', 'junction', 'junction_aa', 'v_cigar', 'd_cigar', 'j_cigar')#
The fields that every AIRR Rearrangement file holds, in order.
- cytearc.writers.airr.AIRR_LOGICAL_FIELDS = frozenset({'complete_vdj', 'full_length', 'high_confidence', 'is_cell', 'productive', 'rev_comp', 'stop_codon', 'vj_in_frame'})#
The logical fields, written
TandF.
- cytearc.writers.chunked_to_zarr(df, z, loc, nthreads, msg=None, mirror=None, resources=None)#
Creates a Zarr hierarchy from a chunked array.
- Parameters:
df (
Any) – ChunkedArray to materialize and write.z (
Group) – Root Zarr group.loc (
str) – Array path within the group.nthreads (
int) – Threads for block compute.msg (
str|None) – Progress bar message (default:Writing data to {loc}).mirror (
Array|None) – Optional second array of the same shape to write each band into during the same pass (local staging cache).resources (
ResourceBudget|None) – Optional memory and worker budget for the write.
- Return type:
None
- cytearc.writers.create_zarr_dataset(g, name, chunks, dtype, shape, overwrite=True)#
Creates and returns a Zarr array.
- Parameters:
g (
Group) – Parent Zarr group.name (
str) – Array name within the group.chunks (
tuple[int,...] |int) – Chunk shape, or a single integer applied to every axis.dtype (
Any) – NumPy dtype for the array.shape (
tuple[int,...]) – Array shape.overwrite (
bool) – If True, replace an existing array of the same name.
- Return type:
Array- Returns:
A Zarr Array.
- cytearc.writers.create_zarr_obj_array(g, name, data, dtype=None, overwrite=True, chunk_size=100000, shape=None)#
Creates and returns a metadata column array.
- Parameters:
g (
Group) – Parent Zarr group.name (
str) – Array name within the group.data (
Any) – Values to write, one per row, or None to create an empty array.dtype (
str|Any) – Optional dtype. Inferred fromdatawhen omitted.overwrite (
bool) – If True, replace an existing array of the same name.chunk_size (
int) – Chunk length along the first axis.shape (
int|None) – Explicit length whendatais None.
- Return type:
Array- Returns:
A Zarr Array.
- Raises:
ValueError – If
datais not one value per row, such as a single value or a two-dimensional array, before anything is written.
- cytearc.writers.create_zarr_count_assay(z, assay_name, workspace, n_cells, feat_ids, feat_names, dtype, *, profile=None, policy=None, normalized_values=None)#
Creates and returns a Zarr array with name ‘counts’.
- Parameters:
z (
Group) – Root Zarr group.assay_name (
str) – Assay group that will own the counts array.workspace (
str|None) – Workspace name. None uses the legacy layout.n_cells (
int) – Number of cells (rows).feat_ids (
ndarray|list[str]) – Feature identifiers written to feature metadata.feat_names (
ndarray|list[str]) – Feature display names written to feature metadata.dtype (
Any) – Storage dtype for counts. Import writers store the dtype thatcount_storage_dtype()resolves from the canonical values.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile. When None, chosen from the store.policy (
CountMatrixPolicy|None) – Count-matrix geometry policy. When None, the default plan is used.normalized_values (
Mapping[str,Any] |None) – ThenormalizedValuesrecord, such as{"importedAs": "normalized", "cellTotal": None}, of an assay whose values were normalized before import, so that steps that need counts refuse it. None declares counts. Log values must be written linear, with the log undone.
- Return type:
Array- Returns:
The created
countsarray.
- cytearc.writers.subset_assay_zarr(zarr_loc, in_grp, out_grp, cells_idx, feat_idx, storage_options=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None)#
Selects a subset of the data in an assay in the specified Zarr hierarchy.
- Parameters:
zarr_loc (
str|Store) – The file name for the Zarr hierarchy.in_grp (
str) – Array in Zarr hierarchy to subset.out_grp (
str) – Path of a new array in Zarr hierarchy to write subsetted assay to.cells_idx (
ndarray) – Distinct non-negative indices of the cells to keep, in the order of the subset’s rows.feat_idx (
ndarray) – Distinct non-negative indices of the features to keep, at least one, in the order of the subset’s columns.storage_options (
dict[str,Any] |None) – Backend options passed when opening the Zarr store.mem_budget (
int|str|None) – Memory available to the conversion. Accepts bytes, a suffixed size (e.g. ‘8G’), or a fraction of total system memory (e.g. ‘0.6’).nthreads (
int|None) – Worker count for write-time concurrency. When None, auto-detected.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
CountMatrixPolicy|None) – Count-matrix geometry policy, used exactly. When None, the default policy is used with unitBytes and chunkBytes halved together until the subset write fitsmem_budget. Either way, a subset that does not fit raises MemoryError beforeout_grpis created.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths. Unset values stay under automatic planning.
The subset keeps the dtype of the source counts.
- Return type:
None- Returns:
None
- Raises:
FileExistsError – If
out_grpexists or its parent group holds counts.
- cytearc.writers.write_renorm_subset_to_zarr(assay, cell_idx, feat_idx, z, loc, nthreads, log_transform=False, msg=None, mirror=None)#
Write library-size normalized subset data in a single scattered read pass.
For HVG subsets the per-cell scale factor is the row sum within each block, so a separate
counts.sum(axis=1)pass is not needed before writing.- Parameters:
assay (
Any) – Source assay providing counts and library sizes.cell_idx (
ndarray) – Cell indices to write.feat_idx (
ndarray) – Feature indices to write.z (
Group) – Destination Zarr group.loc (
str) – Array path within the group.nthreads (
int) – Threads for block compute.log_transform (
bool) – If True, write log1p normalized values.msg (
str|None) – Optional progress message.mirror (
Array|None) – Optional second array of the same shape written in the same pass.
- Return type:
None
Selection and layout behavior#
cytearc.datastore.datastore.DataStore.to_anndata() supports cell selection plus either feature_names or feature_indexes.
The two feature selectors are mutually exclusive.
to_anndata needs the optional anndata package and raises ImportError without it; install it
with pip install 'cytearc[extra]'. to_h5ad writes with h5py, which CyteArc always installs, and
needs no anndata, with or without a run.
SubsetZarr selects cells of one DataStore, the cells of a boolean cell_key column or those that cell_ids names by ID (pass one of the two), and keeps them in store order, whatever order the IDs come in. It retains every feature in each assay it writes.
It keeps the membership column <assay>_I of each assay it writes, for the selected cells, and
does not copy the membership column of an assay that assays= leaves out
(Assay membership).
Without a run, to_h5ad and to_mtx export a complete assay; to_h5ad(..., cell_selection=ref)
exports the cells of a cell-selection artifact instead.
For feature-selective disk export outside a pipeline run, call to_anndata and use AnnData’s
writer.
to_mtx writes a feature ID, name, and type column in the features file whether or not it
compresses, features.tsv.gz with compress=True and genes.tsv without, so CrDirReader
reads an ADT export back as ADT. With compress=True it compresses the matrix, barcode and feature files with gzip level 6.
to_mtx writes each of its three files to a temporary file in the directory and moves it onto its name once all three are complete, so a failed export leaves no partial file, keeps the files that the directory held, and removes the directory if it made it; a replaced file keeps its permissions.
A Matrix Market directory holds no cell metadata, so to_mtx cannot say which cells an assay
measured, and a cell that it did not measure would be written as a zero row that MtxToZarr
reads back as a measured cell. to_mtx therefore raises
UnmeasuredCellsError before it writes anything when the
assay’s membership column <assay>_I marks a cell unmeasured (Assay membership). Export
the measured cells from a subset that SubsetZarr(..., cell_key="<assay>_I") writes, or use
to_h5ad or to_anndata without layers, which declare the membership.
to_h5ad streams the matrix into the file one block of rows at a time, so it never holds the
complete matrix, and it converts a dense block to CSR a bounded step of rows at a time, which the
block’s stream charges against the memory budget.
It compresses the stored values and column indices with gzip, as h5py’s gzip filter does, on nthreads threads, or on the datastore’s threads for a run, and the file is the same for any number of threads. Column indices are stored as 32-bit integers when every feature’s index fits one, as SciPy and AnnData keep them, and row offsets as 64-bit integers.
It writes a temporary file in the same directory
and moves it onto the target once complete, so a failed export leaves no partial file and keeps an
earlier file of the same name; a replaced file keeps its permissions. Without a run, text without missing values is a string array and
both indexes are stored as _index. A column named _index, which AnnData reserves, as stores
imported before this release may hold, exports as source_index, and a column whose name the
export already uses, such as a gene_short_name beside the feature names that to_h5ad writes
under that name, takes the first free <name>_2, with a warning; the store is not changed.
A categorical column, which a store keeps as codes beside its categories, exports as an AnnData categorical of those codes and categories. to_anndata returns a pandas Categorical of the codes of the exported cells or features, and to_h5ad writes them with AnnData’s categorical encoding; both keep every category in its stored order, unused ones included, and the column’s ordered flag, and a missing row takes code -1. The reserved entry that a store adds when the categories number exactly its rows is no category, so no export holds it. An H5adToZarr import of such a file stores its column as the same codes and categories, with the same labels and fingerprints. A run export reads the labels that its run froze, so its fields follow the run’s own rules below.
A column of labels that keeps a source categorical’s levels and ordered attributes, as H5AD and Seurat imports store them, exports as that categorical, with its category order, unused categories, and ordered flag. A value that the levels do not list is appended to the categories with a warning. Either kind of categorical writes the colors of its display attribute as uns["<column>_colors"] in category order.
Cell order in exports#
A shuffled store holds its cells in random order, which no file holds. to_h5ad, to_mtx, to_anndata, clones.export_clones, clones.export_characters and repertoire.export_airr therefore write the cells in the order of the file that the store imported, sorted by their sourceRow, unless cell_order="stored" asks for store order. A shuffled import exported this way gives back its file: the same X, obs, obsm and var, in the file’s order, as an import in the file’s order exports. A reader that dropped cells, such as CrH5Reader with is_filtered=False, gives back the cells it kept, in the file’s order. A store without sourceRow, such as one imported before imports could shuffle, is in its file’s order already and exports alike under either value. A subset, a repack and a mount keep each cell’s sourceRow, so their exports keep the file’s order with the cells they hold, and a merge writes each cell’s row in the concatenation of its sources (Merge). The exported cells’ artifacts, the obsm and obs entries and the graph of Artifacts in exports, and a run’s frozen fields follow the same order, and a graph’s connectivities and distances are permuted on both axes. Exports write no sourceRow column: the file is in that order, and an import of it records its own. A plain column of that name, which no import wrote, exports as any other column.
to_anndata and the clone exports gather the cells into the file’s order in memory. to_h5ad and to_mtx read the counts in store order, the fastest, and send each row to its place in the file through temporary files on local disk, in temp_dir, the system’s temporary directory by default. The files take about one byte per stored count, and each is deleted once its rows are written; a 1 million cell export of 1.7 billion counts wrote 1.8 GB of them beside a 4.3 GB file, so the export needs no disk beyond its file. On 8 CPUs, sending its rows through the files made that export take 148 seconds against 130 seconds in store order, 14% longer: the rows are converted and sent to their buckets while they stream, and compressed into the file on every thread once they come back, which an export in store order does while it reads. The export refuses before it writes anything when the memory budget cannot hold 25 bytes for each exported cell beside one step of converted rows, or the reading back of a row of every feature; cell_order="stored" needs neither. Before the first row is written to the temporary files, the export counts the values that it writes and checks the free disk there against a quarter more than they take at the bytes per value of the first rows, and 33 bytes for each cell: its place and length in the files and their record of it. The values are counted from the summaries that the store keeps of each cell. The values of a pipeline run, and counts that can be negative in a store written before the summaries counted them, take one more read of the values, which makes the export about an eighth longer. A failed export removes its temporary files, and neither to_h5ad nor to_mtx leaves a partial file. repertoire.export_airr renders its rows in store order and sends them to their places through the same kind of temporary files, in its own temp_dir, which hold the rows uncompressed, about the size of the file without gzip, while it holds a few of its blocks of rows (Export AIRR Rearrangement files).
Exported raw counts take the dtype that dtype names. Without it they keep the stored dtype,
except that uint8 and uint16 counts become float32: arithmetic on narrow unsigned integers
wraps silently, as X * 300 does in uint16, and numpy.log1p of uint8 returns float16,
while float32 holds every such count exactly and is the dtype that Scanpy’s readers return. A
count that an explicit dtype cannot hold raises OverflowError.
Nullable metadata columns keep a stored placeholder in each row that their linked missing mask flags. to_anndata and to_h5ad export those rows as missing values with or without run: numeric columns become float64 with NaN, boolean columns become nullable booleans, and other columns hold a missing value, which H5AD files store as a missing category. A column of dates or durations keeps its missing values as NaT, without a mask. to_anndata keeps such a column as pandas dates or durations, whose NaT pandas reads as missing, and to_h5ad, since AnnData stores no dates or durations, writes each value as the text that NumPy writes for it and each NaT as a missing category.
Artifacts in exports#
to_anndata and to_h5ad, with or without a run, export artifacts beside the cells:
adata = ds.to_anndata(
cell_selection=cells,
obsm={"X_pca": pca, "X_umap": umap},
obs={"leiden": leiden, "s_score": (cell_cycle, "s_score")},
graph=graph,
)
cytearc.to_h5ad(ds.RNA, "analysis.h5ad", cell_selection=cells, obsm={"X_pca": pca})
obsm takes two-dimensional per-cell arrays, such as a reduction, a batch_correction,
imported_coordinates, or an embedding. The entry named X_pca also writes the loadings of a
PCA as varm["PCs"], with a row per exported feature and zeros for features that the PCA did not
use, as Scanpy stores them; imported coordinates with a stdev add uns["pca"]["variance"].
obs takes one-dimensional per-cell arrays: labels, such as a clustering, become categoricals of
text labels in natural order, or of the categories and colors that imported labels keep, and
scores stay numbers. A pair (ref, name) exports another per-cell array of an artifact. Every
artifact must hold every exported cell; ValueError names the remedy otherwise, which is to export
the cells of its cell selection with cell_selection=.
graph, a connectivity_map or integrated_graph built over exactly the exported cells, becomes
obsp["connectivities"], the fuzzy union W + W.T - W * W.T of its directed weights, which
CyteArc’s UMAP reads and Scanpy expects to be symmetric, and, for a connectivity map,
obsp["distances"], its KNN distances with k entries per cell. uns["neighbors"] follows
Scanpy’s layout: connectivities_key, distances_key, and params with n_neighbors (k + 1,
because Scanpy counts each cell among its own neighbors), method, metric, and use_rep when
the graph’s coordinates are also exported in obsm. Exporting a graph holds about 96 bytes per
stored edge, which is checked against the memory budget. uns["cytearc"]["artifacts"] records the
reference of every exported artifact by element, such as uns["cytearc"]["artifacts"]["obsm"]["X_pca"].
The two meanings of matrix="normed" differ. Without a run, to_anndata(matrix="normed")
exports the assay’s normed values of the selected cells and features: for RNA, counts scaled by
each cell’s library size over all of its features to 1,000, without a log transform. A run export
with matrix="normed" exports the run’s stored normalized artifact over the run’s selected
features only, which are then the only features: for an RNA run, log1p of counts scaled over its
highly variable genes, as described below.
Without run, to_anndata and to_h5ad export the membership column <assay>_I of the
exported assay as an ordinary obs column and declare it in uns["cytearc"]["assayMembership"],
for example {"RNA": "RNA_I"}, so H5adToZarr restores it as the membership of an imported
assay of that name and a merged store survives export, import, and a second merge. The membership
columns of other assays, including the assays of to_anndata layers, describe assays that the
file does not hold and are not exported, as a merge or subset that leaves an assay out does not
copy its membership column; an import would otherwise keep them as ordinary metadata, which a
later merge with prepend_text=None that includes those assays would refuse. A run’s frozen fields
declare no membership. Because a layer of another assay cannot declare its membership, every
exported cell must be one that the layer’s assay measured: to_anndata with such a layer, with or
without run, raises UnmeasuredCellsError before it reads any value, and a cell_key of the
cells that the layer’s assay measured exports them. A layer of the exported assay is declared with
it.
Pass a completed run to write its frozen cells, feature universe, and result fields directly:
cytearc.to_h5ad(ds.RNA, "analysis.h5ad", run=run)
cytearc.to_h5ad(ds.RNA, "analysis_normalized.h5ad", run=run, matrix="normed")
The assay must be the run’s assay, run.assay, as the exact assay object owned by the datastore that opened the run. A run export to a file holds exactly what to_anndata() returns for the same run and matrix, because one resolution of the run’s rows, columns, and values serves both: the run’s cells, its frozen cell fields in obs with the consecutive UMAP fields in obsm["X_umap"], the PCA of an RNA or ADT run in obsm["X_pca"] with the loadings in varm["PCs"] and its Harmony correction, if any, in obsm["X_pca_harmony"], the LSI of an ATAC run in obsm["X_lsi"] and its Harmony correction, if any, in obsm["X_lsi_harmony"], and its frozen feature fields in var. to_anndata holds that object in memory; to_h5ad streams it into the file. The run’s plan decides which fields are categoricals. Label fields, those with a categorical display (clusters, paris, cell_cycle_phase, and the leiden_<resolution> fields of runs of earlier releases), are categoricals whose categories are their labels as text in natural order, with the run’s display colors as uns["<field>_colors"], so that categorical plots and rank_genes_groups(adata, "clusters") use them without conversion. A frozen snapshot_columns field whose run records the column’s order and colors, those of a column with a stored display or stored as ordered (Frozen fields), is a categorical of those categories in that order, unused ones included, with those colors as uns["<field>_colors"], as run plots draw it; the run records no ordered flag, so the categorical is unordered, and runs of CyteArc 1.3.0 and earlier, which record no order, export the column as other text. With the default raw counts in X, run sc.pp.normalize_total and sc.pp.log1p before rank_genes_groups, which expects log-normalized values. Other text that repeats or has missing values is a categorical whose categories are in natural order (d2 before d10, with a superscript or circled digit kept as text), and text missing in every row is a categorical without categories. to_anndata returns those fields as pandas categoricals with exactly those categories, and the file stores the same categories and codes, so the object, the file, and a file that AnnData.write_h5ad writes from the object agree whatever the AnnData version. Other text is a string array, and the indexes are named ids and gene_ids. The export stores X compressed, stores distinct text as a string array, and leaves out empty layers, obsp, uns, varm, and varp groups. embeddings_cols, feature-count recalculation, a cell selection, and a writer-specific thread override apply only to ordinary assay export and are rejected when run is supplied; obsm, obs, and graph add artifacts over the run’s cells, such as graph=run["connectivity_map"].
With matrix="raw", the default, X holds the raw counts of the run’s cells over its feature universe. With matrix="normed", X is the run’s normalized artifact: the float32 values that normalize() stored for the run, over the run’s selected features in stored feature order: the highly variable genes of an RNA run, the prevalent peaks of an ATAC run, or the panel of an ADT run. var then holds the frozen fields of those features only, and to_anndata layers align to them. The values are read in the artifact’s stored row bands and never converted to float64. The export checks that the store’s dataset fingerprint still matches the artifact and raises ValueError when the run has no normalized output, or when the artifact’s cell selection is not the run’s cell selection or its feature selection is not the run’s selected features. A multimodal run has no normalized output and exports with matrix="raw": X holds the raw counts of run.assay, its first source run’s assay, beside the run’s joint fields, and to_h5ad takes that assay as its assay. Without a run, to_anndata(matrix="normed") normalizes the selected cells and features with the assay’s normed, and refuses a feature that the input of an exported cell of a merged store did not measure; to_h5ad rejects matrix="normed".
H5adToZarr.dump() returns an H5adImportResult containing the written assays, analysis assay,
all-cell selection, and imported embedding and clustering refs. Set analysis_assay when a
multi-assay import selects analytical values. Use DataStore.artifacts.load(ref) for payload access
or pass the exact ref to a consumer. Import does not flatten these results into metadata columns.
Ordinary to_h5ad export writes a complete assay and live metadata. Run-aware export reads only
the completed run’s frozen selections and fields, and for normalized values its normalized
artifact, so export does not require physical result columns.
CrToZarr, MtxToZarr, H5adToZarr, SparseToZarr, and SeuratToZarr select source batch
rows automatically when batch_size is omitted, starting from the smallest destination
row-shard height, which the fitted count layout admits. An explicit positive batch_size is
capped at that height.
Merge#
Use DataStoreMerge to merge DataStores.
Pass assays=["RNA"] when only one assay type is needed.
Features are matched by exact feature ID by default. Gene symbols are display labels and do not
merge distinct IDs; suffixes such as _1 are preserved. An assay present in multiple inputs
raises an error if none of its IDs overlap.
Each merged assay holds the union of its inputs’ features by default, features="union", and the cells of an input that lacks a feature get zero counts of it, which an analysis that does not read the record of what each input measured, below, reads as measured. Planning logs a warning for each assay whose inputs measured different features, such as two antibody panels: it gives the number of features that each input lacks and names up to five of them. features="intersection" keeps only the features that every input holding the assay measured. The plan reports the share of the assay’s features that every input measured as featureOverlapFraction, 1 for an intersection. An input whose assay holds no features lacks every feature: the warning names it, and the share is 0, while an assay of no features in any input reports 1. An input without the assay is left out of the warning, the share and the intersection, since its cells are marked as not measured. An intersection that keeps no feature of an assay that has some is refused before anything is written, and one that keeps fewer than a tenth of the inputs’ features logs a warning with both counts and how many it would keep without each input, so an input that shares few features stands out. create_composite takes the same features and gives the same warnings, and a union composite reads zero counts for the features that a source lacks; its warning also names features="intersection", or says that it would keep none.
When the inputs measured different features, the merged feature table records which features each input measured: a Boolean column measured_in_<name> for each input that holds the assay, true for the features that it measured, as a composite’s feature table does too. Read them as any feature column, for example ds.ADT.feats.to_pandas_dataframe(["names", "measured_in_ctrl", "measured_in_stim"]) for inputs named ctrl and stim. The column of an input whose name holds / or \ takes _ in their place, and each column keeps its input’s name in its source attribute; inputs whose columns would differ only in case, such as Ctrl and ctrl, are refused before anything is written, since a file system that ignores case stores the two as one. Beside them, the merge writes each cell’s input in a categorical cell column of the input names, dataset unless source_column names another, which each record column names in its sourceColumn attribute and through which analyses find which features a cell’s input measured; while a record names the column, it cannot be overwritten or dropped. Subsets, repacks, mounts and H5AD exports keep both, and an H5AD export declares the cell column in uns["cytearc"]["cellSources"], so an import restores it with the record. The ADT recipe (Analysis pipeline API reference) leaves the antibodies that some input of the run’s cells did not measure out of its panel and its markers, plots show a feature as missing in the cells of an input that did not measure it (Plotting API reference), and marker search ranks only the features that the input of every selected cell measured; normalization and normalized exports refuse such a feature, feature selection, gene-set, cell-cycle and chromVAR scores, feature percentages, regulatory networks, grouped assays and bulk profiles leave it out, and mapping projects each cell of a merged query on the reference features that its own input measured (DataStore API reference). An input that a merge or a composite wrote with such a record, such as inner merged from left and right, is recorded by its own inputs: inner__left and inner__right, which start the IDs of their cells, become inputs of the merge, each with its own column in each assay that it holds, such as measured_in_inner__left, and each cell keeps its own input in the cell column of inputs, so a run of one study’s cells keeps that study’s antibodies however often its store is merged again. The merged input’s own columns are not copied. A merged store without a record, whose inputs measured the same features, is recorded as one input. An input column of the same name as one of these columns is left out with a warning. A store merged by an earlier release has no such columns, and every input counts as having measured every feature. An earlier release that merges a store holding the columns copies them as ordinary columns, with missing values for the features of its other inputs; a read of the record then names the column and the call that drops it, such as ds.ADT.feats.drop("measured_in_ctrl").
When inputs use different identifier conventions for the same genes, for example Ensembl IDs in
one input and gene symbols in another, pass feature_key="names" to match features by name.
The merged feature IDs are then the names, and features that share a name within one input are
summed.
Feature annotation columns are merged when the inputs agree. A column whose values differ for a shared feature, such as per-dataset highly variable gene flags, is left out with a warning. The same applies when features that share a name within one input disagree. A NaN or NaT is a missing value, which agrees with any annotation, also where another input holds the column as text. Dates, and durations, of different units take the finest of the units, as cell columns do.
A merge and a composite interleave the cells of their sources at random, and each source gives its cells in the order that it stores them, from a random first cell on and then from its first stored cell up to that one. Pair per-cell values with their cells by cell ID, {name}__{cell_id}, or by sourceRow, each cell’s row in the concatenation of its sources, and never by position. The sources’ cells take turns in the order that the import shuffle with seed gives their concatenation, and seed draws each source’s first cell too, so every contiguous slice of the merged rows holds each source’s cells in proportion to the cells that it gives. When the sources list their cells in random orders of different seeds, as their cellOrder records state, the merged order is uniformly random: every contiguous slice is a random sample of the merged cells, and the merged cell table records the shuffle in its cellOrder attribute, with the seed of the interleaving. The rule compares only the seeds that the merge’s own sources record, and a merged source records the seed of its own interleave, so a merge of merges does not look at the import seeds beneath them. Sources that an import shuffled with one seed, as default imports share shuffle_seed=0, list each file row at about the same place; the random first cells set them apart, so their merge is close to uniform, and it records no shuffle. Close is not exact: two sources of 50 cells that share a seed list their file rows in one order, which the first cells only shift against each other, and over 3,000 such merges the count of a group in the first 20 merged cells departs from the hypergeometric law of a random sample (chi-square p = 7e-6). A source in its file’s order keeps that order from its first cell, so the cells that a slice takes from it come from one stretch of its file, and the merged store records no shuffle. A contiguous slice of a composite reads about one stored shard of every source, since its cells come from every source, so slices of a composite of many sources read more than slices of a merged store, which holds its cells itself. seed is an integer from 0 to 2**64 - 1, 42 by default, and one seed gives one order on every platform; seed=None draws a new order for each merge. create_composite takes no seed and orders the cells that rows selects by the same rule with the merge’s default seed, 42, so a composite of every cell of its sources lists them as a merge of the same sources does. rows selects cells and doesn’t order them: rows={"a": [12, 0, 7, 4]} gives the composite that rows={"a": [0, 4, 7, 12]} gives. A source whose rows entry is empty contributes no cells, but its features still count toward the union or intersection that features asks for. For example, to attach scores, one value for each cell of sources["a"] in its store order, to joint = create_composite(sources, ...):
# Key the scores by the IDs that the cells of source a take in the composite.
ids = sources["a"].cells.fetch_all("ids")
keyed = pd.Series(scores, index=[f"a__{cell}" for cell in ids])
# Line the scores up with the composite's cells; the cells of other sources get NaN.
joint.cells.insert("score", keyed.reindex(joint.cells.fetch_all("ids")))
Each merged cell gets the int64 column sourceRow: its row in the concatenation of the sources, in the order that the merge receives them, each source’s cells in the order that an export of the source writes them. A cell’s sourceRow is the number of cells that the sources before its own hold, plus its rank in its source’s sourceRow, or in its source’s store order when the source holds none, so an export of the merged store in file order writes the exports of its sources one after the other. A source column named sourceRow that no import wrote is replaced with a warning, and source_column cannot be sourceRow. create_composite writes sourceRow alike over the cells that rows selects, and neither copies a source’s sourceRow as an ordinary column such as orig_sourceRow.
Merged cell IDs are {name}__{cell_id}, so source names cannot contain __. Cell metadata columns keep their attributes when the inputs agree, and any other differing attribute is dropped with a warning, except a column’s categories. A column that a source stores as a categorical, or with the levels or categorical display that an import keeps, keeps the categories of the first source that records them, in their order, followed in natural order by the other categories that sources record and the labels of the merged cells, as plots draw the labels that a stored order leaves out; create_composite takes the labels of the cells that rows selects. Categories and labels are compared as the merged column stores them, so where one source holds a column as text and another as integers, the merged column stores text, and the integer 1 and the text "1" are one category. A source that holds the column as floats or dates holds NaN or NaT where a value is missing, and each is a missing row of the merged text column, which its missing mask flags, never a label or category. A column that the sources hold as dates, or as durations, at different units, such as datetime64[s] beside datetime64[ns], takes the finest of the units, as NumPy promotes them, and keeps each NaT, which readers take as missing. A value that the finest unit cannot hold exactly, such as the year 1500 in nanoseconds, or a month between the weeks that months beside weeks take, is refused before the merge writes anything, with an error that names the source’s column and the source, as are durations in months or years beside durations of fixed length, which no unit holds both of. A merged display takes each category’s label and color from the first display that lists it, keeps the color of a later display only when no earlier category has that color, and gives every other category the color that plots generate for its place in the order, or beyond the 102 colors of CyteArc’s palettes the hue that an import gives it, so the display colors every label of the column. The categories stay ordered only when every source stores them ordered in that order. A column of more than 10,000 categories, or of a type that holds no categories, such as dates, keeps its labels alone, as an import keeps a categorical of that many.
Each merged assay keeps the type that its sources declare in assayTypes, such as HTO or
GeneActivity, rather than the preset of its assay class, so a merged HTO assay can be
demultiplexed. Sources that declare different types for one assay are rejected before anything is
written; reopen the source whose declaration is wrong with zarr_mode="r+" and a matching
assay_types.
A merged RNA assay keeps the size factor that its sources normalize with, each session’s sf or, where a session sets none, the factor that the source stores (Library-size normalization), and sources of different size factors are rejected before anything is written; set one on each source, such as ds.RNA.sf = 1000, and merge again. create_composite keeps and checks it alike.
RNA assays write both counts and a gene-major countsT copy, which roughly doubles stored counts for those assays.
Non-RNA assays never write countsT.
Every merged assay gets the membership column <assay>_I described in Assay membership. A
merged cell keeps its source’s membership: False when the source lacks the assay, True when the
source measured every cell with it, and the source’s own value when the source records partial
membership. A source’s membership column is not merged again as an ordinary column such as
orig_<assay>_I, and the membership column of a source assay that assays= leaves out is not
merged at all, so a merge with assays=["RNA"] writes no ADT_I or orig_ADT_I that a later
merge including ADT would trip over. Planning rejects a malformed source membership column, an
ordinary column whose merged name equals a membership column, and a source whose cells outside an
assay have counts of it. A source column named
<assay>_I for a merged assay that lacks the membership attributes raises Cell column '<assay>_I' is reserved for the membership of assay .... Import the file again, which
restores a declared membership and otherwise skips the column with a warning, or drop the plain
column from the source with source.cells.drop("<assay>_I"), after which the source counts every
cell of the assay as measured. MetaData writes no membership column itself: insert,
update_key, and reset_key refuse <assay>_I for any assay of the store, and drop refuses one
that carries the membership role (Assay membership).
The destination must be empty or hold a merge written by DataStoreMerge. A destination that
aliases, contains, or lies inside a source store, or that already holds other content, is refused.
overwrite=True replaces only a merge-owned destination whose assays have not been prepared by
opening it as a DataStore, and it clears the recorded default assay.
Interrupted merges resume at whole-component boundaries (cellData, each assay counts, and each RNA countsT) rather than mid-matrix.
A resume requires the same configuration, the same source counts, assay types, and membership; a
completed countsT whose layout differs from the plan is not rewritten in place. The manifest
must record assayTypes and sourceMembership; without those fields, restart with
overwrite=True. Completed counts keep the layout persisted
with them, so a resume under another mem_budget reuses them, while counts that a resume rewrites
get a layout fitted to its budget.
- class cytearc.merge.DataStoreMerge(datasets, zarr_path, names, *, assays=None, out_workspace=None, overwrite=False, prepend_text='orig', reset_cell_filter=True, seed=42, storage_options=None, source_column=None, mem_budget=None, nthreads=None, profile=None, policy=None, io=None, missing_assay_policy='zero_fill', feature_key='ids', features='union')#
Merge multiple DataStores into one Zarr store.
Construction is side-effect free. Call
plan()to inspect the resolved merge, thendump()to write or resume it.- Parameters:
datasets (
list[Any]) – Source DataStores to merge. At least two are required.zarr_path (
str|Store) – Destination Zarr path or store.names (
list[str]) – Unique name for each source, used in metadata and provenance. Merged cell IDs are{name}__{cell_id}, so a name cannot contain__.assays (
list[str] |None) – Optional assay-name filter. None merges every assay present in any source.out_workspace (
str|None) – Workspace name in the destination store. None uses the legacy layout without a workspace group.overwrite (
bool) – If True, replace a merge-owned destination whose assays have not been prepared by opening it as a DataStore.prepend_text (
str|None) – Prefix joined with_to the name of every cell metadata column copied from the sources, sodonorbecomesorig_donorwith the default, and a column that several sources share is still merged into one column.ids,names,IandsourceRowkeep their names, and the columns derived from a source’s assays, such asRNA_nCountsand the membership columnRNA_I, are computed for the merged store rather than copied. None or""keeps the source names.reset_cell_filter (
bool) – If True, mark every merged cell as selected.seed (
int|None) – Seed of the random order in which the sources’ cells interleave, an integer from 0 to 2**64 - 1. One seed gives one order on every platform. None draws a new order for each merge.storage_options (
dict[str,Any] |None) – Backend options passed when opening the destination.source_column (
str|None) – Cell column that stores each cell’s source name. None writes none, unless the sources measured different features of an assay, when the merge writes the columndataset. Beside a record of which features each source measured, the column is categorical, it names each cell of a merged source by that source’s own source, such asinner__left, and it cannot be overwritten or dropped while the record names it.mem_budget (
int|str|None) – Memory budget for the merge. Accepts bytes, a size such as8G, or a fraction of detected system memory. When None, the tightest source budget is used. The merge reads its sources’ counts within this budget, whatever budgets the sources were opened with.nthreads (
int|None) – Maximum worker budget. When None, the tightest source worker count is used.profile (
Literal['fast_local','cloud'] |None) – Zarr encoding profile (fast_localorcloud). When None, chosen from the destination location.policy (
CountMatrixPolicy|None) – Count-matrix geometry policy, used exactly for every assay. When None, each assay uses the default policy with unitBytes and chunkBytes halved together until its counts write and countsT transpose fitmem_budget. A resumed merge keeps the layout of every assay whose counts are complete, so a change of budget between attempts does not block it.io (
StorageIoPolicy|None) – Optional explicit read, compute, and write widths. Unset values stay under automatic planning.missing_assay_policy (
Literal['zero_fill','error']) –zero_fillwrites zeros for a missing assay in a source.errorrejects that merge.feature_key (
Literal['ids','names']) –idsmatches features across sources by exact feature ID.namesmatches them by feature name, which merges sources that use different ID schemes for the same genes. The merged IDs are then the names, and features that share a name within one source are summed.features (
Literal['union','intersection']) –"union", the default, keeps every feature of any source that holds the assay."intersection"keeps the features that every source holding the assay measured, such as the antibodies that two panels share, logs a warning when they are fewer than a tenth of the union, and refuses to merge when it keeps no feature of an assay that has some.
Merged counts use the common type of the source count dtypes, widened so that features summed by name cannot overflow it.
The number of nonzero values of each cell sizes the batches of the counts write within
mem_budget, and the sources’ count summaries give it. The summaries of stores written by earlier CyteArc versions give it only for unsigned counts, which imports store for whole counts; for signed and float counts of such stores, which can hold negative values, the merge counts the values in a read of the source’s counts, once as it plans and once before it writes. A repack of such a store stores the number.With
features="union", the cells of a source that holds the assay but lacks one of its features get zero counts of that feature. Planning then logs a warning for the assay with the number of features that each such source lacks and up to five of their names, so that a merge of different antibody panels is flagged. When the sources measured different features, the merged feature table records which features each source that holds the assay measured, in a Boolean columnmeasured_in_<name>for each, such asmeasured_in_ctrl, whichds.ADT.feats.to_pandas_dataframe(["names", "measured_in_ctrl", "measured_in_stim"])reads; subsets, repacks and H5AD exports keep them. A name with/or\takes_in their place, and names whose columns would differ only in case are refused before anything is written. The ADT recipe leaves the antibodies that not every source measured out of its panel and its markers. A source that a merge or a composite wrote with such a record, such asinner, merged fromleftandright, is recorded by its own sources:inner__leftandinner__right, each the start of the IDs of its cells, become sources of this merge, each with its own column, such asmeasured_in_inner__left, in each assay that it holds, and each cell keeps its own source in the cell column of sources, so a run of one study’s cells keeps that study’s antibodies however often its store is merged again. The merged source’s own columns are not copied. A merged store without a record, whose sources measured the same features, is recorded as one source. A source column of the same name as one of these columns is left out with a warning.Merged cells interleave the sources’ cells in a random order that
seeddraws, and each source gives its cells in their stored order from a random first cell thatseedalso draws, wrapping round, so every contiguous slice of merged rows holds each source’s cells in proportion to its size. When the sources list their cells in random orders of different seeds, the merged order is uniformly random: every contiguous slice is a random sample of the merged cells, and the merged cell table records the shuffle in itscellOrderattribute. Imports shuffled with one seed, as default imports are, merge close to uniform, and the merge records no shuffle. A source kept in its file’s order keeps that order from its first cell. Pair per-cell values with merged cells by cell ID,{name}__{cell_id}, or bysourceRow, each cell’s row in the concatenation of the sources, and never by position.- dump()#
Write or resume the merge and return a component-level result.
- Return type:
- class cytearc.merge.MergePlan(zarrPath, outWorkspace, sourceNames, nCells, assays, profile, seed, missingAssayPolicy, willResume, canDump, blockedReason, cellDataAction, manifest=<factory>)#
Side-effect-free preview of a DataStoreMerge.
- class cytearc.merge.AssayMergePlan(assayName, assayType, sourcePresent, missingSources, nFeatures, featureOverlapFraction, dtype, chunks, shards, writeCountsT, estimatedWriteTasks, countsAction, countsTAction)#
Resolved plan for one assay in a DataStoreMerge.
featureOverlapFractionis the share of the merged features that every source holding the assay measured. Features match by ID, or by name withfeature_key="names". The merge writes zero counts for the other features in the cells of each source that lacks them, so1.0means that no cell reads a zero count for a feature its source never measured. A source whose assay holds no features measured none of the others’ features, so the assay then reports0.0, while an assay of no features in any source reports1.0. A source without the assay is left out, since the merge marks its cells as not measured, so an assay that only one source holds reports1.0. A merge withfeatures="intersection"keeps only the features that every source holding the assay measured, so it reports1.0.
- class cytearc.merge.MergeResult(zarrPath, nCells, assayNames, components, resumed)#
Result returned by DataStoreMerge.dump().
- class cytearc.merge.ComponentResult(name, action)#
Outcome for one written or skipped merge component.