---
title: "Segmentation of MS imaging experiments with Cardinal"
author: "Kylie Ariel Bemis"
date: "Revised: April 21, 2020"
output:
  BiocStyle::html_document:
  toc: true
vignette: >
  %\VignetteIndexEntry{1. Segmentation: Unsupervised analysis workflow}
  %\VignetteKeyword{ExperimentData, MassSpectrometryData, ImagingMassSpectrometry, Clustering}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r style, echo=FALSE, results='asis'}
BiocStyle::markdown()
```

```{r setup, echo=FALSE, message=FALSE}
library(CardinalWorkflows)
setCardinalBPPARAM(SerialParam())
setCardinalVerbose(FALSE)
RNGkind("L'Ecuyer-CMRG")
```

# Introduction 

The goal of unsupervised analysis of mass spectrometry (MS) imaging experiments is to discover regions in the data with distinct chemical profiles, and to select the *m/z*-values that uniquely distinguish these different regions from each other.

Algorithmically, this means clustering the data. In imaging experiments, the resulting cluster configurations are called spatial segmentations, and the clusters are called segments.

In this vignette, we present an example segmentation workflow using *Cardinal*.

We begin by loading the package:

```{r}
library(Cardinal)
```

# Segmentation of a pig fetus wholy body cross section

This example uses the PIGII_206 dataset: a cross section of a pig fetus captured using a Thermo LTQ instrument using desorption electrospray ionization (DESI).

First, we load the dataset from the *CardinalWorkflows* package. The data is stored in an older format, so we need to coerce it to an `MSImagingExperiment`.

```{r load-pig206}
data(pig206, package="CardinalWorkflows")
pig206 <- as(pig206, "MSImagingExperiment")
```

The dataset contains 4,959 spectra with 10,200 *m/z*-values.

```{r show-pig206}
pig206
```

![Optical image of the pig fetus section](pig206-optical.png)

In the optical image shown above, the brain (left), heart (center), and liver (large dark region) are clearly visible.

```{r mz-885}
image(pig206, mz=885.5, plusminus=0.25)
```

The dataset has been cropped to remove the background slide pixels, leaving only the tissue section itself for analysis.

## Pre-processing

For statistical analysis, it is useful to reduce the dataset to include only the peaks.

We calculate the mean spectrum using `summarizeFeatures()`.

```{r pig206-mean}
pig206_mean <- summarizeFeatures(pig206, "mean")
```

```{r plot-pig206-mean}
plot(pig206_mean)
```

In order to make the mass spectra comparable between different pixels, it is necessary to normalize the data. We will use TIC normalization.

Let's calculate the TIC to see how it currently varies across the dataset in the raw, unprocessed specra.

```{r pig206-tic}
pig206_tic <- summarizePixels(pig206, c(tic="sum"))
```

```{r plot-pig206-tic}
image(pig206_tic)
```

To process the dataset, we will first perform peak picking on the mean spectrum to create a set of reference peaks. We will then bin the peaks in the entire dataset to this reference.

Note that peak picking on the mean spectrum is the fastest option, but may miss low-intensity peaks or peaks that only occur in a small part of the dataset. If we wanted to be more thorough, we could use a similar procedure to perform peak picking on the entire dataset (or on a random sample of many spectra) to create the set of reference peaks.

```{r peak-ref-pig206}
pig206_ref <- pig206_mean %>%
  peakPick(SNR=3) %>%
  peakAlign(ref="mean",
            tolerance=0.5,
            units="mz") %>%
  peakFilter() %>%
  process()
```

Now we bin the rest of the dataset to the reference peaks.

```{r peak-bin-pig206}
pig206_peaks <- pig206 %>%
  normalize(method="tic") %>%
  peakBin(ref=mz(pig206_ref),
          tolerance=0.5,
          units="mz") %>%
  process()

pig206_peaks
```

This produces a centroided dataset with 110 peaks.

## Visualization

Before proceeding with the statistical analysis, we'll first perform some and exploratory visual analysis of the dataset.

### Ion images

Below, we plot several hand-selected peaks corresponding to major organs.

*m/z* 187 appears highly abundant in the heart.

```{r mz-187}
image(pig206_peaks, mz=187)
```

*m/z* 840 appears highly abundant in the brain and spinal cord.

```{r mz-840}
image(pig206_peaks, mz=840)
```

*m/z* 537 appears highly abundant in the liver.

```{r mz-537}
image(pig206_peaks, mz=537)
```

Rather than manually going the full dataset and hand-selecting peaks, the goal of our statistical analysis will be to automatically select the peaks that distinguish such regions (e.g., the major organs).

### Principal components analysis (PCA)

Principal component analysis (PCA) is a popular method for exploring a dataset. PCA is available in *Cardinal* through the `PCA()` method.

Below, we calculate the first 3 principal components.

```{r}
pig206_pca <- PCA(pig206_peaks, ncomp=3)
```

Next, we overlay the first 3 principal components.

The overlay requires some contrast enhancement to see the structures clearly. In addition, the range of the PC scores are normalized to the same range (between 0 and 1).

```{r}
image(pig206_pca, contrast.enhance="histogram", normalize.image="linear")
```

We can plot the loadings for the principal components as well.

```{r}
plot(pig206_pca, lwd=2)
```

PCA can sometimes be useful for exploring a dataset. For example, here, we can see that PC3 appears to distinguish the liver, but also includes several other structures. This makes it difficult to fully utilize PCA for analysis.


## Segmentation with spatial shrunken centroids (SSC)

To segment the dataset and automatically select peaks that distinguish each region, we will use the `spatialShrunkenCentroids()` method provided by *Cardinal*.

Important parameters to this method include:

- `method` The type of spatial weights to use:
    
    + *"gaussian"* weights use a simple Gaussian smoothing kernel
    
    + *"adaptive"* weights use an adaptive kernel that sometimes preserve edges better

- `r` The neighborhood smoothing radius; this should be selected based on the size and granularity of the spatial regions in your dataset

- `s` The shrinkage or sparsity parameter; the higher this number, the fewer peaks will be used to determine the final segmentation.

- `k` The maximum number of segments to try; empty segments are dropped, so the resulting segmentation may use fewer than this number.

It is typically best to set `k` relatively high and let the algorithm drop empty segments. You typically also want to try a wide range of sparsity with the `s` parameter.

```{r ssc}
set.seed(1)
pig206_ssc <- spatialShrunkenCentroids(pig206_peaks, method="adaptive",
                                       r=2, s=c(0,5,10,15,20,25), k=10)
```

```{r show-ssc}
summary(pig206_ssc)
```

As shown in the summary, the resulting number of segments typically decreases as `s` increases. This is because fewer peaks are used to determine the segmentation.

First, non-informative peaks are removed, but as `s` increases meaningful peaks may be removed as well. The most interesting and useful segmentations tend to be the ones with the highest value of `s` just before the resulting number of segments decreases too much.

### Plotting the segmentation

Let's plot the resulting segmentations for s = 10, 15, 20, 25.

```{r ssc-image-multi}
image(pig206_ssc, model=list(s=c(10,15,20,25)))
```

It is useful to see how the segmentation changes as fewer peaks are used and the number of segments decreases. Noisy, less-meaningful segments tend to be removed first, so we want to explore the segmentation with the highest value of `s` that still captures most of the regions we would expect to see.

```{r ssc-image-s20}
image(pig206_ssc, model=list(s=20))
```

Here, we can see the heart, brain, and liver distinguished as segments 1, 5, and 6.

### Plotting the (shrunken) mean spectra

Plotting the shrunken centroids is analogous to plotting the mean spectrum of each segment.

```{r ssc-centers}
plot(pig206_ssc, model=list(s=20), lwd=2)
```

Let's break out the centroids for the heart, brain, and liver segments.

```{r ssc-centers-2}
cols <- discrete.colors(6)
setup.layout(c(3,1))
plot(pig206_ssc, model=list(s=20), column=1, col=cols[1], lwd=2, layout=NULL)
plot(pig206_ssc, model=list(s=20), column=5, col=cols[5], lwd=2, layout=NULL)
plot(pig206_ssc, model=list(s=20), column=6, col=cols[6], lwd=2, layout=NULL)
```

Some differences are visible, but it can be difficult to tell exactly which peaks are changing between different segments based on the mean spectra alone.

### Plotting and interpretting t-statistics of the *m/z* values

Plotting the t-statistics tells us exactly the relationship between each segment's centroid and the global mean spectrum. The t-statistics are the difference between a segment's centroid and the global mean, divided by a standard error.

Positive t-statistics indicate that peak is systematically higher in that segment as compared to the global mean spectrum.

Negative t-statistics indicate that peak is systematically lower in that segment as compared to the global mean spectrum.

Spatial shrunken centroids works by shrinking these t-statistics toward 0 by `s`, and using the new t-statistics to recompute the segment centroids. The effect is that peaks that are not very different between a specific segment and the global mean are effectively eliminated from the segmentation.

```{r ssc-statistic}
plot(pig206_ssc, model=list(s=20), values="statistic", lwd=2)
```

If we break out the t-statistics for the heart, brain, and liver segments we can learn something interesting.

```{r ssc-statistic-2}
setup.layout(c(3,1))
plot(pig206_ssc, model=list(s=20), values="statistic",
     column=1, col=cols[1], lwd=2, layout=NULL)
plot(pig206_ssc, model=list(s=20), values="statistic",
     column=5, col=cols[5], lwd=2, layout=NULL)
plot(pig206_ssc, model=list(s=20), values="statistic",
     column=6, col=cols[6], lwd=2, layout=NULL)
```

Very few peaks distinguish the heart, while many more distinguish the brain and liver.

### Retrieving the top *m/z*-values

Use the `topFeatures()` method to extract the *m/z* values of the peaks that most distinguish each segment, ranked by t-statistic.

Peaks associated with the heart:

```{r top-heart}
topFeatures(pig206_ssc, model=list(s=20), class==1)
```

Peaks associated with the brain:

```{r top-brain}
topFeatures(pig206_ssc, model=list(s=20), class==5)
```

Peaks associated with the liver:

```{r top-liver}
topFeatures(pig206_ssc, model=list(s=20), class==6)
```

The top *m/z* values for each segment match up well with the hand-selected peaks.

# Segmentation of a cardinal painting

It can be difficult to evaluate unsupervised methods (like segmentation) on data where we do not know the ground truth.

In this section, we use an MS image of a painting, where we know the ground truth.

```{r load-cardinal}
data(cardinal, package="CardinalWorkflows")
cardinal <- as(cardinal, "MSImagingExperiment")
```

![Cardinal painting](cardinal-optical.png)

In this experiment, DESI spectra were collected from an oil painting of a cardinal.

```{r show-cardinal}
cardinal
```

The dataset includes 12,600 spectra with 10,800 *m/z* values.

## Pre-processing

First, we will pre-process the dataset as before, by applying peak picking to the mean spectrum.

```{r cardinal-mean}
cardinal_mean <- summarizeFeatures(cardinal, "mean")
```

```{r peak-ref-cardinal}
cardinal_ref <- cardinal_mean %>%
  peakPick(SNR=3) %>%
  peakAlign(ref="mean",
            tolerance=0.5,
            units="mz") %>%
  peakFilter() %>%
  process()
```

```{r peak-bin-cardinal}
cardinal_peaks <- cardinal %>%
  normalize(method="tic") %>%
  peakBin(ref=mz(cardinal_ref),
          tolerance=0.5,
          units="mz") %>%
  process()

cardinal_peaks
```

This results in a centroided dataset with 106 peaks.

## Segmetation with SSC

Now we use spatial shrunken centroids to segment the dataset.

```{r ssc-cardinal}
set.seed(1)
cardinal_ssc <- spatialShrunkenCentroids(cardinal_peaks, method="adaptive",
                                       r=2, s=c(10,20,30,40), k=10)
```

```{r show-ssc-cardinal}
summary(cardinal_ssc)
```

```{r ssc-cardinal-multi}
image(cardinal_ssc)
```

We can see that with s = 10 and s = 20, two segmments are capturing an unwanted background gradient. At s = 30, this background gradient is eliminated.

Now we can use the segmentation to re-construct the original painting.

```{r ssc-cardinal-image}
image(cardinal_ssc, model=list(s=40),
      col=c("1"=NA, "2"="gray", "3"="black", "4"="firebrick",
            "5"="brown", "6"="darkred", "7"="red"))
```

Let's find the *m/z* values associated with the cardinal's body.

```{r top-body}
topFeatures(cardinal_ssc, model=list(s=40), class==7)

image(cardinal, mz=207)
```

And let's find the *m/z* values associated with the "DESI-MS" text.

```{r top-text}
topFeatures(cardinal_ssc, model=list(s=40), class==3)

image(cardinal, mz=649)
```


# Session information

```{r session-info}
sessionInfo()
```



