Skip to contents

Introduction

looplook is an R/Bioconductor package that integrates three-dimensional (3D) chromatin architecture data — derived from HiChIP, ChIA-PET, or Hi-C — with complementary omics datasets, including transcriptomic profiles, chromatin accessibility maps, protein-DNA interaction data (ChIP-seq, CUT&Tag, CUT&RUN), and genetic variants annotated by genome-wide association studies (GWAS).

Distal regulatory elements physically contact target gene promoters through 3D chromatin looping, enabling transcriptional regulation over distances spanning tens of kilobases to megabases along the linear genome. Conventional annotation strategies, however, assign putative regulatory elements to their nearest neighboring genes in cis — a linear approximation that frequently diverges from the underlying 3D topology. Accurate assignment of non-coding variants and orphan regulatory peaks to their cognate target genes therefore remains a central bottleneck in the functional interpretation of genomic regulatory landscapes.

looplook addresses this challenge by systematically prioritizing experimentally detected chromatin contacts to assign target genes to regulatory elements at genome-wide scale, producing evidence-prioritized annotations with systematic provenance tracking.

Beyond target gene assignment, looplook functions as a standalone platform for chromatin loop analysis. Even in the absence of auxiliary omics data, the package enables systematic annotation of the 3D interactome, classification of spatial interaction topologies (e.g., Enhancer–Promoter, Promoter–Promoter), and quantification of node connectivity to identify dense regulatory hubs and enhancer cliques — candidate regulatory domains that may drive cell-type-specific transcriptional programs.

A Triple-Layer Annotation Framework

looplook’s core methodological contribution is a three-layer orthogonal annotation framework that classifies each loop anchor — the fundamental unit connecting 3D contacts to downstream peak and feature annotation — by integrating independent categories of experimental evidence:

  • Genomic annotation provides the baseline anchor assignment from genomic coordinates.
  • Expression-aware refinement adds transcriptional-activity context.
  • Chromatin-Aware Refinement supplies orthogonal histone-mark validation.

These anchor-level classifications propagate through the loop network to determine target-gene assignments for every auxiliary feature (ChIP-seq peaks, ATAC-seq regions, GWAS variants). Because the layers function independently, users may deploy any subset matched to their available data modalities — a single layer for exploratory annotation, two for partial orthogonal support, or all three for maximally resolved regulatory-element classification.

Layer Evidence Question Output
Genomic Annotation Genomic coordinates (TSS / gene-body overlap) Where is it? P / G / E
Expression-Aware Refinement Transcriptomic data (CAGE-seq / PRO-seq > GRO-seq / NET-seq > TT-seq > RNA-seq) Is it active? eP / eG (silent → downgraded)
Chromatin-Aware Refinement Chromatin state (ChIP-seq, CUT&Tag, ATAC-seq) What is it? dual / P / E corrected

Each layer uses orthogonal experimental evidence. Genomic annotation gives the candidate, expression tells you whether the regulatory element is currently in use, and chromatin tells you what regulatory class it actually belongs to.

Why three layers matter — a concrete example:

Consider an anchor located in an intergenic region near MYC. Genomic annotation classifies it as E (enhancer-like) — it does not overlap an annotated TSS. But is it truly an enhancer?

Scenario Genomic Expression Chromatin Correct call
Silent gene body E Gene silent → eP H3K4me3+ → P P — an unannotated promoter
Active enhancer E eRNA detected → active H3K4me1+ H3K27ac+ ATAC+ → E E — confirmed active enhancer
Poised promoter (bivalent) E Gene silent → eP H3K4me3+ H3K27me3+ → P + conflicting_marks P — poised, H3K4me3 defines promoter identity, H3K27me3 marks bivalent state
Dual-function element P Gene active → P H3K4me1+ H3K4me3+ bigWig ratio≥3 (default) → dual dual — promoter + enhancer

Genomic annotation alone offers limited resolution: it provides a plausible first-pass classification but cannot reliably discriminate among distinct regulatory states. Expression data narrows the candidate pool to transcriptionally active elements, while chromatin-state evidence identifies the intrinsic regulatory identity of each anchor. Used together, the three layers can yield substantially more reliable classifications than any single data modality alone.

Key Features

  1. 3D-Guided Multi-Omics Integration: Maps auxiliary genomic features (GWAS SNPs, ChIP-seq peaks, ATAC-seq regions) to target genes via 3D chromatin contacts. A structured fallback mechanism prioritizes loop-mediated target genes and supplements them with nearest-gene assignments only when no spatial interaction is detected, ensuring both 3D specificity and complete coverage.

  2. Systematic Loop Annotation and Hub Detection: Classifies spatial interaction types (E–P, P–P, E–E, and their expression- and chromatin-refined variants) and computes node degree distributions to identify candidate 3D regulatory hubs and enhancer cliques.

  3. Expression-Aware Refinement: Integrates quantitative transcriptomic data to annotate each loop with expression-informed functional status while preserving all structural contacts. Anchors associated with transcriptionally silent reference promoters are reclassified as enhancer-like elements (eP, eG), producing an expression-refined regulatory network without discarding structural evidence. A dataset-adaptive quantile mode (threshold_mode = "quantile") accommodates varying sequencing depths.

  4. Chromatin-Aware Anchor Refinement: Validates and systematically refines loop anchors using orthogonal chromatin mark data (ChIP-seq, CUT&Tag, ATAC-seq). Anchors are scored against ENCODE-inspired active-enhancer criteria across five evidence levels (canonical to uncertain). Important: these levels assess enhancer-like chromatin evidence, not overall classification confidence — a strong promoter (H3K4me3+) may receive only supported because the criteria are enhancer-oriented. Anchor types are updated based on mark combinations — for instance, an eP anchor with H3K4me3+ promoter-like chromatin (without conflicting marks) is reverted to P, while a P anchor with H3K4me1+ H3K4me3+ dual marks is upgraded to dual-signature. Triple-positive anchors (H3K4me1+ H3K4me3+ H3K27me3+) are classified as conflicting_marks and retain their original type. Refinement is fully auditable through per-anchor chromatin state, evidence level, and before/after type columns.

  5. Replicate Consolidation and Multi-Source Consensus: Employs graph-theoretic connected-component clustering to harmonize biological replicates and suppress technical noise. The framework supports multi-source consensus integration — for instance, intersecting HiChIP datasets targeting H3K27ac and RNA Polymerase II — to construct a unified, consensus-supported 3D interactome informed by orthogonal experimental evidence.

  6. Automated Functional Profiling: Delivers an end-to-end analytical pipeline generating publication-ready visualizations and functional interpretations, including network connectivity and expression dynamics, transcription factor motif enrichment (SeqLogos), and pathway association networks (Cnetplots).

Comparison with Existing Tools

looplook bridges the gap between conventional 1D linear annotation and specialized 3D chromatin interaction tools, providing a unified environment for target assignment, expression-aware refinement, consensus consolidation, and functional inference. Table @ref(tab:comparison-table) summarizes the core capabilities of looplook relative to existing tools in the ecosystem.

Comparison of core features between looplook and existing genomic annotation tools.
Feature ChIPseeker GREAT GenomicInteractions FUMA ABC Model looplook
Primary annotation scheme 1D 1D 3D 3D 3D 1D & 3D
User-input 3D interactome ✘ ✘ ✔ ✘ ✔ ✔
User-input omics data ✔ ✔ ✘ ✘ ✔ ✔
Graph-based topological consensus ✘ ✘ ✘ ✘ ✘ ✔
Expression-aware refinement ✘ ✘ ✘ Partial ✘ ✔
Chromatin mark validation ✘ ✘ ✘ ✘ ✘ ✔
Topological refinement ✘ ✘ ✘ ✘ ✘ ✔
Multi-hop network diffusion ✘ ✘ ✘ ✘ ✘ ✔
Smart linear fallback ✘ ✘ ✘ ✘ ✘ ✔
Functional inference ✘ ✔ ✘ ✘ ✘ ✔
Multi-track visualization ✘ ✘ ✘ ✘ ✘ ✔
Local execution ✔ ✘ ✔ ✘ ✔ ✔
Ecosystem R Web R Web Python R

Notes: “1D” = linear proximity-based mapping; “3D” = mapping via spatial chromatin topology; “✔” = native support; “✘” = not supported; “Partial” = partial support (FUMA relies on precompiled data rather than user-provided input).

looplook provides both 1D and 3D target annotation in a unified R workflow. Its three-stage refinement strategy — expression-aware reclassification of silent regulatory elements (P → eP, G → eG), orthogonal chromatin-mark validation against ENCODE-inspired enhancer criteria, and systematic anchor-type reclassification based on mark combinations — distinguishes structural chromatin contacts from functionally active regulatory events. Graph-based replicate consolidation harmonizes loop calls across biological replicates without over-merging, while per-Anchor provenance tracking ensures full auditability of every reclassification decision.


Installation

if (!requireNamespace("BiocManager", quietly = TRUE)) {
    install.packages("BiocManager")
}
BiocManager::install("zying106/looplook")
library(looplook)
# Create a temporary directory to store all output plots and Excel files
out_dir <- tempdir()

Module 1: Data Consolidation & Preprocessing

Chromatin interaction datasets from individual biological replicates invariably contain technical variability and stochastic noise. The consolidate_chromatin_loops function serves as the foundational data-integration module, merging multiple replicates into a standardized, unified 3D interaction coordinate framework.

The module supports multi-source consensus integration across independent experimental designs — for instance, HiChIP assays targeting H3K27ac and RNA Polymerase II. By identifying shared spatial interactions across heterogeneous inputs, the framework enables orthogonal validation that mitigates assay-specific biases and technical artifacts. Consensus loops supported by multiple independent lines of evidence provide a robust foundation for downstream annotation and functional interpretation.

Parameter Strategy

  • mode: Defines the overarching merging algorithm.
    • "consensus" (Recommended): Implements graph-based connected component analysis to cluster spatially proximal anchors across samples. Only retains clusters detected in >= min_consensus biological replicates.
    • "intersect": Enforces strict reference-based filtering, retaining loops that show full genomic overlap with the reference file (File 1).
    • "union": Retains all chromatin interactions across the entire cohort, ideal for exploratory pan-tissue analyses.
  • min_consensus: When using "consensus" mode, this parameter defines the minimum number of biological replicates in which a loop cluster must be detected to be retained in the final dataset. If set to NULL, the algorithm automatically computes the threshold: 100% for 2–3 replicates, and ≥75% (ceiling(0.75 × N)) for N ≥ 4 (e.g., 3 for N=4, 4 for N=5, 6 for N=8).
  • gap: Defines the maximum allowable spatial distance (in base pairs) between loop anchors for them to be considered as part of the same physical cluster (default: 1000). When quiet = FALSE (default), the function prints a pre-clustering gap diagnosis and a post-clustering cluster-span diagnosis, including data-driven gap recommendations and chaining risk assessment. If loop anchors are narrow (e.g., TF HiChIP, 200–400 bp), the diagnosis may suggest reducing gap to avoid over-merging independent regulatory events.
    • How to choose gap: As a rule of thumb, gap should be comparable to (not much larger than) the median loop anchor width in your data. For histone-mark HiChIP (H3K27ac, ~1–3 kb anchors), 1000 is appropriate. For TF HiChIP or ChIA-PET (100–500 bp anchors), consider 100–200. For Hi-C bins (5–50 kb), 1000 is conservative. The automatic diagnosis will guide you if the chosen gap is inappropriate for your data.
  • min_raw_score vs. min_score (The Dual-Filter):
    • min_raw_score acts as a pre-filter applied to individual BEDPE files before clustering (e.g., removing singleton noise where PET count < 2) to help reduce computational memory overhead.
    • min_score serves as a post-filter applied to the final merged chromatin interactome to ensure high-confidence interactions. In "consensus" and "union" modes, this representative score is computed in a replicate-balanced manner: loop scores are averaged within each replicate first, then averaged across replicates.
  • blacklist_species: Automatically excludes chromatin loops overlapping with high-variance, artifact-prone genomic regions (e.g., centromeres, telomeres). Accepts a species name ("hg38", "hg19", "mm10", "mm9") to use the bundled ENCODE blacklist, or a path to a custom blacklist BED file.
  • region_of_interest: Accepts an auxiliary BED file (e.g., a specific disease-associated locus or ChIP-seq peak set) to capture only loops with physical connectivity to the target genomic region of interest (ROI).
  • roi_mode: Controls how strictly loops must overlap the ROI:
    • "any" (Default): Either anchor may overlap the ROI. Suitable for promoter-centric queries (e.g., find all distal interactions involving a specific gene locus).
    • "both": Both loop anchors must overlap the ROI. Suitable for TAD confinement, domain-internal interaction queries, or when filtering with a ChIP-seq peak set (e.g., keep only loops where both anchors fall in H3K27ac-marked regions).
  • score_col: Integer column index for the interaction score (e.g., PET count) when BEDPE files follow a non-standard column layout. If NULL (default), columns 8 and 7 are auto-detected by checking the proportion of numeric values.

Score direction: All score-based filtering assumes higher scores = better interactions. If your BEDPE score column contains p-values (values in [0, 1]), convert them to -log10(p-value) before using min_raw_score or min_score. The function will warn if it auto-detects a p-value-like column, but explicit conversion is the safest approach. * quiet: Logical. If TRUE, suppress progress messages while preserving warnings (default: FALSE).

For single-sample filtering (without replicate merging), use filter_chromatin_loops() — it applies the same blacklist and ROI logic to an existing GInteractions object. See ?filter_chromatin_loops for details. To merge proximal loops on an in-memory GInteractions object without the file-based pipeline (returning the reduced object plus per-loop cluster membership), use reduce_ginteractions().

The exported BEDPE file (when write_output = TRUE and out_file is set) is standard 10-column BEDPE (chr1, start1, end1, chr2, start2, end2, name, score, strand1, strand2) with two documented extension columns appended (columns 11-12): - n_members (column 11): Number of raw loops merged into this consensus entry, giving a sense of cluster size. In intersect mode this is 1 (no merging, each retained loop stands alone); in consensus/union modes it reflects the number of loops clustered. - n_reps (column 12): Number of input files that support this entry, useful for filtering by replication evidence.

Example 1: Building a Global Consensus Interactome

This represents the standard workflow for generating a consolidated whole-genome 3D chromatin interaction dataset via integration of biological replicates and removal of blacklist-associated artifacts.

# Locate example BEDPE replicates
f1 <- system.file("extdata", "example_loops_1.bedpe", package = "looplook")
f2 <- system.file("extdata", "example_loops_2.bedpe", package = "looplook")
global_out <- file.path(out_dir, "consensus_loops_global.bedpe")

# Execute consensus merging with strict Quality Control
consensus_global <- consolidate_chromatin_loops(
  files = c(f1, f2),
  mode = "consensus",
  gap = 1000,
  min_raw_score = 2, # Pre-filter sequencing noise
  blacklist_species = "hg38", # Apply artifact blacklist
  out_file = global_out,
  write_output = TRUE
)

Example 2: Feature-Driven Loop Filtering

In most scenarios, researchers are interested in 3D chromatin interactions associated with specific biological features, such as active enhancers (marked by H3K27ac) or particular transcription factors.

By providing a BED file to region_of_interest, the tool enables efficient “on-the-fly” capture, retaining only those loops whose anchors overlap with the specified functional regions.

# Locate a BED file containing H3K27ac ChIP-seq peaks
h3k27ac_peaks <- system.file("extdata", "example_k27ac_peaks.bed", package = "looplook")
targeted_out <- file.path(out_dir, "H3K27ac_anchored_loops.bedpe")

# Execute consensus merging, strictly capturing H3K27ac-associated loops
consensus_targeted <- consolidate_chromatin_loops(
  files = c(f1, f2),
  mode = "consensus",
  gap = 1000,
  min_raw_score = 2,
  region_of_interest = h3k27ac_peaks,
  out_file = targeted_out,
  write_output = TRUE
)

Example 3: Multi-source Consensus for Orthogonal Validation

In integrative multi-omics analyses, orthogonal validation across independent functional assays is critical for identifying robust 3D regulatory interactions. For instance, enhancer-promoter (E-P) loops are typically supported by the spatial co-localization of H3K27ac (marking active chromatin) and RNA polymerase II (indicative of transcriptional machinery engagement). By utilizing the "consensus" mode to intersect independent loop datasets, looplook facilitates the identification of chromatin interactions supported by multi-source evidence. This conservative intersection strategy may reduce assay-specific technical artifacts, yielding a refined set of loops supported by multiple assays.

loop_k27ac <- system.file("extdata", "example_loops_H3K27ac.bedpe", package = "looplook")
loop_pol2 <- system.file("extdata", "example_loops_pol2.bedpe", package = "looplook")
dual_functional_out <- file.path(out_dir, "Dual_Functional_Consensus.bedpe")

consensus_dual <- consolidate_chromatin_loops(
  files = c(loop_k27ac, loop_pol2),
  mode = "consensus",
  gap = 1000,
  min_raw_score = 2,
  out_file = dual_functional_out,
  write_output = TRUE
)

Module 2: 3D-Guided Annotation & Mapping

annotate_peaks_and_loops serves as the core mapping engine of looplook. It classifies the topological architecture of the 3D interactome — assigning each loop anchor a positional type (P, E, G) and each loop a structural class (E–P, P–P, etc.) — and, when a target_bed file is supplied, traces non-coding regulatory features (GWAS loci, eQTLs, ChIP-seq peaks) to their putative target genes through 3D chromatin contacts.

To resolve mapping ambiguities within densely populated gene loci, where a single loop anchor overlaps multiple candidate genes, the engine implements a rigorous three-step hierarchical annotation pipeline:

  1. Functional Biotype Prioritization: Selects the highest-priority candidates by functional class: Protein Coding > small-ncRNA (miRNA, snoRNA, snRNA, rRNA, scaRNA) > Antisense > lncRNA/ncRNA > Pseudogene. This default hierarchy can be customised via the biotype_order parameter in resolve_gene_conflicts(). The five biotype keywords are "protein" (protein-coding), "small_ncRNA" (miRNA, snoRNA, snRNA, rRNA, scaRNA), "antisense", "lncRNA" (lncRNA and other ncRNA), and "pseudogene". The order of listed keywords determines priority (first = highest); unlisted categories keep their default relative order and are appended after the listed ones. For example, biotype_order = c("lncRNA", "protein") elevates lncRNAs above protein-coding genes while keeping the remaining three categories (small_ncRNA > antisense > pseudogene) in their default order.
  2. Expression Filter: Within the selected biotype tier, excludes transcriptionally silent genes (expression < min_expr) if at least one candidate in the tier is expressed. If no gene in that tier is expressed, all are retained to avoid losing correct annotations due to low expression.
  3. Co-Dominant Expression Tiebreaker: Among remaining candidates, retains all genes with expression >= co_dominance_ratio x the group maximum. The default ratio of 0.1 (one order of magnitude; ~3.3-fold in log2 space) preserves functionally redundant candidates (e.g., bidirectional promoter pairs, typically co-expressed within 2–3 fold) rather than forcing a single-gene assignment.

Parameter Strategy & Core Inputs

This multi-omic integration relies on several key parameters:

  • bedpe_file: The 3D structural framework (e.g., the high-confidence consensus interactome generated in Module 1).
  • target_bed: The auxiliary genomic features of interest (e.g., a BED file of GWAS SNPs, ATAC-seq peaks, or ChIP-seq peaks) awaiting spatial target assignment.
  • expr_matrix_file & sample_columns: Optional but strongly recommended. An expression matrix (e.g., RNA-seq TPM/FPKM, NET-seq/PRO-seq gene-body RPKM, or CAGE-seq) enables the Expression Pre-filter and Tiebreaker logic, which can help reduce false-positive gene assignments in dense genomic loci.
  • min_expr: Minimum expression value for a gene to be considered “active” during anchor-level conflict resolution (default: 0). At the default, any non-zero expression (TPM > 0) qualifies; truly undetected genes (TPM = 0) are excluded. When set to 1 or higher, genes with expression >= min_expr are considered active. Note this is distinct from Module 3’s threshold parameter, which controls promoter reclassification during expression-aware refinement.
  • neighbor_hop: An advanced topological parameter for network traversal. Note: target gene assignment searches one additional graph step (neighbor_hop + 1) to capture genes at the opposite anchor of directly connected loops, while loop-level topology uses the specified hop count.
    • 0 (Default): Loop topology restricted to direct contacts; target genes searched within 1-hop.
    • 1 (Hub Mode): Loop topology includes secondary contacts; target genes searched within 2-hop. Values greater than 1 are not supported.
  • anchor_gap (integer, default -1): Candidate search radius (bp) between a target peak and a loop anchor. -1 (default): strict physical overlap. >= 0: expands the candidate search window (e.g. 200 for cross-experiment coordinate shifts). Note: final retention always requires at least anchor_min_overlap bp of physical overlap. This parameter only controls candidate search, not whether proximity-only pairs are retained.
  • anchor_min_overlap (integer, default 1): Minimum required physical overlap (bp) between peak and anchor. Default 1: at least 1 bp of actual sequence overlap required — proximity-only pairs within the anchor_gap window but without physical overlap are excluded. Increase to 10–100 for broad peaks to avoid spurious boundary overlaps.
  • anchor_min_frac (numeric, 0–1, default 0): After the first two filters, what fraction of the peak width must physically overlap the anchor? 0 accepts any fraction. Set to 0.1–0.5 when peaks are broad (H3K27ac domains, 2–5 kb). Not recommended for point features (SNPs). Applied last.

The three parameters act as a cascade: (1) search radius, (2) minimum overlap bp, (3) fraction of peak. They do not conflict; each narrows the candidate set further.

  • anchor_merge_gap (integer, default 0): Merge loop anchors within this many bp on the same chromosome before building the connectivity graph. 0 (default): no merging; anchors must match exactly on chr/start/end. Set to 50–200 when input BEDPE comes directly from a loop caller without prior replicate consolidation via consolidate_chromatin_loops() — the same biological anchor may appear with slightly different boundaries in different loop rows, fragmenting the graph and underestimating hub connectivity. When input is pre-consolidated (recommended), leave at 0.
  • tss_region: Defines the genomic window surrounding the transcription start site (TSS) used to define promoter regions (default: c(-2000, 2000) bp).
  • conflict_strategy: Controls the order of biotype and expression filtering when multiple genes overlap an anchor. "biotype_first" (default) selects the best biotype tier first, then applies expression filtering within that tier — a silent protein-coding gene is preferred over a highly expressed lncRNA. "expression_first" applies expression filtering across all biotypes before selecting the best tier.
  • hub_metric: Which connectivity count to use for hub detection. "unique_contacts" (default): counts distinct neighbour anchor IDs, robust to duplicate/replicate loop rows. "total_loops": counts all loop rows (backward compatible; may inflate hub calls with unconsolidated replicates).
  • target_priority: Policy for prioritising multiple candidate target genes per feature. Applies only within primary target links (default path_length <= 1); longer paths are reported separately as Expanded_Target_Genes and do not compete for Assigned_Target_Genes. "promoter_then_distance" (default): within primary links, promoter-linked genes beat gene-body genes, with shorter paths breaking ties. Exception: direct strict promoter–promoter contacts (same loop, path0+path1) co-assign both endpoints via union, because endpoint orientation is technical rather than directional. "distance_then_role": path-length dominates — the closest linked gene wins; at equal distance, promoter beats gene-body (legacy behaviour).
  • hub_percentile: Node-degree quantile threshold for identifying highly connected regulatory elements (default: 0.95, i.e. top 5%).
  • species: Genome assembly ("hg38", "hg19", "mm10", or "mm9"). Auto-resolves the corresponding TxDb and OrgDb annotation packages. For other species, pass txdb and org_db as objects or package name strings directly (e.g., txdb = TxDb.Dmelanogaster.UCSC.dm6.ensGene, org_db = "org.Dm.eg.db"). When both txdb and org_db are provided, species is only used for karyotype chromosome ideograms and can be left as the default.
  • color_palette: RColorBrewer palette for loop-type colour assignments in annotation plots (default: "Set2").
  • karyo_bin_size: Genomic bin width in base pairs for karyotype heatmaps (default: 1e5).
Suggested Anchor Overlap Settings (for reference)
Experimental design anchor_gap anchor_min_overlap anchor_min_frac
Same-experiment HiChIP / ChIA-PET (default) -1 1 0
Cross-experiment (ATAC-seq peaks × HiChIP loops) 200–500 10 0
Broad histone-mark peaks (H3K27ac, 2–5 kb) 0 100 0.1
Super-enhancers / wide domains (20–80 kb) 0 500 0.05
Point features (GWAS SNPs, eQTLs) 0 1 0
High-confidence only (stringent) 0 100 0.5

Example A: Integrative Analysis (Loops + Genomic Features + RNA-seq)

This represents the comprehensive “3D Spatial Bridge” scenario. It links external genomic feature (peaks) to 3D‑inferred target genes, while simultaneously resolving ambiguous assignments in dense genomic regions by weighing gene expression.

# Locate auxiliary genomic features and RNA-seq expression matrix
expr_path <- system.file("extdata", "example_tpm.txt", package = "looplook")
atac_path <- system.file("extdata", "example_peaks.bed", package = "looplook")
# Live annotation requires the TxDb/OrgDb packages; when they are missing,
# res_integrated stays NULL and the pre-computed fallback below is used.
res_integrated <- NULL
if (requireNamespace("TxDb.Hsapiens.UCSC.hg38.knownGene", quietly = TRUE) &&
  requireNamespace("org.Hs.eg.db", quietly = TRUE)) {
  res_integrated <- annotate_peaks_and_loops(
    bedpe_file = global_out, # Uses the global consensus network from Module 1
    target_bed = atac_path, # External genomic features
    expr_matrix_file = expr_path, # Activates the rigorous 3-step tiebreaker
    sample_columns = c("con1", "con2"),
    species = "hg38",
    neighbor_hop = 0, # Focus on direct physical contacts
    hub_percentile = 0.95, # Top 5% nodes defined as hubs
    # Peak-anchor overlap: same-experiment defaults (strict physical overlap)
    anchor_gap = -1L, # GenomicRanges default: strict overlap
    anchor_min_overlap = 1L, # any 1 bp touch counts
    anchor_min_frac = 0, # any fraction of peak is accepted
    # anchor_merge_gap = 200,   # Uncomment when input is NOT pre-consolidated
    out_dir = out_dir,
    project_name = "Example_HiChIP_Integrative"
  )
}

Example B: Intrinsic Loop Profiling (Loops ONLY)

For users focused exclusively on 3D interactome architecture without auxiliary data related to genomic features, looplook functions as a standalone platform for loop profiling and structural hub identification.

if (requireNamespace("TxDb.Hsapiens.UCSC.hg38.knownGene", quietly = TRUE) &&
  requireNamespace("org.Hs.eg.db", quietly = TRUE)) {
  res_loops_only <- annotate_peaks_and_loops(
    bedpe_file = global_out,
    target_bed = NULL, # Omit genomic features entirely
    expr_matrix_file = expr_path, # Resolves multi-gene conflicts at loop anchors
    sample_columns = c("con1", "con2"),
    species = "hg38",
    neighbor_hop = 0,
    out_dir = out_dir,
    project_name = "Example_Loops_Only"
  )
}

Deep Dive: Output Data Dictionary

The function exports a comprehensive Excel workbook (*_Basic_Results.xlsx) containing multi-layered annotations. Interpretation of spatial regulatory logic depends critically on the hierarchical structure of its columns:

1. target_annotation (The Genomic Feature-to-3D Mapping Result)

(Generated only when target_bed is provided)

  • annotation: Genomic context of the input peaks (e.g., “Distal Intergenic”, “Promoter”).
  • Linked_Loop_IDs: Identifiers of 3D loops that overlap the peak.
  • All_Loop_Connected_Genes: Inclusive provenance union of all loop-anchor gene links. May include strict promoter/gene-body targets and non-strict positional/enhancer candidates. Not a confirmed target-gene set — use Assigned_Target_Genes or Regulated_promoter_genes for final results.
  • Regulated_promoter_genes: A stringent promoter-target set supported by loop-anchor context. A promoter gene may be local to the overlapped anchor or located on the opposite/interacting anchor; the evidence type is recorded separately.
  • Regulated_promoter_Evidence: Semicolon-delimited evidence labels for Regulated_promoter_genes, such as local_promoter_overlap, distal_promoter, or expanded_promoter_loop.
  • Assigned_Target_Genes: Policy-based strict 3D assignment. Under default promoter_then_distance, strict promoter genes outrank strict gene-body genes, which outrank structurally supported strict enhancer candidates. Shorter paths break ties within a tier, except direct strict promoter–promoter contacts (same loop, both endpoints) are co-assigned. See target_priority for details.
  • *_Filled Columns (The “Smart Fallback” Logic): Columns suffixed with _Filled (e.g., Assigned_Target_Genes_Filled, Regulated_promoter_genes_Filled) provide complete, gapless annotations when the strict 3D assignment is empty. All three *_Filled columns use the same one-level fallback: strict 3D assignment first; expression-filtered linear nearest genes (SYMBOL/geneId) only when strict is empty. No loop-connected gene layer exists in the final output: the unified finalizer re-aggregates all strict/Filled columns from the current target links, so filled genes are always strict winners or linear-annotation genes — never loop-topology genes that failed strict evaluation. The fallback is deliberately one-level: a gene that lost strict evaluation (or was filtered by expression) must not re-enter through the _Filled columns, which would bypass the strict/expression gates.
    • A filled gene is not necessarily a promoter gene — always read *_Filled together with its evidence column (see below). For stringent functional analyses (GSEA/GO), use the strict columns (include_Filled = FALSE).
  • Regulated_promoter_Fallback_Evidence: Records why Regulated_promoter_genes_Filled used a fallback (local_promoter, local_gene_body, linear_nearest, or linear_fallback); it is none when strict loop-derived promoter targets exist. The label is inferred from the feature’s own ChIPseeker annotation: promoter annotation → local_promoter, exon/intron/utr → local_gene_body, other/intergenic → linear_nearest, no annotation → linear_fallback. It tells you the type of gene used for the fill, not its 3D evidence.
  • Expanded_Target_Genes: Multi-hop target genes reachable through 3D shortest-path expansion beyond the primary loop neighbor. These have path_length > 1 and aggregate only strict expanded links. The target_gene_links provenance table may carry broader expanded labels (including expanded_positional_candidate) but the Expanded_Target_Genes column itself includes only strict-eligible genes. They are reported separately and do not compete with Assigned_Target_Genes.
  • Candidate_Positional_Genes: Genes linked only through non-strict positional or unresolved anchor–gene evidence. Includes ordinary E→E nearest-gene candidates, E-origin promoter-like anchors without resolved gene identity (E→P/dual without TSS), and other strict_assignment_eligible=FALSE links. These are positional candidates, not confirmed targets. They appear in All_Loop_Connected_Genes but are excluded from Assigned_Target_Genes, Expanded_Target_Genes, and Regulated_promoter_genes.
  • target_gene_links: A long-format provenance table. Each row is one peak-gene link with source, evidence, anchor_role, gene_role, strict_assignment_eligible, loop_ID, fallback status, and membership flags for the summary columns. The column gene_role distinguishes promoter, gene_body, enhancer_candidate, positional_candidate, and linear_annotation evidence. Only promoter and gene_body roles are structurally strict. enhancer_candidate is strict only for P/eP/G/eG→E origins (structurally resolved); ordinary E→E nearest-gene candidates and positional_candidate are non-strict. In the refined workbook, Filtered Target Gene Links keeps only links still used by the refined target columns and adds Mean_Expression plus Passes_Expression_Filter.
  • SYMBOL: The gene symbol resolved by the biotype-aware conflict resolution logic. May be a single gene or semicolon-delimited when multiple co-dominant candidates are retained.
  • loop_type: The dominant loop topology among the 3D interactions that overlap the feature.
  • All_Loop_Connected_Genes_Filled: Lineage column that preserves the original loop-connected gene set and fills empty entries with the expression-filtered linear gene fallback (same one-level logic as the other *_Filled columns).
1a. Evidence label reference

Regulated_promoter_Evidence — provenance of Regulated_promoter_genes (from 3D loop anchors):

Value Meaning
local_promoter_overlap The peak overlaps the promoter of the anchor gene
distal_promoter The opposite anchor of the linked loop is a promoter
gene_body_context The anchor overlaps a gene body (not a promoter)
expanded_promoter_loop The promoter gene was reached via ego-network expansion (neighbor_hop)
none No loop-derived promoter evidence found

Multiple evidence types may be combined in one cell (semicolon-delimited).

Regulated_promoter_Fallback_Evidence — provenance when Regulated_promoter_genes_Filled used a linear fallback:

Value Meaning
none Strict loop-derived promoter targets exist; no fallback needed
local_promoter Fallback gene overlaps a promoter region near the peak
local_gene_body Fallback gene overlaps an exon/intron/UTR region
linear_nearest Fallback gene is the nearest gene by linear distance
linear_fallback Fallback from annotation column with no location context

target_gene_links — per-link label reference:

Column Possible values
source loop_anchor, linear_annotation
gene_role promoter, gene_body, enhancer_candidate, positional_candidate, linear_annotation
evidence local_promoter_overlap, distal_promoter, gene_body_context, distal_gene_body_context, expanded_gene_body_context, local_enhancer_candidate, distal_enhancer_candidate, expanded_enhancer_candidate, expanded_promoter_loop, expanded_positional_candidate, positional_candidate, linear_annotation, linear_fallback
anchor_role local_anchor, opposite_anchor, expanded_anchor, linear_annotation
used_as_fallback TRUE, FALSE

Membership flags (in_regulated_promoter, in_assigned_target, in_all_loop_connected, in_regulated_promoter_filled, in_assigned_target_filled) indicate which target annotation column(s) contain the gene; refined links additionally carry Mean_Expression and Passes_Expression_Filter.

2. loop_annotation (3D Network Architecture)
  • loop_type: Topological classification (e.g., E-P, P-P, E-E) determined by the biotype-aware logic.
  • All_Anchor_Genes: Genes from promoter-role (promoter) or gene-body-role (gene_body) anchors. This column reflects the anchors’ own structural classification: after chromatin refinement, a P/eP anchor downgraded to enhancer_candidate (e.g., P→E) is no longer a promoter, so its gene is excluded here. The gene remains valid and appears in Putative_Target_Genes (via topology expansion, since strict_assignment_eligible = TRUE), All_Loop_Connected_Genes, and competes in Assigned_Target_Genes at rank 3. E→E nearest-gene candidates and positional-only genes are also excluded — these lack structural or TSS-supported gene identity.
  • Putative_Target_Genes: Biologically resolved target genes. For an E-P loop, this field will report only the gene at the Promoter anchor.
  • Cluster_All_Genes: All genes within the broader 3D cluster or clique in which the loop resides, reflecting the extended topological neighborhood.
  • Coordinate columns (chr1/start1/end1, chr2/start2/end2): 1-based genomic coordinates of the two loop anchors.
  • anchor1_gene / anchor2_gene: Gene symbols associated with each anchor after biotype-aware conflict resolution.
  • anchor1_type / anchor2_type: Positional classification of each anchor relative to gene annotations (P = promoter, E = distal/intergenic — positional, not functional enhancer, G = gene body; after refinement: eP = element-Promoter like, eG = element-Genebody like).
  • loop_ID: Unique loop identifier; cluster_id: connected-component membership.
3. anchor_loci_annotation (Non-redundant Spatial Anchor Footprints)
  • Cluster_Locus_Genes: All genes from loop anchors within a spatially interconnected component (defined by network-connected components), representing the full gene set associated with the deduplicated anchor loci.
  • Backward compatibility: anchor_annotation is retained as an alias of anchor_loci_annotation for older scripts.

Important: The anchor_type column in anchor_loci_annotation reflects the original positional classification (P/G/E from TSS and gene-body overlap) and is not updated by expression-aware or chromatin-aware refinement. Refined anchor types are found in loop_annotation$anchor1_type and loop_annotation$anchor2_type. For a full per-anchor audit trail — including the original annotation type, the expression-refined type, and the chromatin-corrected type — see attr(result, "looplook_anchor_state")$map_info, which contains original_type_code (annotation-time, never overwritten) and type_code (current).

4. promoter_centric_stats & distal_element_stats (Topological Hub Detection)

These metrics quantify interactome connectivity to identify candidate regulatory hubs from complementary perspectives:

A. Gene-Centric (promoter_centric_stats)

  • Total_Loops / n_Linked_Promoters / n_Linked_Distal: Deconstructs a gene’s 3D connectome. High n_Linked_Distal suggests potential regulation by enhancer clusters, whereas high n_Linked_Promoters may indicate possible participation in multi-gene transcription.
  • Dominant_Interaction: The predominant topological class governing the gene (e.g., E-P vs. P-P). When multiple loop types tie for the highest frequency, the first in alphabetical order is selected (e.g., E-P before P-P). This tie-breaking is deterministic but arbitrary; inspect raw counts when ties are likely (small datasets).
  • Is_High_Connectivity_Gene (and Distal variant): Binary flags defined by the hub_percentile to prioritize putative 3D regulatory hubs.

B. Enhancer-Centric (distal_element_stats)

  • Target_Genes: Promoters physically contacted by the distal anchor.
  • n_Linked_Promoters: Facilitates identification of candidate master enhancers that contact multiple distinct genes.
  • Is_High_Connectivity_Distal_Element: Flags highly connected non-coding elements that may act as 3D hubs.

After expression-aware refinement (*_Refined_Results.xlsx), the promoter-centric stats additionally contain:

  • Is_Active_Gene: "Yes" when the gene’s mean expression meets or exceeds the threshold; "No" otherwise. This column distinguishes structurally connected genes from those that are also transcriptionally active in the current sample context.
  • Hub classification columns (Is_High_Connectivity_Gene, Is_High_Distal_Connectivity_Gene) reflect the refined network topology, independent of expression status.

Deep Dive: Output Visualizations

All plots are returned as objects in res_integrated$plots$, enabling direct inspection and customisation with standard ggplot2 layers without re-running the pipeline.

# Representative diagnostic plots from the Module 2 annotation result
print(res_integrated$plots$Basic_Donut)

print(res_integrated$plots$Basic_Circular)

print(res_integrated$plots$Basic_Flower)

print(res_integrated$plots$Karyo_Anchors)

1. Global 3D Network Profiling

(Always Generated)

Plot key Description
Basic_Donut Loop-type frequency (donut chart)
Basic_Circular Unique target genes per loop type (circular bar)
Basic_Flower Shared vs. unique genes across loop types
Karyo_Anchors Genome-wide anchor density heatmap
Karyo_LoopGenes Genome-wide loop-associated gene density
Anchor_Genomic_Distribution Genomic context of anchors (pie)
Target_Genomic_Distribution Genomic context of input features (pie)
2. Genomic Feature-to-3D Target Profiling

(Requires target_bed)

Plot key Description
Target_Rose Loop types linked to input features (coxcomb)
Target_Loop_Genomic_Distribution Genomic context of loop-connected features (pie)
Karyo_TargetGenes Chromosomal density of assigned target genes
Customising Plots

All ggplot-based plots accept standard ggplot2 layers for recolouring, theme adjustment, or annotation:

if (!is.null(res_integrated$plots$Basic_Donut)) {
  # Access a stored plot
  p <- res_integrated$plots$Basic_Donut

  # Extract data and original label mapping
  donut_data <- p$data
  labels_vec <- setNames(donut_data$legend_label, donut_data$loop_type)

  # Apply a custom colour palette
  p + ggplot2::scale_fill_manual(
    values = RColorBrewer::brewer.pal(length(labels_vec), "Dark2"),
    labels = labels_vec
  ) + ggplot2::theme(legend.position = "bottom")
}

To save any plot to disk, use ggplot2::ggsave():

ggplot2::ggsave(
  filename = file.path(out_dir, "my_custom_donut.pdf"),
  plot = res_integrated$plots$Basic_Donut,
  width = 8, height = 6
)

For looplook_karyo objects (karyotype heatmaps), use print() to display:

print(res_integrated$plots$Karyo_Anchors) # renders via grid or opens in browser

Enhancer Clique & Promoter Hub Clustering

cluster_enhancer_cliques() builds the anchor network from annotated (optionally refined) results and resolves enhancer cliques (E-E family) or promoter hubs (P-P family) via connected components, with an optional Leiden modularity refinement. Recommended chain: expression refinement → chromatin validation → clustering; eP/eG boundary decisions (promotion/rerouting/dropping) are counted in summary.

# Expression refinement first (silent promoters -> eP), then chromatin
# validation, then clustering.
refined_res_m6 <- refine_loop_anchors_by_expression(
    annotation_res = res_integrated,
    expr_matrix_file = expr_path,
    sample_columns = c("con1", "con2"),
    threshold = 1.0, unit_type = "TPM",
    reclassify_by_expression = TRUE, quiet = TRUE)

cl_val <- validate_epeG_by_chromatin(
    refined_res_m6,
    chromatin_beds = list(
        H3K4me1 = system.file("extdata", "example_h3k4me1_peaks.bed", package = "looplook"),
        H3K27ac = system.file("extdata", "example_k27ac_peaks.bed", package = "looplook"),
        ATAC    = system.file("extdata", "example_peaks.bed", package = "looplook")))

# The example mark files cover only a handful of anchors, so evidence
# filtering is relaxed here; with real ChIP-seq data keep
# require_chromatin_evidence = TRUE.
cl <- cluster_enhancer_cliques(
    refined_res_m6,
    validation_res = cl_val,
    require_chromatin_evidence = FALSE,
    community_method = "leiden",
    resolution_parameter = 1,
    min_clique_size = 2,
    quiet = TRUE)

cl$cliques                # one row per clique: size, span, evidence, genes
#>  [1] clique_id             n_anchors             n_internal_loops     
#>  [4] chr                   start                 end                  
#>  [7] is_trans_chromosomal  n_chromatin_validated weakest_evidence     
#> [10] mean_intra_degree     max_intra_degree      anchor_genes         
#> [13] linked_promoter_genes n_genes              
#> <0 rows> (or 0-length row.names)
head(cl$membership, 10)   # anchor-level roles, evidence, promotion reasons
#>  [1] anchor_id           chr                 start              
#>  [4] end                 anchor_type         anchor_gene        
#>  [7] effective_type      chromatin_evidence  promotion_reason   
#> [10] clique_id           community_id        intra_clique_degree
#> <0 rows> (or 0-length row.names)
cl$clique_genes           # clique-to-gene provenance (long format)
#> [1] clique_id   gene        gene_role   loop_ID     anchor_role evidence   
#> [7] n_paths    
#> <0 rows> (or 0-length row.names)
cl$summary                # boundary counts + Leiden modularity
#> $n_input_loops
#> [1] 0
#> 
#> $n_edges
#> [1] 0
#> 
#> $n_cliques
#> [1] 0
#> 
#> $clique_size_median
#> [1] NA
#> 
#> $clique_size_max
#> [1] 0
#> 
#> $n_anchors_eligible
#> [1] 0
#> 
#> $n_dropped
#> [1] 0
#> 
#> $n_dropped_insufficient_evidence
#> [1] 0
#> 
#> $n_promoter_signal_not_enhancer
#> [1] 0
#> 
#> $n_rerouted_to_enhancer
#> [1] 0
#> 
#> $n_promoted_to_enhancer
#> [1] 0
#> 
#> $n_promoted_to_promoter
#> [1] 0
#> 
#> $n_unresolved_dropped
#> [1] 0
#> 
#> $n_not_in_family
#> [1] 0
#> 
#> $n_peak_overlaps
#> [1] 0
#> 
#> $clustering_p
#> [1] NA
#> 
#> $modularity
#> [1] NA

Module 3: Refinement & Validation

Module 3 provides two complementary refinement layers that answer distinct biological questions: expression-aware refinement evaluates transcriptional activity (is the gene expressed?), while chromatin-aware refinement evaluates regulatory identity (what is this anchor?) using direct histone mark evidence. Together they transform a structural contact map into a functionally interpretable regulatory network. The ideal workflow combines both — expression marks silent anchors as testable hypotheses (eP/eG), chromatin supports their reclassification into evidence-based types (E, P, G, dual). When only one data type is available, either module can be used independently.

Workflow order is enforced: When using both modules, expression refinement must run before chromatin refinement. Running refine_loop_anchors_by_expression() on a chromatin-refined object will raise an error — the reverse order (chromatin → expression) is not supported. Chromatin refinement can be applied directly to annotate_peaks_and_loops() output (chromatin-only mode) with the understanding that expression-dependent fields will be reported as not assessed.

Submodule 3A: Expression-Aware Refinement

Physical proximity detected by chromatin conformation assays is a structural prerequisite for regulatory interaction, but it does not directly indicate active transcriptional engagement. refine_loop_anchors_by_expression() integrates quantitative transcriptomic data to annotate each loop with expression-informed functional status. All structural loops are preserved; the pipeline reclassifies transcriptionally silent anchors (P → eP, G → eG), designates the expression-supported functional subset via Retained_In_Functional_Network, and records the rationale for each decision in Refinement_Action.

Important: eP/eG labels indicate transcriptional silence at the reference gene — they do not constitute evidence of enhancer activity. Orthogonal chromatin data (ATAC-seq, H3K27ac, H3K4me1) are required for functional enhancer interpretation. These labels should be treated as hypotheses for chromatin validation.

Key Parameters
  • annotation_res: Foundational 3D annotation output from Module 2.
  • expr_matrix_file & sample_columns: Quantitative expression matrix (e.g., TPM, FPKM, or NET-seq gene-body RPKM) and the specific replicates to average. Preferred order: CAGE-seq / PRO-seq > GRO-seq / NET-seq > TT-seq > RNA-seq — methods directly measuring Pol II activity at promoters give the most reliable P/eP classification.
  • threshold & unit_type: Expression cutoff (e.g., threshold = 1, unit_type = "TPM"). Genes with expression ≥ threshold are considered active. For nascent transcription data (NET-seq, PRO-seq), use a lower absolute threshold or quantile mode — Pol II elongation signal is sparser than steady-state mRNA.
  • threshold_mode: "absolute" (default): direct expression cutoff. "quantile": dataset-adaptive quantile (e.g., 0.75 selects top 25% most highly expressed genes).
  • reclassify_by_expression: When TRUE (recommended), silent P/G anchors are reclassified as eP (element-Promoter like) and eG (element-Genebody like) rather than discarded, preserving topology while flagging transcriptional state.
  • species, hub_percentile, karyo_bin_size: Genome assembly, hub-detection quantile, and heatmap bin width (see Module 2).

Expression state semantics: refine_loop_anchors_by_expression() assigns each loop a Target_Expression_State and each target gene link a Passes_Expression_Filter status using a three-class model:

State Passes_Expression_Filter Meaning
active TRUE Gene is measured and expression ≥ threshold
measured_silent FALSE Gene is measured but expression below threshold
unmeasured NA Gene is not present in the expression matrix — not equivalent to zero expression

Why this matters: A gene absent from the expression matrix may reflect annotation mismatch, transcript-level filtering, or platform limitations — it cannot be interpreted as biologically silent. Genes measured at true zero (TPM = 0) are correctly classified as measured_silent, not unmeasured. When threshold = 0, the code uses strict > 0 (not >= 0) to prevent all measured genes from being unconditionally classified as active. The Has_Active_Target flag is NA for loops whose targets are unmeasured, rather than falsely reporting FALSE.

Submodule 3B: Chromatin-Aware Anchor Refinement

refine_loop_anchors_by_chromatin() applies orthogonal chromatin mark evidence (ChIP-seq, CUT&Tag, ATAC-seq) to systematically reclassify loop anchors and update loop topologies. While expression-aware refinement asks whether the gene is transcribed, chromatin-aware refinement asks what the regulatory element is — a more fundamental question answered by direct histone modification data.

The function tests all anchor types (P, G, E, eP, eG by default) against user-supplied BED files for up to five marks: H3K4me1, H3K4me3, H3K27ac, ATAC, and H3K27me3. Each anchor receives an enhancer evidence level (canonical through uncertain), a chromatin state (e.g., active_enhancer_like, dual_like, promoter_like), and an evidence string (e.g., "H3K4me1+; H3K27ac+; H3K4me3-"). Anchors are refined based on mark combinations — for instance, a P anchor with H3K4me1⁺ H3K4me3⁻ H3K27ac⁺ is refined to E, while an eP anchor with H3K4me3⁺ without H3K4me1 is reverted to P. Triple-positive anchors (H3K4me1⁺ H3K4me3⁺ H3K27me3⁺) are classified as conflicting_marks and retain their original eP/eG type.

When recompute_targets = TRUE, target gene links are rebuilt from chromatin-updated anchor types and carry full audit columns (anchor_type_before_chromatin, anchor_type_after_chromatin, chromatin_target_action). See the Chromatin-Aware Anchor Refinement section below for the complete rule set, confidence criteria, and output structure.

Pipeline guidance: The two submodules serve distinct, complementary roles. When you have both expression and ChIP-seq data, use expression refinement first then chromatin refinement — expression marks silent anchors as hypotheses, chromatin resolves them, and the activity columns (Putative_Target_Genes, Retained_In_Functional_Network) are recomputed from stored expression data using the chromatin-updated anchor types. When you have only ChIP-seq, run chromatin refinement directly on Module 2 output. When you have only expression data (RNA-seq, NET-seq, or CAGE-seq), run expression refinement alone — eP/eG labels serve as testable hypotheses for future chromatin validation.

When chromatin data are complete (H3K4me1 + H3K4me3 minimum), the refinement rules update most eP/eG into chromatin-supported types: dual (H3K4me1+ H3K4me3+), E (active/intermediate enhancer chromatin), or P/G (H3K4me3+ promoter signal). eP/eG may persist when chromatin evidence is insufficient to override the expression-based classification — for instance, H3K4me1 alone (other_enhancer_like) cannot distinguish active from poised enhancers, H3K27me3 alone (repressed) is consistent with transcriptional silence, and anchors without detected marks (uncertain) lack the evidence needed for refinement. Residual eP/eG are not errors; they flag loci where the available chromatin data do not resolve the regulatory identity, and the chromatin_validation table records the evidence (or lack thereof) for each anchor.

Expression Refinement Output Structure

The refined loop_annotation contains two target gene columns with distinct semantics:

  • Putative_Target_Genes: Expression-filtered active-only targets. Contains only genes that pass the expression threshold; no fallback genes are included. This column is used for Has_Active_Target and Retained_In_Functional_Network determination.

Each loop is annotated with a Refinement_Action status:

Value Meaning
retained_active_target Loop has at least one active target gene
reclassified_silent_anchor Anchor was reclassified (P→eP or G→eG); no active targets remain
expression_filtered_no_active_target Target genes were filtered by expression; no reclassification occurred
structural_only_no_active_target Loop had no target genes even before refinement

The Has_Active_Target and Retained_In_Functional_Network columns are always identical; both indicate whether the loop belongs to the high-confidence functional subset. To obtain the functional subset, filter on Retained_In_Functional_Network == TRUE. When writing to Excel, a dedicated Functional Loop Annotation sheet is always included (even if empty) for schema stability.

Example A: Standard Refinement (Expression Filtering)

In this scenario, a strict expression threshold identifies loops with transcriptionally active target genes. All structural loops are retained; the Retained_In_Functional_Network flag indicates which loops belong to the functional subset.

res_basic <- refine_loop_anchors_by_expression(
  annotation_res = res_integrated,
  expr_matrix_file = expr_path,
  sample_columns = c("con1", "con2"),
  threshold = 1.0,
  unit_type = "TPM",
  reclassify_by_expression = FALSE,
  out_dir = out_dir,
  project_name = "Example_Basic_Filter"
)

This advanced mode is strongly recommended, as it preserves the valuable 3D structural framework while refining functional annotations. A silent promoter anchor is reclassified as an enhancer (eP), acknowledging that while its reference gene is transcriptionally inactive, this region itself may function as an active regulatory element for a distant gene.

refined_res <- refine_loop_anchors_by_expression(
  annotation_res = res_integrated,
  expr_matrix_file = expr_path,
  sample_columns = c("con1", "con2"),
  threshold = 1.0,
  unit_type = "TPM",
  reclassify_by_expression = TRUE,
  out_dir = out_dir,
  project_name = "Example_Reclassified_Filter"
)

Example C: Refinement + Orthogonal Chromatin Validation

Supply chromatin_beds to automatically validate eP/eG anchors against chromatin mark data. The result is added to the Excel workbook and returned as refined_res$chromatin_validation.

h3k27ac_path <- system.file("extdata", "example_k27ac_peaks.bed", package = "looplook")
h3k4me1_path <- system.file("extdata", "example_h3k4me1_peaks.bed", package = "looplook")
h3k4me3_path <- system.file("extdata", "example_h3k4me3_peaks.bed", package = "looplook")

refined_val <- refine_loop_anchors_by_expression(
  annotation_res = res_integrated,
  expr_matrix_file = expr_path,
  sample_columns = c("con1", "con2"),
  threshold = 1.0,
  reclassify_by_expression = TRUE,
  chromatin_beds = list(
    H3K27ac  = h3k27ac_path,
    H3K4me1  = h3k4me1_path,
    H3K4me3  = h3k4me3_path
  ),
  out_dir = out_dir,
  project_name = "Example_Validated"
)
# View enhancer evidence distribution
table(refined_val$chromatin_validation$enhancer_evidence)
#> 
#> canonical    strong supported   limited uncertain 
#>         0         0         0        14         0

Deep Dive: Expression Refinement Visualizations

Expression refinement automatically generates a suite of visual diagnostics to quantify refinement efficacy and characterize the functional network:

1. Global Refinement Profiling

(Always Generated)

  • Refinement Effect Dumbbell (*_Comparison_Dumbbell.pdf): Quantifies the impact of expression-aware reclassification by visualizing the numerical contrast between original structural loops and refined loops across all topological classes, highlighting reclassification-driven changes in loop type composition.

  • Refined Loop Proportion Rose (*_Rose.pdf): Coxcomb chart illustrating the topological distribution (by count) of the interactome after expression-aware reclassification.

  • Refined Current Target Genes Karyotype (*_Refined_Karyo_CurrentTargets.pdf): Genome-wide ideograms showing the chromosomal density of genes currently represented in the refined loop network through Putative_Target_Genes.

2. Genomic Feature-to-3D Target Annotation Profiling

(Generated only if target_bed was provided in Module 2)

  • Multi-Omics Sankey Diagram (Target_Sankey htmlwidget in-memory; target_sankey.html alongside the report when rendered): Core integration diagnostic that maps the fate of inputted genomic features across three logical tiers: Genomic Region (L1) → 3D Loop Connection (L2) → Target Expression Status (L3). This intuitively reveals the proportion of GWAS/ChIP-seq peaks structurally connected to functionally active genes. When generated through looplook_report(), keep target_sankey.html in the same output directory as the main HTML report.

  • Refined Target Loop Donut (*_Target_Loop_Donut.pdf): Visualizes the loop-type composition of refined loops directly linked to user-defined genomic features through accepted peak-anchor overlaps. The pre-refinement Target_Rose and post-refinement Target_Loop_Donut both summarise loops directly incident to accepted target-overlapping anchors; they differ only in whether loop types are shown before or after refinement.

  • Refined Target Genes Karyotype (*_Refined_Karyo_TargetGenes.pdf): Chromosomal density map of strictly refined putative target genes.

For chromatin refinement visualizations (dumbbell, sankey, mark-enrichment heatmap, rose), see the Chromatin-Aware Anchor Refinement section below.

Orthogonal Validation of eP/eG Anchors (Chromatin Mark Evidence)

After expression-aware refinement produces eP/eG labels, validate_epeG_by_chromatin() tests these anchors against user-supplied chromatin mark BED files (ATAC-seq, ChIP-seq) to distinguish genuine regulatory elements from expression artefacts.

Important: eP/eG labels denote element-Promoter like / element-Genebody like elements — structural positional classifications, not functional enhancer calls. This function provides the orthogonal evidence needed to elevate or discard those candidates.

Workflow
# Validate the eP/eG anchors from the refined result above
val <- validate_epeG_by_chromatin(
  annotation_res = refined_res,
  chromatin_beds = list(
    H3K4me1  = h3k4me1_path,
    H3K27ac  = h3k27ac_path,
    H3K4me3  = h3k4me3_path
  ),
  anchor_gap = 200, # proximity tolerance (bp)
  anchor_min_overlap = 100 # minimum overlap (bp)
)

# View enhancer evidence distribution
table(val$enhancer_evidence)
#> 
#> canonical    strong supported   limited uncertain 
#>         0         0         0        14         0
Enhancer Evidence Levels

Each eP/eG anchor is tested for overlap with up to 5 marks and assigned an enhancer evidence level (highest to lowest). These levels assess how strongly the chromatin marks match an active enhancer, not the overall confidence in the anchor’s classification. A promoter (H3K4me3+) may score only supported because the criteria are enhancer-oriented.

Level Condition
canonical All 5 marks provided; H3K4me1⁺, H3K27ac⁺, ATAC⁺, H3K27me3⁻, H3K4me3⁻
strong H3K4me1⁺ and (H3K27ac⁺ or ATAC⁺); H3K4me3⁻ if tested (H3K4me3⁺ downgrades to supported)
supported At least one of H3K4me1, H3K27ac, or ATAC is positive. H3K4me3⁺ anchors receive a promoter_like evidence tag (does not by itself force reclassification to P; triple-positive anchors are conflicting_marks)
limited No positive marks; H3K27me3 or H3K4me3 not detected in peak calls
uncertain No chromatin data provided or no overlaps detected

Marks not provided are recorded as NA and do not influence scoring — missing data is never treated as negative evidence. H3K4me3⁺ anchors are flagged as promoter_like (an evidence tag, not a reclassification). refine_loop_anchors_by_chromatin() resolves these to P, dual, or retains the original type based on the full mark combination. Triple-positive anchors (H3K4me1⁺/H3K4me3⁺/H3K27me3⁺) are conflicting_marks and retain eP/eG.

Output Columns
Column Description
anchor_id, chr, start, end Anchor identifier and coordinates
anchor_type, anchor_gene Original type and associated gene(s)
H3K4me1..H3K4me3 NA = not provided, TRUE = peak detected, FALSE = peak not called
enhancer_evidence Enhancer evidence level (not classification confidence): canonical > strong > supported > limited > uncertain
evidence Human-readable string (e.g. "H3K4me1+; H3K27ac+; H3K27me3-")

Chromatin-Aware Anchor Refinement

While validate_epeG_by_chromatin() provides a confidence score for each eP/eG anchor independently, refine_loop_anchors_by_chromatin() applies chromatin-mark evidence to systematically refine anchors and update loop topologies. This function can be called on raw annotation output (annotate_peaks_and_loops) to test P/G/E anchors, or on expression-refined output to test eP/eG anchors.

Refinement rules (minimum input: H3K4me1 + H3K4me3):

  • Enhancer BED overlap (highest priority): Known enhancer regions (enhancer_bed parameter, e.g. FANTOM5 or ENCODE cCREs). Overlapping anchors become E (H3K4me3⁻) or dual (H3K4me3⁺).
  • P + H3K4me1⁺ H3K4me3⁺: Resolved by bigWig ratio (chromatin_bw) when available — dual if H3K4me1/H3K4me3 ≥ 3, otherwise P (H3K4me3 dominates). Without bigWig, H3K4me3⁺ always defaults to P.
  • E/G + H3K4me1⁺ H3K4me3⁺: Resolved by bigWig ratio when available — dual if H3K4me1/H3K4me3 ≥ 3, P if K4me3-dominant. Without bigWig, E/G retain their original type (conservative — ratio data required), unlike P which defaults to P.
  • E/G + H3K4me3⁺ H3K4me1⁻ → P: Unannotated or internal promoter.
  • P + H3K4me1⁺ H3K4me3⁻ + (H3K27ac⁺ or ATAC⁺) → E: Conservative reclassification requiring active-mark confirmation.
  • G + H3K4me1⁺ H3K4me3⁻ + (H3K27ac⁺ or ATAC⁺) → E: Intronic enhancer.
  • eP/eG + H3K4me3⁺ (promoter_like, without H3K4me1) → P: Revert to promoter; includes bivalent H3K4me3⁺/H3K27me3⁺. Triple-positive (H3K4me1⁺/H3K4me3⁺/H3K27me3⁺) are conflicting_marks and retain eP/eG, unless the anchor also matches a curated enhancer_bed region with H3K4me3⁺ (rule 1 — highest priority — reclassifies to dual).
  • eP/eG + dual_like: Resolved by bigWig ratio when available — dual if H3K4me1/H3K4me3 ≥ 3, otherwise P (H3K4me3-dominant eG is interpreted as an internal/alternative TSS candidate). Without bigWig, dual-positive (H3K4me1⁺/H3K4me3⁺) anchors retain their eP/eG type (conservative — ratio data required to resolve promoter vs dual-signature); H3K4me3⁺-only anchors (H3K4me1⁻) are reverted to P.
  • Anchor types not matching any rule remain unchanged.

Optional parameters chromatin_bw (bigWig paths for H3K4me1 and H3K4me3) and enhancer_bed (curated enhancer regions) provide quantitative and literature-based evidence to refine dual-classification further. Without these, H3K4me3⁺-only anchors (K4me1⁻) are reclassified to P regardless of original type; dual-positive anchors (H3K4me1⁺/H3K4me3⁺) retain their original type until quantitative ratio data are available.

The chromatin state of each anchor is also inferred (highest-priority match first): conflicting_marks > dual_like > active_enhancer_like > intermediate_enhancer_like > other_enhancer_like > promoter_like > repressed > uncertain > no_data.

Important — H3K4me3 dependency: Rules that test for H3K4me3 absence (e.g., P→E, G→E) require H3K4me3 to be provided in chromatin_beds. When H3K4me3 is omitted, its value is NA for all anchors, and these rules are skipped conservatively — no reclassification without explicit data. Include H3K4me3 (and optionally H3K27me3) to enable the full set of reclassification rules.

Pipeline guidance: The two refinement modules serve distinct roles that complement each other — they do not replace one another. Expression-aware refinement evaluates transcriptional activity (is the gene expressed?) and provides activity metrics (Putative_Target_Genes, Retained_In_Functional_Network, Refinement_Action) required for downstream GSEA, GO enrichment, and differential expression profiling. Chromatin-aware refinement evaluates chromatin identity (what is this anchor?) using direct histone mark evidence, revising positional and expression-derived anchor types into chromatin-supported categories (E, P, G, dual). When you have both expression and ChIP-seq data, use expression refinement first then chromatin refinement — expression marks silent anchors as hypotheses (eP/eG), chromatin supports or revises them, and the expression-filtered target columns are recomputed from stored expression data using the updated chromatin-aware anchor types for consistent downstream profiling. When you have only ChIP-seq data, run chromatin refinement directly on annotate_peaks_and_loops() output. When you have only expression data (RNA-seq, NET-seq, or CAGE-seq), run expression refinement alone — eP/eG labels serve as testable hypotheses for future chromatin validation.

# Run on expression-refined output (tests eP/eG anchors)
cr <- refine_loop_anchors_by_chromatin(
  annotation_res = refined_res,
  chromatin_beds = list(
    H3K4me1  = h3k4me1_path,
    H3K4me3  = h3k4me3_path,
    H3K27ac  = h3k27ac_path
  ),
  anchor_gap = 200,
  anchor_min_overlap = 100,
  recompute_targets = TRUE, # Rebuild target links with updated types
  species = "hg38",
  project_name = "Chromatin_Refined",
  out_dir = out_dir
)

# Summary of reclassification
cr$qc_summary
#>   n_candidate_anchors n_reclassified n_canonical n_strong n_supported n_limited
#> 1                  14              0           0        0           0        14
#>   n_dual n_promoter_like n_TSS_supported n_TSS_provisional n_TSS_unresolved
#> 1      0               0               0                 0                0
#>   n_TSS_validation_unavailable
#> 1                            0

# Updated loop types reflect chromatin evidence
table(cr$loop_annotation$loop_type)
#> 
#> E-P G-G G-P P-P 
#>   1   1   2   3

  # Chromatin provenance columns in target links
  head(cr$target_gene_links[, c(
    "gene", "anchor_type_before_chromatin",
    "anchor_type_after_chromatin", "chromatin_target_action"
  )])
#>        gene anchor_type_before_chromatin anchor_type_after_chromatin
#> 1      FMO1                         <NA>                        <NA>
#> 2     LRRC7                         <NA>                        <NA>
#> 3     BCAR3                         <NA>                        <NA>
#> 4    GALNT2                         <NA>                        <NA>
#> 5 LINC01361                         <NA>                        <NA>
#> 6     NTRK1                         <NA>                        <NA>
#>   chromatin_target_action
#> 1               unchanged
#> 2               unchanged
#> 3               unchanged
#> 4               unchanged
#> 5               unchanged
#> 6               unchanged

The output chromatin_validation table records, for each candidate anchor, the overlap with every provided mark (TRUE/FALSE/NA), its enhancer evidence level, chromatin state, and the reclassification decision (positional type vs. final type). When recompute_targets = TRUE, target gene links carry anchor_type_before_chromatin, anchor_type_after_chromatin, and chromatin_target_action columns for full auditability. When recompute_targets = FALSE, target_annotation and target_gene_links are preserved from the upstream (pre-chromatin) object and do not reflect chromatin-refined anchor roles. Use profile_target_genes(target_source = "loops") for chromatin-aware downstream profiling, or set recompute_targets = TRUE (default) to rebuild target tables with updated anchor types.

Chromatin Refinement Visualizations

refine_loop_anchors_by_chromatin() automatically generates four diagnostic plots (accessible via $plots):

Plot key Type Description
Chromatin_Dumbbell Dumbbell chart Anchor-type counts before vs. after reclassification. Grey = original, green = refined.
Chromatin_Sankey Sankey flow diagram Left: anchor types before reclassification. Right: updated types after chromatin-aware reclassification. Green flows = unchanged, amber flows = reclassified. Each flow’s width is proportional to the number of anchors.
Chromatin_MarkHeatmap Aggregated heatmap % of anchors in each reclassification group positive for each chromatin mark (white = 0%, deep green = 100%). One row per reclassification type (e.g., P→dual), one column per mark. Left bar: anchor count (N) per group. Cell labels show exact percentages.
Chromatin_UpSet UpSet plot Combinatorial view of loop-type intersections after chromatin-aware reclassification. Top: log10 bar chart of counts per combination. Bottom: dot-and-line matrix showing which anchor types participate in each combination, with self-loop arcs on E-E, P-P, and dual-dual types.

All plots are returned as ggplot2 objects (except the heatmap, which is a ComplexHeatmap grob) and accept standard + layers for customisation. To access a specific plot:

cr$plots$Chromatin_Dumbbell

cr$plots$Chromatin_Sankey
#> NULL
cr$plots$Chromatin_MarkHeatmap
#> NULL
cr$plots$Chromatin_UpSet

Interpreting the MarkHeatmap: Rows represent reclassification outcomes (e.g., “P → dual” means a promoter was reclassified as a dual-signature element). Columns represent chromatin marks. High percentages (dark green) indicate marks that are frequently present in that reclassification group — these are the marks driving the reclassification decision. For example, if “P → dual” shows 95% for H3K4me1 and 88% for H3K4me3, it indicates that dual-mark presence is the primary driver of the P→dual reclassification.


Module 4: Automated Functional Profiling

Following identification of evidence-prioritized target genes, profile_target_genes provides a fully automated, end-to-end multi-omics analysis pipeline. It integrates 3D genomic interactions with transcriptomic data to systematically characterize the functional landscape and regulatory mechanisms underlying the identified target genes.

Important: The GO enrichment, motif scanning, and PPI network modules are designed as exploratory (hypothesis-generating) analyses. Statistical tests (Wilcoxon/t-test p-values, GSEA) are reported per-module without global multiple-testing correction across loop types or analysis branches. GSEA uses random down-sampling of target genes controlled by gsea_nSample, introducing stochasticity. Motif enrichment uses GC-matched background sampling with Fisher’s exact test. All exploratory results should be validated with independent experimental approaches before drawing definitive biological conclusions.

Parameter Strategy: A Highly Modular Pipeline

This function supports highly flexible experimental design through a set of routing parameters that define the gene set to be analyzed, as well as toggle parameters that enable or disable specific downstream biological modules.

1. Core Data Inputs
  • annotation_res: The foundational annotation result, inherited directly from Module 2 or the refined output from Module 3.
  • diff_file & lfc_col: Differential expression summary (e.g., from DESeq2) required for fold change profiling and gene set enrichment analysis (GSEA).
  • expr_matrix_file & metadata_file: Normalized expression matrix and sample metadata, which are essential for generating heatmaps and Raincloud plots.
2. Target Selection & Mapping Strategies

This section contains the most critical routing parameters that define the biological scope and stringency of downstream analyses:

  • target_source (The Biological Scope):
    • "targets" (Variant/Peak-Centric): Focuses exclusively on the putative genes regulated by user-defined genomic features (e.g., GWAS SNPs, ATAC-seq peaks).
    • "loops" (Global Network-Centric): Analyzes the full 3D interactome, including all genes associated with spatial loops, without considering user-defined genomic features.
    • c("loops", "targets"): Analyzes both scopes simultaneously, which is strongly recommended for comparative functional profiling.
  • target_mapping_mode:
    • "all" (Default): Retains broad 3D regulatory targets, including distal enhancers looping to gene bodies.
    • "promoter": Applies stringent filtering, requiring loops to anchor explicitly at canonical promoter regions.
  • include_Filled (The Stringency Toggle): Logical parameter controlling the purity of spatial regulation:
    • TRUE (Hybrid Mode): Utilizes the comprehensively merged annotation (_Filled columns from Module 2). It prioritizes 3D loop-derived targets while rescuing unlooped genomic features (peaks) by assigning them the nearest genes, ensuring no data loss and a complete functional overview.
    • FALSE (Pure Spatial Mode): Highly stringent. It only keeps 3D loop-derived targets with clear annotation.

Important — reading _Filled columns correctly: All *_Filled columns use the same one-level fallback: strict 3D assignment first; expression-filtered linear nearest genes only when strict is empty. Loop-connected genes that failed strict evaluation never enter _Filled columns (the unified finalizer re-aggregates from current target links only). In practice this means: peaks with loop connections keep Filled = strict; peaks without loop connections are filled with the linear nearest gene — subject to the expression filter whenever the object carries expression data (an unexpressed linear gene leaves the cell NA rather than being filled). Two usage rules follow:

  1. Always read *_Filled together with its evidence column. Regulated_promoter_genes_Filled can contain genes from any fallback source — a filled gene is not necessarily a promoter gene. Consult Regulated_promoter_Fallback_Evidence (values: local_promoter, local_gene_body, linear_nearest, linear_fallback; inferred from the feature’s ChIPseeker annotation) to know what each filled gene actually is.
  2. Use strict columns for stringent functional analyses (GSEA/GO). _Filled columns provide complete genome-wide coverage (the “gapless annotation” semantics) and therefore mix 3D-derived and linear-nearest genes. When running GSEA or GO enrichment, prefer include_Filled = FALSE (strict Assigned_Target_Genes / Regulated_promoter_genes) so the gene set reflects only spatial regulation; reserve include_Filled = TRUE for exploratory overviews or modules that need complete coverage.
  • use_nearest_gene: Logical parameter. If TRUE, the pipeline bypasses 3D loop-based assignment and uses only the nearest neighboring gene, serving as a conventional baseline reference for Control comparisons.
3. Downstream Functional Analyses
  • loop_types: Character vector of loop types to include in the analysis (default: c("E-P", "P-P")). Used only when target_source = "loops".
  • stat_test: Statistical test for comparing target vs. background LFC distributions ("wilcox.test" or "t.test"; default: "wilcox.test").
  • org_db: Organism annotation database package name for GO and PPI analyses (default: "org.Hs.eg.db").
  • gsea_nSample (numeric or NULL, default NULL): Maximum number of target genes to sample for GSEA. NULL (default) uses the full target gene set without down-sampling. When the gene set is large (hundreds of genes), set to e.g. 20–50 for faster computation. Set to 99999 (effectively all) when passing through looplook_report(). Down-sampling introduces Monte Carlo variance; use seed for reproducible results.
  • heatmap_nSample (numeric, default 99999): Maximum number of target genes to display in the expression heatmap (top by variance). Reduce to e.g. 20–50 for readable heatmaps.
  • cnet_nSample (numeric, default 50): Number of top GO terms to display in the concept network plot.
  • seed (integer or NULL, default NULL): Random seed for reproducible GSEA down-sampling and motif GC-matched background sampling. Set to a positive integer for fully deterministic results.
  • run_go: Executes Gene Ontology enrichment and generates concept network plots (requires clusterProfiler).
  • run_motif & genome_id: Scans proximal and distal anchor sequences against JASPAR core motifs (requires BSgenome and motifmatchr).
  • run_ppi & ppi_score: Constructs Protein-Protein Interaction (PPI) networks via the STRING database (minimum combined score, default: 400). For non-human/non-mouse species, pass the NCBI taxonomy ID via ppi_species_id (e.g. ppi_species_id = 9823 for pig). See ?profile_target_genes for a species reference table.

Ideal for complete multi-omics integration (e.g., HiChIP + ATAC-seq). This mode comprehensively maps and profiles target genes of interest.

diff_path <- system.file("extdata", "example_deg.txt", package = "looplook")
meta_path <- system.file("extdata", "example_coldata.txt", package = "looplook")

res_A <- profile_target_genes(
    annotation_res = res_integrated,
    diff_file = diff_path,
    lfc_col = "log2FoldChange",
    expr_matrix_file = expr_path,
    metadata_file = meta_path,
    target_source = c("loops", "targets"),
    target_mapping_mode = "all",
    include_Filled = TRUE,
    use_nearest_gene = FALSE,
    project_name = "Scenario_A_Integrative",
    run_motif = FALSE,
    run_go = FALSE,
    run_ppi = FALSE
  )

Example B: Peak-Driven Strict Promoter Profiling (High Stringency)

This mode applies a rigorous dual-filtering strategy to yield a stringently filtered target gene set.

First, target_source = "targets" restricts profiling to genes regulated specifically by user-defined genomic features (e.g., GWAS SNPs or TF binding sites), excluding background spatial loops. Second, target_mapping_mode = "promoter" enforces topological stringency: loops linking peaks to target genes must directly contact canonical or reference promoters (i.e., strict E-P or P-P loops), excluding more permissive connections such as enhancer-gene body (E-G) interactions.

res_B <- profile_target_genes(
    annotation_res = res_integrated,
    diff_file = diff_path,
    lfc_col = "log2FoldChange",
    expr_matrix_file = expr_path,
    metadata_file = meta_path,
    target_source = "targets", # 1. Focus exclusively on inputted genomic features
    target_mapping_mode = "promoter", # 2. Require strict loop-to-promoter collision
    include_Filled = TRUE,
    use_nearest_gene = FALSE,
    project_name = "Scenario_B_StrictPromoter",
    run_motif = FALSE, # Set TRUE in real analysis to scan JASPAR motifs
    run_go = FALSE, # Set TRUE in real analysis for pathway enrichment
    run_ppi = FALSE
  )

Example C: 1D Linear Annotation Baseline (The Control)

By setting use_nearest_gene = TRUE, this mode intentionally bypasses the 3D spatial topology and assigns features exclusively to their nearest neighboring gene. It serves as a conventional “baseline control.” Comparing results against Example A or B enables rigorous demonstration of the novel functional insights gained from 3D chromatin looping analyses relative to conventional method.

res_C <- profile_target_genes(
    annotation_res = res_integrated,
    diff_file = diff_path,
    lfc_col = "log2FoldChange",
    expr_matrix_file = expr_path,
    metadata_file = meta_path,
    target_source = "targets", # Focus on inputted peaks
    target_mapping_mode = "all",
    include_Filled = FALSE,
    use_nearest_gene = TRUE, # Nearest neighboring gene (The Control)
    project_name = "Scenario_C_LinearControl",
    run_motif = FALSE, # Set TRUE in real analysis to scan JASPAR motifs
    run_go = FALSE, # Set TRUE in real analysis for pathway enrichment
    run_ppi = FALSE
  )

Deep Dive: Functional Visualizations

Results are returned as a named list, one element per target_source (e.g., "loops", "targets"). Each element contains plots (ggplot objects), target_gene_sets (character vectors), and go_results (data frames).

# Accessing results from a profiling run
names(res_A) # one element per target_source ("loops", "targets")
#> [1] "loops"   "targets"
names(res_A$loops) # "go_results" "target_gene_sets" "plots"
#> [1] "go_results"       "motif_results"    "target_gene_sets" "plots"           
#> [5] "warnings"

# --- Target genes ---
res_A$loops$target_gene_sets # named list of character vectors
#> $EP_Genes
#> [1] "TTF2"
#> 
#> $PP_Genes
#> [1] "DVL1"   "MRPL20" "CDC14A" "ISG15"
names(res_A$loops$target_gene_sets) # gene set keys (e.g. "All", "Up", "Down")
#> [1] "EP_Genes" "PP_Genes"

# --- GO enrichment table (requires run_go = TRUE) ---
if (length(res_A$loops$go_results) > 0) {
  go_df <- res_A$loops$go_results
  head(go_df[order(go_df$pvalue), c("Description", "ONTOLOGY", "pvalue", "Count", "geneID")])
} else {
  message("GO enrichment was not run. Set run_go = TRUE to enable.")
}

# --- All plot keys ---
names(res_A$loops$plots)
#> [1] "PP_Genes"

# --- Representative profiling plots ---
# Plots are grouped per analysis task (see names(res_A$loops$plots)); here we
# show the core plots for the "targets" task.
tg_plots <- res_A$targets$plots$Target_Genes
if (!is.null(tg_plots$LFC_Violin)) print(tg_plots$LFC_Violin)

if (!is.null(tg_plots$Heatmap)) print(tg_plots$Heatmap)
if (!is.null(tg_plots$Scatter)) print(tg_plots$Scatter)
if (!is.null(tg_plots$Raincloud_LFC)) print(tg_plots$Raincloud_LFC)
Available Plot Keys
Key Description
LFC_Violin Differential expression violin + boxplot
Heatmap Expression heatmap with sample annotations
Scatter Connectivity vs. expression scatter
Raincloud_LFC Raincloud plot of log2 fold changes
Raincloud_Expr Raincloud plot of expression levels
GSEA Gene Set Enrichment Analysis plot
GO_Network GO enrichment cnetplot
GO_Lollipop Summary GO lollipop facet
PPI STRING protein-protein interaction network
Proximal_Motif_Bar Proximal anchor motif enrichment barplot
Proximal_Motif_Logos Proximal anchor motif sequence logos
Proximal_Motif_Rank Proximal anchor motif rank scatter
Distal_Motif_Bar Distal anchor motif enrichment barplot
Distal_Motif_Logos Distal anchor motif sequence logos
Distal_Motif_Rank Distal anchor motif rank scatter

All ggplot-based plots accept standard ggplot2 + layers for recolouring or theme adjustment (see Module 2 for examples).


Module 5: IGV-Style Track Visualization

To visualize the local spatial interactome with high resolution, this module generates an IGV-style multi-tiered genomic browser view via the plot_peaks_interactions function. This visualization integrates multi-omics datasets into three distinct, non-overlapping genomic tracks, enabling intuitive assessment of 3D structural context:

  • Loop Track (Top): Depicts 3D chromatin interactions as Bezier arcs connecting paired spatial anchors. When score_to_alpha = TRUE is enabled, the opacity (alpha channel) of each arc is scaled proportionally to the quantitative interaction score.
  • Target Track (Middle): Renders user-provided genomic features (e.g., ChIP-seq peaks or GWAS SNPs) from the input BED file, facilitating direct visualization of their spatial overlap with the loop anchors.
  • Gene Track (Bottom): Retrieves the longest canonical transcript for each gene using standard Bioconductor annotation databases, with exons and introns mapped according to strand directionality. Overlapping gene models are vertically separated to avoid label collisions and improve readability.

Set interactive = TRUE to generate an interactive version with hover tooltips: genomic coordinates and scores on loop arcs and anchors, gene symbols and biotypes on genes, and peak identifiers on target features. When hovered, the selected element is highlighted while others dim for visual focus. Requires the ggiraph package.

Parameter Strategy & Core Inputs

The function provides fine-grained control over genomic locus selection, data filtering, and visual aesthetics through the following arguments:

1. Data Inputs & Genomic Coordinates
  • bedpe_file: Character. Specifies the path to the BEDPE-format spatial interaction file. The function utilizes the first six columns for paired anchor coordinates and the seventh column (if present) as the quantitative interaction score.
  • target_bed: Character (Optional). Specifies the path to a user-supplied genomic feature file in standard BED format, rendered in the middle track to assess overlap with 3D anchors.
  • chr, from, to: Specifies the exact genomic window for visualization. If chr is omitted (NULL), the function defaults to the chromosome with the highest loop count in the BEDPE file.
  • min_score: Numeric (Optional). Applies a threshold to filter the displayed loops based on the interaction score column.
2. Annotation Dependencies
  • species: Character. Specifies the reference genome assembly (supported: "hg38", "hg19", "mm10", or "mm9"). This parameter triggers automatic loading of the corresponding Bioconductor TxDb and OrgDb annotation packages for gene track rendering.
3. Aesthetic Mapping & Track Configuration
  • score_to_alpha: Logical flag. When TRUE, the quantitative interaction score is mapped to the transparency of Bezier arcs, enabling visual differentiation of interaction strength.
  • max_levels: Integer. Defines the maximum number of visible stacking bands for loop arcs. Overlapping loops are separated vertically up to this cap; denser regions are compressed into the available height while preserving relative layering.
  • base_anchor_height: Numeric. Sets the vertical thickness of the rectangular anchors plotted at the base of the loop arcs.
  • Color Controls (loop_color, anchor_color, overlap_color, exon_color, intron_color): Character strings specifying custom colors for structural elements across all three tracks.
  • save_file: Character (Optional). Specifies the output file path and format (e.g., ".pdf") for exporting the final ggplot object.
if (requireNamespace("ggplot2", quietly = TRUE) &&
  requireNamespace("TxDb.Hsapiens.UCSC.hg38.knownGene", quietly = TRUE) &&
  requireNamespace("org.Hs.eg.db", quietly = TRUE)) {
  # If 'from' and 'to' are omitted, it automatically detects the densest viewport.
  track_plot <- plot_peaks_interactions(
    bedpe_file = f1,
    target_bed = atac_path,
    chr = "chr1",
    from = 11884299,
    to = 12106581,
    species = "hg38",
    save_file = file.path(out_dir, "Locus_Track.pdf")
  )
  print(track_plot)
}


One-Click Parameterised Report

For rapid sharing with collaborators, a publication-ready HTML report can be generated with a single function call. The template automatically detects which pipeline stages are configured and hides unavailable sections:

library(looplook)

# ── Required ──────────────────────────────────────────────────
#   bedpe_file         Chromatin loops in BEDPE format
# ── Required for annotation ───────────────────────────────────
#   target_bed         Genomic features (ATAC-seq peaks, etc.)
# ── Optional annotation tuning ─────────────────────────────────
#   anchor_gap = 0L          Peak-anchor candidate search radius
#   anchor_min_overlap = 1L  Min overlap in bp (1 = any touch)
#   anchor_min_frac = 0      Min overlap as fraction of peak width
#   neighbor_hop = 0         k-hop ego-network expansion
# ── Required for refinement + profiling ───────────────────────
#   expr_matrix_file   Normalised expression matrix (TPM/FPKM)
#   diff_file          Differential expression table (CSV/TSV)
#   metadata_file      Sample metadata with Group column
# ── Optional (defaults shown) ─────────────────────────────────
#   species = "hg38"   project_name = "looplook Analysis"
#   threshold = 1.0    unit_type = "TPM"
#   run_go = TRUE      run_ppi = FALSE     run_motif = FALSE
#   ... (see ?looplook_report for full list)
# ── Reproducibility ────────────────────────────────────────
#   The profiling stage uses R's random number generator for GSEA gene-set
#   down-sampling and motif background sampling. For fully reproducible
#   reports, call set.seed() before looplook_report():
#     set.seed(42)
#     looplook_report(...)

# Minimal: annotation only
looplook_report(
    bedpe_file   = system.file("extdata", "example_loops_1.bedpe", package = "looplook"),
    target_bed   = system.file("extdata", "example_peaks.bed", package = "looplook"),
    project_name = "Quick Annotation"
)

# Full pipeline: annotation + refinement + profiling
looplook_report(
    bedpe_file       = "my_loops.bedpe",
    target_bed       = "my_peaks.bed",
    expr_matrix_file = "my_tpm.txt",
    diff_file        = "my_deg.csv",
    metadata_file    = "my_coldata.txt",
    project_name     = "Integrative HiChIP Analysis",
    run_go           = TRUE
)

# Reuse precomputed results: skip annotation and jump to refinement + profiling.
# precomputed_res accepts a file path (.RData) or an in-memory list object.
# bedpe_file is optional when precomputed_res is set.

# Option A — save and reload from .RData:
res <- annotate_peaks_and_loops(
    bedpe_file = "my_loops.bedpe",
    target_bed = "my_peaks.bed",
    project_name = "MyProject"
)
save(res, file = "annotation_results.RData")

looplook_report(
    precomputed_res  = "annotation_results.RData",
    expr_matrix_file = "my_tpm.txt",
    diff_file        = "my_deg.csv",
    metadata_file    = "my_coldata.txt",
    run_go           = TRUE
)

# Option B — pass the object directly:
looplook_report(
    precomputed_res  = res,
    expr_matrix_file = "my_tpm.txt",
    diff_file        = "my_deg.csv",
    metadata_file    = "my_coldata.txt",
    run_go           = TRUE
)

The template is also accessible from the RStudio menu: File → New File → R Markdown → From Template → looplook Report.


Troubleshooting

Installation

TxDb or OrgDb package not found

Error: TxDb.Hsapiens.UCSC.hg38.knownGene not installed

Cause: The required annotation database package is not installed. These are Bioconductor packages, not CRAN.

Solution:

BiocManager::install("TxDb.Hsapiens.UCSC.hg38.knownGene")
BiocManager::install("org.Hs.eg.db")

For mouse data:

BiocManager::install("TxDb.Mmusculus.UCSC.mm10.knownGene")
BiocManager::install("org.Mm.eg.db")

Using non-human / non-mouse species

looplook supports any species with a Bioconductor TxDb and OrgDb package. Pass them explicitly via the txdb and org_db parameters, and set species to any genome assembly string (used for karyotype ideograms and motif filtering):

# Drosophila melanogaster (dm6)
annotate_peaks_and_loops(
    bedpe_file  = "dm6_loops.bedpe",
    target_bed  = "dm6_peaks.bed",
    species     = "dm6",
    txdb        = TxDb.Dmelanogaster.UCSC.dm6.ensGene,
    org_db      = "org.Dm.eg.db"
)

# Danio rerio (danRer11)
annotate_peaks_and_loops(
    bedpe_file  = "drerio_loops.bedpe",
    species     = "danRer11",
    txdb        = TxDb.Drerio.UCSC.danRer11.refGene,
    org_db      = "org.Dr.eg.db"
)

Refinement and profiling functions consume the annotation_res object produced above, so no species-specific parameters are needed downstream:

refined <- refine_loop_anchors_by_expression(annotation_res = anno, ...)
result <- profile_target_genes(annotation_res = refined, ...)

Limitations for non-built-in species:

Feature Status Workaround
Anchor classification, gene assignment, expression & chromatin refinement, profiling Fully supported —
Blacklist filtering Not built-in Pass your own blacklist BED via region_of_interest with roi_mode = "any" and invert = TRUE (see ?filter_chromatin_loops)
Karyotype ideograms Skipped with message if genome unknown No crash; output slot set to NULL. Install karyoploteR data for your genome, or disable with show_karyo = FALSE
BSgenome (motif analysis) Warning + auto-disabled if unavailable Install the corresponding BSgenome.* package
JASPAR motif species filter Depends on JASPAR Set jaspar_collection manually; JASPAR covers major model organisms

Input Data

BEDPE file must have at least 6 columns

Error: BEDPE file must have at least 6 columns.

Cause: The BEDPE file has fewer than 6 columns. BEDPE format requires: chr1, start1, end1, chr2, start2, end2.

Solution: Check that the file is tab-delimited and contains at least 6 columns. Additional columns (name, score, strand) are optional and retained in the output.

BEDPE file contains rows with start >= end

Error: BEDPE file contains rows with start >= end (zero-width or invalid).

Cause: Some rows have invalid coordinates where the start position is greater than or equal to the end position.

Solution: Filter out invalid rows before importing:

awk '$2 < $3 && $5 < $6' input.bedpe > clean.bedpe

Expression matrix contains non-numeric values

Error: Expression matrix contains non-numeric values in sample columns

Cause: The expression matrix contains text values (e.g., gene names) in sample columns.

Solution: Ensure the expression matrix has gene identifiers in the first column and numeric values (TPM, FPKM, counts) in all other columns.

Gene Name Matching

Only X% of annotation gene symbols match

Warning: Only 12.5% of annotation gene symbols match the expression matrix row names.

Cause: Gene identifiers in the expression matrix do not match the OrgDb SYMBOL convention. This commonly occurs when: - Expression matrix uses Ensembl IDs (ENSG00000141510) but OrgDb returns gene symbols (TP53) - Case mismatch: expression matrix has “tp53” but OrgDb returns “TP53”

Solution:

# Check current gene names
head(rownames(expr_matrix))

# Convert to uppercase if needed
rownames(expr_matrix) <- toupper(rownames(expr_matrix))

# Or map Ensembl IDs to symbols
library(org.Hs.eg.db)
symbols <- mapIds(org.Hs.eg.db,
    keys = rownames(expr_matrix),
    column = "SYMBOL", keytype = "ENSEMBL"
)
rownames(expr_matrix) <- symbols

Note: looplook performs case-insensitive matching internally (using toupper() on both sides), but it is best practice to use consistent naming.

Memory and Performance

Clustering large datasets

Warning: Clustering 50000 loops with gap = 1000 bp. Large datasets may require significant memory.

Cause: The connected-component clustering algorithm has O(N²) worst-case complexity per chromosome pair.

Solution:

# Pre-filter low-confidence loops
consolidate_chromatin_loops(
    files = c("rep1.bedpe", "rep2.bedpe"),
    mode = "consensus",
    min_raw_score = 2, # Remove singleton noise
    gap = 500, # Reduce gap for faster clustering
    chaining_policy = "drop" # Remove chained clusters
)

Chaining warning

Warning: 5 cluster(s) have max_span > chaining threshold (5000 bp).

Cause: Connected-component clustering may transitively merge distant loops through intermediate anchors (A-B + B-C merges A and C).

Solution:

# Option 1: Drop chained clusters
consolidate_chromatin_loops(..., chaining_policy = "drop")

# Option 2: Reduce gap to prevent chaining
consolidate_chromatin_loops(..., gap = 500)

# Option 3: Inspect and manually filter
result <- consolidate_chromatin_loops(..., chaining_policy = "none")
# Filter by span
anchors <- anchors(result)
span <- end(anchors$first) - start(anchors$first) + 1
result <- result[span < 5000]

Empty Results

All loops filtered by min_raw_score

Message: All loops filtered out by min_raw_score = 10. Returning empty result.

Cause: The pre-filtering threshold is too high for the data.

Solution: Lower the threshold or disable pre-filtering:

# Check score distribution first
gi <- bedpe_to_gi("my_loops.bedpe")
summary(mcols(gi)$score)

# Use appropriate threshold
consolidate_chromatin_loops(..., min_raw_score = 2)

No peaks overlapped loop anchors

Message: No peaks overlapped loop anchors. Check that target BED and loop BEDPE use the same genome build.

Cause: The target BED file and loop BEDPE file use different genome builds (e.g., hg38 vs hg19) or different chromosome naming conventions (chr1 vs 1).

Solution:

# Check chromosome names
seqlevelsStyle(gr_peaks) # Should match
seqlevelsStyle(gr_anchors) # Should match

# Harmonize if needed
seqlevelsStyle(gr_peaks) <- "UCSC" # Convert to chr1 format

Chromatin Refinement

eP/eG labels dominate the results

Warning: 75% of P/G anchors were reclassified to eP/eG.

Cause: The expression threshold is too high, or the expression matrix does not match the gene annotation.

Solution:

# Check expression distribution
hist(log2(vals + 1), main = "Expression Distribution")

# Lower threshold
refine_loop_anchors_by_expression(..., threshold = 0.5)

# Or use quantile mode
refine_loop_anchors_by_expression(...,
    threshold = 0.25,
    threshold_mode = "quantile"
)

Important: eP/eG labels indicate transcriptional silence, not functional enhancer activity. Validate with orthogonal chromatin data (ATAC-seq, H3K27ac) before biological interpretation.

Chromatin_UpSet / patchwork print error

Error in UseMethod("ggplot_build") : no applicable method for 'ggplot_build'
applied to an object of class "c('gg', 'ggplot')"

Cause: S3 method dispatch failure. The plot_filler class inserted by patchwork v1.3.x layout assembly is not a valid ggplot subclass, so ggplot_build() cannot resolve a method for it. This manifests in interactive printing, ggsave, and knitr rendering contexts.

Solution: Either render via ggsave() which bypasses the issue, or upgrade to patchwork ≥ 1.4.0:

ggsave("upset.pdf", cr$plots$Chromatin_UpSet, width = 10, height = 6)

# or upgrade patchwork
remotes::install_github("thomasp85/patchwork")

Session Info

sessionInfo()
#> R version 4.6.1 (2026-06-24)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 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.26.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8       
#>  [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8   
#>  [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C          
#> [10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C   
#> 
#> time zone: UTC
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] org.Hs.eg.db_3.23.1  AnnotationDbi_1.74.0 IRanges_2.46.0      
#>  [4] S4Vectors_0.50.2     Biobase_2.72.0       BiocGenerics_0.58.1 
#>  [7] generics_0.1.4       looplook_0.99.19     dplyr_1.2.1         
#> [10] BiocStyle_2.40.0    
#> 
#> loaded via a namespace (and not attached):
#>   [1] fs_2.1.0                                
#>   [2] ProtGenerics_1.44.0                     
#>   [3] matrixStats_1.5.0                       
#>   [4] bitops_1.1-0                            
#>   [5] enrichplot_1.32.0                       
#>   [6] httr_1.4.9                              
#>   [7] RColorBrewer_1.1-3                      
#>   [8] InteractionSet_1.40.0                   
#>   [9] tools_4.6.1                             
#>  [10] backports_1.5.1                         
#>  [11] R6_2.6.1                                
#>  [12] lazyeval_0.2.3                          
#>  [13] ggdist_3.3.3                            
#>  [14] withr_3.0.3                             
#>  [15] gridExtra_2.3.1                         
#>  [16] cli_3.6.6                               
#>  [17] textshaping_1.0.5                       
#>  [18] scatterpie_0.2.6                        
#>  [19] labeling_0.4.3                          
#>  [20] sass_0.4.10                             
#>  [21] S7_0.2.2                                
#>  [22] pkgdown_2.2.1                           
#>  [23] Rsamtools_2.28.0                        
#>  [24] systemfonts_1.3.2                       
#>  [25] yulab.utils_0.2.5                       
#>  [26] gson_0.2.1                              
#>  [27] foreign_0.8-91                          
#>  [28] DOSE_4.6.0                              
#>  [29] dichromat_2.0-1                         
#>  [30] plotrix_3.8-14                          
#>  [31] BSgenome_1.80.0                         
#>  [32] maps_3.4.3                              
#>  [33] rstudioapi_0.19.0                       
#>  [34] RSQLite_3.53.3                          
#>  [35] gridGraphics_0.5-1                      
#>  [36] TxDb.Hsapiens.UCSC.hg19.knownGene_3.22.1
#>  [37] BiocIO_1.22.0                           
#>  [38] gtools_3.9.5                            
#>  [39] car_3.1-5                               
#>  [40] distributional_0.9.0                    
#>  [41] zip_3.0.2                               
#>  [42] GO.db_3.23.1                            
#>  [43] Matrix_1.7-5                            
#>  [44] abind_1.4-8                             
#>  [45] lifecycle_1.0.5                         
#>  [46] yaml_2.3.12                             
#>  [47] carData_3.0-6                           
#>  [48] SummarizedExperiment_1.42.0             
#>  [49] qvalue_2.44.0                           
#>  [50] gplots_3.3.0                            
#>  [51] SparseArray_1.12.2                      
#>  [52] grid_4.6.1                              
#>  [53] blob_1.3.0                              
#>  [54] crayon_1.5.3                            
#>  [55] ggtangle_0.1.2                          
#>  [56] lattice_0.22-9                          
#>  [57] GenomicFeatures_1.64.0                  
#>  [58] cigarillo_1.2.1                         
#>  [59] KEGGREST_1.52.2                         
#>  [60] pillar_1.11.1                           
#>  [61] knitr_1.52                              
#>  [62] GenomicRanges_1.64.0                    
#>  [63] rjson_0.2.23                            
#>  [64] boot_1.3-32                             
#>  [65] codetools_0.2-20                        
#>  [66] glue_1.8.1                              
#>  [67] ggiraph_0.9.6                           
#>  [68] ggfun_0.2.1                             
#>  [69] fontLiberation_0.1.0                    
#>  [70] data.table_1.18.6.1                     
#>  [71] vctrs_0.7.3                             
#>  [72] png_0.1-9                               
#>  [73] treeio_1.36.1                           
#>  [74] spam_2.11-4                             
#>  [75] gtable_0.3.6                            
#>  [76] cachem_1.1.0                            
#>  [77] xfun_0.60                               
#>  [78] openxlsx_4.2.9                          
#>  [79] S4Arrays_1.12.0                         
#>  [80] Seqinfo_1.2.0                           
#>  [81] aisdk_1.4.12                            
#>  [82] fields_17.3                             
#>  [83] nlme_3.1-169                            
#>  [84] ggtree_4.2.0                            
#>  [85] bit64_4.8.6                             
#>  [86] fontquiver_0.2.1                        
#>  [87] GenomeInfoDb_1.48.0                     
#>  [88] bslib_0.12.0                            
#>  [89] KernSmooth_2.23-26                      
#>  [90] otel_0.2.0                              
#>  [91] rpart_4.1.27                            
#>  [92] colorspace_2.1-3                        
#>  [93] DBI_1.3.0                               
#>  [94] Hmisc_5.3-0                             
#>  [95] nnet_7.3-20                             
#>  [96] tidyselect_1.2.1                        
#>  [97] processx_3.9.0                          
#>  [98] bit_4.6.0                               
#>  [99] compiler_4.6.1                          
#> [100] curl_8.0.0                              
#> [101] httr2_1.3.0                             
#> [102] htmlTable_2.5.0                         
#> [103] bezier_1.1.2                            
#> [104] desc_1.4.3                              
#> [105] fontBitstreamVera_0.1.1                 
#> [106] DelayedArray_0.38.2                     
#> [107] bookdown_0.48                           
#> [108] rtracklayer_1.72.0                      
#> [109] checkmate_2.3.4                         
#> [110] scales_1.4.0                            
#> [111] caTools_1.18.4                          
#> [112] ChIPseeker_1.48.0                       
#> [113] callr_3.8.0                             
#> [114] rappdirs_0.3.4                          
#> [115] stringr_1.6.0                           
#> [116] digest_0.6.39                           
#> [117] rmarkdown_2.32                          
#> [118] XVector_0.52.0                          
#> [119] htmltools_0.5.9                         
#> [120] pkgconfig_2.0.3                         
#> [121] base64enc_0.1-6                         
#> [122] MatrixGenerics_1.24.0                   
#> [123] regioneR_1.44.0                         
#> [124] fastmap_1.2.0                           
#> [125] ensembldb_2.36.1                        
#> [126] rlang_1.3.0                             
#> [127] htmlwidgets_1.6.4                       
#> [128] UCSC.utils_1.8.0                        
#> [129] farver_2.1.2                            
#> [130] jquerylib_0.1.4                         
#> [131] karyoploteR_1.38.0                      
#> [132] jsonlite_2.0.0                          
#> [133] BiocParallel_1.46.0                     
#> [134] GOSemSim_2.38.3                         
#> [135] VariantAnnotation_1.58.0                
#> [136] RCurl_1.98-1.20                         
#> [137] magrittr_2.0.5                          
#> [138] Formula_1.2-6                           
#> [139] ggplotify_0.1.3                         
#> [140] dotCall64_1.2                           
#> [141] patchwork_1.3.2                         
#> [142] Rcpp_1.1.2                              
#> [143] ape_5.8-1                               
#> [144] ggnewscale_0.5.2                        
#> [145] bamsignals_1.44.1                       
#> [146] viridis_0.6.5                           
#> [147] gdtools_0.5.1                           
#> [148] stringi_1.8.9                           
#> [149] MASS_7.3-65                             
#> [150] plyr_1.8.9                              
#> [151] parallel_4.6.1                          
#> [152] ggrepel_0.9.8                           
#> [153] splines_4.6.1                           
#> [154] Biostrings_2.80.2                       
#> [155] ps_1.9.3                                
#> [156] igraph_2.3.3                            
#> [157] ggpubr_1.0.0                            
#> [158] ggsignif_0.6.4                          
#> [159] enrichit_0.2.1                          
#> [160] reshape2_1.4.5                          
#> [161] XML_3.99-0.24                           
#> [162] evaluate_1.0.5                          
#> [163] biovizBase_1.60.0                       
#> [164] BiocManager_1.30.27                     
#> [165] tweenr_2.0.3                            
#> [166] tidyr_1.3.2                             
#> [167] purrr_1.2.2                             
#> [168] polyclip_1.10-7                         
#> [169] ggplot2_4.0.3                           
#> [170] ggforce_0.5.0                           
#> [171] broom_1.0.13                            
#> [172] restfulr_0.0.17                         
#> [173] AnnotationFilter_1.36.0                 
#> [174] tidytree_0.4.8                          
#> [175] tidydr_0.0.6                            
#> [176] rstatix_1.1.0                           
#> [177] viridisLite_0.4.3                       
#> [178] ggpointdensity_0.2.1                    
#> [179] ragg_1.5.2                              
#> [180] TxDb.Hsapiens.UCSC.hg38.knownGene_3.22.0
#> [181] tibble_3.3.1                            
#> [182] clusterProfiler_4.20.0                  
#> [183] aplot_0.3.1                             
#> [184] memoise_2.0.1                           
#> [185] GenomicAlignments_1.48.0                
#> [186] cluster_2.1.8.2