Convert count files from other tools into CyteArc stores, keep the analysis results that come with them, and export counts and results in formats that Scanpy, Seurat and other tools read. The examples import three public datasets: 1,600 human pancreatic islet cells from Matrix Market files Xin et al., 2016, 3,696 mouse pancreas cells at embryonic day 15.5 from an H5AD file with their published UMAP and eight cell-type labels Bastidas-Ponce et al., 2019, and 8,728 human peripheral blood mononuclear cells (PBMCs) from a 10x Genomics scATAC-seq HDF5 file. The pancreas store then goes back out as Matrix Market and H5AD files, and a latent space computed outside CyteArc comes back in: Leiden clusters built on it agree with those built on CyteArc’s own PCA at an adjusted Rand index of 0.69, and 10 of the 18 PCA clusters keep at least 80% of their cells together.
Each import inspects the source when its layout can vary, opens a reader on it, and writes a store with the matching writer:
| Source | Inspect | Reader | Writer |
|---|---|---|---|
| 10x Genomics HDF5 | CrH5Reader | CrToZarr | |
| Matrix Market or MEX | inspect_mtx | MtxReader | MtxToZarr |
| AnnData H5AD | inspect_h5ad | H5adReader | H5adToZarr |
| Seurat RDS | inspect_seurat | SeuratReader | SeuratToZarr |
| Dense CSV | CSVReader | CSVtoZarr | |
| Matrix in memory | SparseToZarr | ||
| Tapestri DNA and protein HDF5 | TapestriReader | TapestriToZarr |
to_mtx writes Matrix Market files, to_h5ad streams an H5AD file, and DataStore.to_anndata builds an AnnData object in memory. CyteArc writes no Seurat .rds or .h5seurat files; Seurat reads the Matrix Market export with Read10X. CyteArc for Scanpy users and CyteArc for Seurat users map each step of those tools to CyteArc.
Download the example files¶
The example files are in the public CyteBase bucket on Hugging Face. cytearc.datasets.connect("cytearc_docs") opens the bucket’s repository of documentation datasets, whose names follow <author>_<number of cells>_<tissue>_<method>. download_dataset copies one dataset’s files into a directory and returns the directory’s path. This page writes the downloads and every converted store below one temporary directory; use a project directory for your own data.
from pathlib import Path
from tempfile import TemporaryDirectory
import anndata as ad
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import cytearc
# Hide CyteArc's log messages below errors, warnings included, and its progress bars.
cytearc.configure_output(level="ERROR", progress=False)
# Connect to the example datasets and keep this page's files in one temporary directory.
datasets = cytearc.datasets.connect("cytearc_docs")
outputs = TemporaryDirectory()
output_dir = Path(outputs.name)Started: 2026-11-18T00:47:46.034612Z | Wall time: 3.408 s
Import Matrix Market files¶
A Matrix Market import needs three matching files: the count matrix, the feature IDs and names, and the cell barcodes. inspect_mtx searches an .mtx or .mtx.gz file, a directory or a ZIP archive for complete triplets, whether they use 10x names, a common prefix or the Parse Biosciences layout, and reports each triplet’s files and dimensions:
# Download the islet cell files and find each complete matrix, feature and barcode triplet.
mtx_dir = datasets.download_dataset(
name="xin_1K_pancreas_rnaseq", destination=output_dir
)
candidates = cytearc.inspect_mtx(mtx_dir)
# Tabulate each candidate's files and dimensions.
pd.DataFrame(
{
index: {
"matrix file": Path(candidate.matrixPath).name,
"feature file": Path(candidate.featurePath).name,
"cell file": Path(candidate.cellPath).name,
"orientation": candidate.matrixOrientation,
"cells": candidate.nCells,
"features": candidate.nFeatures,
"stored entries": candidate.nEntries,
}
for index, candidate in enumerate(candidates)
}
).rename_axis(columns="candidate")| candidate | 0 |
|---|---|
| matrix file | matrix.mtx.gz |
| feature file | features.tsv.gz |
| cell file | barcodes.tsv.gz |
| orientation | featuresByCells |
| cells | 1600 |
| features | 39846 |
| stored entries | 9160987 |
Started: 2026-11-18T00:47:49.446363Z | Wall time: 0.977 s
The directory holds one triplet of 1,600 cells by 39,846 genes, stored genes by cells as Cell Ranger writes them. Its values are the RPKM values that Xin et al. deposited in GEO, scaled to whole numbers, rather than read counts; an import stores whole numbers as counts. For a source with several triplets, such as raw and filtered matrices, inspect_mtx lists each one and the import reads the candidate passed to MtxReader; pass the filtered one unless you call cells yourself, as Cell calling does.
# Convert the triplet, and open the store with this file's mitochondrial gene names.
mtx_store = output_dir / "xin_1K.zarr"
cytearc.MtxToZarr(cytearc.MtxReader(candidates[0]), zarr_loc=str(mtx_store)).dump()
ds_mtx = cytearc.DataStore(
str(mtx_store), mito_pattern="^(ND[1-6]|ND4L|COX[1-3]|ATP[68]|CYTB)$"
)
ds_mtxDataStore has 1600 (1600) cells with 1 assays: RNA
Cell metadata:
'I', 'ids', 'names', 'RNA_nCounts', 'RNA_nFeatures',
'RNA_percentMito', 'RNA_percentRibo', 'sourceRow'
RNA assay has 39846 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'feature_type',
'nCells'Started: 2026-11-18T00:47:50.426967Z | Wall time: 15.084 s
The store holds the 1,600 cells and 39,846 genes as an RNA assay. Its cell table has each cell’s total (RNA_nCounts), number of detected genes (RNA_nFeatures), mitochondrial and ribosomal percentages (RNA_percentMito, RNA_percentRibo), and its row in the file (sourceRow). The default mito_pattern, ^MT-, finds no gene in this file, which names its mitochondrial protein-coding genes ND1 to ND6, ND4L, COX1 to COX3, ATP6, ATP8 and CYTB, so the first open passes a pattern for those names. A later open keeps the recorded pattern and refuses a different one, so set it on the first open.
The import writes the cells in a random order, the same for every import of the file, so that any contiguous block of the store’s rows is a random sample of the cells rather than the cells of one sample or plate. Exports write the cells back in the file’s order, and shuffle_cells=False keeps the file’s order in the store; Why CyteArc shuffles cells explains what the order guarantees and costs.
I is the cell-table column that marks the active cells, which analyses use by default. The first writable open also removes from I every cell with 10 or fewer detected genes, unless that would remove half of the active cells or more. In the summary, 1600 (1600) gives the active cells and, in parentheses, all cells, so every islet cell stayed active.
Import a Parse Biosciences directory¶
A Parse Biosciences DGE directory holds a cells-by-genes matrix and a cell_metadata.csv table, whose columns other than the cell ID become cell metadata. The reader takes the cell IDs from the bc_wells or the bc_index column; when the table holds both, choose one with cell_id_key:
# Import the Parse triplet with bc_index as the cell ID.
candidate = cytearc.inspect_mtx("/path/to/parse_dge")[0]
reader = cytearc.MtxReader(candidate, cell_id_key="bc_index")
cytearc.MtxToZarr(reader, zarr_loc="parse.zarr").dump()Import an H5AD file with its UMAP and cell types¶
H5AD files differ in where they keep the raw counts, the feature names and the metadata, so inspect a file before converting it. inspect_h5ad samples the values of each matrix in the file, treats a matrix of whole non-negative numbers as counts, and ranks the count matrices by name: raw/X, layers/counts and layers/raw_counts first, then X, then layers/spliced, with the unspliced and ambiguous layers of RNA velocity data last.
import h5py
# Download the pancreas H5AD file and inspect its layout.
h5ad_dir = datasets.download_dataset(
name="bastidas-ponce_4K_pancreas-d15_rnaseq", destination=output_dir
)
h5ad_path = str(h5ad_dir / "data.h5ad")
inspection = cytearc.inspect_h5ad(h5ad_path)
# Check whether X stores the same sparse matrix as layers/spliced.
with h5py.File(h5ad_path, "r") as source:
x_repeats_spliced = all(
np.array_equal(source["X"][part], source["layers/spliced"][part])
for part in ("data", "indices", "indptr")
)
# Tabulate the selected matrix, the alternatives and the metadata keys.
pd.Series(
{
"selected matrix": inspection.matrixKey,
"available matrices": ", ".join(inspection.matrixCandidates),
"encoding": inspection.matrixEncoding,
"integer-like counts": inspection.integerLike,
"cells": inspection.nCells,
"features": inspection.nFeatures,
"cell metadata": inspection.cellAttrsKey,
"feature metadata": inspection.featureAttrsKey,
"feature names": inspection.featureNameKey,
"X repeats layers/spliced": x_repeats_spliced,
},
name="value",
).to_frame()| value | |
|---|---|
| selected matrix | X |
| available matrices | X, layers/spliced, layers/unspliced |
| encoding | csr |
| integer-like counts | True |
| cells | 3696 |
| features | 27998 |
| cell metadata | obs |
| feature metadata | var |
| feature names | index |
| X repeats layers/spliced | True |
Started: 2026-11-18T00:48:05.513995Z | Wall time: 1.331 s
X, layers/spliced and layers/unspliced all hold counts, and inspection selects X, a sparse CSR matrix of 3,696 cells by 27,998 genes. In this file X repeats layers/spliced, so the store holds the spliced counts and leaves out the unspliced ones. To import another matrix, inspect the file again with matrix_key, such as matrix_key="layers/counts" for a file that keeps its raw counts in a layer.
H5adReader.from_inspect opens a reader with the inspected keys. An import writes the counts and the obs and var tables, and brings results computed on the cells only when you name them. embedding_roles maps obsm keys to a role: "umap" or "tsne" for a layout, or "coordinates" for a latent space, such as X_pca or X_scVI, that a neighbor graph can be built on. cluster_keys names obs columns of labels to import as results instead of metadata columns. Each named result becomes an artifact, an immutable saved result that CyteArc refers to by an ArtifactRef. Import the published UMAP and the clusters column of cell types:
# Import the counts with the published UMAP and cell types as artifacts.
reader = cytearc.H5adReader.from_inspect(
inspection, embedding_roles={"X_umap": "umap"}, cluster_keys=("clusters",)
)
pancreas_store = output_dir / "pancreas.zarr"
h5ad_import = cytearc.H5adToZarr(reader, zarr_loc=str(pancreas_store)).dump()
# List the references to the imported results.
{
"embeddings": dict(h5ad_import.embeddingArtifacts),
"clusters": dict(h5ad_import.clusterArtifacts),
}{'embeddings': {'X_umap': ArtifactRef(assay='RNA', kind='embedding', artifact_id='ca4da9d98468...')},
'clusters': {'clusters': ArtifactRef(assay='RNA', kind='cluster_labels', artifact_id='fa3326f44bf4...')}}Started: 2026-11-18T00:48:06.848989Z | Wall time: 2.985 s
dump() returns the references: embeddingArtifacts maps X_umap to an embedding artifact, clusterArtifacts maps clusters to a cluster_labels artifact, and cellSelection refers to a frozen cell selection, an artifact that records the 3,696 imported cells that these results cover. Plots, exports and analyses take these references directly. Open the store and color the imported UMAP by the imported cell types:
# Open the pancreas store and color the imported UMAP by the imported cell types.
ds = cytearc.DataStore(str(pancreas_store))
ds.plots.embedding(
layout=h5ad_import.embeddingArtifacts["X_umap"],
color_by=h5ad_import.clusterArtifacts["clusters"],
legend_loc="on_data",
show_titles=False,
figsize=(6, 4.5),
)
Started: 2026-11-18T00:48:09.836440Z | Wall time: 0.676 s
The UMAP and labels arrive as published, and the plot draws the cell types in the file’s colors. Ductal cells, with Ngn3 low endocrine progenitors (EP) among them, form a loop at one end. Ngn3 high EP cells lead from there into Pre-endocrine cells, from which Beta, Alpha, Epsilon and Delta cells branch off at the other end.
When var holds a column of feature types, such as genes and antibody tags, inspection reports it as assaySplitKey. Pass it to H5adToZarr as assay_split_key to write one assay per type, and name the assay that owns the imported results with analysis_assay. Categorical obs columns keep their category order, unused categories, ordered flag and uns["<column>_colors"] colors, and the import stores each one as integer codes beside its categories, which takes far less space than a label per cell. CyteArc releases before 1.4.0 cannot open such a store; categorical_columns=False stores the labels instead. The import and export API reference covers multi-assay imports and metadata handling.
Import files with repeated cell IDs¶
CyteArc refuses repeated cell IDs by default. Files saved from anndata.concat without index_unique repeat IDs across samples. duplicate_cell_ids="make_unique" keeps the first occurrence of each ID and appends -1, -2 and so on to later ones, as AnnData’s obs_names_make_unique does, so that every row imports; keep a sample column to record where each cell came from. In this three-cell file, the first and third cells share a name:
# Write a three-cell H5AD file whose first and third cells share a name.
repeated_cells = ad.AnnData(np.ones((3, 2), dtype=np.float32))
repeated_cells.obs_names = pd.Index(["cell_a", "cell_b", "cell_a"], name="cell_id")
repeated_path = output_dir / "repeated_cells.h5ad"
repeated_cells.write_h5ad(repeated_path)
# Read the IDs that an import would write.
repeated_reader = cytearc.H5adReader(
str(repeated_path), cell_ids_key="cell_id", duplicate_cell_ids="make_unique"
)
resolved_ids = repeated_reader.cell_ids()
repeated_reader.close()
pd.DataFrame({"source ID": repeated_cells.obs_names, "imported ID": resolved_ids})| source ID | imported ID | |
|---|---|---|
| 0 | cell_a | cell_a |
| 1 | cell_b | cell_b |
| 2 | cell_a | cell_a-1 |
Started: 2026-11-18T00:48:10.514561Z | Wall time: 0.031 s
The second cell_a imports as cell_a-1, and the first keeps its name.
Import a 10x HDF5 file within a memory budget¶
CrH5Reader reads a Cell Ranger HDF5 file and names each assay from the feature types that the file records: gene expression becomes RNA, peaks ATAC and antibody capture ADT. A writer stores the counts in compressed chunks grouped into shards, and mem_budget caps the memory that the conversion plans to use. With mem_budget="4G", the default shards of this 89,796-peak assay do not fit, and the writer would stop with a MemoryError that names the largest halving of the default layout that fits. policy="fit" writes that layout instead:
# Download the 10x ATAC file and convert it with the largest layout that fits 4G.
tenx_dir = datasets.download_dataset(
name="tenx_10K_pbmc-v1_atacseq", destination=output_dir
)
atac_store = output_dir / "pbmc_atac.zarr"
atac_writer = cytearc.CrToZarr(
cytearc.CrH5Reader(str(tenx_dir / "data.h5")),
zarr_loc=str(atac_store),
mem_budget="4G",
policy="fit",
)
atac_writer.dump()
# Show the layout that the writer chose.
atac_writer.policyCountMatrixPolicy(unitBytes=500000000, chunkBytes=50000000)Started: 2026-11-18T00:48:10.548583Z | Wall time: 13.731 s
The writer halved the default layout once, to 500 MB shards made of 50 MB chunks. An RNA store also keeps countsT, a gene-major copy of its counts that serves fast reads of single genes, and smaller shards slow those reads, so give an RNA import a larger mem_budget when the machine has the memory. ATAC and other non-RNA assays write no countsT, so this store does not pay that cost. Memory and execution explains memory planning.
# Open the ATAC store and summarize it.
ds_atac = cytearc.DataStore(str(atac_store))
ds_atacDataStore has 8728 (8728) cells with 1 assays: ATAC
Cell metadata:
'I', 'ids', 'names', 'ATAC_nCounts', 'ATAC_nFeatures',
'sourceRow'
ATAC assay has 89796 features and following metadata:
'I', 'ids', 'names', 'derivation', 'dropOuts',
'feature_type', 'genome', 'nCells'Started: 2026-11-18T00:48:24.284790Z | Wall time: 0.216 s
The store holds 8,728 cells and 89,796 peaks in an ATAC assay. The scATAC-seq tutorial analyzes the same cells.
Import a CSV count table¶
CSVReader and CSVtoZarr convert a dense CSV table whose rows are cells and whose columns are features, and cell_data_cols moves named columns, such as a quality score, into the cell metadata instead of the counts. The reader takes every row as a cell, so transpose a table that has genes as rows, as many GEO tables do: read it with pandas and write the transposed matrix with SparseToZarr, which the next section shows. A dense table stores every zero, so this route suits small data, such as this five-cell table:
# Write a five-cell table with a quality column and three genes, and print it.
csv_path = output_dir / "toy_counts.csv"
csv_path.write_text(
"quality,geneA,geneB,geneC\n"
"10,1,0,2\n"
"20,0,3,0\n"
"30,4,5,6\n"
"40,7,0,8\n"
"50,9,10,0\n",
encoding="utf-8",
)
print(csv_path.read_text(encoding="utf-8"))quality,geneA,geneB,geneC
10,1,0,2
20,0,3,0
30,4,5,6
40,7,0,8
50,9,10,0
Started: 2026-11-18T00:48:24.503165Z | Wall time: 0.006 s
No cell of this three-gene table has more than 10 detected features, so the first-open filter would remove every cell; the open then warns and leaves I unchanged. min_features_per_cell=-1 skips the filter; use it also for a store whose default assay has few features, such as a hashtag or antibody panel, and for a raw droplet matrix whose cells you call yourself:
# Convert the table with quality as metadata, and open it without the low-feature filter.
csv_zarr = output_dir / "toy_csv.zarr"
reader = cytearc.CSVReader(str(csv_path), cell_data_cols=["quality"])
cytearc.CSVtoZarr(reader, zarr_loc=str(csv_zarr), assay_name="RNA").dump()
ds_csv = cytearc.DataStore(str(csv_zarr), min_features_per_cell=-1)
ds_csv.cells.head()| I | ids | names | RNA_nCounts | RNA_nFeatures | quality | sourceRow | |
|---|---|---|---|---|---|---|---|
| 0 | True | cell_0 | cell_0 | 3.0 | 2.0 | 10 | 0 |
| 1 | True | cell_2 | cell_2 | 15.0 | 3.0 | 30 | 2 |
| 2 | True | cell_4 | cell_4 | 19.0 | 2.0 | 50 | 4 |
| 3 | True | cell_3 | cell_3 | 15.0 | 2.0 | 40 | 3 |
| 4 | True | cell_1 | cell_1 | 3.0 | 1.0 | 20 | 1 |
Started: 2026-11-18T00:48:24.512022Z | Wall time: 0.929 s
Each row became a cell named by its position in the file, cell_0 to cell_4, with quality beside the computed totals; pass id_column, the position of a column of cell IDs, to name the cells from the table instead. The table lists the cells in the store’s random order, described above for the islet import, with each cell’s row in the file in sourceRow.
Import a matrix held in memory¶
SparseToZarr writes a cells-by-features matrix that is already in memory, a SciPy sparse matrix or a NumPy array, with one ID per cell and per feature. A mapping of assay names to matrices of the same cells writes one assay for each, which turns RNA, hashtag and protein tables read from GEO into one store.
from scipy.sparse import csr_matrix
# Build a three-cell sparse matrix of ten features and show it in dense form.
mat = csr_matrix(
(
[1, 10, 15, 10, 20, 2, 3, 1, 5],
([0, 0, 0, 1, 1, 1, 2, 2, 2], [1, 3, 8, 2, 3, 1, 2, 8, 9]),
),
shape=(3, 10),
)
mat.toarray()array([[ 0, 1, 0, 10, 0, 0, 0, 0, 15, 0],
[ 0, 2, 10, 20, 0, 0, 0, 0, 0, 0],
[ 0, 0, 3, 0, 0, 0, 0, 0, 1, 5]])Started: 2026-11-18T00:48:25.444069Z | Wall time: 0.008 s
Each of the three cells has three nonzero features, so open this store without the low-feature filter as well:
# Write the matrix with its IDs, and open the store without the low-feature filter.
sparse_zarr = output_dir / "toy_sparse.zarr"
cytearc.SparseToZarr(
mat,
zarr_loc=str(sparse_zarr),
cell_ids=[f"cell_{i}" for i in range(mat.shape[0])],
feature_ids=[f"feat_{i}" for i in range(mat.shape[1])],
assay_name="RNA",
).dump()
ds_sparse = cytearc.DataStore(str(sparse_zarr), min_features_per_cell=-1)
ds_sparseDataStore has 3 (3) cells with 1 assays: RNA
Cell metadata:
'I', 'ids', 'names', 'RNA_nCounts', 'RNA_nFeatures',
'sourceRow'
RNA assay has 10 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'nCells'Started: 2026-11-18T00:48:25.454937Z | Wall time: 0.378 s
Import other formats¶
Import a Seurat object¶
CyteArc reads a saved Seurat .rds file without an R session: its raw counts, cell metadata, identities and reductions. It does not read .h5seurat files. The Seurat import tutorial inspects an object, imports it and shows which Seurat contents become artifacts.
Import Tapestri DNA and protein reads¶
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 file: each cell’s reads of each amplicon become the CNV assay, with each amplicon’s interval as feature metadata, and the reads of each antibody tag become the ADT assay. Cells are named <sample>__<barcode>, so the samples of one file stay apart, and each cell’s sample_name and filtered flag become cell metadata. The store’s tapestri attribute records the file’s panel, genome and pipeline version. ds.variants.import_counts then adds the DNA variants as variant counts; the variants API reference covers their genotype calls and clones:
# Write the amplicon and protein reads to a store.
reader = cytearc.TapestriReader("sample.dna+protein.h5")
cytearc.TapestriToZarr(reader, zarr_loc="sample.zarr").dump()
reader.close()
# Import the variants that pass Tapestri's filters, with their genotype calls.
ds = cytearc.DataStore("sample.zarr", default_assay="ADT")
counts = ds.variants.import_counts(
"sample.dna+protein.h5", cell_selection=ds.snapshot_cell_selection()
)Write a store to object storage¶
Writers also accept a remote location, such as an s3:// URI, with the credentials in storage_options. Remote storage configuration covers other providers, credentials and the cloud storage profile that remote stores use.
import os
# Convert an H5AD file into a store in an S3 bucket, with credentials from the environment.
reader = cytearc.H5adReader.from_inspect(cytearc.inspect_h5ad("counts.h5ad"))
cytearc.H5adToZarr(
reader,
zarr_loc="s3://my-bucket/project/data.zarr",
storage_options={
"access_key_id": os.environ["AWS_ACCESS_KEY_ID"],
"secret_access_key": os.environ["AWS_SECRET_ACCESS_KEY"],
},
).dump()Export to Matrix Market¶
to_mtx writes an assay’s counts as a Matrix Market triplet in the layout of Cell Ranger output, which Seurat’s Read10X and Scanpy’s read_10x_mtx read. The triplet’s feature file holds an ID, a name and a type column, so a later import of the files keeps the assay type, and compress=True writes gzip-compressed files under the names that Cell Ranger 3 uses.
# Write the pancreas counts as a Matrix Market triplet and list the files with their sizes.
mtx_export = output_dir / "pancreas_mtx"
cytearc.to_mtx(assay=ds.RNA, mtx_directory=str(mtx_export))
{
path.name: f"{path.stat().st_size / 1e6:.1f} MB"
for path in sorted(mtx_export.iterdir())
}{'barcodes.tsv': '0.1 MB', 'genes.tsv': '0.9 MB', 'matrix.mtx': '114.5 MB'}Started: 2026-11-18T00:48:25.836327Z | Wall time: 3.479 s
Export to H5AD and AnnData¶
to_h5ad streams an assay into an H5AD file block by block, without building an AnnData object in memory, and DataStore.to_anndata returns the same content as an AnnData object. A pipeline run is the saved record of one call of a recipe such as ds.pipeline.rna, as the PBMC analysis shows. ds.to_anndata(run=run) exports the cells and genes that a completed run analyzed, with its metadata, PCA, UMAP and cluster labels, and refuses other cell or feature selections so that the exported axes match the run.
Without a run, both exports write the cell and feature tables beside the counts and add the artifacts that you name: layouts and coordinates in obsm, labels and scores in obs, and a neighbor graph in obsp. Each artifact must hold a value for every exported cell, so pass the cell selection that the artifacts cover as cell_selection, here the import’s h5ad_import.cellSelection:
import warnings
# Stream the imported cells to H5AD with the imported UMAP in obsm and the cell types in obs.
h5ad_export = output_dir / "pancreas.h5ad"
cytearc.to_h5ad(
ds.RNA,
str(h5ad_export),
cell_selection=h5ad_import.cellSelection,
obsm={"X_umap": h5ad_import.embeddingArtifacts["X_umap"]},
obs={"clusters": h5ad_import.clusterArtifacts["clusters"]},
)
# Read the file back and check its shape, cell order, layout, cell-type categories and colors.
exported = ad.read_h5ad(h5ad_export)
# Read the source file's cell IDs, in the file's order. AnnData warns as it moves
# this older file's neighbor graphs to obsp, which the check does not use.
with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)
source_cells = ad.read_h5ad(h5ad_path).obs_names
{
"file size": f"{h5ad_export.stat().st_size / 1e6:.1f} MB",
"shape": exported.shape,
"cells in the source file's order": exported.obs_names.equals(source_cells),
"obsm": sorted(exported.obsm.keys()),
"obs": exported.obs.columns.tolist(),
"cluster categories": exported.obs["clusters"].cat.categories.tolist(),
"first cluster colors": exported.uns["clusters_colors"][:3].tolist(),
}{'file size': '24.3 MB',
'shape': (3696, 27998),
"cells in the source file's order": True,
'obsm': ['X_umap'],
'obs': ['I',
'names',
'G2M_score',
'RNA_nCounts',
'RNA_nFeatures',
'RNA_percentMito',
'RNA_percentRibo',
'S_score',
'clusters_coarse',
'clusters'],
'cluster categories': ['Ductal',
'Ngn3 low EP',
'Ngn3 high EP',
'Pre-endocrine',
'Beta',
'Alpha',
'Delta',
'Epsilon'],
'first cluster colors': ['#8fbc8f', '#f4a460', '#fdbf6f']}Started: 2026-11-18T00:48:29.318255Z | Wall time: 2.584 s
The file takes 24.3 MB, against 114.5 MB for the uncompressed Matrix Market matrix. It holds the 3,696 cells by 27,998 genes in the source file’s order, the cell table, the imported cell types in obs["clusters"] and the UMAP in obsm["X_umap"]. The cell types keep the source file’s category order, from Ductal through Ngn3 low EP, Ngn3 high EP and Pre-endocrine to Beta, Alpha, Delta and Epsilon, and the source colors in uns["clusters_colors"], starting #8fbc8f, #f4a460 and #fdbf6f, which Scanpy uses to color the categories.
Export a gene panel¶
A full export holds all 27,998 genes. To check a few markers, select the genes first: feature_names exports genes in the requested order and refuses unknown or repeated names, and feature_indexes does the same by stored row. Marker lists often give human symbols in capitals, while this mouse store keeps symbols such as Gcg, so match the requested symbols without regard to case, then export the alpha-cell, delta-cell and ductal markers Gcg, Sst and Krt19:
# Match the requested symbols to the stored gene names without regard to case.
stored_names = ds.RNA.feats.fetch_all("names").astype(str)
name_lookup = {name.upper(): name for name in stored_names}
panel = [name_lookup[gene] for gene in ("GCG", "SST", "KRT19")]
# Export the raw counts of the three genes for the active cells.
selected = ds.to_anndata(from_assay="RNA", matrix="raw", feature_names=panel)
{"shape": selected.shape, "genes": selected.var["names"].tolist()}{'shape': (3696, 3), 'genes': ['Gcg', 'Sst', 'Krt19']}Started: 2026-11-18T00:48:31.905511Z | Wall time: 0.301 s
The panel holds the raw counts of Gcg, Sst and Krt19 in all 3,696 active cells. Without cell_selection, to_anndata exports the active cells of I, while to_h5ad writes every cell of the assay, inactive ones included.
Export results for Scanpy and import a latent space¶
Scanpy reads PCA coordinates from obsm["X_pca"], a neighbor graph from obsp with its settings in uns["neighbors"], and cell groups from categorical obs columns, and to_anndata writes CyteArc results in that layout. The example builds a PCA, a graph, a UMAP and Leiden clusters in CyteArc, exports them, computes a new latent space of the cells outside CyteArc, and imports it back as coordinates for a graph. The outside step is a truncated singular value decomposition (SVD) from scikit-learn; a latent space from scVI or another tool comes back the same way.
# Build a PCA of 2,000 variable genes, a k=11 graph, a UMAP and Leiden clusters.
cells = h5ad_import.cellSelection
hvgs = ds.features.hvgs(cells, top_n=2000, show_plot=False)
normalized = ds.features.normalize(cells, hvgs)
pca = ds.reduction.pca(normalized, dims=20)
graph = ds.graph.connectivity(ds.graph.neighbors(ds.graph.ann_index(pca), k=11))
umap = ds.embeddings.umap(graph, ds.embeddings.initialization(pca))
leiden = ds.clusters.leiden(graph, resolution=1.0)
# Export the counts with the results in Scanpy's layout and list where each result went.
adata = ds.to_anndata(
cell_selection=cells,
obsm={"X_pca": pca, "X_umap": umap},
obs={"leiden": leiden},
graph=graph,
)
{
"obsm": sorted(adata.obsm.keys()),
"obsp": sorted(adata.obsp.keys()),
"varm": sorted(adata.varm.keys()),
"neighbors": adata.uns["neighbors"]["params"],
"leiden dtype": str(adata.obs["leiden"].dtype),
}{'obsm': ['X_pca', 'X_umap'],
'obsp': ['connectivities', 'distances'],
'varm': ['PCs'],
'neighbors': {'n_neighbors': 12,
'method': 'umap',
'metric': 'euclidean',
'use_rep': 'X_pca'},
'leiden dtype': 'category'}Started: 2026-11-18T00:48:32.209105Z | Wall time: 90.245 s
obs["leiden"] is a categorical, so Scanpy groups by it as by its own Leiden result, for example in sc.tl.rank_genes_groups(adata, "leiden"), and uns["neighbors"] lets sc.tl.paga and sc.tl.leiden use the exported graph without sc.pp.neighbors. The exported n_neighbors is 12 because Scanpy counts each cell among its own neighbors and CyteArc’s k=11 does not. varm["PCs"] holds the PCA loadings, zero for genes that the PCA did not use. The outside step log-normalizes the counts of the 2,000 PCA genes and fits a 15-dimensional truncated SVD:
from scipy.sparse import csr_matrix, diags
from sklearn.decomposition import TruncatedSVD
# Scale each cell's counts of the PCA genes to 10,000 and log-transform them.
pca_genes = adata.varm["PCs"].any(axis=1)
counts = csr_matrix(adata.X[:, pca_genes], dtype=np.float32)
scaled = diags(1e4 / np.maximum(counts.sum(axis=1).A1, 1)) @ counts
scaled.data = np.log1p(scaled.data)
# Fit a 15-dimensional latent space of the cells outside CyteArc.
svd = TruncatedSVD(n_components=15, random_state=0)
adata.obsm["X_svd"] = svd.fit_transform(scaled)
{"PCA genes": int(pca_genes.sum()), "latent space": adata.obsm["X_svd"].shape}{'PCA genes': 2000, 'latent space': (3696, 15)}Started: 2026-11-18T00:50:02.457070Z | Wall time: 0.230 s
ds.reduction.import_coordinates brings the latent space back as an artifact. It aligns the rows of a DataFrame to the selected cells by cell ID and records the tool, version and parameters passed as source, so the artifact’s provenance shows where the coordinates came from. A neighbor graph, a UMAP and Leiden clusters then use the imported coordinates as they use a PCA. Build them with the same settings as above and compare the two clusterings:
import sklearn
# Import the latent space for the same cells, with a record of the tool that made it.
latent = ds.reduction.import_coordinates(
pd.DataFrame(adata.obsm["X_svd"], index=adata.obs_names),
cell_selection=cells,
name="X_svd",
source={
"tool": "scikit-learn TruncatedSVD",
"version": sklearn.__version__,
"parameters": {"n_components": 15, "random_state": 0},
},
)
# Build a k=11 graph, a UMAP and Leiden clusters on the imported coordinates.
latent_graph = ds.graph.connectivity(
ds.graph.neighbors(ds.graph.ann_index(latent), k=11)
)
latent_umap = ds.embeddings.umap(latent_graph, ds.embeddings.initialization(latent))
latent_leiden = ds.clusters.leiden(latent_graph, resolution=1.0)
# Count the cells that each PCA cluster shares with each SVD cluster.
pca_labels = ds.artifacts.load_values(leiden).values
svd_labels = ds.artifacts.load_values(latent_leiden).values
shared = pd.crosstab(pca_labels, svd_labels)
# Summarize the agreement of the two clusterings and the recorded source of the coordinates.
kept_together = shared.max(axis=1) / shared.sum(axis=1)
{
"Leiden clusters (PCA, SVD)": shared.shape,
"adjusted Rand index": round(
ds.clusters.compute_concordance(leiden, latent_leiden), 2
),
"PCA clusters with under 80% of cells in one SVD cluster": kept_together.index[
kept_together < 0.8
].tolist(),
"coordinate source": ds.artifacts.inspect(latent).parameters["source"],
}{'Leiden clusters (PCA, SVD)': (18, 17),
'adjusted Rand index': 0.69,
'PCA clusters with under 80% of cells in one SVD cluster': [3,
5,
8,
9,
10,
12,
14,
17],
'coordinate source': {'tool': 'scikit-learn TruncatedSVD',
'version': '1.9.1',
'parameters': {'n_components': 15, 'random_state': 0}}}Started: 2026-11-18T00:50:02.690373Z | Wall time: 4.343 s
The PCA graph gives 18 clusters and the SVD graph 17, which agree with an adjusted Rand index of 0.69, where 1 means identical partitions and 0 the agreement of random labels. ds.artifacts.inspect(latent).parameters["source"] returns the recorded source of the coordinates: scikit-learn’s TruncatedSVD, version 1.9.1, with its parameters. The figure places the UMAP of the imported coordinates beside the share of each PCA cluster’s cells that falls in each SVD cluster, with each PCA cluster named by its most common published cell type:
# Express each PCA cluster's row as fractions, and order the SVD columns along the diagonal.
fractions = shared.div(shared.sum(axis=1), axis=0)
fractions = fractions[shared.idxmax(axis=0).sort_values(kind="stable").index]
# Name each PCA cluster by its most common published cell type.
published = ds.artifacts.load_values(h5ad_import.clusterArtifacts["clusters"]).values
main_type = pd.crosstab(pca_labels, published).idxmax(axis=1)
# Draw the UMAP of the imported coordinates beside the heatmap of shared cells.
figure, (left, right) = plt.subplots(1, 2, figsize=(12, 5.2), layout="constrained")
ds.plots.embedding(
layout=latent_umap,
color_by=h5ad_import.clusterArtifacts["clusters"],
legend_loc="on_data",
show_titles=False,
target=left,
show=False,
)
left.set_title("UMAP of the imported SVD coordinates")
image = right.imshow(fractions.to_numpy(), cmap="Blues", vmin=0, vmax=1)
right.set_xticks(range(fractions.shape[1]), fractions.columns, fontsize=8)
right.set_yticks(
range(fractions.shape[0]),
[f"{cluster} {main_type[cluster]}" for cluster in fractions.index],
fontsize=8,
)
right.set_xlabel("SVD Leiden cluster")
right.set_ylabel("PCA Leiden cluster and its main published cell type")
right.set_title("Cells of each PCA cluster in each SVD cluster")
figure.colorbar(image, ax=right, label="Fraction of the PCA cluster's cells")
plt.show()
Started: 2026-11-18T00:50:07.036365Z | Wall time: 0.781 s
The UMAP of the imported coordinates keeps the published structure, from Ductal and Ngn3 low EP cells through Ngn3 high EP and Pre-endocrine cells to the Beta, Alpha, Epsilon and Delta branches. Ten of the 18 PCA clusters keep at least 80% of their cells in one SVD cluster, along the heatmap’s diagonal. The other eight, clusters 3, 5, 8, 9, 10, 12, 14 and 17, spread over two or three SVD clusters each. The table counts the published cell types in each pair of a split PCA cluster and an SVD cluster that share at least 10 cells, to show where the two graphs divide them:
# Count each published cell type in every pair of a split PCA cluster and an SVD cluster.
in_split = np.isin(pca_labels, kept_together.index[kept_together < 0.8])
split_types = pd.crosstab(
[
pd.Series(pca_labels[in_split], name="PCA cluster"),
pd.Series(svd_labels[in_split], name="SVD cluster"),
],
pd.Series(published[in_split], name="published cell type"),
)
# Show the pairs of at least 10 cells, with the cell types in the source file's order.
type_order = [
name for name in exported.obs["clusters"].cat.categories if name in split_types
]
split_types.loc[split_types.sum(axis=1) >= 10, type_order]| published cell type | Ductal | Ngn3 low EP | Ngn3 high EP | Pre-endocrine | Beta | Alpha | Epsilon | |
|---|---|---|---|---|---|---|---|---|
| PCA cluster | SVD cluster | |||||||
| 3 | 5 | 0 | 0 | 0 | 186 | 23 | 0 | 0 |
| 7 | 0 | 0 | 0 | 85 | 0 | 0 | 0 | |
| 5 | 3 | 0 | 0 | 107 | 6 | 0 | 0 | 0 |
| 7 | 0 | 0 | 5 | 137 | 0 | 0 | 0 | |
| 8 | 9 | 0 | 0 | 0 | 29 | 0 | 20 | 103 |
| 16 | 0 | 0 | 0 | 0 | 0 | 0 | 30 | |
| 9 | 8 | 0 | 0 | 55 | 0 | 0 | 0 | 0 |
| 10 | 20 | 62 | 45 | 0 | 0 | 0 | 0 | |
| 10 | 12 | 133 | 3 | 0 | 0 | 0 | 0 | 0 |
| 13 | 31 | 1 | 0 | 0 | 0 | 0 | 0 | |
| 12 | 1 | 42 | 2 | 0 | 0 | 0 | 0 | 0 |
| 13 | 96 | 4 | 0 | 0 | 0 | 0 | 0 | |
| 14 | 2 | 0 | 0 | 0 | 1 | 5 | 55 | 0 |
| 5 | 0 | 0 | 0 | 34 | 2 | 23 | 0 | |
| 17 | 3 | 0 | 0 | 11 | 1 | 0 | 0 | 0 |
| 14 | 0 | 0 | 0 | 21 | 0 | 0 | 0 | |
| 16 | 0 | 0 | 4 | 47 | 0 | 0 | 2 |
Started: 2026-11-18T00:50:07.821220Z | Wall time: 0.021 s
Ductal clusters 10 and 12, Pre-endocrine cluster 3 and Epsilon cluster 8 divide into parts of one main cell type. In the other four, the SVD graph separates published cell types that the PCA graph groups together. SVD cluster 3, which also holds Ngn3 high EP cluster 6, takes 107 Ngn3 high EP cells from Pre-endocrine cluster 5 and 11 from Pre-endocrine cluster 17, while 137 Pre-endocrine cells of cluster 5 go to SVD cluster 7. SVD cluster 5, which also holds most of Pre-endocrine cluster 3, takes 34 Pre-endocrine cells from Alpha cluster 14, and SVD cluster 10 takes 20 Ductal, 62 Ngn3 low EP and 45 Ngn3 high EP cells from Ngn3 high EP cluster 9, while 55 more Ngn3 high EP cells of that cluster go to SVD cluster 8.
Convert your own files¶
Write each store to a new, empty directory. Writers refuse a path that holds data with
FileExistsErrorand a path inside another store withValueError, andoverwrite=Truereplaces only an earlier conversion that noDataStorehas opened.Check how the source names mitochondrial genes. The default pattern matches the
MT-prefix in upper or lower case; passmito_patternon the first open when the genes carry other names, as for the islet file above.An RNA store opens only with a complete gene-major
countsTcopy of its counts. A conversion that stopped partway, or a store written by an older CyteArc release, can lack one; convert such a store again from its source files.To combine the stores of several samples into one, use
DataStoreMerge, as the dataset merging tutorial shows.
The PBMC analysis continues from a converted RNA store.
- Xin, Y., Kim, J., Okamoto, H., Ni, M., Wei, Y., Adler, C., Murphy, A. J., Yancopoulos, G. D., Lin, C., & Gromada, J. (2016). RNA sequencing of single human islet cells reveals type 2 diabetes genes. Cell Metabolism, 24(4), 608–615. 10.1016/j.cmet.2016.08.018
- Bastidas-Ponce, A., Tritschler, S., Dony, L., Scheibner, K., Tarquis-Medina, M., Salinno, C., Schirge, S., Burtscher, I., Böttcher, A., Theis, F. J., Lickert, H., & Bakhti, M. (2019). Comprehensive single cell mRNA profiling reveals a detailed roadmap for pancreatic endocrinogenesis. Development, 146(12), dev173849. 10.1242/dev.173849