---
title: "loopQTL"
output:
BiocStyle::html_document:
toc: true
toc_depth: 2
package: loopQTL
author: Rhie Lab at the University of Southern California
description: >
This vignette describes the basic usage of the loopQTL package to map
chromatin loop QTLs from Hi-C: which SNPs at a chromatin loop's
anchors associate with the loop's contact strength across samples.
vignette: >
%\VignetteIndexEntry{Using loopQTL}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
\RaggedRight
```{r knitr-setup, echo = FALSE, message = FALSE}
## `crop = NULL` resolves "The magick package is required to crop ..." error;
## see: https://stat.ethz.ch/pipermail/bioc-devel/2020-April/016656.html
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", crop = NULL)
options(tibble.print_min = 4, tibble.print_max = 4)
```
## Introduction
loopQTL identifies SNPs associated with chromatin interaction signals across
samples. It implements a band-wise joint normalization approach
(referenced from Brant et al, Brief Bioinform, 2024) that systematically
tests the association between variants and their anchored loops,
together with downstream functions for annotation and visualization
for the user's convenience.
# Acquiring and installing loopQTL and associated packages
## System requirements
R 4.6 or a newer version is required.
On Ubuntu 24.04, successful installation required several additional packages.
They can be installed by running the following command in a terminal:
```sh
sudo apt-get install r-base-dev libcurl4-openssl-dev libfreetype-dev \
libfribidi-dev libfontconfig-dev libharfbuzz-dev libtiff-dev \
libxml2-dev libssl-dev
```
No dependencies other than R are required on macOS or Windows.
## Installation
Two versions of the package are available.
To install the stable version from Bioconductor, start R and run:
```{r install-bioc, eval = FALSE}
## Install BiocManager, which is required to install packages from Bioconductor
if (!requireNamespace("BiocManager", quietly = TRUE)) {
install.packages("BiocManager")
}
BiocManager::install("loopQTL")
```
The development version containing the most recent updates is available from
our GitHub repository ().
To install the development version from GitHub, start R and run:
```{r install-github, eval = FALSE}
## Install prerequisite packages to install the development version from GitHub
if (!requireNamespace("BiocManager", quietly = TRUE)) {
install.packages("BiocManager")
}
if (!requireNamespace("remotes", quietly = TRUE)) {
install.packages("remotes")
}
BiocManager::install(version = "devel")
BiocManager::install("rhielab/loopQTL")
```
# Overview
1. `loopQTLsetup` - Validate the multi-sample VCF header and per-sample
`.hic` metadata, read per-sample loop BEDPEs, and build the
exact-coordinate consensus loop set kept in `loops(obj)`.
2. `loopQTLnormalize` - Per-chromosome whole-genome straw pull followed by
band-wise quantile normalization across samples The output is saved in
`phenotype(obj)`. Optionally caches per-SNP contact-window matrices to a
file for later visualization with `loopQTLplotSnpWindow()` or
`loopQTLnormalize()`.
3. `loopQTLchooseK` - Runs PCA on the normalized phenotype matrix and picks
K via PCAForQTL's method. This function returns the chosen K and the
corresponding sample PCs.
4. `runQTL` - Tabix-reads anchor-window SNPs from the VCF, runs MatrixEQTL
to perform the loopQTL analysis. The output is saved in `results(obj)`.
5. `loopQTLpairData` - Return the sample-level phenotype and genotype for a
single `(loopID, snpID)` pair - the row-level view behind any per-pair
downstream plot or custom test.
6. `loopQTLannotate` - Adds `gene`, `peak` (optional), and `Type` columns
to `results(obj)` using a GTF for TSS mapping and an optional peak BED
file for regulatory-element overlap.
7. `loopQTLplotPair` - Generates boxplot of the loop's contact-strength
phenotype grouped by the SNP's dosage class (0/1/2), for a specific SNP-loop
pair.
8. `loopQTLplotLocus` - Locus-level ggplot track combining consensus loops,
the tested SNP, and (optionally) gene annotations, over a user-specified
genomic region.
9. `loopQTLplotSnpWindow` - Hi-C-style beta heatmap around a chosen SNP: for
every bin-pair in the SNP's neighborhood, plots the per-sample
regression coefficient of phenotype on the SNP's dosage.
To begin, load `loopQTL` and any downstream plotting deps.
```{r setup, message = FALSE}
library(loopQTL)
library(ggplot2)
```
## `loopQTLsetup`: Validate inputs and build loopQTL object
`loopQTLsetup()` is the entry point of the pipeline. It:
* validates the input files header, including .vcf and .hic files;
* reads each per-sample BEDPE and builds a consensus loop set by
exact-coordinate matching. Loops found fewer than `minSamples`
samples will be dropped;
* Automatically computes per-sample cis-contact depth from the `.hic` files
when the samplesheet lacks a `cis` column.
The samplesheet is a tab-separated file with columns `Sample`, `hic`,
`loops`, and optionally `cis`.
```{r prepare-samplesheet}
extdataDir <- system.file("extdata", package = "loopQTL")
vcfPath <- file.path(extdataDir, "example.vcf.gz")
samplesheetPath <- file.path(extdataDir, "example_samplesheet.tsv")
samples <- read.table(samplesheetPath, header = TRUE)
## Fix the input file paths to be absolute since we don't know what the working
## directory will be when the vignette is built. It is not necessary to do this
## during normal use of loopQTL if the working directory is set correctly.
samples$hic <- unlist(
lapply(samples$hic, function(x) {
file.path(extdataDir, x)
})
)
samples$loops <- unlist(
lapply(samples$loops, function(x) {
file.path(extdataDir, x)
})
)
## Display the format of the samplesheet
head(samples)
```
```{r run-setup}
## Run loopQTLsetup
obj <- loopQTLsetup(
samples = samples,
vcf = vcfPath,
resolution = 5000,
minSamples = 2
)
obj
```
## `loopQTLnormalize`: Cross-normalization on Hi-C signal
`loopQTLnormalize()` normalizes contact strength across samples so that
per-loop phenotypes are directly comparable. For each chromosome it pulls
the whole-genome straw matrix per sample, log-CPM adjusts, then does
band-wise quantile normalization across samples per genomic-distance band.
Normalized values at the consensus-loop bin-pairs are written to
`phenotype(obj)`. Parallelizes per chromosome via `BiocParallel`.
Set `saveWindows = TRUE` to additionally output a per-SNP contact-window
matrix as .rds file. This file is needed by `loopQTLplotSnpWindow()`
downstream. Please note that this option does not change `phenotype(obj)`
or affect the `runQTL()` step.
```{r run-normalize}
## Get the path to a temporary directory in which to save the output interact
## file
tempDirectory <- tempdir()
obj <- loopQTLnormalize(
obj,
BPPARAM = BiocParallel::MulticoreParam(workers = 2),
saveWindows = TRUE,
windowsOut = file.path(tempDirectory, "loop_snp_windows.rds"),
window = 2000000,
snpWindow = 10000
)
head(phenotype(obj)[, 1:5])
```
## `loopQTLchooseK`: Auto-select the number of PCs for covariates
`loopQTLchooseK()` runs PCA on the normalized phenotype matrix and picks a
number of principal components K to use as covariates in the downstream
regression. This function returns a list with the chosen K and the
sample × K matrix of PCs.
```{r run-chooseK}
Kres <- loopQTLchooseK(obj, Kmethod = "elbow", Kmax = 2)
message("PCAForQTL chose K = ", Kres$K, " via ", Kres$method)
head(Kres$PCs)
```
## `runQTL`: Anchor-restricted association testing
`runQTL()` reads all anchor-window SNPs from the VCF in a single targeted
tabix pass, converts them to dosages (0/1/2), and runs MatrixEQTL twice -
once treating anchor A as the gene position, once anchor B. The two result
tables are outer-joined on SNP-loop level. Covariates are supplied via the
`covariates` argument - typically the phenotype PCs chosen in the previous step.
RINT is applied per loop before regression by default.
```{r run-qtl}
obj <- runQTL(
obj,
window = 10000,
covariates = Kres$PCs
)
head(results(obj))
```
## `loopQTLpairData`: Sample-level view of one loop × SNP pair
`loopQTLpairData()` returns the per-sample phenotype and genotype
(dosage 0/1/2) for a single SNP-loop pair. Useful for inspecting a
specific hit or exporting sample-level values for reporting.
```{r run-pairData}
pair <- loopQTLpairData(
obj,
loopID = "L0000037_chr2_172207000_172457000",
snpID = "rs12052253"
)
head(pair)
```
## `loopQTLannotate`: Annotate results with target genes and regulatory peaks
`loopQTLannotate()` adds three columns to `results(obj)`:
* **`gene`** - comma-separated gene names whose TSS (± `TSSwindow`) sits in
the SNP's *partner* anchor.
* **`peak`** - logical: does the SNP overlap any peak from the user-supplied
peak file . If the distal TSS peaks are preferred, then you can set
`removeTSS = TRUE``.
* **`Type`** - annotation of each SNP-loop pair such as `WithinTSS`, `rs-gene`,
`rs-`, `rs-O`, `rs()-gene`, or
`rs()-` summarizing the SNP–loop types.
```{r run-annotate}
peaksPath <- system.file(
"extdata", "example_annotation.bed",
package = "loopQTL"
)
gtfPath <- system.file("extdata", "example.gtf.gz", package = "loopQTL")
obj <- loopQTLannotate(
obj,
peak = peaksPath,
peakAnnotation = "Enhancer",
TSSwindow = 2000,
removeTSS = TRUE,
gtf = gtfPath
)
head(results(obj))
```
## `loopQTLplotPair`: Boxplot of loop strength by SNP dosage
`loopQTLplotPair()` renders the per-sample boxplot behind a chosen result
SNP-loop pair. Please note that the plot is a ggplot object that you can save
with `ggsave()`.
```{r run-plotPair}
p <- loopQTLplotPair(
obj,
loopID = "L0000037_chr2_172207000_172457000",
snpID = "rs12052253"
)
p
```
## `loopQTLplotLocus`: Locus-level track view of loops, SNPs, and genes
`loopQTLplotLocus()` renders a locus-scale ggplot combining the consensus
loops, the tested SNP, and (when a GTF is supplied) gene annotations, over
a user-specified region. Please note that to sse `values = "cpm"` or
`values = "raw"` to show per-loop contact strength, you need to set
`saveWindows = TRUE` to save the per-SNP contact-window matrices from
loopQTLnormalize.
```{r run-plotLocus}
gtfPath <- system.file("extdata", "example.gtf.gz", package = "loopQTL")
p <- loopQTLplotLocus(
obj,
chrom = "chr2",
start = 172100000,
end = 172550000,
snpID = "rs12052253",
values = "cpm",
gtf = gtfPath
)
p
```
## `loopQTLplotSnpWindow`: Hi-C-style beta heatmap around a SNP
`loopQTLplotSnpWindow()` renders a Hi-C-style heatmap centered on a chosen
SNP: for every bin-pair in the SNP's cached contact window (from
`loopQTLnormalize(saveWindows = TRUE)`), the color encodes the per-sample
regression coefficient (beta) of the bin-pair's contact strength on the SNP's
dosage. Set `normal = TRUE` and `covariates = "auto"` to match the model
used in `runQTL()`.
```{r run-plotSnpWindow}
p <- loopQTLplotSnpWindow(
obj,
chrom = "chr2",
start = 172100000,
end = 172550000,
snpID = "rs12052253",
normal = TRUE,
covariates = "auto",
Kmax = 2
)
## Delete the output file, since this is just an example.
## Do not use this line if running on real data, as it will delete your created
## file.
invisible(file.remove(metadata(obj)$windowsOut))
p
```
# Interoperability with other Bioconductor packages
`loopQTL` is designed to plug into the standard Bioconductor data
structures for genomic ranges and interactions, so that loops, SNPs, and
QTL results can be composed with tools from `GenomicRanges`,
`InteractionSet`, `SummarizedExperiment`, `rtracklayer`, and
`VariantAnnotation` without any intermediate format conversion. See below
example usuage.
## `loops(obj)` is a `GInteractions`
```{r interop-ginteractions}
gi <- loops(obj)
class(gi)
## Anchors are plain GRanges and can be used with the full
## GenomicRanges functions.
InteractionSet::anchors(gi, type = "first")[1:3]
InteractionSet::anchors(gi, type = "second")[1:3]
## Example: anchor-to-anchor distance for each loop, using standard
## GenomicRanges accessors.
anchA <- InteractionSet::anchors(gi, type = "first")
anchB <- InteractionSet::anchors(gi, type = "second")
head(abs(GenomicRanges::start(anchB) - GenomicRanges::start(anchA)))
```
## Overlapping loop anchors with a `GRanges` annotation
Any `GRanges` object (gene bodies, ChIP-seq peaks, etc.) can be
intersected with `loops(obj)` using standard `GenomicRanges` operations.
Here we use the `H3K27ac` peak file shipped with the package to find
loops whose first anchor falls in a peak.
```{r interop-overlap}
peakFile <- system.file(
"extdata", "example_annotation.bed",
package = "loopQTL"
)
peaks <- rtracklayer::import(peakFile)
ov <- GenomicRanges::findOverlaps(
InteractionSet::anchors(loops(obj), type = "first"),
peaks
)
length(unique(S4Vectors::queryHits(ov))) # loops with a peak at anchor A
```
The same pattern lets you pull QTL rows whose SNP overlaps any
`GRanges` of interest (e.g. a credible-set region or a regulatory
annotation):
```{r interop-snps}
res <- results(obj)
snpGR <- GenomicRanges::GRanges(
seqnames = res$chrom,
ranges = IRanges::IRanges(res$pos, width = 1),
snpID = res$snpID
)
snpGR[seq_len(3)]
```
## Building an `InteractionSet` for downstream Bioc tools
If a downstream tool expects a full `InteractionSet` (interactions +
sample-level assays), one can be constructed directly from
`loops(obj)` and `phenotype(obj)`:
```{r interop-iset}
iset <- InteractionSet::InteractionSet(
assays = list(phenotype = phenotype(obj)),
interactions = loops(obj),
colData = S4Vectors::DataFrame(sample = samples(obj))
)
iset
```
## Exporting to standard genomic formats
Loops, SNPs, and results can be written to `.bed` / `.bedpe` files
using `rtracklayer` so that they can be loaded into IGV, the UCSC
Genome Browser, or any other tool that reads BED-family formats.
```{r interop-export, eval = FALSE}
## Export the first anchor of each loop as a BED track.
rtracklayer::export(
InteractionSet::anchors(loops(obj), type = "first"),
con = "loops_anchorA.bed",
format = "BED"
)
## Export the SNP positions from the QTL results as a BED track.
rtracklayer::export(snpGR, con = "qtl_snps.bed", format = "BED")
```
# Comparison with existing tools
To our knowledge, at the time of writing there is no Bioconductor
package dedicated to chromatin loop QTL mapping. Several existing
Bioconductor packages address adjacent problems — `InteractionSet`
stores genomic interactions, `BNBC` normalizes Hi-C matrices,
`multiHiCcompare` performs multi-sample Hi-C differential analysis,
and `MatrixEQTL` provides a fast QTL regression engine — but none
combines these into an end-to-end loop QTL workflow. `loopQTL`
composes with these packages (building on `InteractionSet` for loop
storage, `MatrixEQTL` for the regression).
The most directly comparable tool is **IQTL** (Bhattacharyya & Ay,
*Nat Commun*, 2024), a Snakemake pipeline that identifies genetic
variants associated with chromatin interactions using the RASQUAL
allele-specific regression model, after FitHiChIP coverage-bias
correction on the loop counts. `loopQTL` differs from IQTL on two
axes:
1. **Platform.** `loopQTL` is a single installable R package built on
Bioconductor data structures, while IQTL is a multi-tool Snakemake
workflow constructed on HiC-Pro, FitHiChIP, RASQUAL, GATK, and
auxiliary R scripts.
2. **Normalization.** `loopQTL` applies a band-wise joint quantile
normalization (in the style of BNBC, Brant et al., *Brief Bioinform*,
2024) that equalizes contact strength within each genomic-distance
band before association testing. IQTL relies on FitHiChIP's
coverage-bias regression on loop counts.
# Funding
This work was supported in part by grants R21CA260082, R21CA264637,
R21HG011506, and P30CA014089 from the National Institutes of Health,
W81XWH-21-1-0805 grant from the Department of Defense, and pilot grants
from the USC Keck School of Medicine, the USC Center for Genetic
Epidemiology, and the USC Norris Comprehensive Cancer Center.
# Session info
```{r session-info}
sessionInfo()
```