---
title: "DEBrowser: Interactive Differential Expression Analysis"
author:
  - "Alper Kucukural"
  - "Onur Yukselen"
  - "Manuel Garber"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_document:
    toc: true
    toc_float: true
    toc_depth: 3
    number_sections: true
    highlight: pygments
vignette: >
  %\VignetteIndexEntry{DEBrowser Vignette}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```

> **📖 Full illustrated user guide.** This vignette is a concise reference. The
> complete, screenshot-by-screenshot walkthrough — the Data Prep wizard, every
> QC plot, enrichment, and the worked examples — lives at
> **<https://debrowser.readthedocs.io>**. It is kept outside the package so the
> package itself stays small.

# Introduction

Differential expression (DE) analysis is a core step in RNA-Seq and other
high-throughput studies: given counts for two or more groups of samples, which
genes or regions change more than expected by chance? **DEBrowser** turns that
analysis into an interactive, point-and-click experience. It wraps three
established Bioconductor engines —
[DESeq2](https://bioconductor.org/packages/DESeq2) (Love et al., 2014),
[edgeR](https://bioconductor.org/packages/edgeR) (Robinson et al., 2010), and
[limma](https://bioconductor.org/packages/limma) (Ritchie et al., 2015) — in a
[Shiny](https://shiny.posit.co) application so that changing a cutoff, a
normalization method, or a comparison re-draws every plot and table in real
time.

Beyond the DE test itself, DEBrowser bundles quality-control views (PCA,
sample-to-sample correlation, IQR, density), batch-effect correction,
interactive scatter/volcano/MA plots with linked heatmaps, GO/KEGG and GSEA
enrichment, cross-contrast concordance, exportable result tables, and an
optional AI interpretation assistant — all without writing code.

The interface is organized as a **six-step Data Prep wizard** (Quick start →
Upload → Filter & normalize → Batch effect → Comparison → DE analysis) followed
by five result tabs — **Main Plots**, **QC Plots**, **Concordance**,
**Enrichment**, and **Tables** — reachable with the number keys `1`–`6`. A
light/dark theme toggle (the moon/sun button, or the `T` key) rounds out the
chrome.

# Quick start

Install DEBrowser from Bioconductor and launch it:

```r
# 1. Install DEBrowser and its dependencies
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("debrowser")

# 2. Load the library
library(debrowser)

# 3. Start DEBrowser
startDEBrowser()
```

`startDEBrowser()` opens the app in your browser on a fixed port (`3838` by
default, so bookmark URLs stay stable across restarts). If your operating system
is missing system libraries, see *Operating System Dependencies* below.

The fastest way to see DEBrowser in action is the **Quick Start** step: it
explains what each stage does and lets you load a bundled demo (Vernia et al.,
2014) with one click, so you can walk the whole pipeline before bringing your
own data.

# Scriptable analytic core

DEBrowser's normalization, filtering, and DE steps are also available as pure
functions you can call directly — handy for scripting or reproducing an
interactive analysis. For example, median-ratio-normalize the bundled demo
counts:

```{r demo, message=FALSE, warning=FALSE}
library(debrowser)
load(system.file("extdata", "demo", "demodata.Rda", package = "debrowser"))

norm <- getNormalizedMatrix(demodata, method = "MRN")
round(head(norm[, seq_len(4)]), 1)
```

The same building blocks (`filter_low_counts()`, `run_deseq2()`, `run_edger()`,
`run_limma()`, `run_de()`) power the interactive app and can be composed in a
script.

# The Data Prep pipeline

All data loading and preparation happens on the **Data Prep** tab, organized as
a wizard down the left rail. Steps light up as their prerequisites are met.

## Uploading counts and metadata

On the **Upload data** step, drop in a *count matrix* and, optionally, a
*metadata* table. Both accept comma-, semicolon-, or tab-separated files
(`.csv`, `.tsv`, `.txt`, or gzip-compressed `.csv.gz`). To try DEBrowser without
your own data, click **Vernia et al.** or **Donnard et al.** under *Demos*, then
**Upload**.

The count matrix has genes/regions in the first column and one raw-count column
per sample. DEBrowser reads gene names from the first column, skips other
non-numeric columns, and reads counts from the numeric columns:

| gene     | transcript | exper_rep1 | exper_rep2 | control_rep1 | control_rep2 |
|----------|------------|------------|------------|--------------|--------------|
| DQ714826 | uc007tfl.1 | 0.00       | 0.00       | 0.00         | 0.00         |
| AK028549 | uc011wpi.1 | 2.00       | 1.29       | 0.00         | 0.00         |

> DESeq2 requires **un-normalized** counts (it models library size internally).
> Only use pre-normalized values with edgeR or limma.

The optional metadata table maps each sample to a condition and, if relevant, a
batch — this is what powers batch correction and grouped comparisons:

| sample       | batch | condition |
|--------------|-------|-----------|
| exper_rep1   | 1     | A         |
| control_rep1 | 2     | B         |

Once loaded, DEBrowser shows an **upload summary** — sample count, gene count,
number of conditions, a preview of the count matrix, and the sample-design
table — so you can confirm the data was parsed as expected.

## Low-count filtering & normalization

The **Filter & normalize** step trims features with little or no signal. Pick a
filtering method — **Max**, **Mean**, or **CPM** — and a cutoff; DEBrowser shows
the row count *before* and *after* filtering side by side, plus per-sample count
histograms.

## Batch-effect correction

The **Batch effect** step (optional) corrects technical confounders. Choose a
**normalization method** (MRN, TMM, RLE, upperquartile, or none) and a
**correction method** (ComBat, ComBat-Seq, or Harman), then **Submit**. Inline
QC plots — **PCA**, **IQR**, and **Density**, each with a *Before* / *After*
view — let you confirm that samples cluster by biology rather than by batch.

## Choosing comparisons and running DE

The **Comparison** step is where you define which groups to test. DEBrowser
auto-populates a first comparison from your conditions; use **Add comparison** to
set up several contrasts at once (each becomes its own DE result set you can
switch between later). Assign samples to the *Treatment* and *Control* side, pick
the DE engine and its parameters, then click **Start DE**. DEBrowser reports
progress in stages (Normalizing → Fitting → Contrasts) and, when finished,
unlocks the result tabs and jumps to **Main Plots**.

# Differential expression engines

DEBrowser exposes the parameters that matter for each engine on the Comparison
step, under **Advanced model settings**.

## DESeq2

DESeq2 groups samples into conditions and computes, for every gene, the
probability of differential expression using a negative binomial model,
reporting both nominal and multiple-testing-corrected (`padj`) p-values.

- **fitType** — `parametric`, `local`, or `mean`: how dispersions are fit to the
  mean intensity.
- **betaPrior** — whether to place a zero-mean normal prior on the non-intercept
  coefficients.
- **testType** — `Wald` (nbinomWaldTest) or `LRT` (likelihood-ratio test).
- **rowsum.filter** — features with total count below this value are filtered
  out.

DESeq2 needs raw, un-normalized integer counts.

## edgeR

- **Normalization** — `TMM`, `RLE`, `upperquartile`, or `none`.
- **Dispersion** — a numeric dispersion or a string telling edgeR to estimate it
  from the data.
- **testType** — `exactTest` or `glmLRT`.
- **rowsum.filter** — low-total-count features are removed.

## limma

limma is ideal when data are already normalized (e.g. spike-in or another
scaling), in which case prefer it over DESeq2 or edgeR.

- **Normalization** — `TMM`, `RLE`, `upperquartile`, or `none`.
- **Fit Type** — `ls` (least squares) or `robust` (robust regression).
- **Norm. Bet. Arrays** — normalize between arrays so intensities/log-ratios
  share similar distributions across samples.
- **rowsum.filter** — low-total-count features are removed.

# Exploring results

**Main Plots** is DEBrowser's interactive heart: choose **Scatter**, **Volcano
Plot**, or **MA Plot**; genes are colored **Up** (red), **Down** (blue), or
**NS** (grey) by your `padj` and log2-fold-change cutoffs, and every change is
instant. Hover a point for its identity and per-sample bar graphs, and lasso- or
box-select a region to spawn a linked heatmap of just those genes.

The other result tabs:

- **QC Plots** — all-to-all correlation, PCA, IQR, density, and several
  sample-level QC views, independent of any single comparison.
- **Concordance** — where two or more comparisons agree and disagree.
- **Enrichment** — GO/KEGG over-representation (clusterProfiler) and GSEA
  (fgsea) with a leading-edge and NES-heatmap view.
- **Tables** — searchable, sortable result tables (All Detected, Up/Down, Most
  varied, Comparison differences) with regex search that applies everywhere.

## Heatmap clustering & scale

Heatmaps (on the QC tab and next to a Main-Plot selection) support several
linkage methods (complete, ward.D2, single, average, mcquitty, median, centroid)
and distance methods (cor, euclidean, maximum, manhattan, canberra, minkowski).
The **Scale Option** panel controls centering, scaling, `log2`, and a
pseudo-count. See the [online guide](https://debrowser.readthedocs.io) for
details.

# Bookmarking, export & reproducibility

The **Bookmark** button captures the *entire* analysis state behind a stable URL
you can revisit or share. The **Export** menu turns your interactive session into
reusable artifacts: an **R script**, **R Markdown / HTML**, a **Jupyter
notebook**, or a copy-ready **methods paragraph** for a manuscript.

# AI interpretation (optional)

DEBrowser includes an optional AI assistant that summarizes the biology of a
gene set alongside a selected GSEA pathway on the Enrichment tab. It is **off by
default** — no network calls happen until you enable it and configure a provider
(**Anthropic**, **OpenAI**, or local **Ollama**). Per-call privacy modes control
what leaves your machine; API keys are stored encrypted in your OS keychain via
`keyring`, never in plaintext. Install the extras once:

```r
install.packages(c("ellmer", "whisker", "keyring"))
```

If any are missing, AI stays unavailable and the rest of the app is unaffected.
`R CMD check` and `BiocCheck` both pass without any AI package installed. For
provider setup (including a local, privacy-preserving Ollama install), see the
[online guide](https://debrowser.readthedocs.io).

# Operating system dependencies

On Fedora / Red Hat / CentOS:

```sh
openssl-devel libxml2-devel libcurl-devel libpng-devel
```

On Ubuntu / Debian:

```sh
sudo apt-get install libcurl4-openssl-dev libssl-dev \
  libxml2-dev libudunits2-dev
```

# Session information

```{r session, echo=FALSE, eval=TRUE}
sessionInfo()
```

# References

1. Love M.I. et al. (2014) Moderated estimation of fold change and dispersion
   for RNA-seq data with DESeq2. *Genome Biol.* 15, 550.
2. Robinson M.D. et al. (2010) edgeR: a Bioconductor package for differential
   expression analysis of digital gene expression data. *Bioinformatics* 26,
   139–140.
3. Ritchie M.E. et al. (2015) limma powers differential expression analyses for
   RNA-sequencing and microarray studies. *Nucleic Acids Res.* 43, e47.
4. Vernia S. et al. (2014) The PPARα-FGF21 hormone axis contributes to metabolic
   regulation by the hepatic JNK signaling pathway. *Cell Metab.* 20, 512–525.
