source("SeuratV4CellAnnotateFunc.R")

h5_directory <- "./GSE221978_RAW/"
h5_files <- list.files(h5_directory, pattern = "\\.h5$", full.names = TRUE)
samples = list.files("./GSE221978_RAW/")
samples
dir <- file.path('./GSE221978_RAW/', samples)

seurat_objects <- lapply(h5_files, function(file) {
  data <- Read10X_h5(file)
  seurat_object <- CreateSeuratObject(counts = data, project = basename(file), min.cells = 0, min.features = 300)
  return(seurat_object)
})
lapply(seurat_objects, print)

scRNA <- merge(seurat_objects[[1]], seurat_objects[[2]], add.cell.ids = dir,project = "Seurat")
table(scRNA$orig.ident)

scRNA$orig.ident <- stringr::str_split(scRNA$orig.ident, '_', simplify = T)[, 1]
scRNA@active.ident <- factor(scRNA$orig.ident)
scRNA@meta.data[["group"]] <- ifelse(
  scRNA@meta.data[["orig.ident"]] %in% c("GSM6911083"), "Control", "Disease")
scRNA@meta.data[["group"]] <- factor(scRNA@meta.data[["group"]])

table(scRNA$orig.ident)
table(scRNA@meta.data[["group"]])

scRNA <- scRNAAutoAnno(Path = "./", SeuratObject = scRNA, Multi = T, DoubletFinder = T,species = "mouse")
DimPlot(scRNA,group.by = "RNA_snn_res.0.2",label = T)

scRNA <- readRDS("./.Cluster/data.merge.harmony.2000.rds")
load("refdata/Mus/ImmGen.Rdata")
load("refdata/Mus/MouseRNAseq.Rdata")

scRNA <- scRNAAutoAnno(Path = "./", SeuratObject = scRNA,Multi = TRUE,
                       ref = list(ImmGen,MouseRNAseq),
                       labels = list(ImmGen$label.main,MouseRNAseq$label.main),
                       species = "mouse",
                       Idents = "RNA_snn_res.0.2")

# 0:SMC; 1:Fibroblasts; 2:Macrophages; 3:Neutrophils; 4:T cells; 5:B cells; 6:SMC; 
# 7:Endothelial cells; 8:Schwann cells; 9:Schwann cells; 10:Erythrocytes; 11:Platelets

markers <- list("Neutrophils" = c("Cxcr2", "S100a8", "Il1b"),
                "Platelets" = c("Clec1b", "Ppbp", "Itga2b", "Gp9"),
                "Endothelial cells" = c("Pecam1", "Cdh5", "Cd36", "Fabp4"),
                "Macrophages" = c("Mrc1", "F13a1", "Dab2", "Lyz2", "Cd68", "Adgre1"),
                "Schwann cells" = c("Ncam1", "Ngfr", "S100b", "Sox10", "Mpz", "Egr2", "MbP", "Plp1"),
                "T cells" = c("Cd3g", "Cd3e", "Trbc1", "Trbc2", "Ms4a4b", "Cd8a"),
                "B cells" = c("Ebf1", "Jchaln", "Ms4a1", "Cd79a", "Cd79b", "Fcmr"),
                "Erythrocytes" = c("Hbb−bt", "Hba−a2", "Hba−a1", "Hbb−bs"),
                "Fibroblasts" = c("Col1a1", "Dcn", "Clec3b", "Pdgfra", "Col3a1"),
                "SMC" = c("Myh11", "Cnn1", "Tagln", "Acta2"))
markers <- markers %>% enframe(name = "cluster", value = "gene") %>% unnest(gene)

cluster.label <- scRNA@meta.data$RNA_snn_res.0.2
cluster.label <- gsub("^0$", "SMC", cluster.label)
cluster.label <- gsub("^1$", "Fibroblasts", cluster.label)
cluster.label <- gsub("^2$", "Macrophages", cluster.label)
cluster.label <- gsub("^3$", "Neutrophils", cluster.label)
cluster.label <- gsub("^4$", "T cells", cluster.label)
cluster.label <- gsub("^5$", "B cells", cluster.label)
cluster.label <- gsub("^6$", "SMC", cluster.label)
cluster.label <- gsub("^7$", "Endothelial cells", cluster.label)
cluster.label <- gsub("^8$", "Schwann cells", cluster.label)
cluster.label <- gsub("^9$", "Schwann cells", cluster.label)
cluster.label <- gsub("^10$", "Erythrocytes", cluster.label)
cluster.label <- gsub("^11$", "Platelets", cluster.label)


scRNA@meta.data$RNA_snn_res.0.2 <- cluster.label
scRNA$cellType_1 <- factor(scRNA$cellType_1,c("SMC", "Fibroblasts", "Macrophages", "Neutrophils", "T cells", "B cells", "Endothelial cells", "Schwann cells", "Erythrocytes", "Platelets"))

saveRDS(scRNA,"./result.rds")

Idents(scRNA) <- "cellType_1"
sub.markers <- FindAllMarkers(scRNA,only.pos = T, min.pct = 0.25, logfc.threshold = 0.25)
write.csv(sub.markers,"./.CellAnnotate/Findall.markers.cellType_1.csv")

scRNA <- readRDS("./result.rds")
source("scRNACheck.R")
setwd("./")
RePlot(scRNA, Ident = "RNA_snn_res.0.2")

library(homologene)
genelist <- c("Gns", "G6s", "Bcam", "Tutf1", "Abo", "Vwf")
KeyGen <- human2mouse(genelist)

scRNA <- scRNAAutoAnno(Path = "./", SeuratObject = scRNA, KeyGene = KeyGen)


p <- VlnPlot(scRNA, features = KeyGen, slot = "data", log = TRUE)
ggsave("./.KeyGene expression abundance/3.Keygene.VlnPlot.pdf", plot = p, width = 16, height = 8)



# 细胞通讯 -----------------------------------------------------------------
source("SeuratV4CellAnnotateFunc.R")
library(ComplexHeatmap)
library(SeuratData)
library(ggalluvial)
library(patchwork)
library(tidyverse)
library(CellChat)
library(ggplot2)
library(svglite)
library(future)
library(Seurat)
library(NMF)
library(Seurat)
library(magrittr)
library(openxlsx)
library(GSVA)
library(ggplot2)
library(glue)


scRNA <- readRDS("./result.rds")



# select:4
scRNAAutoAnno(Path = "./", SeuratObject = scRNA, species = "mouse")

cellchat <- readRDS("./.Cellchat/cellchat.rds")
cellchat <- netAnalysis_computeCentrality(cellchat, slot.name = "netP")

n <- 3
for (pattern in c("outgoing", "incoming")) {
  source("SeuratV4CellAnnotateFunc.R")
  nPatterns = 2
  cellchat <- identifyCommunicationPatterns(cellchat, pattern = pattern, k = nPatterns,
                                            width = 5, height = 9, font.size = 6)
  
  data1 <- cellchat@netP[["pattern"]][[pattern]][["pattern"]][["cell"]]
  data2 <- cellchat@netP[["pattern"]][[pattern]][["pattern"]][["signaling"]]
  data <- cellchat@netP[["pattern"]][[pattern]][["data"]]
  cutoff <- 1/length(unique(data1$Pattern))
  
  options(warn = -1)
  data1$Contribution[data1$Contribution < cutoff] <- 0
  data2$Contribution[data2$Contribution < cutoff] <- 0
  data3 = merge(data1, data2, by.x = "Pattern", by.y = "Pattern")
  data3$Contribution <- data3$Contribution.x * data3$Contribution.y
  data3 <- data3[, colnames(data3) %in% c("CellGroup", "Signaling", "Contribution")]
  
  data <- as.data.frame(as.table(data))
  data <- data[data[, 3] != 0, ]
  data12 <- paste0(data[, 1], data[, 2])
  data312 <- paste0(data3[, 1], data3[, 2])
  idx1 <- which(match(data312, data12, nomatch = 0) == 0)
  data3$Contribution[idx1] <- 0
  data3$id <- data312
  data3 <- data3 %>% group_by(id) %>% top_n(1, Contribution)
  data3$Contribution[which(data3$Contribution == 0)] <- NA
  df <- data3
  
  eval(parse(text = glue("data{n + 1} <- data3")))
  eval(parse(text = glue("sorted_data{n + 1} <- data{n + 1}[order(data{n + 1}$CellGroup, -data{n + 1}$Contribution),]")))
  eval(parse(text = glue("pathway <- unique(sorted_data{n + 1}$Signaling)")))
  eval(parse(text = glue("pathway <- unique(sorted_data{n + 1}$Signaling)")))
  df$Signaling <- factor(df$Signaling, levels = pathway)
  df <- df[order(df$Signaling), ]
  
  if (!is.null(pattern)) {
    if (pattern == "outgoing") {
      main.title = "Outgoing communication patterns of secreting cells"
    }
    else if (pattern == "incoming") {
      main.title = "Incoming communication patterns of target cells"
    }
  }
  
  color.use <- scPalette(nlevels(data1$CellGroup))
  
  gg <- ggplot(data = df, aes(x = Signaling, y = CellGroup)) + 
    geom_point(aes(size = Contribution, fill = CellGroup, 
                   colour = CellGroup), shape = 21) + scale_size_continuous(range = c(1, 3)) + 
    theme_linedraw() + scale_x_discrete(position = "bottom") + 
    ggtitle(main.title) + theme(plot.title = element_text(hjust = 0.5)) + 
    theme(text = element_text(size = 10), plot.title = element_text(size = 12, face = "plain"), 
          axis.text.x = element_text(angle = 45, hjust = 1), axis.text.y = element_text(angle = 0, hjust = 1), 
          axis.title.x = element_blank(), axis.title.y = element_blank()) + 
    theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25)) + 
    theme(panel.grid.major = element_line(colour = "grey90", 
                                          size = (0.1)))
  gg <- gg + scale_y_discrete(limits = rev(levels(data3$CellGroup)))
  gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, 
                                                       alpha = 1), drop = FALSE, na.value = "white")
  gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, 
                                 na.value = "white")
  gg <- gg + guides(colour = "none") + guides(fill = "none")
  gg <- gg + theme(legend.title = element_text(size = 10), 
                   legend.text = element_text(size = 8))
  gg
  ggsave_fun(plot = gg, paste0("./.Cellchat/", n, ".Dotplot_", pattern), height = 10, width = 10)
  
  n <- n + 1
}

p1 <- netAnalysis_signalingRole_scatter(cellchat)
pdf("./.Cellchat/5.Scatter.pdf", width = 10, height = 10)
p1
dev.off()

pathways.show <- c(unique(na.omit(sorted_data4)$Signaling, na.omit(sorted_data5)$Signaling))

pdf("./.Cellchat/6.Chord.pdf", width = 10, height = 10)
netVisual_aggregate(cellchat, signaling = pathways.show, layout = "chord")
dev.off()

pdf("./.Cellchat/7.Violin.pdf", width = 10, height = 150)
plotGeneExpression(cellchat, signaling = pathways.show, enriched.only = TRUE, type = "violin")
dev.off()

# 改
pdf("./.Cellchat/8.Dotplot.pdf", height = 20, width = 20)
netVisual_bubble(cellchat, remove.isolate = FALSE)    # 关键细胞顺序cellchat@idents
dev.off()
