---
title: "CytoR"
author: "Marcel Costa-Garcia"
date: "`r Sys.Date()`"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
```

First we load the required libreries and import functions from `functionsCyto.R`:
```{r}
library(tidyverse)
library(flowWorkspace)
library(Biobase)
library(flowGate)
source("functionsCyto.R")
```

We import the .LMD or .fcs files to a FlowSet object that we convert into a GatingSet (in the case of LMD files, they include both the format FCS2 and FCS3, which is accessed as dataset=2):
```{r}
fs<-read.ncdfFlowSet(files=list.files("BcellPhenotype-Files/",".LMD", full.names = T), readonly = F, dataset=2)
gs <- GatingSet(fs)
gs
```

Next, we will compensate with the compensation matrix of the adquisition, which is embed into the file. We can import another compensation matrix:

```{r}
comp<-spillover(fs[[1]])$`$SPILLOVER`
colnames(comp)<-colnames(gs)[5:14]
rownames(comp)<-colnames(gs)[5:14]
comp
gs<-compensate(gs, comp)
```

To transform the axis in an interactive and visual way, I have created the following function:
```{r, eval=FALSE}
trans_params<-transform_gs(gs)
```

![](trans_params.jpg)

```{r, include=F}
trans_params<-readRDS("BcellPhenotype-trans_params.rds")
trans_apply(gs, trans_params = trans_params)
```

```{r}
trans_params$`FL3-A`
```
We can save the transformation params in a file and latter we can import and apply directly (including in other experiments):
```{r, eval=F}
saveRDS(trans_params, "BcellPhenotype-trans_params.rds")
```


```{r, eval=F}
trans_params<-readRDS("BcellPhenotype-trans_params.rds")
trans_apply(gs, trans_params = trans_params)
```

As it wasn't done during the acquisition, we will define the marker name for the channels of interest:
```{r}
markers<-colnames(gs)
markers[c(7,13)]<-c("CD19","L&D")
names(markers)<-colnames(gs)
markernames(gs)<-markers
markernames(gs)
```

Finally, we will clean a bit the sample names:
```{r}
sampleNames(gs)
sampleNames(gs)<-gsub("\\s[0-9]*.LMD","",sampleNames(gs))
sampleNames(gs)<-gsub(".*\\s","",sampleNames(gs))
pData(gs)$name<-rownames(pData(gs))
sampleNames(gs)
```


And we are ready to gate! We will be using the `gs_interactive_gate` function from `flowGate` package.
```{r, include=F}
gates<-readRDS("BcellPhenotype-gates.rds")
gs<-gates_apply(gs, gates)
```

```{r, eval=F}
gs_gate_interactive(gs,
                    filterId = "Leukocytes",
                    dims = list("FS-A", "SS-A"))
```
![](Gates.jpg)

```{r, eval=F}
gs_gate_interactive(gs,
                    subset = "Leukocytes",
                    filterId = "CD19 L&D",
                    dims = list("CD19", "L&D"))
```

We can save the created gates into a file to import latter on (which may be also used to apply the gating strategy into a new experiment):
```{r, eval=F}
gates<-gates_save(gs, file = "BcellPhenotype-gates.rds")

gates<-readRDS("BcellPhenotype-gates.rds")
gs<-gates_apply(gs, gates)
```

```{r}
plot(gs)
```

We can rapidly explore the results using the `autoplot` function:
```{r}
autoplot(gs, "Leukocytes", bins=128, nrow=1)
autoplot(gs[["aCDE19"]], bins=128, nrow=1)
```
We can further personalize the plot with similar sintaxis as `ggplot` with the `ggcyto` package:
```{r}
g<-ggcyto(gs, subset = "Leukocytes", bins=128, aes(CD19,`L&D`))+
  facet_grid(.~factor(name, levels=c("Unst","aCDE19")))+
  geom_hex(bins=128)+
  geom_gate()+
  geom_stats()+
  scale_fill_gradient(low="black", high="violet")
g
```

Finally, we can export the stats and plot them:
```{r, fig.width=4}
stats<-gs_pop_get_stats(gs, nodes=gs_get_pop_paths(gs, path = "auto")[3:6], type="perc")
stats

g2<-ggplot(stats, aes(factor(sample, levels=c("Unst","aCDE19")), percent, fill=pop))+
  geom_bar(stat="identity", color="black")+xlab("Samples")

ggpubr::ggarrange(as.ggplot(g), g2, ncol=1)

```

Code:
```r
library(tidyverse)
library(flowWorkspace)
library(Biobase)
library(flowGate)
source("functionsCyto.R")

fs<-read.ncdfFlowSet(files=list.files("BcellPhenotype-Files/",".LMD", full.names = T), readonly = F, dataset=2)
gs <- GatingSet(fs)

comp<-spillover(fs[[1]])$`$SPILLOVER`
colnames(comp)<-colnames(gs)[5:14]
rownames(comp)<-colnames(gs)[5:14]
gs<-compensate(gs, comp)

trans_params<-transform_gs(gs)

markers<-colnames(gs)
markers[c(7,13)]<-c("CD19","L&D")
names(markers)<-colnames(gs)
markernames(gs)<-markers

sampleNames(gs)<-gsub("\\s[0-9]*.LMD","",sampleNames(gs))
sampleNames(gs)<-gsub(".*\\s","",sampleNames(gs))
pData(gs)$name<-rownames(pData(gs))

gs_gate_interactive(gs,
                    filterId = "Leukocytes",
                    dims = list("FS-A", "SS-A"))

gs_gate_interactive(gs,
                    subset = "Leukocytes",
                    filterId = "CD19 L&D",
                    dims = list("CD19", "L&D"))
					
g<-ggcyto(gs, subset = "Leukocytes", bins=128, aes(CD19,`L&D`))+
  facet_grid(.~factor(name, levels=c("Unst","aCDE19")))+
  geom_hex(bins=128)+
  geom_gate()+
  geom_stats()+
  scale_fill_gradient(low="black", high="violet")
  
stats<-gs_pop_get_stats(gs, nodes=gs_get_pop_paths(gs, path = "auto")[3:6], type="perc")
stats

g2<-ggplot(stats, aes(factor(sample, levels=c("Unst","aCDE19")), percent, fill=pop))+
  geom_bar(stat="identity", color="black")+xlab("Samples")

ggpubr::ggarrange(as.ggplot(g), g2, ncol=1)
```
