---
title: IrisSpatialFeatures - An R package to quantify the tumor microenvironment based
  on multiplex IF data
author: "Daniel Gusenleitner"
date: '`r Sys.Date()`'
output: pdf_document
vignette: >
  %\VignetteIndexEntry{Vignette Title}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---
# Short example on how to use the IrisSpatialFeatures package

## Reading the dataset

This is a toy example, based on 2 sample with 2 coordinates each. The 20x images were acquired on the Mantra system of PerkinElmer, analyzed in inForm. There are three different phenotypes present in this example: melanoma cells (SOX10+ cells), CD8 cells indicating cytotoxic T-cells and other or undefined cells which have neither SOX10 or CD8 protein expression, but show up as cells according to the nuclear stain.
In addition, PD1 and PD-L1 expression was scored in each sample and a threshold was determined in inForm that let's us distinguish between PD1+ and PD1- cells as well as PD-L1+/-. PD-L1 is only relevant in melanoma cells, whereas PD1 is relevant in the other two cell types. 
Since the toy example only shows the area of a very small image, the resulting statistics often contain NA value, because cell types are not present, which is especially the case in ROI analyses. Look at the full example datasets for more realistic examples.


```{r reading}
require(IrisSpatialFeatures)
raw_data<- read_raw(path=system.file("extdata", package = "IrisSpatialFeatures"),
                    format='Mantra')

#apply all the thresholds PD1 for T and other cells, PD-L1 for macrophages and tumor cells
dataset <- threshold_dataset(raw_data,
                             marker='PD-Ligand-1 (Opal 690)',
                             marker_name='PDL1',
                             base=c('SOX10+'))
dataset <- threshold_dataset(dataset,
                             marker='PD-1 (Opal 540)',
                             marker_name='PD1',
                             base=c('CD8+','OTHER'))
```

## Overview plots
Next we plot all the cell coordinates color coordinated in .pdf format
```{r overview_plots}
plot_dir <- file.path(tempdir(),'plots')
if (!file.exists(plot_dir)){
    dir.create(file.path(plot_dir))
}
p <- overview_plot(dataset,outdir=plot_dir,palette=NULL,type='png')
```

![Example of an Overview plot](`r plot_dir`/MEL3_120116_1.png?raw=true "Overview Example")

## Extract counts and ratios
Here we extract counts per mm2 for each marker, both for each coordinate and collapsed across the multiple images per sample.
```{r counts}
get_counts_per_mm2(dataset)
get_counts_per_mm2_noncollapsed(dataset)
get_count_ratios(dataset,'SOX10+ PDL1-','SOX10+ PDL1+')
```

## Nearest neighbor analysis
Next step we calculate the average nearest neighbor distances for each cell-type, plot barplots compare different distances and finally generate ray plots that show a visual representation of these distances for each coordinate.

```{r nearest_neighbor, fig.width=5, fig.height=5}
dataset <- extract_nearest_neighbor(dataset,min_num_cells=2)
get_nearest_neighbors(dataset,"SOX10+ PDL1+")
p <- plot_nearest_neighbor(dataset,'CD8+ PD1+','SOX10+ PDL1')
p <- plot_nearest_neighbor(dataset,'SOX10+ PDL1+','SOX10+ PDL1-')

#ray plots for 
plot_dir <- file.path(tempdir(),'ray_plots')
if (!file.exists(plot_dir)){
    dir.create(file.path(plot_dir))
}
neighbor_ray_plot(dataset,from_type='CD8+ PD1+',to_type='SOX10+ PDL1+',plot_dir=plot_dir,format ='pdf')
```

## Interaction analysis
Here we extract the interactions between different cell types, generate an interaction profile for SOX10+ PDL1+ cells and also generate interaction maps for each coordinate showing the interactions between CD8+ PD1+ cells and SOX10+ PD-L1+ cells.
```{r interaction_analysis, fig.width=7, fig.height=7}
dataset <- extract_interactions(dataset)
get_interactions(dataset,'SOX10+ PDL1+')

#plotting interaction summaries
p <- plot_interactions(dataset,'SOX10+ PDL1+',xlim_fix=4)

#plotting interaction maps
int_markers <- c('CD8+ PD1+','SOX10+ PDL1+')
int_marker_cols <- c('#fc5858','#66c2a4')
silent_markers <- c('CD8+ PD1-','SOX10+ PDL1-' )
silent_col=c('#fff7bc','#a6bddb')
plot_dir <- file.path(tempdir(),'interaction_maps')
if (!file.exists(plot_dir)){
    dir.create(file.path(plot_dir))
}
p <- interaction_maps(dataset,int_markers,int_marker_cols,silent_markers,
                      silent_col,outdir=plot_dir)
```

![Example of a Interaction map](`r plot_dir`/MEL2_080416_2_CD8+_PD1+__SOX10+_PDL1+__CD8+_PD1-__SOX10+_PDL1-.png?raw=true "Interaction map example")

##Running the proximity analysis
Calculating the number of cells within 25 pixels distance for each cell and then showing the the profile for SOX10+ PDL1-
```{r proximity_analysis, fig.width=7, fig.height=7}
dataset <- extract_proximity(dataset,only_closest=TRUE,radii=25)
p <- plot_proximities(dataset,"SOX10+ PDL1-",xlim_fix=3)


```




