---
title: "Differential analysis of Hi-C data with treediff"
output:
  rmarkdown::html_vignette:
    toc: true
vignette: >
  %\VignetteIndexEntry{Differential analysis of Hi-C data with treediff}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
hicream_available <- requireNamespace("hicream", quietly = TRUE)
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE,
                      warning = FALSE, eval = hicream_available)
```

```{r nodata, echo = FALSE, eval = !hicream_available, results = "asis"}
cat("**The package `hicream` is not available on this machine: the code of",
    "this vignette is displayed but has not been evaluated.** `hicream`",
    "provides the Hi-C example files used below.")
```

## Introduction

`treediff` tests whether two families of trees (hierarchical clusterings) have
the same structure. The test is based on the cophenetic distances of the trees
and on aggregated Student's tests, with moderated variances
(Neuvial *et al.*, 2024). 

`treediff` is a general purpose test for trees but has been initially designed
to compare 3D genomic structure based on Hi-C data. In this context, trees are
obtained using adjacency-constrained clustering of Hi-C contact maps along the 
genome (as implemented in Ambroise *et al.*, 2019), where several maps from two 
conditions are available.

This vignette illustrates the main features of the package on a small Hi-C
data set, stored in the `extdata` directory of the `hicream` package:

* the wrapper `HiC2Tree()`, which goes from Hi-C files to test results in a
  single call;
* the step by step pipeline (`HiCDataSet()`, `normalizeCount()`, 
  `clusterTree()`, and `treediff()`);
* the exploration of the results (`print()` and `summary()` methods and link 
  with genomic coordinates).

```{r library}
library("treediff")
```

## The `pighic` dataset

The `pighic` dataset is an extract of the dataset published in (Marti-Marimon 
*et al.*, 2021). It contains 6 Hi-C matrices (3 in each condition) obtained from
two different developmental stages of pig embryos (90 and 110 days of gestation)
for two chromosomes (1 and 2). Hi-C contact maps are provided in HiC-Pro format
and an additional file (the *index*) gives the genomic coordinates of the bins.

```{r files}
replicates <- 1:3
conditions <- c("90", "110")
chromosomes <- 1:2

all_begins <- as.character(interaction(expand.grid(replicates, conditions),
                                       sep = "-"))
allMat <- lapply(chromosomes, function(chr) {
  paste0("Rep", all_begins, "-chr", chr, "_200000.bed")
})

files <- system.file("extdata", unlist(allMat), package = "hicream")
index <- system.file("extdata", "index.200000.longest18chr.abs.bed",
                     package = "hicream")
format <- rep("HiC-Pro", length(files))
binsize <- 200000
nb_replicates <- c(3, 3)
basename(files)
```

Files must be ordered by chromosome, then by condition, then by replicate. The
vector `nb_replicates` gives the number of replicates in each condition (here,
3 in the first condition, `90`, and 3 in the second one, `110`).

## All-in-one analysis with `HiC2Tree()`

`HiC2Tree()` reads the files, normalizes the contact counts, builds one tree
per matrix and runs the `treediff` test:

```{r hic2tree}
res <- HiC2Tree(files, format, binsize, index, chromosomes, nb_replicates)
names(res)
```

The output is a list with four entries:

* `trees`: the list of all trees (one for each matrix);
* `metadata`: a description of each tree (matrix, chromosome and cluster);
* `index`: the genomic coordinates of the bins;
* `testRes`: the results of the `treediff` test.

```{r metadata}
res$metadata
```

Each chromosome is split into clusters of bins (here, one cluster per 
chromosome), and one tree is built for each cluster and each replicate. One 
test is performed for each cluster.

```{r testres}
res$testRes
```

The returned object has class `treeTest`. Its `summary()` method gives more
details on the distribution of the $p$-values and of the individual statistics:

```{r summary}
summary(res$testRes)
```

The test finds no difference between the two conditions for the first
chromosome (cluster 1) but a very significant one for the second chromosome
(cluster 2).

## Step by step analysis

`HiC2Tree()` is a wrapper that successively calls the functions described in
this section. They can be used separately, for instance to provide a different
normalization or to inspect intermediate results.

### Import the data

`HiCDataSet()` parses the files (with the `HiCParser` package) and returns
the contact matrices together with the bin coordinates:

```{r hicdataset}
data <- HiCDataSet(files, format, binsize, chromosomes, index)
names(data)
length(data$HiCDataSet)
head(data$indexData)
data$index_mat_chr
```

### Normalize the counts

`normalizeCount()` normalizes the contact counts of all matrices of a same
chromosome together (cyclic loess normalization) and returns one data frame
per chromosome, with one column per matrix:

```{r normalize}
norm_counts <- normalizeCount(data$HiCDataSet)
length(norm_counts)
head(norm_counts[[1]])
```

### Build the trees

`clusterTree()` clusters the bins of each chromosome with a constrained
hierarchical clustering (only adjacent bins can be merged,
`adjclust::adjClust()`), cuts the chromosome into clusters using the
broken-stick rule and builds one tree for each cluster and each matrix.

```{r clustertree}
clust <- clusterTree(norm_counts)
names(clust)
class(clust$trees[[1]])
clust$metadata
```

### Run the test

`treediff()` takes two lists of trees. Within each list, trees are ordered by
cluster and then by replicate. The number of replicates in each condition is
given by `replicates`, and one $p$-value is obtained for each cluster.

Here, we first select the trees of each condition (the first 3 trees of each
cluster belong to the first condition and the last 3 to the second one) and
run the test on all clusters:

```{r treediff}
nb_clusters <- nrow(unique(clust$metadata[, c("chromosome", "cluster")]))
in_cond1 <- rep(rep(c(TRUE, FALSE), nb_replicates), nb_clusters)
trees1 <- clust$trees[in_cond1]
trees2 <- clust$trees[!in_cond1]

test <- treediff(trees1, trees2, replicates = nb_replicates)
test$p.value
```

These are the same $p$-values as the ones obtained with `HiC2Tree()`:

```{r identical}
all.equal(test$p.value, res$testRes$p.value)
```

The trees of the second condition may have a different number of replicates
than the trees of the first one: It is enough to give the right values in
`replicates`. Two options of `treediff()` are also useful in practice:

* `scale = TRUE` rescales all trees so that their heights range between 0 and
  1, which removes global differences in height between the trees. In practice,
  we do not recommend using this option unless you know what you are doing;
* `order_labels = TRUE` aligns the order of the leaves between all trees,
  which is required when the trees have not been built with the same leaf 
  ordering.

```{r scale}
treediff(trees1, trees2, replicates = nb_replicates, scale = TRUE)$p.value
```

## Exploring the results

The `p.value.indiv` and `statistic` entries of the output contain the Student's 
test of each pair of leaves of the trees (for all clusters). Their distribution 
can be used to check how the signal is distributed:

```{r hist, fig.width = 6, fig.height = 4}
hist(test$p.value.indiv, breaks = 50, main = "Individual p-values",
     xlab = "p-value")
```

The cluster-level $p$-values are linked to genomic regions through the 
`metadata` and `index` entries of the `HiC2Tree()` output. For instance, the
genomic span of the bins of each chromosome is:

```{r coords}
aggregate(cbind(start, end) ~ seqnames, data = res$index,
          FUN = function(x) c(min = min(x), max = max(x)))
```

## References

Ambroise C., Dehman A., Neuvial P., Rigaill G. and Vialaneix N. (2019)
Adjacency-constrained hierarchical clustering of a band similarity matrix with
application to genomics. *Algorithms for Molecular Biology*, **14**(22),
363-389.

Marti-Marimon, M., Vialaneix, N., Lahbib-Mansais, Y., Zytnicki, M., Camut, S., 
Robelin, D., Yerle-Bouissou, M., & Foissac, S. (2021). Major reorganization of 
chromosome conformation during muscle development in pig. *Frontiers in 
Genetics*, 12, 748239.

Neuvial P., Randriamihamison N., Chavent M., Foissac S. and Vialaneix N.
(2024) A two-sample tree-based test for hierarchically organized genomic
signals. *Journal of the Royal Statistical Society, Series C*, Forthcoming.

## Session information

```{r sessionInfo}
sessionInfo()

```
