library(Seurat)
library(DT)
## The following object is masked from 'package:Seurat':
## 
##     JS
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
cds <- readRDS("../../ee_seurat2_By_yangfu/G101_PC20res04.rds")
cds <- UpdateSeuratObject(cds)
## Validating object structure
## Updating object slots
## Ensuring keys are in the proper strucutre
## Ensuring feature names don't have underscores or pipes
## Object representation is consistent with the most current Seurat version
DimPlot(cds,label = TRUE)

G1 <- c(1,3,4,5,7)
G2 <- c(0,2,6,8,9)
DEGs <- FindMarkers(cds,ident.1 = G1,ident.2 = G2,logfc.threshold = 0,min.pct = 0,min.diff.pct = 0,thresh.use = 1)
DEGs$pct.diff <- DEGs$pct.1 - DEGs$pct.2
TFs <- read.delim("../ee_extract_TF_from_cluster_markers/all_candidates TFs.csv",stringsAsFactors = FALSE)
df.anno <- function(df, 
                    ref, 
                    df.by = "GeneSymbol", 
                    ref.by = "GeneSymbol",
                    Prefix = "GPCR",
                    add.annos = c("Type","Family")){
    ref.subset <- ref[ref[,ref.by] %in% df[,df.by],]
    for (add.anno in add.annos){
        ref.subset[,add.anno] <- as.character(ref.subset[,add.anno])
        df$temp <- ""
        if(!is.null(Prefix)){
           new.name <- paste(Prefix,add.anno,sep = "_")
        }else{
          new.name <- add.anno
        }
        df$temp[match(ref.subset[,ref.by],df[,df.by])] <- ref.subset[,add.anno]
        colnames(df)[match("temp",colnames(df))] <- new.name
    }
    return(df)
}
DEGs$GeneSymbol <- rownames(DEGs)
DEGs.anno <- df.anno(df = DEGs,
        ref = TFs,
        df.by = "GeneSymbol",
        ref.by = "symbol",
        Prefix = "TF",
        add.annos = colnames(TFs)[c(1:3,5,6)])

DT::datatable(DEGs.anno,extensions = 'Buttons',
        options = list(dom = 'Bfrtip',
                       buttons = list('copy', 'print', list(extend = 'collection', buttons = c('csv', 'excel', 'pdf'), text = 'Download' ))))  %>%
formatSignif(c("p_val","avg_logFC","p_val_adj","pct.diff" ),digits = 3)
DT::datatable(dplyr::filter(DEGs.anno,TF_symbol != ""),extensions = 'Buttons',
        options = list(dom = 'Bfrtip',
                       buttons = list('copy', 'print', list(extend = 'collection', buttons = c('csv', 'excel', 'pdf'), text = 'Download' ))))  %>%
formatSignif(c("p_val","avg_logFC","p_val_adj","pct.diff" ),digits = 3)