Many analyses need to know which features overlap which ranges. Reads
are assigned to genes. Peaks are matched to promoters. Variants are
matched to exons. In Bioconductor you do this with
findOverlaps() and countOverlaps() from GenomicRanges.
GenomicRanges builds an index of the subject, called an NCList, each
time you call these functions. You can also build it once yourself with
GNCList().
superintervalsr gives you a different index for the
subject, based on the SuperIntervals algorithm. It stores intervals in
one sorted array, with a second small array that lets a query skip
intervals that cannot overlap. This is compact and fast to search. It
helps most when you query the same annotation many times, for
example:
The package fits into existing Bioconductor code:
SuperIntervalMap() takes a GRanges and
returns an index. You pass it to findOverlaps() or
countOverlaps() in place of the GRanges.Hits you get back point at rows of your original
GRanges, so its metadata is easy to recover.type = "within" or a maxgap, are passed on to
GenomicRanges. You always get the same answer.The package also has a lower-level IntervalMap class for
plain integer intervals. It adds operations such as merge, gaps and
flank.
When should you use it? For a single query, plain GenomicRanges is
simpler and fast enough. When you query the same subject repeatedly,
building a SuperIntervalMap once makes each query faster.
The README has timings against both a plain GRanges and a
prebuilt GNCList.
Install from Bioconductor:
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("superintervalsr")Building from source needs a C++17 compiler. The examples also use airway and SummarizedExperiment. Install these the same way.
Some function names here, such as count(),
coverage(), gaps() and flank(),
also exist in other packages. We load superintervalsr last
so its versions are used. Elsewhere, write
superintervalsr::count() to be sure.
Build the index once. The GRanges can span several
chromosomes and both strands.
genes <- GRanges(
seqnames = c("chr1", "chr1", "chr1", "chr2"),
ranges = IRanges(start = c(20, 1, 8, 1), end = c(30, 10, 18, 10)),
strand = c("+", "-", "*", "+"),
gene_id = c("GENE_C", "GENE_A", "GENE_B", "GENE_D")
)
gene_index <- SuperIntervalMap(genes)
gene_index
#> SuperIntervalMap with 4 ranges on 2 indexed sequencesUse the index wherever you would use the GRanges
subject:
peaks <- GRanges(c("chr1", "chr1", "chr2"),
IRanges(c(5, 15, 40), c(8, 22, 45)), strand = "+")
hits <- findOverlaps(peaks, gene_index)
hits
#> Hits object with 3 hits and 0 metadata columns:
#> queryHits subjectHits
#> <integer> <integer>
#> [1] 1 3
#> [2] 2 1
#> [3] 2 3
#> -------
#> queryLength: 3 / subjectLength: 4
countOverlaps(peaks, gene_index)
#> [1] 1 2 0Subject hits are row numbers in genes.
as_granges() returns the original GRanges, so
you can look up any metadata column:
overlapping_rows <- as(hits, "List")
mcols(peaks)$genes <- extractList(as_granges(gene_index)$gene_id,
overlapping_rows)
peaks
#> GRanges object with 3 ranges and 1 metadata column:
#> seqnames ranges strand | genes
#> <Rle> <IRanges> <Rle> | <CharacterList>
#> [1] chr1 5-8 + | GENE_B
#> [2] chr1 15-22 + | GENE_C,GENE_B
#> [3] chr2 40-45 + |
#> -------
#> seqinfo: 2 sequences from an unspecified genome; no seqlengthsThe counts are the same as with genes as the
subject:
Strand is used by default, and "*" matches either
strand. To ignore strand:
The airway
data hold RNA-seq counts from human airway smooth muscle cells, stored
as a RangedSummarizedExperiment. Its
rowRanges() hold the exons of each gene.
The question: for the most highly expressed genes, which other genes overlap their promoter?
First, turn each gene into one range covering all its exons, and add the mean read count. Genes with exons on more than one chromosome or strand are dropped.
data("airway", package = "airway")
gene_spans <- range(rowRanges(airway))
single_span <- lengths(gene_spans) == 1L
gene_bodies <- unlist(gene_spans[single_span], use.names = FALSE)
names(gene_bodies) <- names(gene_spans)[single_span]
mcols(gene_bodies)$mean_count <- rowMeans(assay(airway))[single_span]
gene_bodies
#> GRanges object with 63677 ranges and 1 metadata column:
#> seqnames ranges strand | mean_count
#> <Rle> <IRanges> <Rle> | <numeric>
#> ENSG00000000003 X 99883667-99894988 - | 741.875
#> ENSG00000000005 X 99839799-99854882 + | 0.000
#> ENSG00000000419 20 49551404-49575092 - | 534.875
#> ENSG00000000457 1 169818772-169863408 - | 242.000
#> ENSG00000000460 1 169631245-169823221 + | 58.375
#> ... ... ... ... . ...
#> ENSG00000273489 7 131178723-131182453 - | 0.250
#> ENSG00000273490 HSCHR19LRC_LRC_J_CTG1 54693789-54697585 + | 0.000
#> ENSG00000273491 HG1308_PATCH 130600118-130603315 + | 0.000
#> ENSG00000273492 21 27543189-27589700 + | 0.125
#> ENSG00000273493 3 58315692-58315845 + | 0.125
#> -------
#> seqinfo: 722 sequences (1 circular) from an unspecified genomeWe will query these gene bodies, so index them once:
body_index <- SuperIntervalMap(gene_bodies)
body_index
#> SuperIntervalMap with 63677 ranges on 265 indexed sequencesTake promoters of the top 200 genes and find what they overlap:
top_genes <- head(gene_bodies[order(-mcols(gene_bodies)$mean_count)], 200)
promoter_windows <- promoters(top_genes, upstream = 2000, downstream = 200)
promoter_hits <- findOverlaps(promoter_windows, body_index)
promoter_hits
#> Hits object with 275 hits and 0 metadata columns:
#> queryHits subjectHits
#> <integer> <integer>
#> [1] 1 4464
#> [2] 2 305
#> [3] 3 18297
#> [4] 3 22324
#> [5] 3 18277
#> ... ... ...
#> [271] 196 5411
#> [272] 197 18123
#> [273] 198 16314
#> [274] 199 3602
#> [275] 200 9282
#> -------
#> queryLength: 200 / subjectLength: 63677Each hit links a promoter to a gene body. Every promoter overlaps its own gene, so drop those and list the neighbours:
neighbours <- data.frame(
promoter_of = names(promoter_windows)[queryHits(promoter_hits)],
overlaps_gene = names(gene_bodies)[subjectHits(promoter_hits)],
neighbour_mean_count =
mcols(gene_bodies)$mean_count[subjectHits(promoter_hits)]
)
neighbours <- neighbours[neighbours$promoter_of != neighbours$overlaps_gene, ]
head(neighbours)
#> promoter_of overlaps_gene neighbour_mean_count
#> 4 ENSG00000198804 ENSG00000210117 0.00
#> 5 ENSG00000198804 ENSG00000198763 31922.25
#> 6 ENSG00000198804 ENSG00000210112 0.00
#> 7 ENSG00000198804 ENSG00000210100 0.00
#> 8 ENSG00000198804 ENSG00000198888 30838.62
#> 13 ENSG00000087086 ENSG00000267898 1.00Results can go straight back into the experiment. Here we store the
number of neighbouring genes in rowData(), so it stays with
the counts:
top_se <- airway[names(top_genes), ]
other_genes <- countOverlaps(promoter_windows, body_index) - 1L
rowData(top_se)$promoter_neighbours <- other_genes
table(rowData(top_se)$promoter_neighbours)
#>
#> 0 1 2 3 4 5 6 7
#> 167 19 3 4 1 3 2 1Finally, check the hits match GenomicRanges, with and without strand:
same_pairs <- function(a, b) {
pairs_a <- sort(paste(queryHits(a), subjectHits(a)))
pairs_b <- sort(paste(queryHits(b), subjectHits(b)))
identical(pairs_a, pairs_b)
}
agree <- vapply(c(FALSE, TRUE), function(ignore) {
same_pairs(
findOverlaps(promoter_windows, body_index, ignore.strand = ignore),
findOverlaps(promoter_windows, gene_bodies, ignore.strand = ignore))
}, logical(1))
stopifnot(all(agree))saveRDS() cannot save
it. Save as_granges(index) and rebuild after loading.GRanges.
Build a new one.IntervalMap is the structure underneath
SuperIntervalMap. It holds integer intervals on one
coordinate line, such as one chromosome. It ignores strand. Each
interval can carry any R value. Use it when you are not working with
GRanges, or when you need the extra operations below.
Build a map from start and end vectors, a data.frame, or
a GRanges on one chromosome. Both ends of each interval are
included, as in IRanges.
im <- IntervalMap(c(10, 15, 30), ends = c(20, 25, 40),
values = c("Gene A", "Gene B", "Gene C"))
im
#> IntervalMap with 3 intervals
#> [1] 10-20 -> Gene A
#> [2] 15-25 -> Gene B
#> [3] 30-40 -> Gene C
chr1_map <- IntervalMap(genes, seqname = "chr1", value_column = "gene_id")
chr1_map
#> IntervalMap with 3 intervals
#> [1] 1-10 -> GENE_A
#> [2] 8-18 -> GENE_B
#> [3] 20-30 -> GENE_CYou can also add intervals one at a time. Call build()
when you are done and before you query. The constructors above do this
for you.
add() and build() change the map in place.
Unlike most R objects, im3 <- im2 does not make a
copy.
Each function returns a different view of the overlapping intervals:
has_overlaps(im, 12, 18)
#> [1] TRUE
count(im, 12, 18)
#> [1] 2
search_values(im, 12, 18)
#> [[1]]
#> [1] "Gene B"
#>
#> [[2]]
#> [1] "Gene A"
search_items(im, 12, 18)
#> $start
#> [1] 15 10
#>
#> $end
#> [1] 25 20
#>
#> $value
#> $value[[1]]
#> [1] "Gene B"
#>
#> $value[[2]]
#> [1] "Gene A"
search_point(im, 35)
#> [[1]]
#> [1] "Gene C"search_idxs() returns positions in the map.
at() returns the interval at a position. Positions follow
the sorted order made by build(), not your input order. To
get back to your input rows, store the row number as the value.
Every call from R into C++ has a small cost. With thousands of
queries, that cost can outweigh the search itself. The
.batch functions take vectors of starts and ends and run
every query in one call.
Both versions below give the same answer. The batch version skips the R loop:
query_starts <- c(5, 12, 22, 35)
query_ends <- c(8, 18, 32, 50)
one_at_a_time <- vapply(seq_along(query_starts), function(i) {
count(im, query_starts[i], query_ends[i])
}, integer(1))
all_at_once <- count.batch(im, query_starts, query_ends)
stopifnot(identical(one_at_a_time, all_at_once))
all_at_once
#> [1] 0 2 2 1
search_idxs.batch(im, query_starts, query_ends)
#> [[1]]
#> integer(0)
#>
#> [[2]]
#> [1] 2 1
#>
#> [[3]]
#> [1] 3 2
#>
#> [[4]]
#> [1] 3These return a new map, ready to query. They work like
reduce(), gaps() and flank() in
IRanges, but keep each interval’s value.
merged <- merge_overlaps(im)
search_keys(merged, 1, 50)
#> $start
#> [1] 30 10
#>
#> $end
#> [1] 40 25
uncovered <- gaps(merged, 1, 50)
search_keys(uncovered, 1, 50)
#> $start
#> [1] 41 26 1
#>
#> $end
#> [1] 50 29 9
windows <- expand(im, 5, 5, lo = 1, hi = 50)
search_keys(windows, 1, 50)
#> $start
#> [1] 25 10 5
#>
#> $end
#> [1] 45 30 25
span(im)
#> $start
#> [1] 10
#>
#> $end
#> [1] 40Merging keeps one value per merged region.
intersection() keeps values from its first argument and can
return overlapping pieces. Run merge_overlaps() on the
result to join them.
coverage() returns the number of overlapping intervals
and their total overlap with the query. Each interval counts on its own,
so shared bases count more than once.
as_granges() turns search_items() output
into a GRanges. An IntervalMap does not know
its chromosome, so you supply it:
chr1_items <- search_items(chr1_map, 5, 22)
as_granges(chr1_items, seqname = "chr1", valuename = "gene_id")
#> GRanges object with 3 ranges and 1 metadata column:
#> seqnames ranges strand | gene_id
#> <Rle> <IRanges> <Rle> | <list>
#> [1] chr1 20-30 * | GENE_C
#> [2] chr1 8-18 * | GENE_B
#> [3] chr1 1-10 * | GENE_A
#> -------
#> seqinfo: 1 sequence from an unspecified genome; no seqlengthssessionInfo()
#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 26.04.1 LTS
#>
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.32.so; LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
#> [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
#> [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
#> [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
#> [9] LC_ADDRESS=C LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
#>
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#>
#> attached base packages:
#> [1] stats4 stats graphics grDevices utils datasets methods
#> [8] base
#>
#> other attached packages:
#> [1] superintervalsr_0.99.8 SummarizedExperiment_1.43.0
#> [3] Biobase_2.73.2 MatrixGenerics_1.25.0
#> [5] matrixStats_1.5.0 GenomicRanges_1.65.4
#> [7] Seqinfo_1.3.2 IRanges_2.47.5
#> [9] S4Vectors_0.51.10 BiocGenerics_0.59.12
#> [11] generics_0.1.4 BiocStyle_2.41.0
#>
#> loaded via a namespace (and not attached):
#> [1] Matrix_1.7-6 jsonlite_2.0.0 compiler_4.6.2
#> [4] BiocManager_1.30.27 Rcpp_1.1.2 jquerylib_0.1.4
#> [7] yaml_2.3.12 fastmap_1.2.0 lattice_0.23-1
#> [10] XVector_0.53.0 R6_2.6.1 S4Arrays_1.13.2
#> [13] knitr_1.52 DelayedArray_0.39.8 maketools_1.3.2
#> [16] bslib_0.12.0 rlang_1.3.0 cachem_1.1.0
#> [19] xfun_0.62 sass_0.4.10 sys_3.4.3
#> [22] otel_0.3.0 SparseArray_1.13.4 cli_3.6.6
#> [25] digest_0.6.39 grid_4.6.2 lifecycle_1.0.5
#> [28] evaluate_1.0.5 buildtools_1.0.0 abind_1.4-8
#> [31] rmarkdown_2.32 tools_4.6.2 htmltools_0.5.9