library(shiny)
library(Seurat)
library(tidyverse)
options(shiny.trace = F)

# rownames(macrophages)[rownames(macrophages) %in% c("CD206")]
macrophages <- readRDS("/home/wangyang/workspace/scRNA_MYC/data/Macrophages_new_empty.rds")
macrophages[["percent.mt"]] <- PercentageFeatureSet(macrophages, pattern = "^MT-")
summary(macrophages@meta.data$nFeature_RNA)
VlnPlot(macrophages, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3)

# macrophages <- subset(macrophages, subset = nFeature_RNA > 200 & nFeature_RNA < 3000 & percent.mt < 30)


#### NormalizeData

macrophages <- NormalizeData(macrophages, 
                            normalization.method = "LogNormalize", 
                            scale.factor = 10000)

#### FindVariableFeatures
# top10 <- head(VariableFeatures(macrophages), 10)
# (plot1<- VariableFeaturePlot(macrophages))
# LabelPoints(plot = plot1,
#                      points = top10,
#                      xnudge = 0,
#                      ynudge = 0, 
#                      repel = TRUE)
#### ScaleData
all.genes <- rownames(macrophages)
macrophages <- ScaleData(macrophages, features = all.genes)


#### dimension

# DimPlot(macrophages, reduction = "pca",group.by = "orig.ident")
# FeaturePlot(macrophages, features = c("CD14","CD163","CCR7","IL7R"),label.size = 1,reduction = 'pca')


# MYC_marker <- read_csv("/home/wangyang/workspace/scRNA_MYC/data/MYC_marker.csv")

# all_genes <- MYC_marker$gene
all_genes <- rownames(macrophages)
features <- c("CD14","CD163","CD209","IL1B","CCR7","TLR7")


ui <- fluidPage(
 titlePanel("巨噬细胞(Macrophages)单细胞数据分析"),

   sidebarLayout(
     sidebarPanel(
       sliderInput("nfeatures", h3("nfeatures"),
                     min = 100, max = 5000, value = 3000),
       sliderInput("neighbor", h3("FindNeighbors"),
                     min = 1, max = 25, value = 18),
       sliderInput("resolution", h3("FindClusters"),
                     min = 0, max = 1, value = 0.15),
       sliderInput("perplexity", h3("tsne perplexity"),
                     min = 1, max = 100, value = 20),
       selectInput("reduction", h3("Select reduction"), 
                     choices = c("umap","tsne","pca"), selected = "tsne",multiple = F),
       # selectInput("pca_dims", h3("Select pca dims"), 
       #               choices = c(1,2,3,4), selected = 1,multiple = F),
       selectizeInput(inputId   = "genes",
               h3("Select gene from deg"),
               choices   = features,
               multiple = TRUE,
               selected = features
       ),
       submitButton("Update View", icon("sync")),
       p("M1 macrophage:CCR7, IL7R, [FCGR3A, FCGR3B], [FCGR2A, FCGR2B, FCGR2C], [SELE, SELP, SELL], FCGR1A, CD80, CD86, CXCL10, IL15RA, IL17RA, IL1R1, IL2RA, TLR2, TLR4"),             
       p("M2 macrophage:CD14, CD163"),
       p("M0 macrophage:"),
     ),
     mainPanel(
       textOutput("neighbor"),
       textOutput("resolution"),
       textOutput("nfeatures"),
       textOutput("genes"),
       textOutput("reduction"),
       textOutput("pca_dims"),
       textOutput("perplexity"),
       plotOutput(outputId = "DimPlot"),
       plotOutput(outputId = "FeaturePlot"),
       plotOutput(outputId = "VlnPlot"),
       plotOutput(outputId = "DimHeatmap1"),
       plotOutput(outputId = "DimHeatmap2"),

   )
 )
)

# Define server logic ----
server <- function(input, output,session) {
 updateSelectizeInput(
         session,
         inputId = 'genes',
         choices = unique(all_genes),
         selected=features,
         server = TRUE
 )
 output$resolution <- renderText(paste0("resolution: ",input$resolution))
 output$neighbor <- renderText(paste0("neighbor: ",input$neighbor))
 output$nfeatures <- renderText(paste0("nfeatures: ",input$nfeatures))
 output$genes <- renderText(paste0("genes: ",input$genes))
 output$reduction <- renderText(paste0("reduction: ",input$reduction))
 output$perplexity <- renderText(paste0("perplexity: ",input$perplexity))
 # output$pca_dims <- renderText(paste0("pca_dims: ",input$pca_dims))


 macrophagesFun <- reactive({
   macrophages <- FindVariableFeatures(macrophages, selection.method = "vst", nfeatures = input$nfeatures)
   macrophages <- RunPCA(macrophages, features = VariableFeatures(object = macrophages))

   # DimPlot(macrophages, reduction = "umap",label = T)
   macrophages <- FindNeighbors(macrophages, dims = 1:input$neighbor)
   macrophages <- FindClusters(macrophages, resolution = input$resolution)
   res <- NULL
   if(input$reduction=="umap"){
     res <- RunUMAP(macrophages, dims = 1:input$neighbor)
   }else if (input$reduction=="tsne") {
     res <- RunTSNE(macrophages,dims = 1:input$neighbor,perplexity=input$perplexity)
   }else {
     res <- macrophages
   }
   
   return(res)
 })



 output$DimHeatmap1 <- renderPlot({
   macrophages <- macrophagesFun()
   DimHeatmap(macrophages, dims = 1, cells = 500, balanced = TRUE)
 }) 
 output$DimHeatmap2 <- renderPlot({
   macrophages <- macrophagesFun()
   DimHeatmap(macrophages, dims = 2, cells = 500, balanced = TRUE)
 }) 


 output$DimPlot <- renderPlot({
   macrophages <- macrophagesFun()
   # plot(input$resolution)
   DimPlot(macrophages, reduction = input$reduction,label = T)
    
 })  
 output$FeaturePlot <- renderPlot({
   macrophages <- macrophagesFun()
   FeaturePlot(macrophages, 
             features = input$genes,
             label.size = 1,
             reduction = input$reduction)
 })
 output$VlnPlot <- renderPlot({
   macrophages <- macrophagesFun()
   VlnPlot(macrophages, features =input$genes, ncol = 3)
 })
 

}
shinyApp(ui = ui, server = server)