Skip to content

Downstream Analysis Guide

This guide describes how to import data generated by DNBelab C Series™ single-cell analysis software (dnbc4tools) into popular bioinformatics ecosystems (R / Seurat / Signac / scRepertoire / ArchR and Python / Scanpy / SnapATAC2 / AnnData / Scirpy) for downstream exploration.

scRNA Gene Expression • C6 Multiplexed scRNA • scATAC Chromatin Accessibility • scVDJ Immune Profiling • Deliverables Quick Reference


1. Single-Cell RNA Gene Expression (scRNA)

Version 3.2 concurrently provides standardized MEX directories, H5 files, and H5AD files under the outs/ root directory. Choose single-file formats (.h5 or .h5ad) according to the downstream tool. Loading time and memory usage depend on matrix size, storage, and the reader used.

R Ecosystem (Seurat)

library(Seurat)
library(dplyr)

# Method 1: Load compressed H5 format (recommended, fastest)
counts <- Read10X_h5("outs/filtered_feature_bc_matrix.h5")

# Method 2: Load canonical MEX directory
# counts <- Read10X(data.dir = "outs/filtered_feature_bc_matrix")

# Create Seurat object
scRNA <- CreateSeuratObject(
  counts = counts,
  project = "dnbc4_rna",
  min.cells = 3,
  min.features = 200
)

# Mitochondrial percentage and downstream processing pipeline
scRNA[["percent.mt"]] <- PercentageFeatureSet(scRNA, pattern = "^MT-|^mt-")
scRNA <- NormalizeData(scRNA) %>%
  FindVariableFeatures(selection.method = "vst", nfeatures = 2000) %>%
  ScaleData() %>%
  RunPCA() %>%
  FindNeighbors(dims = 1:30) %>%
  FindClusters(resolution = 0.5) %>%
  RunUMAP(dims = 1:30)

# Visualize clusters
DimPlot(scRNA, reduction = "umap", label = TRUE)

Python Ecosystem (Scanpy)

import scanpy as sc

# Method 1: Load pre-packaged AnnData format (recommended, ready to use)
adata = sc.read_h5ad("outs/filtered_feature_bc_matrix.h5ad")

# Method 2: Load 10X H5 format
# adata = sc.read_10x_h5("outs/filtered_feature_bc_matrix.h5")

# Method 3: Load canonical MEX directory
# adata = sc.read_10x_mtx("outs/filtered_feature_bc_matrix")

# Standard Scanpy QC, dimensionality reduction, and clustering
adata.var_names_make_unique()
sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_genes(adata, min_cells=3)

# Annotate mitochondrial features
adata.var["mt"] = adata.var_names.str.startswith(("MT-", "mt-"))
sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], percent_top=None, log1p=False, inplace=True)

# Normalization, PCA, neighborhood graph, and clustering
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, min_mean=0.0125, max_mean=3, min_disp=0.5)
adata = adata[:, adata.var.highly_variable]
sc.pp.scale(adata, max_value=10)
sc.tl.pca(adata, svd_solver="arpack")
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30)
sc.tl.umap(adata)
sc.tl.leiden(adata, resolution=0.5)

# Plot clusters
sc.pl.umap(adata, color=["leiden"])

2. C6 Multiplexed scRNA Analysis

The C6 multiplexed workflow pools and sequences multiplexed samples within a single library, delivering both per-sample output directories (outs/rna/per_sample_outs/<sample>/) and pooled global matrices (outs/rna/).

Independent Per-Sample Analysis

Each demultiplexed sample contains its own filtered expression matrix ready for standalone analysis:

# R: Load sample-specific matrix (e.g. Sample1)
library(Seurat)
sample1_counts <- Read10X_h5("outs/rna/per_sample_outs/Sample1/filtered_feature_bc_matrix.h5")
sample1_obj <- CreateSeuratObject(counts = sample1_counts, project = "Sample1")
# Python: Load sample-specific AnnData
import scanpy as sc
adata_s1 = sc.read_h5ad("outs/rna/per_sample_outs/Sample1/filtered_feature_bc_matrix.h5ad")

Full Droplet Metadata & Valid Cell Filtering (singlecell.csv.gz)

The exported columns are cell,reads,gene,umi,is_cell_barcode,barcode; the table does not contain sample_id or cell_barcode. The examples below use each delivered sample matrix's barcodes.tsv.gz to map the full cell identifier to its sample directory, then filter called cells. They do not infer sample names by splitting barcode suffixes. If sample directories are missing or failed, resolve unmatched calls before proceeding. The R and Python blocks are independent alternatives.

library(data.table)

# Build sample membership from delivered filtered matrix barcode lists.
sample_dirs <- list.dirs("outs/rna/per_sample_outs", recursive = FALSE)
barcode_files <- file.path(sample_dirs, "filtered_feature_bc_matrix", "barcodes.tsv.gz")
barcode_files <- barcode_files[file.exists(barcode_files)]
if (!length(barcode_files)) stop("No per-sample filtered barcode files found")
cell_sample <- rbindlist(lapply(barcode_files, function(path) {
  con <- gzfile(path, "rt")
  cells <- readLines(con, warn = FALSE)
  close(con)
  cells <- cells[nzchar(cells)]
  data.table(cell = cells, sample_id = rep(basename(dirname(dirname(path))), length(cells)))
}))
if (anyDuplicated(cell_sample$cell)) stop("Cell IDs are not unique across samples")

meta_all <- fread(
  "outs/rna/singlecell.csv.gz",
  colClasses = list(character = c("cell", "is_cell_barcode"))
)
meta_cells <- meta_all[tolower(is_cell_barcode) %in% c("1", "true")]
meta_cells <- merge(meta_cells, cell_sample, by = "cell", all.x = TRUE, sort = FALSE)
if (anyNA(meta_cells$sample_id)) stop("Called cells lack sample assignments; check missing/failed outputs")
if (anyDuplicated(meta_cells$cell)) stop("Duplicate called-cell rows")
table(meta_cells$sample_id)
from collections import Counter
from pathlib import Path
import csv
import gzip

# Build sample membership without parsing or truncating barcode suffixes.
barcode_files = sorted(Path("outs/rna/per_sample_outs").glob(
    "*/filtered_feature_bc_matrix/barcodes.tsv.gz"
))
if not barcode_files:
    raise ValueError("No per-sample filtered barcode files found")
cell_to_sample = {}
for path in barcode_files:
    sample_id = path.parents[1].name
    with gzip.open(path, "rt", newline="") as handle:
        for row in csv.reader(handle, delimiter="\t"):
            if not row or not row[0]:
                continue
            cell = row[0]
            if cell in cell_to_sample:
                raise ValueError(f"Duplicate cell ID in sample barcode lists: {cell}")
            cell_to_sample[cell] = sample_id

# Stream the full table and write only mapped, called cells.
counts = Counter()
seen_cells = set()
with gzip.open("outs/rna/singlecell.csv.gz", "rt", newline="") as source, \
        open("called_cell_metadata.csv", "w", newline="") as output:
    reader = csv.DictReader(source)
    if not {"cell", "is_cell_barcode"}.issubset(reader.fieldnames or []):
        raise ValueError("Missing cell or is_cell_barcode column")
    writer = csv.DictWriter(output, fieldnames=list(reader.fieldnames) + ["sample_id"])
    writer.writeheader()
    for row in reader:
        if row["is_cell_barcode"].strip().lower() not in {"1", "true"}:
            continue
        cell = row["cell"]
        if cell not in cell_to_sample:
            raise ValueError(f"Called cell lacks a sample assignment: {cell}")
        if cell in seen_cells:
            raise ValueError(f"Duplicate called-cell row: {cell}")
        seen_cells.add(cell)
        row["sample_id"] = cell_to_sample[cell]
        writer.writerow(row)
        counts[row["sample_id"]] += 1
print(dict(counts))

The Python example writes called_cell_metadata.csv with a derived sample_id column. Its original identifier column remains cell.

Multi-Sample Integration & Batch Correction

To perform joint analysis across pooled samples, load the combined matrix from outs/rna/filtered_feature_bc_matrix.h5 (or .h5ad), attach demultiplexed sample_id metadata, and apply batch integration using Harmony or Seurat v5:

library(Seurat)
library(harmony)

# Load global pooled matrix
all_counts <- Read10X_h5("outs/rna/filtered_feature_bc_matrix.h5")
merged_obj <- CreateSeuratObject(counts = all_counts, project = "C6_Pool")

# Use meta_cells from the R mapping example above.
meta_df <- as.data.frame(meta_cells)
stopifnot(!anyDuplicated(meta_df$cell))
rownames(meta_df) <- meta_df$cell
common_cells <- intersect(colnames(merged_obj), rownames(meta_df))
if (!length(common_cells)) stop("No matching cell IDs")
merged_obj <- merged_obj[, common_cells]
merged_obj$sample_id <- meta_df[colnames(merged_obj), "sample_id"]

# Run Harmony batch correction
merged_obj <- NormalizeData(merged_obj) %>%
  FindVariableFeatures() %>%
  ScaleData() %>%
  RunPCA() %>%
  RunHarmony(group.by.vars = "sample_id") %>%
  RunUMAP(reduction = "harmony", dims = 1:30)

DimPlot(merged_obj, reduction = "umap", group.by = "sample_id")

3. Single-Cell ATAC Chromatin Accessibility (scATAC)

Cutsite Quantification Note

Version 3.2 defaults peak calling and matrix quantification to cutsite mode (Tn5 insertion endpoints adjusted for 9-bp stagger), providing higher fidelity for local accessibility. FRIP and TSS scores remain evaluated on deduplicated unique fragments.

R Ecosystem (Signac)

Choose either H5 or MTX below, then run the shared Signac analysis block. MTX input uses the three files matrix.mtx.gz, peaks.bed.gz, and barcodes.tsv.gz in the same directory; the matrix has peaks as rows and cells as columns.

H5 input

counts <- Seurat::Read10X_h5("outs/filtered_peak_bc_matrix.h5")
peak_ranges <- NULL

MTX input

read_atac_mtx <- function(mex_dir) {
  matrix_con <- gzfile(file.path(mex_dir, "matrix.mtx.gz"), "rt")
  on.exit(close(matrix_con), add = TRUE)
  counts <- as(Matrix::readMM(matrix_con), "CsparseMatrix")

  peaks <- read.delim(gzfile(file.path(mex_dir, "peaks.bed.gz")),
                      header = FALSE, colClasses = c("character", "integer", "integer"))
  barcodes <- read.delim(gzfile(file.path(mex_dir, "barcodes.tsv.gz")),
                         header = FALSE, colClasses = "character")[[1]]
  stopifnot(nrow(counts) == nrow(peaks), ncol(counts) == length(barcodes))
  rownames(counts) <- paste0(peaks[[1]], ":", peaks[[2]], "-", peaks[[3]])
  colnames(counts) <- barcodes

  # BED: 0-based, half-open; GRanges: 1-based, closed.
  peak_ranges <- GenomicRanges::GRanges(
    seqnames = peaks[[1]],
    ranges = IRanges::IRanges(start = peaks[[2]] + 1L, end = peaks[[3]])
  )
  list(counts = counts, ranges = peak_ranges)
}

mtx_data <- read_atac_mtx("outs/filtered_peak_bc_matrix")
counts <- mtx_data$counts
peak_ranges <- mtx_data$ranges

Shared Signac analysis

Use counts and peak_ranges from your chosen input method. MTX BED coordinates are converted to 1-based ranges explicitly for Signac. Keep the complete cell barcodes when matching metadata and fragments.

library(Signac)
library(Seurat)
library(GenomicRanges)

# 2. Load cell metadata and filter valid cells
metadata <- read.csv("outs/singlecell.csv", row.names = 1)
metadata <- metadata[metadata$is_cell_barcode %in% c(1, "True", "true"), ]

# Align cell barcodes
common_cells <- intersect(colnames(counts), rownames(metadata))
counts <- counts[, common_cells, drop = FALSE]
metadata <- metadata[common_cells, , drop = FALSE]

# 3. Create ChromatinAssay bound to fragments file
chrom_assay <- CreateChromatinAssay(
  counts = counts,
  ranges = peak_ranges,
  sep = c(":", "-"),
  fragments = "outs/fragments.tsv.gz",
  min.cells = 10,
  min.features = 200
)

# 4. Create Seurat object and run TF-IDF and SVD (LSI)
scATAC <- CreateSeuratObject(counts = chrom_assay, assay = "peaks", meta.data = metadata)
scATAC <- RunTFIDF(scATAC) %>%
  FindTopFeatures(min.cutoff = "q0") %>%
  RunSVD() %>%
  RunUMAP(reduction = "lsi", dims = 2:30) %>%
  FindNeighbors(reduction = "lsi", dims = 2:30) %>%
  FindClusters(algorithm = 3, resolution = 0.5)

DimPlot(scATAC, reduction = "umap", label = TRUE)

R Ecosystem (ArchR)

ArchR is optimized for large-scale ATAC-seq datasets. Build Arrow files from either fragments.tsv.gz (raw fragments) or filtered.fragments.tsv.gz (pre-filtered cells):

library(ArchR)
addArchRThreads(threads = 16)
addArchRGenome("hg38") # Set reference accordingly

# Create Arrow files from dnbc4tools filtered fragments
ArrowFiles <- createArrowFiles(
  inputFiles = "outs/filtered.fragments.tsv.gz",
  sampleNames = "Sample_ATAC",
  filterTSS = 4,
  filterFrags = 1000,
  addTileMat = TRUE,
  addGeneScoreMat = TRUE
)

proj <- ArchRProject(ArrowFiles = ArrowFiles, outputDirectory = "ArchR_Output")
proj <- addIterativeLSI(ArchRProj = proj, useMatrix = "TileMatrix", name = "IterativeLSI")
proj <- addUMAP(ArchRProj = proj, reducedDims = "IterativeLSI")
plotEmbedding(proj, colorBy = "cellColData", name = "Sample")

Python Ecosystem (SnapATAC2)

This example uses the existing peak count matrix with SnapATAC2 for feature selection, spectral embedding, neighbor graph construction, and clustering. Keep the raw cutsite counts in adata_atac.X; this workflow does not apply RNA-style total-count normalization, log transformation, HVG selection, or PCA.

Choose either H5 or MTX input below. Scanpy is used only to read the 10x-compatible H5 file: pass gex_only=False because ATAC peaks are not gene-expression features. MTX input reads the peak BED file explicitly instead of expecting features.tsv.gz. Both methods create an in-memory AnnData object for the shared SnapATAC2 analysis block.

H5 input

import scanpy as sc

# Load ATAC filtered peak matrix
adata_atac = sc.read_10x_h5("outs/filtered_peak_bc_matrix.h5", gex_only=False)
adata_atac.var_names_make_unique()

MTX input

The read_atac_C4 function loads the peak BED and complete cell barcodes separately, then transposes the sparse matrix into AnnData’s cell-by-peak layout. BED coordinates in adata_atac.var retain their original 0-based, half-open convention.

from pathlib import Path

import anndata as ad
import pandas as pd
from scipy.io import mmread
from scipy.sparse import csr_matrix


def read_atac_C4(path):
    mex_dir = Path(path)
    counts = mmread(str(mex_dir / "matrix.mtx.gz"))
    barcodes = pd.read_csv(
        mex_dir / "barcodes.tsv.gz", sep="\t", header=None, dtype=str,
        keep_default_na=False,
    )[0]
    peaks = pd.read_csv(
        mex_dir / "peaks.bed.gz", sep="\t", header=None,
        names=["chrom", "chromStart", "chromEnd"],
        dtype={"chrom": str, "chromStart": int, "chromEnd": int},
        keep_default_na=False,
    )
    if counts.shape != (len(peaks), len(barcodes)):
        raise ValueError("Matrix dimensions do not match peaks and barcodes")
    obs = pd.DataFrame(index=pd.Index(barcodes, name="barcode"))
    peaks.index = pd.Index(
        peaks["chrom"] + ":" + peaks["chromStart"].astype(str)
        + "-" + peaks["chromEnd"].astype(str), name="peak",
    )
    # Matrix Market: peaks x cells; AnnData: cells x peaks.
    adata = ad.AnnData(X=csr_matrix(counts.T), obs=obs, var=peaks)
    adata.var_names_make_unique()
    return adata


adata_atac = read_atac_C4("outs/filtered_peak_bc_matrix")

Shared SnapATAC2 analysis

Choose one input method above before running this block. The calls follow the SnapATAC2 2.10 feature-selection API and spectral-embedding API. The example selects up to 50,000 peaks and computes up to 30 spectral components; adjust feature count, component count, neighbor count, and clustering resolution to your dataset. It assumes a non-empty matrix with enough cells and peaks for these settings.

This example clusters the published peak matrix. Fragment-based operations, such as recomputing TSS enrichment or constructing a gene activity matrix, require importing fragments separately.

import snapatac2 as snap
from scipy.sparse import csr_matrix

# Keep raw cutsite counts in sparse CSR format
adata_atac.X = csr_matrix(adata_atac.X)

snap.pp.select_features(adata_atac, n_features=min(50000, adata_atac.n_vars))
snap.tl.spectral(adata_atac, n_comps=30, random_state=0)
snap.pp.knn(adata_atac, n_neighbors=15, use_rep="X_spectral")
snap.tl.leiden(adata_atac, resolution=0.5, random_state=0)
snap.tl.umap(adata_atac, use_rep="X_spectral", random_state=0)
snap.pl.umap(adata_atac, color="leiden", show=True)

4. Single-Cell V(D)J Immune Profiling (scVDJ)

The key output for scVDJ is outs/filtered_contig_annotations.csv, containing high-confidence TCR / BCR chain rearrangements, CDR3 sequences, and clonotype classifications.

R Ecosystem (scRepertoire Integration with Seurat)

scRepertoire is widely used to combine single-cell RNA and immune receptor repertoires:

library(scRepertoire)
library(Seurat)

# 1. Load contig annotation table
contigs <- read.csv("outs/filtered_contig_annotations.csv")

# 2. Combine TCR (or BCR) clonotypes
combined_tcr <- combineTCR(
  list(Sample1 = contigs),
  samples = "Sample1",
  removeNA = FALSE
)

# 3. Load processed scRNA Seurat object
scRNA <- readRDS("scRNA_analyzed.rds")

# 4. Seamlessly map immune clonotypes onto scRNA cells
scRNA <- combineExpression(
  combined_tcr,
  scRNA,
  cloneCall = "gene",
  proportion = FALSE
)

# Visualize clonotype expansion on the RNA UMAP embedding
DimPlot(scRNA, group.by = "cloneSize")

Python Ecosystem (Scirpy Integration with Scanpy)

Scirpy can be used with Scanpy for single-cell immune receptor analysis:

import scanpy as sc
import scirpy as ir

# 1. Load RNA and VDJ datasets
adata_rna = sc.read_h5ad("outs/filtered_feature_bc_matrix.h5ad")
adata_vdj = ir.io.read_10x_vdj("outs/filtered_contig_annotations.csv")

# 2. Index and align immune receptor chains
ir.pp.index_chains(adata_vdj)

# 3. Merge VDJ annotations into RNA AnnData
ir.pp.merge_with_ir(adata_rna, adata_vdj)

# 4. Perform clonotype expansion and diversity analysis
ir.tl.chain_qc(adata_rna)
ir.tl.clonal_expansion(adata_rna)

# Plot clonal expansion on the RNA UMAP
sc.pl.umap(adata_rna, color=["clonal_expansion", "has_ir"])

5. Deliverables Quick Reference

The table below summarizes key deliverables, file formats, and recommended loader functions across R and Python:

File / Directory Format Modality R Reader Python Reader Intended Downstream Usage
filtered_feature_bc_matrix.h5 HDF5 (.h5) scRNA / C6 / Multi Seurat::Read10X_h5() scanpy.read_10x_h5() Filtered gene expression matrix (rapid single-file load)
filtered_feature_bc_matrix.h5ad AnnData (.h5ad) scRNA / C6 / Multi anndata::read_h5ad() scanpy.read_h5ad() Pre-packaged sparse matrix and feature metadata (Python standard)
filtered_feature_bc_matrix/ MEX Directory (.mtx.gz) scRNA / C6 / Multi Seurat::Read10X() scanpy.read_10x_mtx() Canonical 10X-compatible three-file directory
filtered_peak_bc_matrix.h5 HDF5 (.h5) scATAC / Multi Seurat::Read10X_h5() scanpy.read_10x_h5(gex_only=False) Filtered peak accessibility matrix
filtered_peak_bc_matrix/ MEX scATAC / Multi Matrix::readMM() + read.delim() scipy.io.mmread() + pandas.read_csv() Read matrix.mtx.gz, peaks.bed.gz, and barcodes.tsv.gz separately; peaks are matrix rows and cells are columns
fragments.tsv.gz Tab-delimited (Indexed) scATAC / Multi Signac::CreateChromatinAssay() pysam.TabixFile() Tn5 fragment coordinate records with insertion cutsite info
filtered_contig_annotations.csv CSV scVDJ / Multi scRepertoire::combineTCR() scirpy.io.read_10x_vdj() High-confidence immune receptor CDR3 and full contig calls
singlecell.csv.gz / singlecell.csv Compressed CSV scRNA / scATAC / C6 / Multi data.table::fread() pandas.read_csv() All droplet records (filter by is_cell_barcode==1)
metrics_summary.xls TSV Plain Text All Pipelines read.delim(check.names=F) pandas.read_csv(sep="\t") Summary QC metrics table (do not use Excel readers)

For complete directory structures and metric definitions, see the Output Files Guide.