vignettes/allelespec.Rmd
allelespec.RmdAt a heterozygous SNP, both alleles are in the same nucleus and in the same ATAC-seq library. If one allele gets more reads than the other, the variant itself changes accessibility. This is allele-specific chromatin accessibility (ASC).
ChrAccR stores allele counts in a DsASC
object. It holds two matrices, reference reads and alternative reads,
with one row per SNP and one column per sample.
This vignette has two parts:
DsASC
object from BAM and VCF files. These chunks are shown but not run,
because they need the full dataset.The example comes from the immune cell atlas of (Calderon et al. 2019). The complete re-analysis is in the AlleleSpeC repository.
The ASC functions are in the alleleSpec branch of
ChrAccR. The example data are in
ChrAccRex.
if (!is.element('devtools', installed.packages()[,"Package"])) install.packages('devtools')
devtools::install_github("EpigenomeInformatics/ChrAccR", ref = "alleleSpec", dependencies = TRUE)
devtools::install_github("EpigenomeInformatics/ChrAccRex")
# needed for counting, for the sharing estimate and for the motif analysis
BiocManager::install(c("VariantAnnotation", "Rsamtools", "HDF5Array", "DelayedArray",
"JASPAR2020", "TFBSTools", "motifmatchr",
"BSgenome.Hsapiens.UCSC.hg38"))
install.packages("ashr")
library(ChrAccR)
library(GenomicRanges)
library(data.table)
library(ggplot2)
theme_set(theme_bw(base_size = 11))
ChrAccR. The
last box includes the optional filter for sites that are supported by at
least two donors.| Step | What happens | Function |
|---|---|---|
| 1 | Genotype each donor | GATK (outside R) |
| 2 | Remove mapping bias | WASP (outside R) |
| 3 | Build one SNP list for all donors | buildMasterSNPs() |
| 4 | Count reference and alternative reads | DsASC.gatk() |
| 5 | Keep SNPs in peaks |
annotateASCSites(),
filterASCByPeaks()
|
| 6 | Remove likely errors |
ascDropHomozygous(), ascFilterRegions(),
ascFilterCommonVariants()
|
| 7 | Sum technical replicates | ascPoolReplicates() |
| 8 | Test each site |
ascTestCounts(), calcASCStatistics()
|
| 9 | Optional: keep sites found in several donors | filterForRecurrence() |
| 10 | Compare conditions or cell types |
ascAggregate(), ascSharing()
|
| 11 | Link imbalance to TF motifs |
ascMotifPreference(),
ascPreferenceTable(), ascPreferenceTest()
|
Steps 1 and 2 run outside R. Every step after WASP is a
ChrAccR function.
The example holds one donor (1001) with resting and stimulated samples. Steps 1 to 7 of the workflow are already done. It also contains precomputed motif scores.
example <- ChrAccRex::loadExample("dsAsc_ia_example")
dsDemo <- example$ds
deltaDemo <- example$delta
annotDemo <- as.data.table(getSampleAnnot(dsDemo))
dsDemo> DsASC allele-specific chromatin accessibility dataset
> contains:
> * 34 samples
> * 211 heterozygous SNP sites
> * accessibility: not loaded
> * allele assays: ref, alt
getRefCounts() and getAltCounts() return
the two count matrices. getAllelicBalance() returns the
fraction of reads on the alternative allele, and sets sites below
minCoverage to NA.
> [1] 211 34
> Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
> 0.000 0.375 0.488 0.482 0.588 1.000 5384
The median should be close to 0.5. Most heterozygous sites are balanced, and ASC sites are the exceptions.
calcASCStatistics() runs a two-sided binomial test
against 0.5 for every site in every sample. P-values are corrected with
the Benjamini-Hochberg method within each sample.
Two thresholds decide which sites are tested:
minCoverage: the number of reads a site needs in
total.minAllele: the number of reads each allele needs. This
removes sites where only one allele was seen, which are often genotyping
errors.
ascStats <- calcASCStatistics(dsDemo, minCoverage = 10, minAllele = 2)> 2026-11-15 17:43:26 2.0 STATUS STARTED Calculating ASC Statistics (binomial test vs p = 0.5)
> 2026-11-15 17:43:26 2.1 INFO Running two-sided binomial test against p = 0.5
> 2026-11-15 17:43:26 2.1 INFO Tested 1747 site-sample observations; 47 significant at FDR < 0.1.
> 2026-11-15 17:43:26 2.1 STATUS COMPLETED Calculating ASC Statistics (binomial test vs p = 0.5)
ascStats[order(fdr)][1:5, .(snpId, sampleId, ref, alt, total, log2FC, fdr)]> snpId sampleId ref alt total log2FC
> <char> <char> <num> <num> <num> <num>
> 1: chr20:25390923_C_T Bmem_S_1002_b 6 45 51 2.716207
> 2: chr20:844525_A_G TeffNaive_U_1001_a 29 3 32 -2.906891
> 3: chr20:62938103_G_C Bmem_U_1001_a 24 2 26 -3.058894
> 4: chr20:2301403_A_C Bmem_U_1001_b 6 32 38 2.237039
> 5: chr20:844525_A_G TeffNaive_S_1001_b 21 3 24 -2.459432
> fdr
> <num>
> 1: 1.337625e-06
> 2: 3.450620e-04
> 3: 1.468658e-03
> 4: 3.578356e-03
> 5: 7.793037e-03
A site with an FDR below 0.1 is called ASC. The volcano plot shows effect size against significance. The Manhattan plot shows the same calls along the genome.
plotASCVolcano(dsDemo, stats = ascStats, sigCut = 0.1)
plotASCManhattan(dsDemo, stats = ascStats, sigCut = 0.1)
With several donors, you can keep only the sites that are significant in at least two of them. This step is optional.
recurrent <- filterForRecurrence(ascStats, minDonors = 2, fdrCutoff = 0.1)plotASCBalance() shows one site in every sample. Each
row is a sample, the point is the fraction of reads on the reference
allele, and the bar is its 95% confidence interval. Faded points are not
significant.
topSite <- ascStats[order(fdr)][1, snpId]
plotASCBalance(dsDemo, topSite, colorBy = "stimulus", orderBy = "cellType",
sigStats = ascStats, sigCut = 0.1) +
scale_colour_manual(values = c(S = "#C0392B", U = "#2C7FB8"), name = "stimulus")
Is a site that is imbalanced in resting cells also imbalanced after
stimulation? ascAggregate() sums the reads over a set of
samples. ascSharing() takes the sites that are significant
in the first set and sorts them into three groups in the second set:
minReadsB
reads, so the site cannot be judged.ashr (Stephens 2017).
resting <- ascAggregate(refMat, altMat, annotDemo[stimulus == "U", sampleId])
stimulated <- ascAggregate(refMat, altMat, annotDemo[stimulus == "S", sampleId])
ascSharing(resting$ref, resting$alt, stimulated$ref, stimulated$alt,
fdrA = 0.01, minReadsB = 4)> $n_total
> [1] 28
>
> $Inaccessible
> [1] 0
>
> $NotShared
> [1] 0.4285714
>
> $Shared
> [1] 0.5714286
The result is the fraction of sites in each group. It is
NULL if no site is significant in the first set. The same
call works for two cell types: pass the samples of each cell type to
ascAggregate().
If a variant weakens a TF motif, the allele with the weaker motif
should be less accessible. ascMotifPreference() scores the
sequence around each SNP with a motif, once per allele, and gives each
SNP a preference:
prefDelta, and a motif match overlaps the SNP.Here we score two motifs of JASPAR 2020 (Fornes et al. 2020): JUNB, which is activated by stimulation, and CTCF as a control.
motifPkgs <- c("JASPAR2020", "TFBSTools", "motifmatchr", "BSgenome.Hsapiens.UCSC.hg38")
canScore <- all(sapply(motifPkgs, requireNamespace, quietly = TRUE))
pwms <- lapply(c(JUNB = "MA0490.2", CTCF = "MA0139.1"), function(id)
TFBSTools::getMatrixByID(JASPAR2020::JASPAR2020, id))
prefDt <- ascMotifPreference(rownames(refMat), pwms,
genome = BSgenome.Hsapiens.UCSC.hg38::BSgenome.Hsapiens.UCSC.hg38)
prefDt[, .N, by = .(tf, preference)]> tf preference N
> <char> <char> <int>
> 1: JUNB_MA0490.2 No preference 210
> 2: JUNB_MA0490.2 Alternative 1
> 3: CTCF_MA0139.1 No preference 179
> 4: CTCF_MA0139.1 Alternative 15
> 5: CTCF_MA0139.1 Reference 17
Without the motif packages, the scores that come with the example are used instead.
prefDt <- copy(deltaDemo)
prefDt[, preference := fifelse(delta > 1, "Alternative",
fifelse(delta < -1, "Reference", "No preference"))]
prefDt[, .N, by = .(tf, preference)]ascPreferenceTable() adds the reference allele fraction
of each SNP in a set of samples. We use resting and stimulated samples
of one cell type. SNPs with fewer than four reads are dropped.
# the cell type with the most samples in both conditions
ctCounts <- annotDemo[, .(nU = sum(stimulus == "U"), nS = sum(stimulus == "S")), by = cellType]
focusCt <- ctCounts[nU > 0 & nS > 0][order(-(nU + nS))][1, cellType]
samplesU <- annotDemo[cellType == focusCt & stimulus == "U", sampleId]
samplesS <- annotDemo[cellType == focusCt & stimulus == "S", sampleId]
prefTab <- rbind(
ascPreferenceTable(refMat, altMat, samplesU, prefDt, minReads = 4)[, condition := "Resting"],
ascPreferenceTable(refMat, altMat, samplesS, prefDt, minReads = 4)[, condition := "Stimulated"])
prefTab[, preference := factor(preference, levels = c("Alternative", "No preference", "Reference"))]If the TF opens chromatin, SNPs that prefer the reference allele lie above 0.5 and SNPs that prefer the alternative allele lie below it.
ggplot(prefTab, aes(x = condition, y = refFrac, fill = preference)) +
geom_hline(yintercept = 0.5, linetype = "dotted") +
geom_boxplot(outlier.size = 0.3, position = position_dodge(width = 0.8)) +
facet_wrap(~ tf, ncol = 4) +
scale_fill_manual(values = c("Alternative" = "#1B9E77",
"No preference" = "#D95F02",
"Reference" = "#7570B3"), name = "Binding preference") +
labs(x = NULL, y = "Proportion of reads on the reference allele", title = focusCt) +
theme(legend.position = "bottom")
ascPreferenceTest() compares the two groups of each
motif with a Wilcoxon test. The table also gives the number of SNPs in
each group.
tests <- prefTab[, ascPreferenceTest(.SD), by = condition]
tests[, pAdj := p.adjust(p, method = "bonferroni")] # over all motifs and both conditions
tests> condition tf sitesReference sitesAlternative refFracReference
> <char> <char> <int> <int> <num>
> 1: Resting CTCF_MA0139.1 16 14 0.4837091
> 2: Resting JUNB_MA0490.2 0 1 NaN
> 3: Stimulated CTCF_MA0139.1 16 14 0.5322168
> 4: Stimulated JUNB_MA0490.2 0 1 NaN
> refFracAlternative p diff pAdj z
> <num> <num> <num> <num> <num>
> 1: 0.5604750 0.1700694 -0.07676592 0.3401389 -1.3719808
> 2: 0.3437500 NA NaN NA NA
> 3: 0.6085105 0.3183743 -0.07629369 0.6367486 -0.9978042
> 4: 0.5500000 NA NaN NA NA
In the full dataset, the AP-1 family motifs (BATF, FOSL1, JUNB and others) separate weakly in resting cells and strongly after stimulation. Motifs such as CTCF, GATA3, IRF4, NFKB1 and TCF7 do not separate after stimulation.
The chunks in this section are not run.
{donor}_heterozygous.vcf.gz. Without genotyping
arrays, the SNPs can be called from the ATAC-seq reads with GATK
HaplotypeCaller (McKenna et al. 2010).sampleId, bamFilename and donor.
Add cellType and stimulus for the
comparisons.DsATAC object of the same samples.Each donor is heterozygous at different sites.
buildMasterSNPs() reads all VCF files and returns one
sorted list, so that all objects have the same rows.
masterGr <- buildMasterSNPs(donors = unique(meta$donor), vcfDir = vcfDir, genome = "hg38")DsASC.gatk() counts the reference and alternative reads
at every SNP. A sample is counted only at the SNPs that are heterozygous
in its donor; all other entries are NA. With
diskDump = TRUE the counts are kept on disk, which saves
memory.
dsAsc <- DsASC.gatk(
sampleAnnot = as.data.frame(meta),
vcfDir = vcfDir,
genome = "hg38",
diskDump = TRUE,
masterGr = masterGr
)For a large dataset, run one job per cell type and pass the same
masterGr to each.
dsAtac <- loadDsAcc(atacDir)
peakGr <- getCoord(dsAtac, "cons_peaks")
names(peakGr) <- paste0("peak_", seq_along(peakGr))
dsAsc <- filterChroms(dsAsc, remove = c("chrX", "chrY", "chrM"))
dsAsc <- filterLowCovg(dsAsc, thresh = 5, reqSamples = 1) # 5 reads in at least one sample
dsAsc <- annotateASCSites(dsAsc, peakGr)
dsAsc <- filterASCByPeaks(dsAsc)Four steps clean the counts before testing. Each one removes a known source of false calls.
refMat <- as.matrix(getRefCounts(dsAsc))
altMat <- as.matrix(getAltCounts(dsAsc))
annot <- as.data.table(getSampleAnnot(dsAsc))
# 1. Genotyping errors: a site that shows only one allele in all reads of a donor
# is homozygous. Its counts are set to zero for that donor.
cleaned <- ascDropHomozygous(refMat, altMat, annot, minMinor = 2L, minTotal = 10L)
# 2. Regions with poor mappability: remove SNPs in the ENCODE blacklist.
keepIds <- ascFilterRegions(rownames(cleaned$ref), blacklistGr)
# 3. Rare variants: keep SNPs with an allele frequency above 1% in 1000 Genomes.
# Rare and unknown variants are often homozygous sites that were called heterozygous.
library(MafDb.1Kgenomes.phase3.GRCh38)
keepIds <- ascFilterCommonVariants(keepIds, MafDb.1Kgenomes.phase3.GRCh38, minMaf = 0.01)
# 4. Technical replicates: sum them, so that each test uses one biological sample.
pooled <- ascPoolReplicates(cleaned$ref[keepIds, ], cleaned$alt[keepIds, ], annot,
groupCols = c("cellType", "stimulus", "donor"))Step 3 matters most when the genotypes come from the ATAC-seq reads. With genotypes from arrays you can skip it.
ascTestCounts() runs the same test as
calcASCStatistics(), but on the cleaned count matrices.
ascStats <- ascTestCounts(pooled$ref, pooled$alt, minCoverage = 10, minAllele = 2)
ascStats[fdr < 0.1, .N, by = sampleId] # ASC sites per sampleThe functions of the quick start take the same count matrices:
# resting against stimulated
resting <- ascAggregate(pooled$ref, pooled$alt, pooled$annot[stimulus == "U", sampleId])
stimulated <- ascAggregate(pooled$ref, pooled$alt, pooled$annot[stimulus == "S", sampleId])
ascSharing(resting$ref, resting$alt, stimulated$ref, stimulated$alt)
# TF motifs
prefDt <- ascMotifPreference(rownames(pooled$ref), pwms, genome = BSgenome.Hsapiens.UCSC.hg38)
prefTab <- ascPreferenceTable(pooled$ref, pooled$alt, pooled$annot[stimulus == "S", sampleId], prefDt)
ascPreferenceTest(prefTab)> R version 4.4.1 (2024-06-14)
> Platform: x86_64-conda-linux-gnu
> Running under: Debian GNU/Linux 12 (bookworm)
>
> Matrix products: default
> BLAS/LAPACK: /icbb/projects/share/software/packages/miniconda3/envs/alleleSpec/lib/libopenblasp-r0.3.30.so; LAPACK version 3.12.0
>
> locale:
> [1] C
>
> time zone: Europe/Berlin
> tzcode source: system (glibc)
>
> attached base packages:
> [1] stats4 stats graphics grDevices utils datasets methods
> [8] base
>
> other attached packages:
> [1] ggplot2_4.0.1 data.table_1.17.8 GenomicRanges_1.58.0
> [4] GenomeInfoDb_1.42.3 IRanges_2.40.1 S4Vectors_0.44.0
> [7] BiocGenerics_0.52.0 ChrAccR_0.9.26
>
> loaded via a namespace (and not attached):
> [1] JASPAR2020_0.99.10 RColorBrewer_1.1-3
> [3] jsonlite_2.0.0 magrittr_2.0.4
> [5] farver_2.1.2 rmarkdown_2.30
> [7] fs_1.6.6 BiocIO_1.16.0
> [9] zlibbioc_1.52.0 ragg_1.5.0
> [11] vctrs_0.6.5 memoise_2.0.1
> [13] Rsamtools_2.22.0 RCurl_1.98-1.17
> [15] SQUAREM_2021.1 mixsqp_0.3-54
> [17] htmltools_0.5.8.1 S4Arrays_1.6.0
> [19] curl_8.1.0 truncnorm_1.0-9
> [21] Rhdf5lib_1.28.0 CNEr_1.42.0
> [23] SparseArray_1.6.2 rhdf5_2.50.0
> [25] sass_0.4.10 bslib_0.9.0
> [27] htmlwidgets_1.6.4 desc_1.4.3
> [29] plyr_1.8.9 cachem_1.1.0
> [31] GenomicAlignments_1.42.0 mime_0.13
> [33] lifecycle_1.0.4 pkgconfig_2.0.3
> [35] Matrix_1.7-4 R6_2.6.1
> [37] fastmap_1.2.0 GenomeInfoDbData_1.2.13
> [39] MatrixGenerics_1.18.1 digest_0.6.39
> [41] colorspace_2.1-4 TFMPvalue_0.0.9
> [43] AnnotationDbi_1.68.0 irlba_2.3.5.1
> [45] textshaping_1.0.1 RSQLite_2.4.5
> [47] seqLogo_1.72.0 invgamma_1.2
> [49] labeling_0.4.3 httr_1.4.7
> [51] abind_1.4-8 compiler_4.4.1
> [53] bit64_4.6.0-1 withr_3.0.2
> [55] S7_0.2.1 BiocParallel_1.40.2
> [57] DBI_1.2.3 HDF5Array_1.34.0
> [59] R.utils_2.13.0 poweRlaw_1.0.0
> [61] DelayedArray_0.32.0 rjson_0.2.23
> [63] gtools_3.9.5 caTools_1.18.3
> [65] tools_4.4.1 R.oo_1.27.1
> [67] glue_1.8.0 restfulr_0.0.17
> [69] rhdf5filters_1.18.0 grid_4.4.1
> [71] reshape2_1.4.5 TFBSTools_1.44.0
> [73] generics_0.1.4 BSgenome_1.74.0
> [75] gtable_0.3.6 tzdb_0.5.0
> [77] R.methodsS3_1.8.2 hms_1.1.4
> [79] XVector_0.46.0 motifmatchr_1.30.0
> [81] pillar_1.11.1 stringr_1.6.0
> [83] muRtools_0.9.6 dplyr_1.1.4
> [85] lattice_0.22-7 rtracklayer_1.66.0
> [87] bit_4.6.0 annotate_1.84.0
> [89] BSgenome.Hsapiens.UCSC.hg38_1.4.5 tidyselect_1.2.1
> [91] DirichletMultinomial_1.48.0 GO.db_3.20.0
> [93] Biostrings_2.74.1 knitr_1.50
> [95] SummarizedExperiment_1.36.0 xfun_0.62
> [97] Biobase_2.66.0 matrixStats_1.5.0
> [99] stringi_1.8.7 UCSC.utils_1.2.0
> [101] yaml_2.3.11 evaluate_1.0.5
> [103] codetools_0.2-20 ChrAccRex_0.4
> [105] tibble_3.3.0 cli_3.6.5
> [107] xtable_1.8-4 systemfonts_1.3.1
> [109] jquerylib_0.1.4 dichromat_2.0-0.1
> [111] Rcpp_1.1.0 png_0.1-8
> [113] XML_3.99-0.20 parallel_4.4.1
> [115] pkgdown_2.2.0 readr_2.1.6
> [117] blob_1.2.4 bitops_1.0-9
> [119] pwalign_1.2.0 muLogR_0.2
> [121] scales_1.4.0 crayon_1.5.3
> [123] rlang_1.1.6 ashr_2.2-63
> [125] KEGGREST_1.46.0