ATAC¶
Single cell ATAC: peak or tile counts, QC, TF-IDF, LSI, links to genes.
Two kinds of experiment hold ATAC:
- a
SingleCellsMultiModalwith RNA: the ATAC counts live in a second store underatac/, written for every cell of the RNA store in the same order, so the RNA cell filter applies to both.bv.mm.generate_wnn_graphfuses the two. - a
SingleCellsAtac, ATAC only: the peaks or tiles are the experiment's own store. Load one withbv.io.load_atac_fragmentsorbv.io.load_atac_tenx.
Every function here takes either. From the LSI on, the regular single cell
functions take modality="atac" and embd_to_use="lsi"; on a
SingleCellsAtac the default modality means the ATAC store as well.
# multiome
mm = bv.SingleCellsMultiModal(sc.dir)
bv.atac.add_atac_tenx(mm, "filtered_feature_bc_matrix.h5")
bv.atac.fragment_qc(mm, "atac_fragments.tsv.gz", "genes.gtf.gz")
bv.atac.run_tfidf(mm)
bv.atac.find_top_features(mm, min_cutoff="q5")
bv.atac.calculate_lsi(mm, n_comp=30)
bv.mm.generate_wnn_graph(mm, modality_2="atac", embd_to_use_2="lsi")
# ATAC only
counts = bv.atac.barcode_fragment_counts("atac_fragments.tsv.gz")
x = bv.io.load_atac_fragments(
"exp", "atac_fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
)
Peaks or fragments. add_atac_tenx takes the peak matrix Cell Ranger ARC
wrote into the h5. add_atac_fragments counts the fragment file itself into
a BED of peaks or fixed-width tiles; its default mode="insertion" counts
each Tn5 insertion as Cell Ranger does, and reproduces the h5 matrix on
Cell Ranger's peaks.
Calling peaks. call_peaks calls peaks on the fragments per cluster
(group_by), a native port of MACS3 callpeak (exact coordinates and
summits against MACS3 3.1.0); Cell Ranger's peak set under-calls rare
populations. remove_blacklisted drops peaks on blacklist regions before
the result goes into add_atac_fragments(peaks=...). annotate_peaks
names each feature's closest gene.
Barcodes and files. Fragment barcodes are the cell ids unless
barcode_map says otherwise (a -1 suffix, a sample prefix).
merge_fragments merges per-sample fragment files into one, barcodes
prefixed per sample, as cellranger-arc aggr does. Every fragment pass
errors when no cell id is a barcode of the file or the fragments and the
features share no chromosome name, and warns on partial mismatches.
Multiplets. amulet flags multiplets from loci where more than two of a
cell's fragments overlap (AMULET); it needs no clustering and no RNA. Pass
repeat and blacklist BEDs as restrict_beds.
Gene activity. gene_activity counts fragments over gene body plus
promoter (Signac's GeneActivity) into its own SingleCells, the query side
of an RNA to ATAC label transfer; get_gene_activity reopens it with the
experiment's cell filter. It is not RNA: methods that assume an mRNA count
model (residuals, doublets, Bonsai, gene set proportions) refuse it, and
those biased by gene length or by fragments shared between neighbouring genes
(AUCell, ScType, lm_activity, NMF, Hotspot gene correlations, SCENIC,
CellPhoneDB) warn. Peaks and tiles are refused by every method that works on
genes.
Links and profiles. peak_to_gene correlates peaks with nearby genes
over groups of cells (ArchR's peak to gene links). fragment_profiles gives
the TSS insertion profile and the fragment length histogram per group, for
bv.pl.tss_profile_plot and bv.pl.fragment_length_plot.
Mapping and integration. project_lsi puts a query onto a reference
LSI (Seurat's lsiproject); run_rlsi integrates batches through
reciprocal LSI anchors. bv.integrate.harmony(x, "batch", embd_to_use="lsi",
modality="atac") corrects the LSI instead and writes "harmony" to the ATAC
cache.
Gotchas. run_tfidf computes the IDF over the kept cells: run it again,
then the LSI, after changing them; it also clears the ATAC cache.
calculate_lsi drops component 1 by default, as the Signac vignettes do;
get_lsi_depth_cor and bv.pl.lsi_depth_plot show whether that is right
for the data.
Worked through in Joint RNA and ATAC and
ATAC without RNA. The ATAC-only loaders,
bv.io.load_atac_fragments and bv.io.load_atac_tenx, are on the
I/O page; the SingleCellsAtac class on the core page.
Adding the counts¶
Single cell ATAC: peak or tile counts, QC, TF-IDF, LSI, links to genes.
Two kinds of experiment hold ATAC:
- a
SingleCellsMultiModalwith RNA: the ATAC counts live in a second store underatac/, written for every cell of the RNA store in the same order, so the RNA cell filter applies to both.bv.mm.generate_wnn_graphfuses the two. - a
SingleCellsAtac, ATAC only: the peaks or tiles are the experiment's own store. Load one withbv.io.load_atac_fragmentsorbv.io.load_atac_tenx.
Every function here takes either. From the LSI on, the regular single cell
functions take modality="atac" and embd_to_use="lsi"; on a
SingleCellsAtac the default modality means the ATAC store as well.
# multiome
mm = bv.SingleCellsMultiModal(sc.dir)
bv.atac.add_atac_tenx(mm, "filtered_feature_bc_matrix.h5")
bv.atac.fragment_qc(mm, "atac_fragments.tsv.gz", "genes.gtf.gz")
bv.atac.run_tfidf(mm)
bv.atac.find_top_features(mm, min_cutoff="q5")
bv.atac.calculate_lsi(mm, n_comp=30)
bv.mm.generate_wnn_graph(mm, modality_2="atac", embd_to_use_2="lsi")
# ATAC only
counts = bv.atac.barcode_fragment_counts("atac_fragments.tsv.gz")
x = bv.io.load_atac_fragments(
"exp", "atac_fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
)
Peaks or fragments. add_atac_tenx takes the peak matrix Cell Ranger ARC
wrote into the h5. add_atac_fragments counts the fragment file itself into
a BED of peaks or fixed-width tiles; its default mode="insertion" counts
each Tn5 insertion as Cell Ranger does, and reproduces the h5 matrix on
Cell Ranger's peaks.
Calling peaks. call_peaks calls peaks on the fragments per cluster
(group_by), a native port of MACS3 callpeak (exact coordinates and
summits against MACS3 3.1.0); Cell Ranger's peak set under-calls rare
populations. remove_blacklisted drops peaks on blacklist regions before
the result goes into add_atac_fragments(peaks=...). annotate_peaks
names each feature's closest gene.
Barcodes and files. Fragment barcodes are the cell ids unless
barcode_map says otherwise (a -1 suffix, a sample prefix).
merge_fragments merges per-sample fragment files into one, barcodes
prefixed per sample, as cellranger-arc aggr does. Every fragment pass
errors when no cell id is a barcode of the file or the fragments and the
features share no chromosome name, and warns on partial mismatches.
Multiplets. amulet flags multiplets from loci where more than two of a
cell's fragments overlap (AMULET); it needs no clustering and no RNA. Pass
repeat and blacklist BEDs as restrict_beds.
Gene activity. gene_activity counts fragments over gene body plus
promoter (Signac's GeneActivity) into its own SingleCells, the query side
of an RNA to ATAC label transfer; get_gene_activity reopens it with the
experiment's cell filter. It is not RNA: methods that assume an mRNA count
model (residuals, doublets, Bonsai, gene set proportions) refuse it, and
those biased by gene length or by fragments shared between neighbouring genes
(AUCell, ScType, lm_activity, NMF, Hotspot gene correlations, SCENIC,
CellPhoneDB) warn. Peaks and tiles are refused by every method that works on
genes.
Links and profiles. peak_to_gene correlates peaks with nearby genes
over groups of cells (ArchR's peak to gene links). fragment_profiles gives
the TSS insertion profile and the fragment length histogram per group, for
bv.pl.tss_profile_plot and bv.pl.fragment_length_plot.
Mapping and integration. project_lsi puts a query onto a reference
LSI (Seurat's lsiproject); run_rlsi integrates batches through
reciprocal LSI anchors. bv.integrate.harmony(x, "batch", embd_to_use="lsi",
modality="atac") corrects the LSI instead and writes "harmony" to the ATAC
cache.
Gotchas. run_tfidf computes the IDF over the kept cells: run it again,
then the LSI, after changing them; it also clears the ATAC cache.
calculate_lsi drops component 1 by default, as the Signac vignettes do;
get_lsi_depth_cor and bv.pl.lsi_depth_plot show whether that is right
for the data.
AtacInfo
dataclass
¶
AtacInfo(
kind: Literal["peak", "tile"],
count_mode: CountMode,
tf_idf: bool = False,
depth_cor: ndarray | None = None,
lsi_dropped: tuple[int, ...] = (),
lsi_features: ndarray | None = None,
lsi_loadings: ndarray | None = None,
lsi_singular_values: ndarray | None = None,
)
What the ATAC store holds and how far it was processed.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
Literal['peak', 'tile']
|
|
count_mode |
CountMode
|
What one count is: |
tf_idf |
bool
|
Whether the store is TF-IDF normalised. |
depth_cor |
ndarray | None
|
Correlation of each LSI component with the library size, all components including any dropped one. |
lsi_dropped |
tuple[int, ...]
|
0-based LSI components left out of the |
lsi_features |
ndarray | None
|
0-based ATAC feature rows the LSI was fitted on. |
lsi_loadings |
ndarray | None
|
Features x components loadings of the LSI, all components, for projecting other cells onto it. |
lsi_singular_values |
ndarray | None
|
Singular values of the LSI. |
add_atac_tenx
¶
add_atac_tenx(
mm: SingleCellsMultiModal,
h5_path: Path | str,
*,
overwrite: bool = False,
max_mem_gb: float | None = None,
verbose: Verbose = 1,
) -> None
Add the Peaks of a 10x multiome h5 as the ATAC store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mm
|
SingleCellsMultiModal
|
The experiment, its RNA loaded from the same h5 (or with the same barcodes). |
required |
h5_path
|
Path | str
|
The Cell Ranger ARC |
required |
overwrite
|
bool
|
Replace an existing ATAC store. |
False
|
max_mem_gb
|
float | None
|
Memory budget of the peak-major conversion. |
None
|
verbose
|
Verbose
|
|
1
|
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If an ATAC store exists and |
ValueError
|
If a cell of the store is not in the h5. |
add_atac_fragments
¶
add_atac_fragments(
mm: SingleCellsMultiModal,
fragments: Path | str,
*,
peaks: Path | str | DataFrame | None = None,
tile_width: int | None = None,
chrom_sizes: Mapping[str, int] | None = None,
mode: CountMode = "insertion",
barcode_map: BarcodeMap = None,
overwrite: bool = False,
max_mem_gb: float | None = None,
verbose: Verbose = 1,
) -> None
Count a fragment file into peaks or genome tiles as the ATAC store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mm
|
SingleCellsMultiModal
|
The experiment; every cell of its store is counted. |
required |
fragments
|
Path | str
|
The fragment file (BGZF, gzip or plain). |
required |
peaks
|
Path | str | DataFrame | None
|
A BED file or a frame with |
None
|
tile_width
|
int | None
|
Tile width in bp, instead of |
None
|
chrom_sizes
|
Mapping[str, int] | None
|
Chromosome lengths, for the tiles. |
None
|
mode
|
CountMode
|
|
'insertion'
|
barcode_map
|
BarcodeMap
|
Cell id to fragment barcode, where they differ. |
None
|
overwrite
|
bool
|
Replace an existing ATAC store. |
False
|
max_mem_gb
|
float | None
|
Memory budget of the peak-major conversion. |
None
|
verbose
|
Verbose
|
|
1
|
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If an ATAC store exists and |
ValueError
|
Unless exactly one of |
Barcodes and fragment files¶
Single cell ATAC: peak or tile counts, QC, TF-IDF, LSI, links to genes.
Two kinds of experiment hold ATAC:
- a
SingleCellsMultiModalwith RNA: the ATAC counts live in a second store underatac/, written for every cell of the RNA store in the same order, so the RNA cell filter applies to both.bv.mm.generate_wnn_graphfuses the two. - a
SingleCellsAtac, ATAC only: the peaks or tiles are the experiment's own store. Load one withbv.io.load_atac_fragmentsorbv.io.load_atac_tenx.
Every function here takes either. From the LSI on, the regular single cell
functions take modality="atac" and embd_to_use="lsi"; on a
SingleCellsAtac the default modality means the ATAC store as well.
# multiome
mm = bv.SingleCellsMultiModal(sc.dir)
bv.atac.add_atac_tenx(mm, "filtered_feature_bc_matrix.h5")
bv.atac.fragment_qc(mm, "atac_fragments.tsv.gz", "genes.gtf.gz")
bv.atac.run_tfidf(mm)
bv.atac.find_top_features(mm, min_cutoff="q5")
bv.atac.calculate_lsi(mm, n_comp=30)
bv.mm.generate_wnn_graph(mm, modality_2="atac", embd_to_use_2="lsi")
# ATAC only
counts = bv.atac.barcode_fragment_counts("atac_fragments.tsv.gz")
x = bv.io.load_atac_fragments(
"exp", "atac_fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
)
Peaks or fragments. add_atac_tenx takes the peak matrix Cell Ranger ARC
wrote into the h5. add_atac_fragments counts the fragment file itself into
a BED of peaks or fixed-width tiles; its default mode="insertion" counts
each Tn5 insertion as Cell Ranger does, and reproduces the h5 matrix on
Cell Ranger's peaks.
Calling peaks. call_peaks calls peaks on the fragments per cluster
(group_by), a native port of MACS3 callpeak (exact coordinates and
summits against MACS3 3.1.0); Cell Ranger's peak set under-calls rare
populations. remove_blacklisted drops peaks on blacklist regions before
the result goes into add_atac_fragments(peaks=...). annotate_peaks
names each feature's closest gene.
Barcodes and files. Fragment barcodes are the cell ids unless
barcode_map says otherwise (a -1 suffix, a sample prefix).
merge_fragments merges per-sample fragment files into one, barcodes
prefixed per sample, as cellranger-arc aggr does. Every fragment pass
errors when no cell id is a barcode of the file or the fragments and the
features share no chromosome name, and warns on partial mismatches.
Multiplets. amulet flags multiplets from loci where more than two of a
cell's fragments overlap (AMULET); it needs no clustering and no RNA. Pass
repeat and blacklist BEDs as restrict_beds.
Gene activity. gene_activity counts fragments over gene body plus
promoter (Signac's GeneActivity) into its own SingleCells, the query side
of an RNA to ATAC label transfer; get_gene_activity reopens it with the
experiment's cell filter. It is not RNA: methods that assume an mRNA count
model (residuals, doublets, Bonsai, gene set proportions) refuse it, and
those biased by gene length or by fragments shared between neighbouring genes
(AUCell, ScType, lm_activity, NMF, Hotspot gene correlations, SCENIC,
CellPhoneDB) warn. Peaks and tiles are refused by every method that works on
genes.
Links and profiles. peak_to_gene correlates peaks with nearby genes
over groups of cells (ArchR's peak to gene links). fragment_profiles gives
the TSS insertion profile and the fragment length histogram per group, for
bv.pl.tss_profile_plot and bv.pl.fragment_length_plot.
Mapping and integration. project_lsi puts a query onto a reference
LSI (Seurat's lsiproject); run_rlsi integrates batches through
reciprocal LSI anchors. bv.integrate.harmony(x, "batch", embd_to_use="lsi",
modality="atac") corrects the LSI instead and writes "harmony" to the ATAC
cache.
Gotchas. run_tfidf computes the IDF over the kept cells: run it again,
then the LSI, after changing them; it also clears the ATAC cache.
calculate_lsi drops component 1 by default, as the Signac vignettes do;
get_lsi_depth_cor and bv.pl.lsi_depth_plot show whether that is right
for the data.
barcode_fragment_counts
¶
barcode_fragment_counts(
fragments: Path | str,
*,
exclude_chroms: Sequence[str] = MITO_CHROMS,
) -> DataFrame
Fragments per barcode, every barcode in the file, for cell calling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fragments
|
Path | str
|
The fragment file. |
required |
exclude_chroms
|
Sequence[str]
|
Chromosomes not counted. |
MITO_CHROMS
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
read_cellranger_barcodes
¶
The cell barcodes Cell Ranger ATAC called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
|
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
The barcodes, in file order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For another file type, or a CSV without
|
merge_fragments
¶
merge_fragments(
fragments: Sequence[Path | str],
out: Path | str,
*,
prefixes: Sequence[str] | None = None,
suffixes: Sequence[str] | None = None,
) -> DataFrame
Merge per-sample fragment files into one, as cellranger-arc aggr does.
Each file's barcodes get its prefix and suffix, so the same barcode in two samples stays two cells; give every file its own. The output is a sorted BGZF file with a tabix index, which every function here reads as one experiment. Files with a tabix index are read one chromosome at a time; others are held in memory whole.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fragments
|
Sequence[Path | str]
|
The fragment files. |
required |
out
|
Path | str
|
The merged file; the index goes next to it as |
required |
prefixes
|
Sequence[str] | None
|
Barcode prefix per file, e.g. |
None
|
suffixes
|
Sequence[str] | None
|
Barcode suffix per file, e.g. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither |
QC and multiplets¶
Single cell ATAC: peak or tile counts, QC, TF-IDF, LSI, links to genes.
Two kinds of experiment hold ATAC:
- a
SingleCellsMultiModalwith RNA: the ATAC counts live in a second store underatac/, written for every cell of the RNA store in the same order, so the RNA cell filter applies to both.bv.mm.generate_wnn_graphfuses the two. - a
SingleCellsAtac, ATAC only: the peaks or tiles are the experiment's own store. Load one withbv.io.load_atac_fragmentsorbv.io.load_atac_tenx.
Every function here takes either. From the LSI on, the regular single cell
functions take modality="atac" and embd_to_use="lsi"; on a
SingleCellsAtac the default modality means the ATAC store as well.
# multiome
mm = bv.SingleCellsMultiModal(sc.dir)
bv.atac.add_atac_tenx(mm, "filtered_feature_bc_matrix.h5")
bv.atac.fragment_qc(mm, "atac_fragments.tsv.gz", "genes.gtf.gz")
bv.atac.run_tfidf(mm)
bv.atac.find_top_features(mm, min_cutoff="q5")
bv.atac.calculate_lsi(mm, n_comp=30)
bv.mm.generate_wnn_graph(mm, modality_2="atac", embd_to_use_2="lsi")
# ATAC only
counts = bv.atac.barcode_fragment_counts("atac_fragments.tsv.gz")
x = bv.io.load_atac_fragments(
"exp", "atac_fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
)
Peaks or fragments. add_atac_tenx takes the peak matrix Cell Ranger ARC
wrote into the h5. add_atac_fragments counts the fragment file itself into
a BED of peaks or fixed-width tiles; its default mode="insertion" counts
each Tn5 insertion as Cell Ranger does, and reproduces the h5 matrix on
Cell Ranger's peaks.
Calling peaks. call_peaks calls peaks on the fragments per cluster
(group_by), a native port of MACS3 callpeak (exact coordinates and
summits against MACS3 3.1.0); Cell Ranger's peak set under-calls rare
populations. remove_blacklisted drops peaks on blacklist regions before
the result goes into add_atac_fragments(peaks=...). annotate_peaks
names each feature's closest gene.
Barcodes and files. Fragment barcodes are the cell ids unless
barcode_map says otherwise (a -1 suffix, a sample prefix).
merge_fragments merges per-sample fragment files into one, barcodes
prefixed per sample, as cellranger-arc aggr does. Every fragment pass
errors when no cell id is a barcode of the file or the fragments and the
features share no chromosome name, and warns on partial mismatches.
Multiplets. amulet flags multiplets from loci where more than two of a
cell's fragments overlap (AMULET); it needs no clustering and no RNA. Pass
repeat and blacklist BEDs as restrict_beds.
Gene activity. gene_activity counts fragments over gene body plus
promoter (Signac's GeneActivity) into its own SingleCells, the query side
of an RNA to ATAC label transfer; get_gene_activity reopens it with the
experiment's cell filter. It is not RNA: methods that assume an mRNA count
model (residuals, doublets, Bonsai, gene set proportions) refuse it, and
those biased by gene length or by fragments shared between neighbouring genes
(AUCell, ScType, lm_activity, NMF, Hotspot gene correlations, SCENIC,
CellPhoneDB) warn. Peaks and tiles are refused by every method that works on
genes.
Links and profiles. peak_to_gene correlates peaks with nearby genes
over groups of cells (ArchR's peak to gene links). fragment_profiles gives
the TSS insertion profile and the fragment length histogram per group, for
bv.pl.tss_profile_plot and bv.pl.fragment_length_plot.
Mapping and integration. project_lsi puts a query onto a reference
LSI (Seurat's lsiproject); run_rlsi integrates batches through
reciprocal LSI anchors. bv.integrate.harmony(x, "batch", embd_to_use="lsi",
modality="atac") corrects the LSI instead and writes "harmony" to the ATAC
cache.
Gotchas. run_tfidf computes the IDF over the kept cells: run it again,
then the LSI, after changing them; it also clears the ATAC cache.
calculate_lsi drops component 1 by default, as the Signac vignettes do;
get_lsi_depth_cor and bv.pl.lsi_depth_plot show whether that is right
for the data.
fragment_qc
¶
fragment_qc(
x: AtacHost,
fragments: Path | str,
gtf: Path | str,
*,
biotypes: Sequence[str] = ("protein_coding",),
mito_chroms: Sequence[str] = MITO_CHROMS,
barcode_map: BarcodeMap = None,
) -> DataFrame
Per-cell QC from the fragment file, written to obs.
Adds atac_n_fragments, atac_nucleosome_signal, atac_tss_enrichment
(Signac's fast definition) and atac_mito_fraction for every cell, plus
atac_frip on a peak store: its library size over the fragments, in the
store's count unit, so with insertion counts the share of insertions in
peaks (two per fragment) and otherwise Signac's fragments in peaks over
fragments.
The nucleosome signal is mononucleosomal over nucleosome-free fragments,
as in Signac: infinite for a cell with mononucleosomal but no
nucleosome-free fragments (a bad cell, which any upper threshold drops),
and 0 rather than Signac's NaN for a cell with neither, so robust
statistics over the column stay defined.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
AtacHost
|
The experiment. |
required |
fragments
|
Path | str
|
The fragment file. |
required |
gtf
|
Path | str
|
Gene annotation for the TSSs. |
required |
biotypes
|
Sequence[str]
|
Gene biotypes whose TSSs count (Signac: protein coding). |
('protein_coding',)
|
mito_chroms
|
Sequence[str]
|
Names of the mitochondrial genome. |
MITO_CHROMS
|
barcode_map
|
BarcodeMap
|
Cell id to fragment barcode, where they differ. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The obs columns added, with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no cell id is a barcode of the file, or the fragments and the GTF share no chromosome. |
fragment_profiles
¶
fragment_profiles(
x: AtacHost,
fragments: Path | str,
gtf: Path | str,
*,
group_by: str | None = None,
half_width: int = 2000,
max_len: int = 1000,
flank: int = 100,
biotypes: Sequence[str] = ("protein_coding",),
barcode_map: BarcodeMap = None,
) -> tuple[DataFrame, DataFrame]
TSS insertion profile and fragment length histogram of the kept cells.
One pass over the fragment file, per level of group_by (SnapATAC2's
TSS_profile and frag_size_distr, which these reproduce): insertions
are a fragment's start and end - 1, offsets are strand aware, positive
downstream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
AtacHost
|
The experiment. |
required |
fragments
|
Path | str
|
The fragment file. |
required |
gtf
|
Path | str
|
Gene annotation for the TSSs. |
required |
group_by
|
str | None
|
obs column to split by; |
None
|
half_width
|
int
|
Profile half width in bp. |
2000
|
max_len
|
int
|
Longest fragment length in the histogram. |
1000
|
flank
|
int
|
Bases at each end of the profile whose mean is the background of the enrichment. |
100
|
biotypes
|
Sequence[str]
|
Gene biotypes whose TSSs count. |
('protein_coding',)
|
barcode_map
|
BarcodeMap
|
Cell id to fragment barcode, where they differ. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
(insertions over the mean of both flanks); and |
tuple[DataFrame, DataFrame]
|
|
tuple[DataFrame, DataFrame]
|
For |
amulet
¶
amulet(
sc: SingleCells,
fragments: Path | str,
*,
restrict_beds: Sequence[Path | str] = (),
max_overlap: int = 2,
max_fragment_len: int = 900,
repeat_q: float = 0.01,
multiplet_q: float = 0.01,
chroms: Sequence[str] | None = None,
barcode_map: BarcodeMap = None,
max_mem_gb: float | None = None,
count_trailing_loci: bool = False,
) -> DataFrame
Flag multiplets from fragment overlaps (AMULET), written to obs.
A diploid nucleus yields at most two overlapping fragments at a locus. Per cell, the loci with more are counted (autosomes, restriction regions dropped), sites shared by too many cells are dropped as repeats, and the count is tested against the mean (Poisson, Benjamini-Hochberg). Implemented from Thibodeau et al. (Genome Biology, 2021); on the test data it reproduces the reference implementation's counts and p-values. Needs no clustering and no RNA, so it works for ATAC-only experiments. Run it per library: multiplets are a property of one capture.
Adds amulet_n_overlaps, amulet_n_sites, amulet_p, amulet_q and
amulet_multiplet for every cell of the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment; every cell of its store is tested. |
required |
fragments
|
Path | str
|
The fragment file. |
required |
restrict_beds
|
Sequence[Path | str]
|
BED files of regions to ignore: repeats, segmental duplications, blacklists. The paper uses all three. |
()
|
max_overlap
|
int
|
Overlapping fragments a cell can explain; 2 for diploid. |
2
|
max_fragment_len
|
int
|
Longest valid fragment. |
900
|
repeat_q
|
float
|
q-value under which a site is a repeat. |
0.01
|
multiplet_q
|
float
|
q-value under which a cell is a multiplet. |
0.01
|
chroms
|
Sequence[str] | None
|
Chromosomes to use; |
None
|
barcode_map
|
BarcodeMap
|
Cell id to fragment barcode, where they differ. |
None
|
max_mem_gb
|
float | None
|
Read budget; |
None
|
count_trailing_loci
|
bool
|
Count a cell's last loci on the last chromosome used, which the reference implementation drops. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The obs columns added, with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no fragment lies on a chromosome AMULET uses, or no restriction region does. |
Peaks¶
Single cell ATAC: peak or tile counts, QC, TF-IDF, LSI, links to genes.
Two kinds of experiment hold ATAC:
- a
SingleCellsMultiModalwith RNA: the ATAC counts live in a second store underatac/, written for every cell of the RNA store in the same order, so the RNA cell filter applies to both.bv.mm.generate_wnn_graphfuses the two. - a
SingleCellsAtac, ATAC only: the peaks or tiles are the experiment's own store. Load one withbv.io.load_atac_fragmentsorbv.io.load_atac_tenx.
Every function here takes either. From the LSI on, the regular single cell
functions take modality="atac" and embd_to_use="lsi"; on a
SingleCellsAtac the default modality means the ATAC store as well.
# multiome
mm = bv.SingleCellsMultiModal(sc.dir)
bv.atac.add_atac_tenx(mm, "filtered_feature_bc_matrix.h5")
bv.atac.fragment_qc(mm, "atac_fragments.tsv.gz", "genes.gtf.gz")
bv.atac.run_tfidf(mm)
bv.atac.find_top_features(mm, min_cutoff="q5")
bv.atac.calculate_lsi(mm, n_comp=30)
bv.mm.generate_wnn_graph(mm, modality_2="atac", embd_to_use_2="lsi")
# ATAC only
counts = bv.atac.barcode_fragment_counts("atac_fragments.tsv.gz")
x = bv.io.load_atac_fragments(
"exp", "atac_fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
)
Peaks or fragments. add_atac_tenx takes the peak matrix Cell Ranger ARC
wrote into the h5. add_atac_fragments counts the fragment file itself into
a BED of peaks or fixed-width tiles; its default mode="insertion" counts
each Tn5 insertion as Cell Ranger does, and reproduces the h5 matrix on
Cell Ranger's peaks.
Calling peaks. call_peaks calls peaks on the fragments per cluster
(group_by), a native port of MACS3 callpeak (exact coordinates and
summits against MACS3 3.1.0); Cell Ranger's peak set under-calls rare
populations. remove_blacklisted drops peaks on blacklist regions before
the result goes into add_atac_fragments(peaks=...). annotate_peaks
names each feature's closest gene.
Barcodes and files. Fragment barcodes are the cell ids unless
barcode_map says otherwise (a -1 suffix, a sample prefix).
merge_fragments merges per-sample fragment files into one, barcodes
prefixed per sample, as cellranger-arc aggr does. Every fragment pass
errors when no cell id is a barcode of the file or the fragments and the
features share no chromosome name, and warns on partial mismatches.
Multiplets. amulet flags multiplets from loci where more than two of a
cell's fragments overlap (AMULET); it needs no clustering and no RNA. Pass
repeat and blacklist BEDs as restrict_beds.
Gene activity. gene_activity counts fragments over gene body plus
promoter (Signac's GeneActivity) into its own SingleCells, the query side
of an RNA to ATAC label transfer; get_gene_activity reopens it with the
experiment's cell filter. It is not RNA: methods that assume an mRNA count
model (residuals, doublets, Bonsai, gene set proportions) refuse it, and
those biased by gene length or by fragments shared between neighbouring genes
(AUCell, ScType, lm_activity, NMF, Hotspot gene correlations, SCENIC,
CellPhoneDB) warn. Peaks and tiles are refused by every method that works on
genes.
Links and profiles. peak_to_gene correlates peaks with nearby genes
over groups of cells (ArchR's peak to gene links). fragment_profiles gives
the TSS insertion profile and the fragment length histogram per group, for
bv.pl.tss_profile_plot and bv.pl.fragment_length_plot.
Mapping and integration. project_lsi puts a query onto a reference
LSI (Seurat's lsiproject); run_rlsi integrates batches through
reciprocal LSI anchors. bv.integrate.harmony(x, "batch", embd_to_use="lsi",
modality="atac") corrects the LSI instead and writes "harmony" to the ATAC
cache.
Gotchas. run_tfidf computes the IDF over the kept cells: run it again,
then the LSI, after changing them; it also clears the ATAC cache.
calculate_lsi drops component 1 by default, as the Signac vignettes do;
get_lsi_depth_cor and bv.pl.lsi_depth_plot show whether that is right
for the data.
call_peaks
¶
call_peaks(
sc: SingleCells,
fragments: Path | str,
*,
group_by: str | None = None,
combine: bool = True,
tag_source: TagSource = "insertion",
keep_dup: int | None = None,
shift: int = -100,
extsize: int = 200,
genome_size: float = 2700000000.0,
llocal: int = 10000,
q_value: float = 0.05,
min_length: int | None = None,
max_gap: int | None = None,
barcode_map: BarcodeMap = None,
max_mem_gb: float | None = None,
tmp_dir: Path | str | None = None,
) -> DataFrame
Call peaks on the kept cells, pooled or per group (MACS3 callpeak).
A native port of MACS3 callpeak --nomodel without a control track, one
call per group, as Signac's CallPeaks(group.by = ...) runs MACS. Against
MACS3 3.1.0 the peak coordinates, summits and pileups are exact and the
scores agree to MACS's printed precision. Pass the result as peaks to
add_atac_fragments or load_atac_fragments to count against it.
Memory: with a tabix index next to the fragment file (.tbi, which Cell
Ranger writes), the file is read one chromosome at a time and the sorted
tags wait in a scratch file (4 bytes per tag) between passes. Without an
index every tag is held at once while reading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment; its kept cells are pooled. |
required |
fragments
|
Path | str
|
The fragment file. |
required |
group_by
|
str | None
|
obs column to call per level of (clusters, samples); |
None
|
combine
|
bool
|
Merge overlapping peaks across groups into one set, with the
groups each was called in. |
True
|
tag_source
|
TagSource
|
|
'insertion'
|
keep_dup
|
int | None
|
Tags kept per position; |
None
|
shift
|
int
|
Tag shift before extension ( |
-100
|
extsize
|
int
|
Tag extension, the fragment size ( |
200
|
genome_size
|
float
|
Effective genome size ( |
2700000000.0
|
llocal
|
int
|
Window of the local lambda ( |
10000
|
q_value
|
float
|
q-value cutoff ( |
0.05
|
min_length
|
int | None
|
Minimum peak length; |
None
|
max_gap
|
int | None
|
Largest gap merged into a peak; |
None
|
barcode_map
|
BarcodeMap
|
Cell id to fragment barcode, where they differ. |
None
|
max_mem_gb
|
float | None
|
Tag budget of the reading pass; |
None
|
tmp_dir
|
Path | str | None
|
Directory of the scratch file; |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
With |
DataFrame
|
|
DataFrame
|
group and peak, with |
DataFrame
|
|
DataFrame
|
none of whose cells has a fragment has no peaks. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
remove_blacklisted
¶
Drop the peaks that overlap a blacklist region.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peaks
|
DataFrame
|
Regions with |
required |
blacklist
|
Path | str | DataFrame
|
A BED file (plain or gzip) or a frame of regions, e.g. the ENCODE blacklist. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The peaks that touch no blacklist region, in order. |
annotate_peaks
¶
annotate_peaks(
x: AtacHost,
gtf: Path | str,
*,
biotypes: Sequence[str] = ("protein_coding",),
) -> DataFrame
The closest gene of every ATAC feature (Signac ClosestFeature).
Written to the ATAC feature table as closest_gene, closest_gene_id,
distance_to_gene (bases to the gene body, 0 inside or touching it)
and distance_to_tss (feature centre to TSS, positive downstream).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
AtacHost
|
The experiment. |
required |
gtf
|
Path | str
|
Gene annotation. |
required |
biotypes
|
Sequence[str]
|
Biotypes to consider, empty for all. |
('protein_coding',)
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
TF-IDF and LSI¶
Single cell ATAC: peak or tile counts, QC, TF-IDF, LSI, links to genes.
Two kinds of experiment hold ATAC:
- a
SingleCellsMultiModalwith RNA: the ATAC counts live in a second store underatac/, written for every cell of the RNA store in the same order, so the RNA cell filter applies to both.bv.mm.generate_wnn_graphfuses the two. - a
SingleCellsAtac, ATAC only: the peaks or tiles are the experiment's own store. Load one withbv.io.load_atac_fragmentsorbv.io.load_atac_tenx.
Every function here takes either. From the LSI on, the regular single cell
functions take modality="atac" and embd_to_use="lsi"; on a
SingleCellsAtac the default modality means the ATAC store as well.
# multiome
mm = bv.SingleCellsMultiModal(sc.dir)
bv.atac.add_atac_tenx(mm, "filtered_feature_bc_matrix.h5")
bv.atac.fragment_qc(mm, "atac_fragments.tsv.gz", "genes.gtf.gz")
bv.atac.run_tfidf(mm)
bv.atac.find_top_features(mm, min_cutoff="q5")
bv.atac.calculate_lsi(mm, n_comp=30)
bv.mm.generate_wnn_graph(mm, modality_2="atac", embd_to_use_2="lsi")
# ATAC only
counts = bv.atac.barcode_fragment_counts("atac_fragments.tsv.gz")
x = bv.io.load_atac_fragments(
"exp", "atac_fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
)
Peaks or fragments. add_atac_tenx takes the peak matrix Cell Ranger ARC
wrote into the h5. add_atac_fragments counts the fragment file itself into
a BED of peaks or fixed-width tiles; its default mode="insertion" counts
each Tn5 insertion as Cell Ranger does, and reproduces the h5 matrix on
Cell Ranger's peaks.
Calling peaks. call_peaks calls peaks on the fragments per cluster
(group_by), a native port of MACS3 callpeak (exact coordinates and
summits against MACS3 3.1.0); Cell Ranger's peak set under-calls rare
populations. remove_blacklisted drops peaks on blacklist regions before
the result goes into add_atac_fragments(peaks=...). annotate_peaks
names each feature's closest gene.
Barcodes and files. Fragment barcodes are the cell ids unless
barcode_map says otherwise (a -1 suffix, a sample prefix).
merge_fragments merges per-sample fragment files into one, barcodes
prefixed per sample, as cellranger-arc aggr does. Every fragment pass
errors when no cell id is a barcode of the file or the fragments and the
features share no chromosome name, and warns on partial mismatches.
Multiplets. amulet flags multiplets from loci where more than two of a
cell's fragments overlap (AMULET); it needs no clustering and no RNA. Pass
repeat and blacklist BEDs as restrict_beds.
Gene activity. gene_activity counts fragments over gene body plus
promoter (Signac's GeneActivity) into its own SingleCells, the query side
of an RNA to ATAC label transfer; get_gene_activity reopens it with the
experiment's cell filter. It is not RNA: methods that assume an mRNA count
model (residuals, doublets, Bonsai, gene set proportions) refuse it, and
those biased by gene length or by fragments shared between neighbouring genes
(AUCell, ScType, lm_activity, NMF, Hotspot gene correlations, SCENIC,
CellPhoneDB) warn. Peaks and tiles are refused by every method that works on
genes.
Links and profiles. peak_to_gene correlates peaks with nearby genes
over groups of cells (ArchR's peak to gene links). fragment_profiles gives
the TSS insertion profile and the fragment length histogram per group, for
bv.pl.tss_profile_plot and bv.pl.fragment_length_plot.
Mapping and integration. project_lsi puts a query onto a reference
LSI (Seurat's lsiproject); run_rlsi integrates batches through
reciprocal LSI anchors. bv.integrate.harmony(x, "batch", embd_to_use="lsi",
modality="atac") corrects the LSI instead and writes "harmony" to the ATAC
cache.
Gotchas. run_tfidf computes the IDF over the kept cells: run it again,
then the LSI, after changing them; it also clears the ATAC cache.
calculate_lsi drops component 1 by default, as the Signac vignettes do;
get_lsi_depth_cor and bv.pl.lsi_depth_plot show whether that is right
for the data.
run_tfidf
¶
Switch the ATAC store to TF-IDF over the kept cells (Signac method 1).
Header metadata only; no count is rewritten. Run again after the kept
cells change. Everything in the ATAC cache (LSI, embeddings, kNN) was
built on the old norm and is dropped; rerun calculate_lsi.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
AtacHost
|
The experiment, with ATAC. |
required |
scale
|
float
|
Scale factor of the term frequencies. |
TF_IDF_SCALE
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The IDF per feature. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no ATAC store was added. |
find_top_features
¶
The most accessible features (Signac FindTopFeatures).
Totals are summed over the kept cells; the ATAC feature table gains
count, percentile and top_feature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
AtacHost
|
The experiment, with ATAC. |
required |
min_cutoff
|
str | float | None
|
|
'q5'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
0-based indices of the top features. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no ATAC store was added, or for a malformed
|
calculate_lsi
¶
calculate_lsi(
x: AtacHost,
*,
n_comp: int = 50,
features: ndarray | Sequence[int] | None = None,
drop_first: bool = True,
solver: Literal[
"auto", "exact", "randomised", "covariance"
] = "auto",
scale_max: float | None = None,
seed: int = 42,
verbose: Verbose = 1,
) -> ndarray
LSI over the TF-IDF of the kept cells (Signac RunSVD).
The embedding (components z-scored over the cells) goes to
x.atac_cache.embeddings["lsi"], stamped "atac:lsi", for
find_neighbours, harmony, umap and generate_wnn_graph with
modality="atac", embd_to_use="lsi".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
AtacHost
|
The experiment, after |
required |
n_comp
|
int
|
Components to compute. |
50
|
features
|
ndarray | Sequence[int] | None
|
0-based features; |
None
|
drop_first
|
bool
|
Leave component 1 out of the embedding. It usually tracks
sequencing depth; |
True
|
solver
|
Literal['auto', 'exact', 'randomised', 'covariance']
|
SVD solver. |
'auto'
|
scale_max
|
float | None
|
Clip the z-scores to |
None
|
seed
|
int
|
Seed of the solver. |
42
|
verbose
|
Verbose
|
|
1
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The correlation of every component with the library size. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Before |
get_lsi_depth_cor
¶
Correlation of each LSI component with the library size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
AtacHost
|
The experiment, after |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Before |
Gene activity and links¶
Single cell ATAC: peak or tile counts, QC, TF-IDF, LSI, links to genes.
Two kinds of experiment hold ATAC:
- a
SingleCellsMultiModalwith RNA: the ATAC counts live in a second store underatac/, written for every cell of the RNA store in the same order, so the RNA cell filter applies to both.bv.mm.generate_wnn_graphfuses the two. - a
SingleCellsAtac, ATAC only: the peaks or tiles are the experiment's own store. Load one withbv.io.load_atac_fragmentsorbv.io.load_atac_tenx.
Every function here takes either. From the LSI on, the regular single cell
functions take modality="atac" and embd_to_use="lsi"; on a
SingleCellsAtac the default modality means the ATAC store as well.
# multiome
mm = bv.SingleCellsMultiModal(sc.dir)
bv.atac.add_atac_tenx(mm, "filtered_feature_bc_matrix.h5")
bv.atac.fragment_qc(mm, "atac_fragments.tsv.gz", "genes.gtf.gz")
bv.atac.run_tfidf(mm)
bv.atac.find_top_features(mm, min_cutoff="q5")
bv.atac.calculate_lsi(mm, n_comp=30)
bv.mm.generate_wnn_graph(mm, modality_2="atac", embd_to_use_2="lsi")
# ATAC only
counts = bv.atac.barcode_fragment_counts("atac_fragments.tsv.gz")
x = bv.io.load_atac_fragments(
"exp", "atac_fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
)
Peaks or fragments. add_atac_tenx takes the peak matrix Cell Ranger ARC
wrote into the h5. add_atac_fragments counts the fragment file itself into
a BED of peaks or fixed-width tiles; its default mode="insertion" counts
each Tn5 insertion as Cell Ranger does, and reproduces the h5 matrix on
Cell Ranger's peaks.
Calling peaks. call_peaks calls peaks on the fragments per cluster
(group_by), a native port of MACS3 callpeak (exact coordinates and
summits against MACS3 3.1.0); Cell Ranger's peak set under-calls rare
populations. remove_blacklisted drops peaks on blacklist regions before
the result goes into add_atac_fragments(peaks=...). annotate_peaks
names each feature's closest gene.
Barcodes and files. Fragment barcodes are the cell ids unless
barcode_map says otherwise (a -1 suffix, a sample prefix).
merge_fragments merges per-sample fragment files into one, barcodes
prefixed per sample, as cellranger-arc aggr does. Every fragment pass
errors when no cell id is a barcode of the file or the fragments and the
features share no chromosome name, and warns on partial mismatches.
Multiplets. amulet flags multiplets from loci where more than two of a
cell's fragments overlap (AMULET); it needs no clustering and no RNA. Pass
repeat and blacklist BEDs as restrict_beds.
Gene activity. gene_activity counts fragments over gene body plus
promoter (Signac's GeneActivity) into its own SingleCells, the query side
of an RNA to ATAC label transfer; get_gene_activity reopens it with the
experiment's cell filter. It is not RNA: methods that assume an mRNA count
model (residuals, doublets, Bonsai, gene set proportions) refuse it, and
those biased by gene length or by fragments shared between neighbouring genes
(AUCell, ScType, lm_activity, NMF, Hotspot gene correlations, SCENIC,
CellPhoneDB) warn. Peaks and tiles are refused by every method that works on
genes.
Links and profiles. peak_to_gene correlates peaks with nearby genes
over groups of cells (ArchR's peak to gene links). fragment_profiles gives
the TSS insertion profile and the fragment length histogram per group, for
bv.pl.tss_profile_plot and bv.pl.fragment_length_plot.
Mapping and integration. project_lsi puts a query onto a reference
LSI (Seurat's lsiproject); run_rlsi integrates batches through
reciprocal LSI anchors. bv.integrate.harmony(x, "batch", embd_to_use="lsi",
modality="atac") corrects the LSI instead and writes "harmony" to the ATAC
cache.
Gotchas. run_tfidf computes the IDF over the kept cells: run it again,
then the LSI, after changing them; it also clears the ATAC cache.
calculate_lsi drops component 1 by default, as the Signac vignettes do;
get_lsi_depth_cor and bv.pl.lsi_depth_plot show whether that is right
for the data.
gene_activity
¶
gene_activity(
sc: SingleCells,
fragments: Path | str,
gtf: Path | str,
*,
dir_out: Path | str | None = None,
upstream: int = 2000,
downstream: int = 0,
max_width: int = 500000,
biotypes: Sequence[str] = ("protein_coding",),
target_size: float | None = None,
barcode_map: BarcodeMap = None,
overwrite: bool = False,
max_mem_gb: float | None = None,
verbose: Verbose = 1,
) -> SingleCells
Count fragments over gene body plus promoter into a gene activity store.
Signac's GeneActivity: per gene, the longest span of its biotype, under
max_width, extended upstream of the TSS; each overlapping fragment
counts once. The result is a SingleCells over every cell of sc, in its
order and with its obs and cell filter, so it serves as the query of
bv.annotate.transfer_labels_seurat and of the RNA tools. Methods that
assume RNA counts refuse it or warn. Written to the default directory,
later cell filters on sc reach it; reopen it with get_gene_activity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment whose cell ids are the fragment barcodes. |
required |
fragments
|
Path | str
|
The fragment file (BGZF, gzip or plain). |
required |
gtf
|
Path | str
|
Gene annotation (GENCODE, Ensembl, or a transcript-only GTF). |
required |
dir_out
|
Path | str | None
|
Output directory. |
None
|
upstream
|
int
|
Bases added upstream of the TSS. |
2000
|
downstream
|
int
|
Bases added downstream of the gene end. |
0
|
max_width
|
int
|
Genes this long or longer are dropped. |
500000
|
biotypes
|
Sequence[str]
|
Biotypes to keep, empty for all. |
('protein_coding',)
|
target_size
|
float | None
|
Target of the log-CPM norm. |
None
|
barcode_map
|
BarcodeMap
|
Cell id to fragment barcode, where they differ. |
None
|
overwrite
|
bool
|
Replace an existing store at |
False
|
max_mem_gb
|
float | None
|
Memory budget of the gene-major conversion. |
None
|
verbose
|
Verbose
|
|
1
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The gene activity experiment. var holds |
SingleCells
|
without its version, as Cell Ranger keys the RNA), |
SingleCells
|
unique), |
SingleCells
|
the gene activity's. |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If a store exists at |
ValueError
|
If |
get_gene_activity
¶
get_gene_activity(
x: SingleCells, directory: Path | str | None = None
) -> SingleCells
Open an experiment's gene activity store, its cell filter brought in line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
SingleCells
|
The experiment the gene activity was counted for. |
required |
directory
|
Path | str | None
|
Where it was written; |
None
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The gene activity experiment, with |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If there is no store. |
ValueError
|
If it was written for other cells (a re-ingest since). |
peak_to_gene
¶
peak_to_gene(
mm: SingleCellsMultiModal,
gtf: Path | str,
group_by: str,
*,
max_distance: int = 250000,
biotypes: Sequence[str] = ("protein_coding",),
genes: Sequence[str] | None = None,
min_cells: int = 10,
fdr: float | None = 0.05,
verbose: Verbose = 1,
) -> DataFrame
Link peaks to nearby genes by correlation over groups of cells.
ArchR's addPeak2GeneLinks. Peak and gene counts are summed per level of
group_by (fine clusters, or metacell assignments, of the kept cells),
log-normalised per group,
log2(x / total * 1e4 + 1), and correlated over the groups for every
peak within max_distance of a gene's TSS. p-values are the two-sided
t-test of each correlation, FDR Benjamini-Hochberg over all pairs. Unlike
Signac's LinkPeaks there is no GC-matched background, which needs the
genome sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mm
|
SingleCellsMultiModal
|
A multi-modal experiment with RNA and ATAC. |
required |
gtf
|
Path | str
|
Gene annotation for the TSSs, matched to the RNA on |
required |
group_by
|
str
|
obs column whose levels are the groups; ArchR uses a few hundred groups of ~100 cells. |
required |
max_distance
|
int
|
Largest distance from a peak to a TSS. |
250000
|
biotypes
|
Sequence[str]
|
Gene biotypes to link. |
('protein_coding',)
|
genes
|
Sequence[str] | None
|
Gene ids to restrict to; |
None
|
min_cells
|
int
|
Groups with fewer kept cells are left out. |
10
|
fdr
|
float | None
|
Keep links below this FDR; |
0.05
|
verbose
|
Verbose
|
|
1
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
TSS), |
Raises:
| Type | Description |
|---|---|
ValueError
|
With fewer than three groups. |
Mapping and integration¶
Single cell ATAC: peak or tile counts, QC, TF-IDF, LSI, links to genes.
Two kinds of experiment hold ATAC:
- a
SingleCellsMultiModalwith RNA: the ATAC counts live in a second store underatac/, written for every cell of the RNA store in the same order, so the RNA cell filter applies to both.bv.mm.generate_wnn_graphfuses the two. - a
SingleCellsAtac, ATAC only: the peaks or tiles are the experiment's own store. Load one withbv.io.load_atac_fragmentsorbv.io.load_atac_tenx.
Every function here takes either. From the LSI on, the regular single cell
functions take modality="atac" and embd_to_use="lsi"; on a
SingleCellsAtac the default modality means the ATAC store as well.
# multiome
mm = bv.SingleCellsMultiModal(sc.dir)
bv.atac.add_atac_tenx(mm, "filtered_feature_bc_matrix.h5")
bv.atac.fragment_qc(mm, "atac_fragments.tsv.gz", "genes.gtf.gz")
bv.atac.run_tfidf(mm)
bv.atac.find_top_features(mm, min_cutoff="q5")
bv.atac.calculate_lsi(mm, n_comp=30)
bv.mm.generate_wnn_graph(mm, modality_2="atac", embd_to_use_2="lsi")
# ATAC only
counts = bv.atac.barcode_fragment_counts("atac_fragments.tsv.gz")
x = bv.io.load_atac_fragments(
"exp", "atac_fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
)
Peaks or fragments. add_atac_tenx takes the peak matrix Cell Ranger ARC
wrote into the h5. add_atac_fragments counts the fragment file itself into
a BED of peaks or fixed-width tiles; its default mode="insertion" counts
each Tn5 insertion as Cell Ranger does, and reproduces the h5 matrix on
Cell Ranger's peaks.
Calling peaks. call_peaks calls peaks on the fragments per cluster
(group_by), a native port of MACS3 callpeak (exact coordinates and
summits against MACS3 3.1.0); Cell Ranger's peak set under-calls rare
populations. remove_blacklisted drops peaks on blacklist regions before
the result goes into add_atac_fragments(peaks=...). annotate_peaks
names each feature's closest gene.
Barcodes and files. Fragment barcodes are the cell ids unless
barcode_map says otherwise (a -1 suffix, a sample prefix).
merge_fragments merges per-sample fragment files into one, barcodes
prefixed per sample, as cellranger-arc aggr does. Every fragment pass
errors when no cell id is a barcode of the file or the fragments and the
features share no chromosome name, and warns on partial mismatches.
Multiplets. amulet flags multiplets from loci where more than two of a
cell's fragments overlap (AMULET); it needs no clustering and no RNA. Pass
repeat and blacklist BEDs as restrict_beds.
Gene activity. gene_activity counts fragments over gene body plus
promoter (Signac's GeneActivity) into its own SingleCells, the query side
of an RNA to ATAC label transfer; get_gene_activity reopens it with the
experiment's cell filter. It is not RNA: methods that assume an mRNA count
model (residuals, doublets, Bonsai, gene set proportions) refuse it, and
those biased by gene length or by fragments shared between neighbouring genes
(AUCell, ScType, lm_activity, NMF, Hotspot gene correlations, SCENIC,
CellPhoneDB) warn. Peaks and tiles are refused by every method that works on
genes.
Links and profiles. peak_to_gene correlates peaks with nearby genes
over groups of cells (ArchR's peak to gene links). fragment_profiles gives
the TSS insertion profile and the fragment length histogram per group, for
bv.pl.tss_profile_plot and bv.pl.fragment_length_plot.
Mapping and integration. project_lsi puts a query onto a reference
LSI (Seurat's lsiproject); run_rlsi integrates batches through
reciprocal LSI anchors. bv.integrate.harmony(x, "batch", embd_to_use="lsi",
modality="atac") corrects the LSI instead and writes "harmony" to the ATAC
cache.
Gotchas. run_tfidf computes the IDF over the kept cells: run it again,
then the LSI, after changing them; it also clears the ATAC cache.
calculate_lsi drops component 1 by default, as the Signac vignettes do;
get_lsi_depth_cor and bv.pl.lsi_depth_plot show whether that is right
for the data.
project_lsi
¶
Project the query's kept cells onto the reference LSI.
Seurat's ProjectSVD(mode = "lsi") as FindTransferAnchors(reduction =
"lsiproject") runs it: the query's own TF-IDF times the reference
loadings, divided by the singular values, with no centring or scaling.
The reference "lsi" embedding is z-scored, the projection is not; L2
normalise both per cell before comparing them, as Seurat does. Components
the reference dropped are dropped here too. Either side may be
multi-modal or ATAC-only.
Written to query.atac_cache.embeddings as "lsi_projected".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference
|
AtacHost
|
The experiment after |
required |
query
|
AtacHost
|
The experiment to project, after |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Kept query cells x components. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Without a reference LSI or a query TF-IDF, or if a reference LSI feature is not in the query. |
run_rlsi
¶
run_rlsi(
x: AtacHost,
batch_column: str,
*,
embedding: str = "lsi",
features: ndarray | Sequence[int] | None = None,
dims: Sequence[int] = tuple(range(1, 30)),
n_comp: int = 30,
k_anchor: int = 5,
k_score: int = 30,
k_weight: int = 100,
sd: float = 1.0,
l2_norm: bool = True,
solver: Literal[
"auto", "exact", "randomised", "covariance"
] = "auto",
knn_params: KnnParams | None = None,
seed: int = 42,
verbose: Verbose = 1,
) -> ndarray
rLSI integration, Signac's FindIntegrationAnchors(reduction = "rlsi").
Then IntegrateEmbeddings. Per batch: IDF over its own cells, TF-IDF
and LSI of features; anchors between every batch pair in the
reciprocal LSI spaces; then embedding is corrected along the anchor
tree. Written to x.atac_cache.embeddings as "rlsi".
Signac integrates all LSI components and leaves component 1 out
afterwards: calculate_lsi(x, drop_first=False), run_rlsi(x, ...),
then "rlsi"[:, 1:]. With the default drop_first=True the depth
component is left out of the integration too, which changes the
correction weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
AtacHost
|
The experiment, after |
required |
batch_column
|
str
|
obs column with the batch of each cell. |
required |
embedding
|
str
|
The ATAC embedding to integrate. |
'lsi'
|
features
|
ndarray | Sequence[int] | None
|
0-based ATAC feature rows of the per-batch LSIs. |
None
|
dims
|
Sequence[int]
|
0-based per-batch LSI components the anchors use; the default
is Signac's |
tuple(range(1, 30))
|
n_comp
|
int
|
Components of the per-batch LSIs; must exceed |
30
|
k_anchor
|
int
|
Neighbours for the anchors. |
5
|
k_score
|
int
|
Neighbours for the anchor scores. |
30
|
k_weight
|
int
|
Anchors per cell in the correction weights. |
100
|
sd
|
float
|
Bandwidth divisor of the weights. |
1.0
|
l2_norm
|
bool
|
Scale and L2 normalise the anchor spaces. |
True
|
solver
|
Literal['auto', 'exact', 'randomised', 'covariance']
|
SVD solver of the per-batch LSIs. |
'auto'
|
knn_params
|
KnnParams | None
|
kNN backend. |
None
|
seed
|
int
|
Seed of the solvers and the kNN backend. |
42
|
verbose
|
Verbose
|
|
1
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The integrated embedding, kept cells x its dimensions. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Without the embedding, with fewer than two batches, or if
|