## ----Setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  out.width = "100%"
)

## ----Install packages, eval = FALSE-------------------------------------------
# if (!requireNamespace("BiocManager", quietly = TRUE))
#   install.packages("BiocManager")
# BiocManager::install("polyICSFlow")

## ----Load libraries-----------------------------------------------------------
library(polyICSFlow)

## ----Load preprocessed data---------------------------------------------------
# define path to data
path_data <- system.file("extdata", package = "polyICSFlow")

# load pre-processed fcs files as flowSet
fs <- flowCore::read.flowSet(path = path_data,
                             pattern = ".fcs",
                             truncate_max_range = FALSE,
                             transformation = FALSE)

flowWorkspace::pData(fs)

## ----Create gatingSet---------------------------------------------------------
# create GatingSet from flowSet 
gs <- flowWorkspace::GatingSet(fs)

## ----Check cell population, warning = FALSE, fig.width=8, fig.height=4, dev='png', eval = requireNamespace("CytoExploreR", quietly = TRUE)----
# # check marker expression on cells
# CytoExploreR::cyto_plot_custom(matrix(c(1:2),ncol=2))
# for(channel_plot in c("CD8","CD4")){
#   CytoExploreR::cyto_plot(gs[[1]],
#                           parent = "root",
#                           channels = c("CD3",channel_plot),
#                           ylim = c(0,4))
#   }
# 
# 

## ----Apply gatingTemplate-----------------------------------------------------
# apply GatingTemplate to flowSet 
gt <- openCyto::gatingTemplate(file.path(path_data, "gatingTemp_cytokines.csv"))
openCyto::gt_gating(x = gt, y = gs)

# see nodes in gatingSet
names(gt_get_nodes(gt))


## ----Plot gating1, warning=FALSE, eval = requireNamespace("CytoExploreR", quietly = TRUE)----
# plot(gs)
# CytoExploreR::cyto_plot_gating_tree(gs)

## ----Plot gating2, warning=FALSE,fig.width=12, fig.height=6, dev='png', eval = requireNamespace("CytoExploreR", quietly = TRUE)----
# CytoExploreR::cyto_plot_custom(matrix(c(1:8),ncol=4,byrow=TRUE))
# for(sample_plot in c(1,2)){
#   for(channel_plot in c("IFN","TNFa","IL2","CD107a")){
#     CytoExploreR::cyto_plot(gs[[sample_plot]],
#                             parent = "root",
#                             channels = c(channel_plot,"CD8"),
#                             alias = "")
#     }
# }

## ----population labels--------------------------------------------------------
markers_clust <- c("CD45RA","CCR7","CD27","CD95","TCF1","Tbet","TIGIT","CD39","CCR4","CD16")
channels_clust <- flowCore::pData(flowCore::parameters(fs[[1]])) %>% dplyr::filter(desc %in% markers_clust)%>%dplyr::pull(name) %>% unname
fsom <- FlowSOM::FlowSOM(fs,
                         compensate = FALSE,
                         transform = FALSE,
                         scale = FALSE,
                         colsToUse = channels_clust,
                         xdim = 8,
                         ydim = 8,
                         nClus = 10)

cell_labels <- fsom$metaclustering[fsom$map$mapping[,1]]


## ----Load cell labels---------------------------------------------------------
cell_labels_external <- readRDS(file.path(path_data, "cell_labels.rds"))

## ----polyICSFlow1-------------------------------------------------------------
# Get marker positivity per cell
df_markerPos <- getMarkerPositivity(x = gs,
                                    gate_names = c("IFN+","TNFa+","IL2+","CD107a+"))

head(df_markerPos)

## ----polyICSFlow2a------------------------------------------------------------
# Assign marker combinations to each cell based on marker positivity
# Simple mode
df_markerComb <- assignMarkerCombinations(data_markerPos = df_markerPos,
                                          mode = "simple")
head(df_markerComb)

## ----polyICSFlow2b------------------------------------------------------------
# Exhaustive mode
df_markerComb <- assignMarkerCombinations(data_markerPos = df_markerPos,
                                          mode = "exhaustive")
names(df_markerComb)


## ----polyICSFlow3-------------------------------------------------------------
# Read metadata 
df_md <- read.csv(file.path(path_data, "metadata.csv"))

# Add metadata to dataframe
df <- df_markerComb %>%
    dplyr::mutate(ID = df_md$ID,
                  Stimulation = df_md$Stimulation,
                  cell_type = cell_labels_external)

# Alternatively use the cell labels obtained from FlowSOM clustering in step 2.3
# df <- df_markerComb %>%
#     dplyr::mutate(ID = df_md$ID,
#                   Stimulation = df_md$Stimulation,
#                   cell_type = cell_labels)

## ----polyICSFlow 3a-----------------------------------------------------------
# Calculate by Marker Count
result <- calcPolyfunctionality(x = df,
                                md_cols = c("ID"),
                                pop_col = "cell_type",
                                resolution = "MarkerCount",
                                condition_col = "Stimulation",
                                background_val = "Unstim")

head(result)


## ----Plot result 3a-----------------------------------------------------------
palette_MarkerCounts <- scales::brewer_pal(type = "qual")(4)

result %>%
  dplyr::filter(Stimulation != "Unstim")%>%
  ggplot2::ggplot(ggplot2::aes(x = cell_type,
                               y = perc_pos_backgroundSubtracted,
                               fill = as.factor(MarkerCount)))+
  ggh4x::facet_grid2(Stimulation~ID)+
  ggplot2::geom_bar(stat="identity")+
  ggplot2::theme_bw()+
  ggplot2::ylab("Frequency of HIV-1-Gag specific CD8 T cells")+
  ggplot2::xlab("CD8 metacluster")+
  ggplot2::scale_fill_manual(values = palette_MarkerCounts,
                             name = "Number of functions")


## ----polyICSFlow3b------------------------------------------------------------

# Calculate by Marker Combination
result <- calcPolyfunctionality(x = df,
                                md_cols = c("ID"),
                                pop_col = "cell_type",
                                resolution = "MarkerComb",
                                condition_col = "Stimulation",
                                background_val = "Unstim")

head(result)

## ----Plot result 3b-----------------------------------------------------------
palette_markerCombs <- c("#DC050C","#FB8072","#1965B0","#7BAFDE",
                         "#882E72","#B17BA6","#FF7F00","#FDB462",
                         "#E7298A","#E78AC3","#33A02C", "#B2DF8A",
                         "#55A1B1","#8DD3C7","#A6761D")
result %>%
  dplyr::filter(Stimulation != "Unstim")%>%
  ggplot2::ggplot(ggplot2::aes(x = cell_type,
                               y = perc_pos_backgroundSubtracted,
                               fill = MarkerComb))+
  ggh4x::facet_grid2(Stimulation~ID)+
  ggplot2::geom_bar(stat="identity")+
  ggplot2::theme_bw()+
  ggplot2::ylab("Frequency of HIV-1-Gag specific CD8 T cells")+
  ggplot2::xlab("CD8 metacluster")+
  ggplot2::scale_fill_manual(values = palette_markerCombs,
                             name = "Cytokine combinations")

## ----polyICSFlow3c------------------------------------------------------------
# Calculate by Polyfunctional_atleast_IFN+
result <- calcPolyfunctionality(x = df,
                                md_cols = c("ID"),
                                pop_col = "cell_type",
                                resolution = "Polyfunctional_atleast_IFN+",
                                condition_col = "Stimulation",
                                background_val = "Unstim")

head(result)

## ----Plot result 3c-----------------------------------------------------------
result %>%
  dplyr::filter(Stimulation != "Unstim")%>%
  ggplot2::ggplot(ggplot2::aes(x = cell_type,
                               y = perc_pos_backgroundSubtracted,
                               fill = cell_type))+
  ggplot2::geom_bar(stat="identity")+
  ggplot2::theme_bw()+
  ggplot2::ylab("Frequency of polyfunctional IFN+ HIV-1-Gag specific CD8 T cells")+
  ggplot2::xlab("CD8 metacluster")

## ----Plotting polyICSFlow1, fig.width=7, fig.height=3.5-----------------------

plotMarkerCombHeatmap(marker_names = c("IFN","TNFa","IL2","CD107a"),
                       orientation = "horizontal")



## ----Plotting polyICSFlow2, fig.height = 5, fig.width=3.5, out.width = "50%"----
plotCellCountsExactly(data_markerComb = df_markerComb)

## ----Plotting polyICSFlow3, fig.width=7, fig.height=5-------------------------
plotCellCountsAtLeast(data_markerComb = df_markerComb)

## ----Plotting polyICSFlow4, fig.width=10, fig.height=6------------------------
library(patchwork)
p1 <- plotCellCountsExactly(data_markerComb = df_markerComb)
p2 <- plotCellCountsAtLeast(data_markerComb = df_markerComb)
p1+p2+plot_layout(guides = "collect",widths = c(1,4))

## ----Plotting polyICSFlow5, fig.width=16,fig.height=16------------------------
set.seed(1) # setting a seed is recommended to get reproducible visualizations
plotMarkerComb2DScatters(input = fs,
                         assigned_MarkerCombs = df_markerComb$MarkerComb)

## ----Extract numbers----------------------------------------------------------
extractCellCounts(df_markerComb)

## ----sessionInfo--------------------------------------------------------------
sessionInfo()

