# Purpose of the analysis

This notebook illustrates one way that you can use harmonized RNA-seq data from refine.bio in downstream analyses, specifically in plotting clustered heatmaps.

⬇️ [**Jump to the analysis code**](#analysis) ⬇️

# How to run this example

For general information about our tutorials and the basic software packages you will need, please see our ['Getting Started' section](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#how-this-tutorial-is-structured).
We recommend taking a look at our [Resources for Learning R](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#resources-for-learning-r) if you have not written code in R before. 

## Obtain the `.Rmd` file

To run this example yourself, [download the `.Rmd` for this analysis by clicking this link](https://alexslemonade.github.io/refinebio-examples/03-rnaseq/clustering_rnaseq_01_heatmap.Rmd). 

Clicking this link will most likely send this to your downloads folder on your computer. 
Move this `.Rmd` file to where you would like this example and its files to be stored.

You can open this `.Rmd` file in RStudio and follow the rest of these steps from there. (See our [section about getting started with R notebooks](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#how-to-get-and-use-rmds) if you are unfamiliar with `.Rmd` files.)

## Set up your analysis folders 

Good file organization is helpful for keeping your data analysis project on track!
We have set up some code that will automatically set up a folder structure for you. 
Run this next chunk to set up your folders! 

If you have trouble running this chunk, see our [introduction to using `.Rmd`s](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#how-to-get-and-use-rmds) for more resources and explanations. 

```{r}
# Create the data folder if it doesn't exist
if (!dir.exists("data")) {
  dir.create("data")
}

# Define the file path to the plots directory
plots_dir <- "plots"

# Create the plots folder if it doesn't exist
if (!dir.exists(plots_dir)) {
  dir.create(plots_dir)
}

# Define the file path to the results directory
results_dir <- "results"

# Create the results folder if it doesn't exist
if (!dir.exists(results_dir)) {
  dir.create(results_dir)
}
```

In the same place you put this `.Rmd` file, you should now have three new empty folders called `data`, `plots`, and `results`!

## Obtain the dataset from refine.bio

For general information about downloading data for these examples, see our ['Getting Started' section](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#how-to-get-the-data). 

Go to this [dataset's page on refine.bio](https://www.refine.bio/experiments/SRP070849).

Click the "Download Now" button on the right side of this screen.  

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/download-now.png" width=200>  

Fill out the pop up window with your email and our Terms and Conditions:  

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/download-email.png" width=500>  

We are going to use non-quantile normalized data for this analysis.
To get this data, you will need to check the box that says "Skip quantile normalization for RNA-seq samples".
Note that this option will only be available for RNA-seq datasets.

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/skip-quantile-normalization.png" width=500>

It may take a few minutes for the dataset to process.
You will get an email when it is ready. 

## About the dataset we are using for this example

For this example analysis, we will use this [acute myeloid leukemia sample dataset](https://www.refine.bio/experiments/SRP070849).

The data that we downloaded from refine.bio for this analysis has 19 samples (obtained from 19 mice with acute myeloid leukemia (AML)), containing RNA-sequencing results for types of AML under controlled treatment conditions.

## Place the dataset in your new `data/` folder

refine.bio will send you a download button in the email when it is ready. 
Follow the prompt to download a zip file that has a name with a series of letters and numbers and ends in `.zip`. 
Double clicking should unzip this for you and create a folder of the same name.  

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/download-folder-structure.png" width=400> 

For more details on the contents of this folder see [these docs on refine.bio](http://docs.refine.bio/en/latest/main_text.html#rna-seq-sample-compendium-download-folder).

The `<experiment_accession_id>` folder has the data and metadata TSV files you will need for this example analysis.
Experiment accession ids usually look something like `GSE1235` or `SRP12345`.

Copy and paste the `SRP070849` folder into your newly created `data/` folder.

## Check out our file structure!

Your new analysis folder should contain: 

- The example analysis `.Rmd` you downloaded  
- A folder called "data" which contains:
  - The `SRP070849` folder which contains:
    - The gene expression  
    - The metadata TSV  
- A folder for `plots` (currently empty)
- A folder for `results` (currently empty)

Your example analysis folder should now look something like this (except with respective experiment accession ID and analysis notebook name you are using): 

<img src="https://github.com/AlexsLemonade/refinebio-examples/raw/40e47f4d3f39283effbd9843a457168061be9680/template/screenshots/analysis-folder-structure.png" width=400>

In order for our example here to run without a hitch, we need these files to be in these locations so we've constructed a test to check before we get started with the analysis. 
These chunks will declare your file paths and double check that your files are in the right place. 

First we will declare our file paths to our data and metadata files, which should be in our data directory.
This is handy to do because if we want to switch the dataset (see next section for more on this) we are using for this analysis, we will only have to change the file path here to get started. 

```{r}
# Define the file path to the data directory
# Replace with the path of the folder the files will be in
data_dir <- file.path("data", "SRP070849")

# Declare the file path to the gene expression matrix file
# inside directory saved as `data_dir`
# Replace with the path to your dataset file
data_file <- file.path(data_dir, "SRP070849.tsv")

# Declare the file path to the metadata file
# inside the directory saved as `data_dir`
# Replace with the path to your metadata file
metadata_file <- file.path(data_dir, "metadata_SRP070849.tsv")
```

Now that our file paths are declared, we can use the `file.exists()` function to check that the files are where we specified above. 

```{r}
# Check if the gene expression matrix file is at the path stored in `data_file`
file.exists(data_file)

# Check if the metadata file is at the file path stored in `metadata_file`
file.exists(metadata_file)
```

If the chunk above printed out `FALSE` to either of those tests, you won't be able to run this analysis _as is_ until those files are in the appropriate place.

If the concept of a "file path" is unfamiliar to you; we recommend taking a look at our [section about file paths](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#an-important-note-about-file-paths-and-Rmds). 

# Using a different refine.bio dataset with this analysis?

If you'd like to adapt an example analysis to use a different dataset from [refine.bio](https://www.refine.bio/), we recommend placing the files in the `data/` directory you created and changing the filenames and paths in the notebook to match these files (we've put comments to signify where you would need to change the code).
We suggest saving plots and results to `plots/` and `results/` directories, respectively, as these are automatically created by the notebook.
From here you can customize this analysis example to fit your own scientific questions and preferences.

***

<!-- Do not delete this line --> <a name="analysis" style="padding-top:56px;margin-top:-56px;">&nbsp;</a>


# Clustering Heatmap - RNA-seq

## Install libraries

See our Getting Started page with [instructions for package installation](https://alexslemonade.github.io/refinebio-examples/01-getting-started/getting-started.html#what-you-need-to-install) for a list of the other software you will need, as well as more tips and resources.

In this analysis, we will be using the R package [`DESeq2`](http://bioconductor.org/packages/devel/bioc/vignettes/DESeq2/inst/doc/DESeq2.html) [@Love2014] for normalization and the R package `pheatmap` [@Slowikowski2017] for clustering and creating a heatmap.

```{r}
if (!("pheatmap" %in% installed.packages())) {
  # Install pheatmap
  install.packages("pheatmap", update = FALSE)
}

if (!("DESeq2" %in% installed.packages())) {
  # Install DESeq2
  BiocManager::install("DESeq2", update = FALSE)
}
```

Attach the `pheatmap` and `DESeq2` libraries:

```{r message=FALSE}
# Attach the `pheatmap` library
library(pheatmap)

# Attach the `DESeq2` library
library(DESeq2)

# We will need this so we can use the pipe: %>%
library(magrittr)

# Set the seed so our results are reproducible:
set.seed(12345)
```

## Import and set up data

Data downloaded from refine.bio include a metadata [tab separated values (TSV)](https://en.wikipedia.org/wiki/Tab-separated_values) file and a data TSV file.
This chunk of code will read in both TSV files and add them as data frames to your environment.

We stored our file paths as objects named `metadata_file` and `data_file` in [this previous step](#check-out-our-file-structure).

```{r}
# Read in metadata TSV file
metadata <- readr::read_tsv(metadata_file)

# Read in data TSV file
expression_df <- readr::read_tsv(data_file) %>%
  # Here we are going to store the gene IDs as row names so that
  # we can have only numeric values to perform calculations on later
  tibble::column_to_rownames("Gene")
```

Let's take a look at the metadata object that we read into the R environment.

```{r}
head(metadata)
```

Now let's ensure that the metadata and data are in the same sample order. 

```{r}
# Make the data in the order of the metadata
expression_df <- expression_df %>%
  dplyr::select(metadata$refinebio_accession_code)

# Check if this is in the same order
all.equal(colnames(expression_df), metadata$refinebio_accession_code)
```

Now we are going to use a combination of functions from the `DESeq2` and `pheatmap` packages to look at how are samples and genes are clustering.

## Define a minimum counts cutoff

We want to filter out the genes that have not been expressed or that have low expression counts since these genes are likely to add noise rather than useful signal to our analysis.
We are going to do some pre-filtering to keep only genes with 10 or more reads total.
Note that rows represent gene data and the columns represent sample data in our dataset.

```{r}
# Define a minimum counts cutoff and filter the data to include
# only rows (genes) that have total counts above the cutoff
filtered_expression_df <- expression_df %>%
  dplyr::filter(rowSums(.) >= 10)
```

We also need our counts to be rounded before we can use them with the `DESeqDataSetFromMatrix()` function.

```{r}
# The `DESeqDataSetFromMatrix()` function needs the values to be integers
filtered_expression_df <- round(filtered_expression_df)
```

## Create a DESeqDataset

We will be using the `DESeq2` package for [normalizing and transforming our data](https://alexslemonade.github.io/refinebio-examples/03-rnaseq/00-intro-to-rnaseq.html#deseq2-transformation-methods), which requires us to format our data into a `DESeqDataSet` object.
We turn the data frame (or matrix) into a [`DESeqDataSet` object](https://alexslemonade.github.io/refinebio-examples/03-rnaseq/00-intro-to-rnaseq.html#02_About_DESeq2). ) and specify which variable labels our experimental groups using the [`design` argument](http://bioconductor.org/packages/devel/bioc/vignettes/DESeq2/inst/doc/DESeq2.html#multi-factor-designs) [@Love2014].
In this chunk of code, we will not provide a specific model to the `design` argument because we are not performing a differential expression analysis.

```{r}
# Create a `DESeqDataSet` object
dds <- DESeqDataSetFromMatrix(
  countData = filtered_expression_df, # the counts values for all samples
  colData = metadata, # annotation data for the samples
  design = ~1 # Here we are not specifying a model
  # Replace with an appropriate design variable for your analysis
)
```

## Perform DESeq2 normalization and transformation

We are going to use the `rlog()` function from the `DESeq2` package to normalize and transform the data.
For more information about these transformation methods, [see here](https://alexslemonade.github.io/refinebio-examples/03-rnaseq/00-intro-to-rnaseq.html#deseq2-transformation-methods). 

```{r}
# Normalize the data in the `DESeqDataSet` object
# using the `rlog()` function from the `DESEq2` R package
dds_norm <- rlog(dds)
```

## Choose genes of interest

Although you may want to create a heatmap including all of the genes in the dataset, this can produce a very large image that is hard to interpret. 
Alternatively, the heatmap could be created using only genes of interest.
For this example, we will sort genes by variance and select genes in the upper quartile, but there are many alternative criterion by which you may want to sort your genes, <i>e.g.</i> fold change, t-statistic, membership in a particular gene ontology, so on.

```{r}
# Calculate the variance for each gene
variances <- apply(assay(dds_norm), 1, var)

# Determine the upper quartile variance cutoff value
upper_var <- quantile(variances, 0.75)

# Filter the data choosing only genes whose variances are in the upper quartile
df_by_var <- data.frame(assay(dds_norm)) %>%
  dplyr::filter(variances > upper_var)
```

## Create a heatmap

To further customize the heatmap, see a vignette for a guide at this [link](https://slowkow.com/notes/pheatmap-tutorial/) [@Slowikowski2017].

```{r}
# Create and store the heatmap object
heatmap <- pheatmap(
  df_by_var,
  cluster_rows = TRUE, # Cluster the rows of the heatmap (genes in this case)
  cluster_cols = TRUE, # Cluster the columns of the heatmap (samples),
  show_rownames = FALSE, # There are too many genes to clearly show the labels
  main = "Non-Annotated Heatmap",
  colorRampPalette(c(
    "deepskyblue",
    "black",
    "yellow"
  ))(25
  ),
  scale = "row" # Scale values in the direction of genes (rows)
)
```

We've created a heatmap but although our genes and samples are clustered, there is not much information that we can gather here because we did not provide the `pheatmap()` function with annotation labels for our samples.

First let's save our clustered heatmap.

### Save heatmap as a PNG 
You can easily switch this to save to a JPEG or tiff by changing the function and file name within the function to the respective file suffix.

```{r}
# Open a PNG file
png(file.path(
  plots_dir,
  "SRP070849_heatmap_non_annotated.png" # Replace with a relevant file name
))

# Print your heatmap
heatmap

# Close the PNG file:
dev.off()
```

Now, let's add some annotation bars to our heatmap.

## Prepare metadata for annotation

From the accompanying [paper](https://pubmed.ncbi.nlm.nih.gov/28193779/), we know that the mice with `IDH2` mutant AML were treated with vehicle or AG-221 (the first small molecule in-vivo inhibitor of IDH2 to enter clinical trials) and the mice with `TET2` mutant AML were treated with vehicle or 5-Azacytidine (Decitabine, hypomethylating agent). [@Shih2017]
We are going to manipulate the metadata and add variables with the information for each sample, from the experimental design briefly described above, that we would like to use to annotate the heatmap.

```{r}
# Let's prepare the annotation for the uncollapsed `DESeqData` set object
# which will be used to annotate the heatmap
annotation_df <- metadata %>%
  # Create a variable to store the cancer type information
  dplyr::mutate(
    mutation = dplyr::case_when(
      startsWith(refinebio_title, "TET2") ~ "TET2",
      startsWith(refinebio_title, "IDH2") ~ "IDH2",
      startsWith(refinebio_title, "WT") ~ "WT",
      # If none of the above criteria are satisfied,
      # we mark the `mutation` variable as "unknown"
      TRUE ~ "unknown"
    )
  ) %>%
  # select only the columns we need for annotation
  dplyr::select(
    refinebio_accession_code,
    mutation,
    refinebio_treatment
  ) %>%
  # The `pheatmap()` function requires that the row names of our annotation
  # data frame match the column names of our `DESeaDataSet` object
  tibble::column_to_rownames("refinebio_accession_code")
```

### Create annotated heatmap

You can create an annotated heatmap by providing our annotation object to the `annotation_col` argument of the `pheatmap()` function.

```{r}
# Create and store the annotated heatmap object
heatmap_annotated <-
  pheatmap(
    df_by_var,
    cluster_rows = TRUE,
    cluster_cols = TRUE,
    show_rownames = FALSE,
    annotation_col = annotation_df,
    main = "Annotated Heatmap",
    colorRampPalette(c(
      "deepskyblue",
      "black",
      "yellow"
    ))(25
    ),
    scale = "row" # Scale values in the direction of genes (rows)
  )
```

Now that we have annotation bars on our heatmap, we have a better idea of the sample variable groups that appear to cluster together.

Let's save our annotated heatmap.

### Save annotated heatmap as a PNG 
You can switch this to save to a JPEG or TIFF by changing the function and file name within the function to the respective file suffix.

```{r}
# Open a PNG file
png(file.path(
  plots_dir,
  "SRP070849_heatmap_annotated.png" # Replace with a relevant file name
))

# Print your heatmap
heatmap_annotated

# Close the PNG file:
dev.off()
```

# Further learning resources about this analysis

- [Make heatmaps in R with pheatmap](https://slowkow.com/notes/pheatmap-tutorial/) [@Slowikowski2017]
- To customize heatmaps even further than the functions in the `pheatmap` package allow, see the [ComplexHeatmap Complete Reference Manual](https://jokergoo.github.io/ComplexHeatmap-reference/book/) [@Gu2016]

# Session info

At the end of every analysis, before saving your notebook, we recommend printing out your session info. 
This helps make your code more reproducible by recording what versions of software and packages you used to run this. 

```{r}
# Print session info
sessioninfo::session_info()
```

# References
